Rijndael加密/解密引发异常

时间:2014-08-28 21:45:35

标签: c# encryption

当我尝试使用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;
}

2 个答案:

答案 0 :(得分:1)

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

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

绝对是胡说八道。请查看这些功能的作用,然后重试。

答案 1 :(得分:0)

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

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