我正在尝试编写用于消息的 AES CBC 加密的 C# 实现。目标是“正确”加密 C# 中的消息,以便 C 实现可以正确解密它。
C 解密实现如下所示(使用 openssl):
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new())) {
handleErrors();
}
if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (unsigned char*)key, (unsigned char*)iv)) {
handleErrors();
}
if(1 != EVP_DecryptUpdate(ctx, (unsigned char*)plaintext, &len, (unsigned char*)encrypted_text, encrypted_text_len)) {
handleErrors();
}
plaintext_len = len;
if(1 != EVP_DecryptFinal_ex(ctx, (unsigned char*)plaintext + len, &len)) {
//Error happens here...
}
我收到以下错误:
error: digital envelope routines:EVP_DecryptFinal_ex:wrong final block length:evp_enc.c:518:
C# 代码:
static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
byte[] encrypted;
// Create an Aes object
// with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Mode = CipherMode.CBC;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
我已经尝试了所有的填充模式,但没有运气。关于问题可能是什么的任何想法吗?
最佳答案
错误表明encrypted_text_len % 16 != 0
。
如果您正在从文件中读取数据,您应该仔细检查缓冲区中是否有意外的换行符。
关于c# - C 和 C# 实现之间的 AES/CBC 加密差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40183680/