Rijndael加密/解密

1 .net c#

我有以下加密和解密代码.问题是除了解密文本解密外,我在文本后面还有一些"aaaaa".为什么?需要一些帮助.谢谢!

public static byte[] Encrypt(byte[] PlainTextBytes, string key , string InitialVector)
        {
            try
            {
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
               Byte[] KeyBytes = encoding.GetBytes(key);
                byte[] InitialVectorBytes = encoding.GetBytes(InitialVector); 
                RijndaelManaged SymmetricKey = new RijndaelManaged();
                ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes);
                MemoryStream MemStream = new MemoryStream();
                CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write);

                CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                CryptoStream.FlushFinalBlock();
                byte[] CipherTextBytes = MemStream.ToArray();

               return CipherTextBytes;
Run Code Online (Sandbox Code Playgroud)

// decrytion

public static string Decrypt(byte[] PlainTextBytes1, string key, string InitialVector)
    {
        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
        Byte[] KeyBytes = encoding.GetBytes(key);
        RijndaelManaged SymmetricKey = new RijndaelManaged();
        byte[] InitialVectorBytes = Encoding.UTF8.GetBytes(InitialVector);

        ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes);
        MemoryStream MemStream1 = new MemoryStream(PlainTextBytes1);
        CryptoStream CryptoStream = new CryptoStream(MemStream1, Decryptor, CryptoStreamMode.Read);
        Byte[] pltxt = new byte[PlainTextBytes1.Length];
        CryptoStream.Read(pltxt, 0, pltxt.Length);

         ASCIIEncoding textConverter = new ASCIIEncoding();

         round = textConverter.GetString(pltxt);
          return round;

    }
Run Code Online (Sandbox Code Playgroud)

我哪里错了?

Cod*_*aos 5

在您的解密功能中,您有:

Byte[] pltxt = new byte[PlainTextBytes1.Length];
Run Code Online (Sandbox Code Playgroud)

这是错误的,因为密码文本比纯文本长,因为它被填充以获得块大小的倍数.

 CryptoStream.Read(pltxt, 0, pltxt.Length);
Run Code Online (Sandbox Code Playgroud)

Read返回实际返回的字节数.它不保证它将返回您请求的字节数.


然后还有其他多个缺陷/坏的风格:

  1. 传入的参数Decrypt被称为PlainTextBytes1它应该被称为密文.
  2. 从字符串创建key/initvec字节的方式.ASCII编码在这里是一个糟糕的选择.ASCII不能表示任何字节串.也许你想要十六进制/解码一个两倍大小的密钥字符串?
  3. ASCII en /解码明文只适用于ASCII字符,并且会无声地破坏所有其他字符.为什么不使用UTF-8?
  4. .net命名约定说你应该使用小写名称作为参数