【发布时间】:2016-10-30 12:14:11
【问题描述】:
我正在编写一个 fuse 文件系统,但我遇到了一个问题。
我正在使用 CBC AES 对磁盘中的数据进行加密。问题是填充。例如,当要加密的大小为 15 个字节时,这没有问题,因为它额外增加了 1 个字节。问题是,当我尝试加密 4096 个字节时,它还会给我添加 16 个字节的填充,这对我来说是失败的。我不知道为什么要添加填充,因为 4096 是 128 的倍数(大小 aes 块)。我需要修改我的 c 代码,以便对 openssl 说,仅在必要时添加填充,但并非总是如此......
我知道如果明文不是 128 的倍数,它将添加填充。但如果不是,为什么?我能做什么?
这是我的密码:
int encrypt_data(unsigned char *plaintext, int plaintext_len, unsigned char *key,
unsigned char *iv, unsigned char *ciphertext, int algorithm_pos)
{
EVP_CIPHER_CTX *ctx;
int len;
int ciphertext_len;
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
/* Initialise the encryption operation. IMPORTANT - ensure you use a key
* and IV size appropriate for your cipher
* In this example we are using 256 bit AES (i.e. a 256 bit key). The
* IV size for *most* modes is the same as the block size. For AES this
* is 128 bits */
if(1 != EVP_EncryptInit_ex(ctx, ciphers[algorithm_pos].algorithm(), NULL, key, iv))
handleErrors();
/* Provide the message to be encrypted, and obtain the encrypted output.
* EVP_EncryptUpdate can be called multiple times if necessary
*/
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
handleErrors();
ciphertext_len = len;
/* Finalise the encryption. Further ciphertext bytes may be written at
* this stage.
*/
if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
ciphertext_len += len;
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
}
【问题讨论】:
-
CBC 模式只提供机密性,您通常必须添加 MAC 才能安全地使用 CBC 模式。您可能应该使用经过身份验证的加密,因为它提供 机密性和真实性。请参阅 OpenSSL wiki 上的 EVP Authenticated Encryption and Decryption。
标签: c encryption openssl aes pkcs#7