如何修复AES加密功能在加密文本末尾添加



当我使用 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 = 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:我没有使用与原始代码相同的键

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

是的,只需使用:

read = csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
return (Encoding.UTF8.GetString(fromEncrypt, 0, read));

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

请注意,零

填充的使用不多,因为如果您的明文以一个或多个零字节结尾,则可能会删除这些字节。因此,某些消息无法以这种方式成功解密(密码学家希望加密任意消息,而不仅仅是字符串(。

相关内容

  • 没有找到相关文章

最新更新