【发布时间】:2015-07-08 06:27:39
【问题描述】:
我正在使用 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;
}
它抛出错误“填充无效并且无法删除” 我看到了一些建议,比如删除填充,但它似乎不是正确的解决方案。 我无法找到这背后的原因,因为有时它运行完美而不会抛出错误。
非常感谢任何帮助或建议。
用于加密 - 在 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 });
【问题讨论】:
-
这个函数对我来说看起来还不错,所以问题很可能出在你没有显示的 encryption 函数中。请编辑您的问题以包含它。
-
我添加了在客户端完成的加密部分。我们在客户端进行加密并在服务器端解密吗?@Iridium
标签: c# .net encryption cryptography aes