-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaes_cbc.c
More file actions
58 lines (50 loc) · 1.63 KB
/
Copy pathaes_cbc.c
File metadata and controls
58 lines (50 loc) · 1.63 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
// AES-256-CBC con OpenSSL EVP. Cifra y descifra una string fija.
//
// Compilar:
// gcc aes_cbc.c -o aes_cbc -lcrypto
//
// Notas:
// * CBC sin MAC NO es seguro contra modificación. Usar solo con MAC encima
// (HMAC-SHA256 al ciphertext) o, mejor, AES-GCM (ver aes_gcm.c).
// * Esto es ilustrativo; en código real usar libsodium.
#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[] = "Mensaje secreto de prueba.";
int plen = strlen((const char *) plain);
unsigned char key[32], iv[16];
RAND_bytes(key, sizeof key);
RAND_bytes(iv, sizeof iv);
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
unsigned char ct[1024];
int len, clen;
// Cifrado
EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv);
EVP_EncryptUpdate(ctx, ct, &len, plain, plen);
clen = len;
EVP_EncryptFinal_ex(ctx, ct + len, &len);
clen += len;
hexdump("key:", key, sizeof key);
hexdump("iv:", iv, sizeof iv);
hexdump("plaintext:", plain, plen);
hexdump("ciphertext:", ct, clen);
// Descifrado
unsigned char pt[1024];
int dlen;
EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv);
EVP_DecryptUpdate(ctx, pt, &len, ct, clen);
dlen = len;
EVP_DecryptFinal_ex(ctx, pt + len, &len);
dlen += len;
pt[dlen] = '\0';
printf("descifrado: \"%s\"\n", pt);
EVP_CIPHER_CTX_free(ctx);
return 0;
}