C语言 AES 加密 - 使用 OpenSSL 生成密钥

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5580662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:18:01  来源:igfitidea点击:

AES Encryption -Key Generation with OpenSSL

cencryptionopensslaes

提问by pimmling

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

作为这篇文章的参考和延续: 如何使用 OpenSSL 解密 Java AES 加密的数据?

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.

我正在使用 OpenSSL 库和 C 编程来加密 aes-cbc-128 中的数据。我得到了任何输入二进制数据,我必须对其进行加密。

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

我了解到 Java 也有一个 CipherParameters 接口来设置 IV 和 KeyParameters。

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?

有没有办法使用openSSL生成IV和密钥?简而言之,如何在 C 程序中使用来为这些目的调用 openSSL 的随机生成器。你们中的任何人都可以提供一些关于此的文档/示例/链接吗?

Thanks

谢谢

回答by Thomas Pornin

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/randomand /dev/urandomon Linux). The function is RAND_bytes(). So the code would look like this:

AES 密钥和对称加密的 IV 只是一堆随机字节。所以任何加密强的随机数生成器都可以做到这一点。OpenSSL提供了(这本身就什么操作系统提供饲料,如这样的随机数生成器CryptGenRandom()在Windows或/dev/random/dev/urandomLinux上)。函数是RAND_bytes()。所以代码看起来像这样:

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

回答by Dmitry Dvoinikov

Assuming AES-128:

假设 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.

随机数发生器需要使用一个之前被接种