c# - C 和 C# 实现之间的 AES/CBC 加密差异

标签 c# c encryption cryptography aes

我正在尝试编写用于消息的 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/

相关文章:

C# 重复公共(public)代码的单元测试

c - 基于 switch case 的代码片段的输出,其中具有匹配 case 的 block 没有代码语句

java - 最小化通过 UDP 传输的数据的最有效方法是什么?

ios - 在浏览器中打开 Realm 文件总是需要加密 key

ruby - 在 ruby​​ 中,如何使用 ECB 模式和 PKCS7 填充进行 DES 加密

c# - 如何在 "normal"c# 类中使用/注入(inject)服务,例如 Blazor @inject ClassName classObject

c# - 如何在 ASP.NET Core 6 中使用 Autofac/CaSTLe DynamicProxy 拦截器?

c# - 自动发现本地异常 : The Autodiscover service couldn't be located

c - 如何键入用数字初始化的巨大数组的强制转换元素

c - 如何使用程序名称和其他输入来运行程序?