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
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 */
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With