當我嘗試使用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;
}
一定表示你的問題的編程語言。否則,它們將不容易被看到,並且自動語法突出顯示也不會被應用。 – 2014-08-28 22:12:32
不要大幅編輯您的問題。如果您認爲您的原始問題不再有效,請刪除它或其他內容,但絕不會對其進行實質性更改(尤其是在回答問題後)。 – 2014-08-28 22:18:05
Moi,請不要爲標題添加標籤,使用適當的標籤標記問題就足夠了。 – 2014-08-28 22:36:39