Last active
February 21, 2022 19:51
-
-
Save VictorQueiroz/648656918142318619ec11fbf0188feb to your computer and use it in GitHub Desktop.
Working example of AES_ige_encrypt usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <assert.h> | |
#include <openssl/aes.h> | |
#include <openssl/ssl.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <stdint.h> | |
/** | |
* Interestingly enough, using `iv` and `userKey` directly will | |
* result in corrupted encrypted data, so we need to copy iv and userKey to temporary | |
* userKey2 and iv2 for it to work. | |
*/ | |
int main(){ | |
char iv[32]; | |
uint8_t userKey[32]; | |
uint8_t userKey2[32]; | |
uint8_t iv2[32]; | |
memset(iv,0,32); | |
memset(userKey,0,32); | |
uint32_t data_len = 64; | |
unsigned char data[data_len]; | |
memset(data,0,data_len); | |
AES_KEY aes_key; | |
unsigned char encrypted[data_len]; | |
uint32_t i; | |
printf("encrypted buffer before encryption:\n"); | |
for(i = 0; i < data_len;i++) { | |
printf("%d ",encrypted[i]); | |
} | |
printf("\n\n"); | |
printf("user key:\n"); | |
for(i = 0; i < 32;i++) { | |
printf("%d ",userKey[i]); | |
} | |
printf("\n\n"); | |
printf("iv:\n"); | |
for(i = 0; i < AES_BLOCK_SIZE*2;i++) { | |
printf("%d ",iv[i]); | |
} | |
printf("\n\n"); | |
memcpy(userKey2,userKey,32); | |
memcpy(iv2,iv,32); | |
assert(AES_set_encrypt_key(userKey2,256,&aes_key) == 0); | |
AES_ige_encrypt(data,encrypted,data_len,&aes_key,iv2,AES_ENCRYPT); | |
printf("encrypted:\n"); | |
for(i = 0; i < data_len;i++) { | |
printf("%d ",encrypted[i]); | |
} | |
printf("\n\n"); | |
printf("decrypted buffer after encryption:\n"); | |
for(i = 0; i < data_len;i++) { | |
printf("%d ",data[i]); | |
} | |
printf("\n\n"); | |
printf("user key after encryption:\n"); | |
for(i = 0; i < 32;i++) { | |
printf("%d ",userKey[i]); | |
} | |
printf("\n\n"); | |
memcpy(userKey2,userKey,32); | |
memcpy(iv2,iv,32); | |
unsigned char decrypted[data_len]; | |
AES_KEY aes_key2; | |
assert(AES_set_decrypt_key(userKey,256,&aes_key2) == 0); | |
AES_ige_encrypt(encrypted,decrypted,data_len,&aes_key2,iv2,AES_DECRYPT); | |
printf("decrypted:\n"); | |
for(i = 0; i < data_len;i++) { | |
printf("%d ",decrypted[i]); | |
} | |
printf("\n"); | |
uint8_t expected_decrypted[data_len]; | |
memset(expected_decrypted,0,data_len); | |
assert(memcmp(decrypted,expected_decrypted,data_len)==0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment