AES Encryption -Key Generation with OpenSSL

泄露秘密 提交于 2019-12-18 04:14:09

问题


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


回答1:


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 */
}



回答2:


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.



来源:https://stackoverflow.com/questions/5580662/aes-encryption-key-generation-with-openssl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!