Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AES Encryption -Key Generation with OpenSSL

As a reference and as continuation to the post: how to use OpenSSL to decrypt Java AES-encrypted data?

I have the following questions.

I am using OpenSSL libs and programming in C for encrypting data in aes-cbc-128. I am given any input binary data and I have to encrypt this.

I learn that Java has a CipherParameters interface to set IV and KeyParameters too.

Is there a way to generate IV and a key using openSSL? In short how could one use in a C program to call the random generator of openSSL for these purposes. Can any of you provide some docs/examples/links on this?

Thanks

like image 718
pimmling Avatar asked Apr 07 '11 11:04

pimmling


2 Answers

An AES key, and an IV for symmetric encryption, are just bunchs of random bytes. So any cryptographically strong random number generator will do the trick. OpenSSL provides such a random number generator (which itself feeds on whatever the operating system provides, e.g. CryptGenRandom() on Windows or /dev/random and /dev/urandom on Linux). The function is RAND_bytes(). So the code would look like this:

#include <openssl/rand.h>

/* ... */
unsigned char key[16], iv[16];

if (!RAND_bytes(key, sizeof key)) {
    /* OpenSSL reports a failure, act accordingly */
}
if (!RAND_bytes(iv, sizeof iv)) {
    /* OpenSSL reports a failure, act accordingly */
}
like image 74
Thomas Pornin Avatar answered Sep 26 '22 20:09

Thomas Pornin


Assuming AES-128:

unsigned char key[16];
RAND_bytes(key, sizeof(key));

unsigned char iv[16];
RAND_bytes(iv, sizeof(iv));

The random generator needs to be seeded before using one of those.

like image 31
Dmitry Dvoinikov Avatar answered Sep 24 '22 20:09

Dmitry Dvoinikov