I want to develop functions for encrypt and decrypt. the key size should be at least 128 bits (16 bytes).
I used the AES*
api functions from the OpenSSL. but there is some restriction in the AES*
functions: the input data buffers should be multiple of 16!
Here after my functions:
unsigned char encrypt_aes_key[]={0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xAA,0xBB,0xCC,0xDD,0xEE,0xFF};
static inline int enc_array_decrypt(unsigned char *encarray, unsigned char *decarray, int size)
{
int i;
AES_KEY dec_key;
unsigned char apibuf[512] = {0};
unsigned char iv[AES_BLOCK_SIZE];
memset(iv, 0x00, AES_BLOCK_SIZE);
AES_set_decrypt_key(encrypt_aes_key, sizeof(encrypt_aes_key)*8, &dec_key); // Size of key is in bits
AES_cbc_encrypt(encarray, apibuf, size, &dec_key, iv, AES_DECRYPT);
memcpy(decarray, apibuf, size);
return 0;
}
static inline int enc_array_encrypt(unsigned char *array, unsigned char *encarray, int size)
{
int i;
AES_KEY enc_key;
unsigned char apibuf[512] = {0};
unsigned char iv[AES_BLOCK_SIZE];
memset(iv, 0x00, AES_BLOCK_SIZE);
AES_set_encrypt_key(encrypt_aes_key, sizeof(encrypt_aes_key)*8, &enc_key); // Size of key is in bits
AES_cbc_encrypt((unsigned char *)array, apibuf, size, &enc_key, iv, AES_ENCRYPT);
memcpy(encarray, apibuf, size);
return 0;
}
if I call my functions with buffer size 9 for example, the functions will return wron output
example:
int main(int argc, char *argv[] )
{
char buf[9] = {0}, encbuf[9] = {0}, decbuf[9] = {0};
strcpy(buf, argv[1]);
enc_array_encrypt(buf, encbuf, 9);
enc_array_decrypt(encbuf, decbuf, 9);
printf("%s \n%s\n", buf, decbuf);
return 0;
}
The program returns:
$ ./myprogram any
any
2�����S�
How I can fix that?
by the way I can not force the buffer to be 16x multiplier size. because I will integrate my functions in a big source code (SDK) in which I will call my functions in many places with different input buffer sizes.
I m open to use any other kind of encryption (other than AES), but should support key of 128 bits length. The input buffer and the encrypted buffer should have the same size