-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrsa_demo.c
More file actions
73 lines (65 loc) · 2.43 KB
/
Copy pathrsa_demo.c
File metadata and controls
73 lines (65 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// RSA-2048 con OpenSSL EVP — generación de keys, cifrado OAEP y firma PSS.
//
// Compilar:
// gcc rsa_demo.c -o rsa_demo -lcrypto
#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/err.h>
void hex(const char *label, const unsigned char *buf, size_t n) {
printf("%-12s ", label);
for (size_t i = 0; i < n; i++) printf("%02x", buf[i]);
printf("\n");
}
int main(void) {
// 1. Generar par de keys RSA-2048
EVP_PKEY_CTX *kctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL);
EVP_PKEY_keygen_init(kctx);
EVP_PKEY_CTX_set_rsa_keygen_bits(kctx, 2048);
EVP_PKEY *pkey = NULL;
EVP_PKEY_keygen(kctx, &pkey);
EVP_PKEY_CTX_free(kctx);
printf("[+] Par de keys RSA-2048 generado (n bits = %d)\n",
EVP_PKEY_get_size(pkey) * 8);
// 2. Cifrado RSA-OAEP
const unsigned char msg[] = "secreto bajo OAEP";
unsigned char ct[512];
size_t clen = sizeof ct;
EVP_PKEY_CTX *ectx = EVP_PKEY_CTX_new(pkey, NULL);
EVP_PKEY_encrypt_init(ectx);
EVP_PKEY_CTX_set_rsa_padding(ectx, RSA_PKCS1_OAEP_PADDING);
EVP_PKEY_encrypt(ectx, ct, &clen, msg, strlen((char *) msg));
EVP_PKEY_CTX_free(ectx);
hex("ciphertext:", ct, clen);
unsigned char pt[512];
size_t plen = sizeof pt;
EVP_PKEY_CTX *dctx = EVP_PKEY_CTX_new(pkey, NULL);
EVP_PKEY_decrypt_init(dctx);
EVP_PKEY_CTX_set_rsa_padding(dctx, RSA_PKCS1_OAEP_PADDING);
EVP_PKEY_decrypt(dctx, pt, &plen, ct, clen);
EVP_PKEY_CTX_free(dctx);
pt[plen] = '\0';
printf("descifrado: \"%s\"\n", pt);
// 3. Firma RSA-PSS sobre el mensaje
EVP_MD_CTX *mctx = EVP_MD_CTX_new();
EVP_PKEY_CTX *sctx = NULL;
EVP_DigestSignInit(mctx, &sctx, EVP_sha256(), NULL, pkey);
EVP_PKEY_CTX_set_rsa_padding(sctx, RSA_PKCS1_PSS_PADDING);
EVP_DigestSignUpdate(mctx, msg, strlen((char *) msg));
unsigned char sig[512];
size_t siglen = sizeof sig;
EVP_DigestSignFinal(mctx, sig, &siglen);
EVP_MD_CTX_free(mctx);
hex("firma PSS:", sig, siglen);
// 4. Verificar firma
mctx = EVP_MD_CTX_new();
EVP_DigestVerifyInit(mctx, &sctx, EVP_sha256(), NULL, pkey);
EVP_PKEY_CTX_set_rsa_padding(sctx, RSA_PKCS1_PSS_PADDING);
EVP_DigestVerifyUpdate(mctx, msg, strlen((char *) msg));
int ok = EVP_DigestVerifyFinal(mctx, sig, siglen);
printf("verificar: %s\n", ok == 1 ? "OK" : "FALLO");
EVP_MD_CTX_free(mctx);
EVP_PKEY_free(pkey);
return 0;
}