如何解决在加密文本的末尾添加\ 0 \ 0 \ 0的AES加密功能?

时间:2019-05-27 13:29:37

标签: c# encryption aes rijndaelmanaged

当我使用AES加密解密加密的用户名时,在解密的用户名末尾显示一堆“ \ 0 \ 0 \ 0”。有没有办法在加密时不添加这些?

加密和解密的示例代码:

  string ky = xx_Convert.Base64ToString("RllhSzNjM09PZFAwT2RYMkdxOFI2cG9HYjVmWVIybnQ=");
  string iv = xx_Convert.Base64ToString("Y2pZQmJsdVlqdlBYM0RtcXVleDJkNGNTa0FIYjhYQ2Y=");

  string username = "test@mail.com";

  string encriptedUsername = xx_Crypto.EncryptAES(ky, iv, username);
  string encriptedPassword = xx_Crypto.EncryptAES(ky, iv, "password");

  string decryptedUsername = xx_Crypto.DecryptAES(ky, iv, encriptedUsername);
  string decryptedPassword = xx_Crypto.DecryptAES(ky, iv, encriptedPassword);

这在检查变量时为 decryptedUsername 提供了以下结果:“ test@mail.com \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 \ 0“

这可能是加密功能的Padding属性的结果。 在“加密”功能中,“填充”设置为Padding = PaddingMode.Zeros,但是当我删除此行时,它仍然填充结果,但带有其他不可见的字符。

加密功能:

public static string EncryptAES(string keyString, string ivString, string 
text)
{
  RijndaelManaged myRijndael = new RijndaelManaged()
  {
    Padding = PaddingMode.Zeros,
    Mode = CipherMode.CBC,
    KeySize = 256,
    BlockSize = 256
  };

  byte[] key = Encoding.UTF8.GetBytes(keyString);
  byte[] IV = Encoding.UTF8.GetBytes(ivString);

  ICryptoTransform encryptor = myRijndael.CreateEncryptor(key, IV);

  byte[] encrypted = null;
  using (MemoryStream msEncrypt = new MemoryStream())
  {
    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, 
          CryptoStreamMode.Write))
    {
      using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
      {
        //Write all data to the stream.
        swEncrypt.Write(text);
      }
      encrypted = msEncrypt.ToArray();
    }
  }

  return (Convert.ToBase64String(encrypted));
}

编辑:此处要求提供解密功能:

public static string DecryptAES(string keyString, string ivString, string text)
{
  var myRijndael = new RijndaelManaged()
  {
    Padding = PaddingMode.Zeros,
    Mode = CipherMode.CBC,
    KeySize = 256,
    BlockSize = 256
  };

  byte[] key = Encoding.UTF8.GetBytes(keyString);
  byte[] IV = Encoding.UTF8.GetBytes(ivString);

  ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV);

  byte[] sEncrypted = Convert.FromBase64String(text);

  byte[] fromEncrypt = new byte[sEncrypted.Length];

  MemoryStream msDecrypt = new MemoryStream(sEncrypted);
  CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);

  csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

  return (Encoding.UTF8.GetString(fromEncrypt));
}

那么可以在加密功能中防止这种情况吗?

PS::我没有使用与原始代码相同的键

1 个答案:

答案 0 :(得分:0)

  

那么可以在加密功能中防止这种情况吗?

是的,只需使用:

<security>

您当前正在编码整个缓冲区。创建缓冲区时,将在填充期间删除填充字节,但将缓冲区中的字节预设为零。

请注意,零填充的用处不大,因为如果纯文本以一个或多个零字节结尾,则这些字节可能会被删除。因此,某些消息无法通过这种方式成功解密(密码学家想加密任意消息,而不仅仅是字符串)。