Rijndael加密/解密抛出异常
当我尝试使用AES加密,我得到的错误Invalid length for a Base-64 char array or string
当我尝试执行这行代码:Rijndael加密/解密抛出异常
byte[] clearBytes = Convert.FromBase64String(clearText);
这里是我的代码:
public string AESEncrypt(string clearText)
{
clearText = HttpUtility.UrlEncode(clearText) ;
byte[] clearBytes = Convert.FromBase64String(clearText) ;
byte[] ivBytes = Encoding.UTF8.GetBytes(InitV);
byte[] keyBytes = Encoding.UTF8.GetBytes(EncryptionKey) ;
var symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
var enctryptor = symmetricKey.CreateEncryptor(keyBytes, ivBytes);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, enctryptor, CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
return clearText;
}
或者,当我尝试解密,我得到的错误The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
试图执行这行代码:
byte[] cipherBytes = Convert.FromBase64String(cipherText);
这里是我的代码:
public string AESDecrypt(string cipherText)
{
string clearText;
cipherText = HttpUtility.UrlEncode(cipherText) ;
byte[] cipherBytes = Convert.FromBase64String(cipherText);
byte[] ivBytes = Encoding.UTF8.GetBytes(InitV);
byte[] keyBytes = Encoding.UTF8.GetBytes(EncryptionKey);
var symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
var enctryptor = symmetricKey.CreateDecryptor(keyBytes, ivBytes);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, enctryptor, CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
return clearText;
}
我不知道是什么让你认为URL编码生成基地64个编码的字节,但对其进行解码通常会导致你得到的错误。
cipherText = HttpUtility.UrlEncode(cipherText);
byte[] cipherBytes = Convert.FromBase64String(cipherText);
只是绝对的废话。请查看这些功能的功能,然后重试。
谢谢你的建议 – 2014-08-28 22:05:07
对不起,在答案上有点生硬。 URLEncode替换非URL友好字符,其中base 64是字节数组的字符编码。如上所述,彼此完全不同。 – 2014-08-28 22:11:32
我知道它是什么,我不想开始一些幼稚的战斗...我只补充说,因为我看到一个博客,建议它,我得到它的工作买去除,获得明文的UTF表示,但解密不是显示加密的内容。 – 2014-08-28 22:13:19
您是否将您的base64编码字符串传递给QueryString?如果是这样,它可能包含“+”符号,这些符号不是QueryString上的有效数据。 URL编码您的base 64字符串。
http://msdn.microsoft.com/en-us/library/zttxte6w(v=vs.110).aspx
现在要清楚了,这个方法需要一个静态的“123456789”作为测试..... – 2014-08-28 22:51:23
一定表示你的问题的编程语言。否则,它们将不容易被看到,并且自动语法突出显示也不会被应用。 – 2014-08-28 22:12:32
不要大幅编辑您的问题。如果您认为您的原始问题不再有效,请删除它或其他内容,但绝不会对其进行实质性更改(尤其是在回答问题后)。 – 2014-08-28 22:18:05
Moi,请不要为标题添加标签,使用适当的标签标记问题就足够了。 – 2014-08-28 22:36:39