【发布时间】:2016-05-28 12:21:01
【问题描述】:
我有一个 1MB 大小的数据,想使用 aes_128_ctr 进行加密。我在 openssl 中找到源代码如下。
/* The input encrypted as though 128bit counter mode is being
* used. The extra state information to record how much of the
* 128bit block we have used is contained in *num, and the
* encrypted counter is kept in ecount_buf. Both *num and
* ecount_buf must be initialised with zeros before the first
* call to AES_ctr128_encrypt().
*/
void AES_ctr128_encrypt(const unsigned char *in, unsigned char *out,
const unsigned long length, const AES_KEY *key,
unsigned char counter[AES_BLOCK_SIZE],
unsigned char ecount_buf[AES_BLOCK_SIZE],
unsigned int *num) {
unsigned int n;
unsigned long l=length;
assert(in && out && key && counter && num);
assert(*num < AES_BLOCK_SIZE);
n = *num;
while (l--) {
if (n == 0) {
AES_encrypt(counter, ecount_buf, key);
AES_ctr128_inc(counter);
}
*(out++) = *(in++) ^ ecount_buf[n];
n = (n+1) % AES_BLOCK_SIZE;
}
*num=n;
}
我的问题是:为了加密整个 1MB 数据,我是否需要使用 while 循环来加密每个 128 位?我可以通过将长度设置为(1024 * 1024 / 16)来调用这个函数一次吗?而且我不明白这个 *num 做什么。谁能帮我解释一下?
【问题讨论】:
-
您必须多次调用 encrypt 函数来加密所有数据,但您必须只初始化一次 ctr_state struct,它将被 encrypt 函数使用。 num 参数是一个指针,它将指向 ctr_state 结构的 num 元素:&state->num。也许this 的回答会对你有所帮助。
-
你应该不使用
AES_encrypt和朋友。这是一个纯软件实现,因此您不会享受硬件支持,如 AES-NI。您应该使用EVP_*函数。请参阅 OpenSSL wiki 上的 EVP Symmetric Encryption and Decryption。事实上,您可能应该使用经过身份验证的加密,因为它提供 机密性和真实性。请参阅 OpenSSL wiki 上的 EVP Authenticated Encryption and Decryption。 -
可能相关:AES CTR 256 Encryption Mode of operation on OpenSSL(或至少在 Stack Overflow 上已提供参考)。另见Is it possible to use AES CTR mode encryption using the EVP API。
标签: c encryption openssl