aes解密有时无法正常工作

时间:2015-07-08 06:27:40

标签: c# .net encryption cryptography aes

我正在使用aes来加密/解密文本,但有时它会在解密后给我一些确切的值,而有些时候我会收到错误。我提到了不同的答案,但没有找到问题的根本原因。

private static string DecryptStringFromBytes(byte[] cipherText, byte[] key, byte[] iv)
    {
        // Declare the string used to hold the decrypted text.  
        string plaintext = null;

        // Create an RijndaelManaged object  
        // with the specified key and IV.  
        using (var rijAlg = new System.Security.Cryptography.RijndaelManaged())
        {
            //Settings  
            rijAlg.Mode = System.Security.Cryptography.CipherMode.CBC;
            rijAlg.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            rijAlg.FeedbackSize = 128;

            rijAlg.Key = key;
            rijAlg.IV = iv;

            // Create a decrytor to perform the stream transform.  
            var decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

            try
            {
                // Create the streams used for decryption.  
                using (var msDecrypt = new System.IO.MemoryStream(cipherText))
                {
                    using (var csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
                    {

                        using (var srDecrypt = new System.IO.StreamReader(csDecrypt))
                        {
                            // Read the decrypted bytes from the decrypting stream  
                            // and place them in a string.  
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }
            catch
            {
                plaintext = "keyError";
            }
        }
        return plaintext;
    }

它会抛出错误" 填充无效且无法删除" 我看到一些建议,如删除填充,但它似乎没有适当的解决方案。 我无法找到这背后的原因,因为有时它运行完美而不会抛出错误。

非常感谢任何帮助或建议。

For Encryption - 正在js中对客户端进行加密,并将加密文本传递给服务器。

var key = CryptoJS.enc.Utf8.parse("16 digit number here");
            var iv = CryptoJS.enc.Utf8.parse("16 digit number here");
            var EncryptedString = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse("entered string to encrypt"), key,
             { keySize: 128 / 8, iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });

1 个答案:

答案 0 :(得分:1)

通过在.NET中使用类似的加密例程来解密函数,我能够成功地将明文转换为密文并返回明文,因此解密函数本身似乎没问题。因此,您用于加密的密钥和/或IV似乎很可能与您在解密时使用的值无法逐字节匹配。

鉴于您的加密代码使用UTF-8编码版本的字符串值来形成密钥和IV,因此在您的解密代码中使用Encoding.UTF8.GetBytes())也值得这样做。

然而,值得注意的是,虽然这可能解决了眼前的问题,但如果没有某种形式的密钥派生过程(例如Rfc2898DeriveBytes),将字符串值直接用于密钥本身就是一种不好的做法,应该为加密函数的每个应用程序随机生成和IV。这些只是您使用加密技术的一些问题(并且与代码是否有效无关)。

相关问题