Skip to content

Instantly share code, notes, and snippets.

@paigeruten
Created September 7, 2014 19:29
Show Gist options
  • Save paigeruten/a1405c329d0dba00e31e to your computer and use it in GitHub Desktop.
Save paigeruten/a1405c329d0dba00e31e to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <openssl/evp.h>
int main(void) {
unsigned char plaintext[] = "AAAAAAAAAAAAAAAA";
unsigned char key[] = "BBBBBBBBBBBBBBBB";
unsigned char iv[] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
unsigned char res[32];
// Encrypting
// ----------
printf("ENCRYPTING\n\n");
EVP_CIPHER_CTX * ctx = EVP_CIPHER_CTX_new();
const EVP_CIPHER * evp = EVP_aes_128_ecb();
EVP_CIPHER_CTX_set_padding(ctx, 0);
EVP_CipherInit(ctx, evp, key, iv, 1);
int reslen = 32;
EVP_CipherUpdate(ctx, res, &reslen, plaintext, 16);
unsigned char res_final[16];
int reslen_final = 16;
EVP_CipherFinal(ctx, res_final, &reslen_final);
printf("reslen = %d\nres: ", reslen);
int i;
for (i = 0; i < 32; i++) {
printf("%02x ", res[i]);
}
printf("\n\n");
printf("reslen_final = %d\nres_final: ", reslen_final);
for (i = 0; i < 16; i++) {
printf("%02x ", res_final[i]);
}
printf("\n\n\n");
// Decrypting
// ----------
printf("DECRYPTING\n\n");
ctx = EVP_CIPHER_CTX_new();
EVP_CIPHER_CTX_set_padding(ctx, 0);
EVP_CipherInit(ctx, evp, key, iv, 0);
unsigned char resd[32];
reslen = 32;
EVP_CipherUpdate(ctx, resd, &reslen, res, 16);
unsigned char resd_final[16];
reslen_final = 16;
EVP_CipherFinal(ctx, resd_final, &reslen_final);
printf("reslen = %d\nresd: ", reslen);
for (i = 0; i < 32; i++) {
printf("%02x ", resd[i]);
}
printf("\n\n");
printf("reslen_final = %d\nresd_final: ", reslen_final);
for (i = 0; i < 16; i++) {
printf("%02x ", resd_final[i]);
}
printf("\n");
return 0;
}
@paigeruten
Copy link
Author

Output:

ENCRYPTING

reslen = 16
res: 12 66 73 34 44 73 0c b9 c5 84 a2 e9 bf 3f 73 52 2e 4e 3d f6 00 00 00 00 7d 05 40 00 00 00 00 00 

reslen_final = 16
res_final: 26 08 03 68 4c d0 fa d7 9c e8 f6 91 19 e4 5b 54 


DECRYPTING

reslen = 0
resd: 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 

reslen_final = 0
resd_final: 00 00 00 00 00 00 00 00 6f 8a 74 31 ea 7f 00 00

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment