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

时间:2016-10-21 18:56:15

标签: 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;
        }

我尝试了所有的填充模式,没有运气。关于问题可能是什么想法?

1 个答案:

答案 0 :(得分:0)

错误表示encrypted_text_len % 16 != 0

如果你正在从文件中读取,你应该仔细检查你是否没有在缓冲区中出现意外换行。