Skip to content

Instantly share code, notes, and snippets.

@mythosil
Created October 17, 2011 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mythosil/1292328 to your computer and use it in GitHub Desktop.
Save mythosil/1292328 to your computer and use it in GitHub Desktop.
decryption by AES(128bit) using libcrypto
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/evp.h>
int main(int argc, const char* argv[])
{
if (argc <= 3) {
fprintf(stderr, "Usage: %s <key> <iv> <data>\n", argv[0]);
exit(EXIT_FAILURE);
}
const char *key, *iv, *data;
int key_length, iv_length, data_length;
key = argv[1];
key_length = strlen(key);
iv = argv[2];
iv_length = strlen(iv);
data = argv[3];
data_length = strlen(data);
const EVP_CIPHER *cipher;
int cipher_key_length, cipher_iv_length;
cipher = EVP_aes_128_cbc();
cipher_key_length = EVP_CIPHER_key_length(cipher);
cipher_iv_length = EVP_CIPHER_iv_length(cipher);
if (key_length != cipher_key_length) {
fprintf(stderr, "Error: key length must be %d\n", cipher_key_length);
exit(EXIT_FAILURE);
}
if (iv_length != cipher_iv_length) {
fprintf(stderr, "Error: iv length must be %d\n", cipher_iv_length);
exit(EXIT_FAILURE);
}
const char *p;
char *datax;
int i, datax_length;
datax = (char *)malloc(data_length);
for (p = data, i = 0; *p != '\0'; p += 2, i++) {
char buf[3];
buf[0] = *p;
buf[1] = *(p+1);
buf[2] = '\0';
datax[i] = strtol(buf, NULL, 16);
}
datax_length = i;
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
EVP_DecryptInit_ex(&ctx, cipher, NULL, (unsigned char *)key, (unsigned char *)iv);
int plain_length, final_length;
unsigned char *plaintext;
plain_length = datax_length;
plaintext = (unsigned char *)malloc(plain_length + 1);
EVP_DecryptUpdate(&ctx, plaintext, &plain_length, (unsigned char *)datax, datax_length);
EVP_DecryptFinal_ex(&ctx, plaintext + plain_length, &final_length);
plaintext[plain_length + final_length] = '\0';
printf("%s\n", plaintext);
free(plaintext);
free(datax);
EVP_CIPHER_CTX_cleanup(&ctx);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment