-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaes_gcm.c
More file actions
75 lines (67 loc) · 2.59 KB
/
Copy pathaes_gcm.c
File metadata and controls
75 lines (67 loc) · 2.59 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
74
75
// AES-256-GCM con OpenSSL EVP. AEAD: confidencialidad + integridad en una sola op.
//
// Compilar:
// gcc aes_gcm.c -o aes_gcm -lcrypto
//
// Reglas:
// * El nonce (IV) DEBE ser único por (key, mensaje). Reusar nonce con la
// misma key permite recuperar la key de autenticación → catástrofe.
// * El tag (16 bytes) se transmite junto al ciphertext.
// * Si la verificación del tag falla, NO usar el plaintext.
#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
void hexdump(const char *label, const unsigned char *buf, int len) {
printf("%-12s ", label);
for (int i = 0; i < len; i++) printf("%02x", buf[i]);
printf("\n");
}
int main(void) {
const unsigned char plain[] = "AEAD: confidencialidad + autenticidad.";
const unsigned char aad[] = "header v1, content-type=text/plain";
int plen = strlen((const char *) plain);
int alen = strlen((const char *) aad);
unsigned char key[32], nonce[12], tag[16];
RAND_bytes(key, sizeof key);
RAND_bytes(nonce, sizeof nonce);
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
unsigned char ct[1024];
int len, clen;
// ------ encrypt ------
EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, NULL);
EVP_EncryptInit_ex(ctx, NULL, NULL, key, nonce);
EVP_EncryptUpdate(ctx, NULL, &len, aad, alen); // AAD (no se cifra)
EVP_EncryptUpdate(ctx, ct, &len, plain, plen);
clen = len;
EVP_EncryptFinal_ex(ctx, ct + len, &len);
clen += len;
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag);
hexdump("key:", key, sizeof key);
hexdump("nonce:", nonce, sizeof nonce);
hexdump("aad:", aad, alen);
hexdump("plaintext:", plain, plen);
hexdump("ciphertext:", ct, clen);
hexdump("tag:", tag, sizeof tag);
// ------ decrypt ------
unsigned char pt[1024];
int dlen;
EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, NULL);
EVP_DecryptInit_ex(ctx, NULL, NULL, key, nonce);
EVP_DecryptUpdate(ctx, NULL, &len, aad, alen);
EVP_DecryptUpdate(ctx, pt, &len, ct, clen);
dlen = len;
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, tag);
int ok = EVP_DecryptFinal_ex(ctx, pt + len, &len);
dlen += len;
if (ok > 0) {
pt[dlen] = '\0';
printf("descifrado: OK -> \"%s\"\n", pt);
} else {
printf("descifrado: TAG INVÁLIDO — mensaje alterado, descartar\n");
}
EVP_CIPHER_CTX_free(ctx);
return 0;
}