Rijndael加密/解密引发异常

本文关键字:异常 解密 加密 Rijndael | 更新日期: 2023-09-27 18:19:59

当我尝试使用AES加密时,当我尝试执行这行代码时,我得到错误Invalid length for a Base-64 char array or string

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;
}

Rijndael加密/解密引发异常

我不知道是什么让你认为URL编码会生成64个基本编码字节,但解码它通常会导致错误。

    cipherText = HttpUtility.UrlEncode(cipherText);
    byte[] cipherBytes = Convert.FromBase64String(cipherText);

完全是胡说八道。请查找这些函数的作用,然后重试。

是否在QueryString上传递base64编码的字符串?如果是这样,它可能包含"+"符号,这些符号不是QueryString上的有效数据。URL对您的基64字符串进行编码。

http://msdn.microsoft.com/en-us/library/zttxte6w(v=vs.110).aspx