gpt4 book ai didi

c# - Rijndael加密/解密

转载 作者:太空宇宙 更新时间:2023-11-03 20:33:45 25 4
gpt4 key购买 nike

我有下面的加解密代码。问题是在解密时,除了解密的文本外,我在文本后还有一些“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;

//解密

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;

}

我哪里错了?

最佳答案

在你的解密函数中你有:

Byte[] pltxt = new byte[PlainTextBytes1.Length];

这是错误的,因为密文比明文长,因为它被填充以获得 block 大小的倍数。

 CryptoStream.Read(pltxt, 0, pltxt.Length);

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


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

  1. 传递给Decrypt的参数叫做PlainTextBytes1,应该叫做cyphertext。
  2. 从字符串创建 key/initvec 字节的方式。 ASCII 编码在这里是一个糟糕的选择。 ASCII 不能表示任何字节串。也许您想对两倍于 key 大小的字符串进行十六进制编码/解码?
  3. ASCII en/decoding the plaintext 将只对 ASCII 字符起作用,并默默地破坏所有其他字符。为什么不改用 UTF-8?
  4. .net 命名约定说您应该为参数使用小写名称

关于c# - Rijndael加密/解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6055201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com