Professional Documents
Culture Documents
Openssl Aes.c
Openssl Aes.c
Openssl Aes.c
<string.h>
<stdio.h>
<stdlib.h>
<openssl/evp.h>
/**
* Create an 256 bit key and IV using the supplied key_data. salt can be added f
or taste.
* Fills in the encryption and decryption ctx objects and returns 0 on success
**/
int aes_init(unsigned char *key_data, int key_data_len, unsigned char *salt, EVP
_CIPHER_CTX *e_ctx,
EVP_CIPHER_CTX *d_ctx)
{
int i, nrounds = 5;
unsigned char key[32], iv[32];
/*
* Gen key & IV for AES 256 CBC mode. A SHA1 digest is used to hash the suppli
ed key material.
* nrounds is the number of times the we hash the material. More rounds are mo
re secure but
* slower.
*/
i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), salt, key_data, key_data_len
, nrounds, key, iv);
if (i != 32) {
printf("Key size is %d bits - should be 256 bits\n", i);
return -1;
}
EVP_CIPHER_CTX_init(e_ctx);
EVP_EncryptInit_ex(e_ctx, EVP_aes_256_cbc(), NULL, key, iv);
EVP_CIPHER_CTX_init(d_ctx);
EVP_DecryptInit_ex(d_ctx, EVP_aes_256_cbc(), NULL, key, iv);
return 0;
}
/*
* Encrypt *len bytes of data
* All data going in & out is considered binary (unsigned char[])
*/
unsigned char *aes_encrypt(EVP_CIPHER_CTX *e, unsigned char *plaintext, int *len
)
{
/* max ciphertext len for a n bytes of plaintext is n + AES_BLOCK_SIZE -1 byte
s */
int c_len = *len + AES_BLOCK_SIZE, f_len = 0;
unsigned char *ciphertext = malloc(c_len);
}
/* encrypt and decrypt each input string and compare with the original */
for (i = 0; input[i]; i++) {
char *plaintext;
unsigned char *ciphertext;
int olen, len;
/* The enc/dec functions deal with binary data and not C strings. strlen() w
ill
return length of the string without counting the '\0' string marker. We a
lways
pass in the marker byte to the encrypt/decrypt functions so that after de
cryption
we end up with a legal C string */
olen = len = strlen(input[i])+1;
ciphertext = aes_encrypt(&en, (unsigned char *)input[i], &len);
plaintext = (char *)aes_decrypt(&de, ciphertext, &len);
if (strncmp(plaintext, input[i], olen))
printf("FAIL: enc/dec failed for \"%s\"\n", input[i]);
else
printf("OK: enc/dec ok for \"%s\"\n", plaintext);
free(ciphertext);
free(plaintext);
}
EVP_CIPHER_CTX_cleanup(&en);
EVP_CIPHER_CTX_cleanup(&de);
return 0;
}