AES/CBC加密在C和c#实现中的区别

本文关键字:实现 区别 CBC 加密 AES | 更新日期: 2023-09-27 18:14:20

我正在尝试为消息的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;
        }

我尝试了所有的填充模式,没有运气。知道是什么问题吗?

AES/CBC加密在C和c#实现中的区别

错误提示encrypted_text_len % 16 != 0 .

当你从一个文件中读取时,你应该仔细检查你的缓冲区中没有意外的换行符