gpt4 book ai didi

c# - AES 字符串加密/解密字符被隔开

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

我正在使用 AES 加密然后解密一个字符串。但我的输出看起来像这样:

Original text >> HI WORLD  
Decrypted text >> H I W O R L D

我已经尝试了很多代码,但我没有发现问题。

这里的问题在哪里?

class Program
{
public static void Main(string[] args)
{
byte[] aesKey = Cryptography.GenerateAes128Key();
Console.WriteLine("AES key >> " + aesKey.Length);
string originalText = "HI WORLD";
byte[] myMess = ASCIIEncoding.Unicode.GetBytes(originalText);
Console.WriteLine("Original text >> " + ASCIIEncoding.Unicode.GetString(myMess));
byte[] myEcnryptedMess = Cryptography.Encrypt(myMess, aesKey);
Console.WriteLine("Encrypted text >> " + ASCIIEncoding.Unicode.GetString(myEcnryptedMess));
Console.WriteLine("Decrypted text >> " + Cryptography.Decrypt(myEcnryptedMess, aesKey));
Console.WriteLine("Press any key to continue . . . ");
Console.ReadKey(true);
}

public static byte[] Encrypt(byte[] plainTextBytes, byte[] Key)
{
byte[] iv = new byte[Key.Length];
Aes myAes = Aes.Create();
ICryptoTransform encryptor = myAes.CreateEncryptor(Key, iv);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
// Close both streams.
memoryStream.Close();
cryptoStream.Close();
return cipherTextBytes;
}

public static string Decrypt(byte[] cipherTextBytes, byte[] Key)
{
byte[] iv = new byte[Key.Length];
Aes myAes = Aes.Create();
ICryptoTransform decryptor = myAes.CreateDecryptor(Key, iv);
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
// Start decrypting.
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
// Close both streams.
memoryStream.Close();
cryptoStream.Close();
// Convert decrypted data into a string.
// Let us assume that the original plaintext string was UTF8-encoded.
string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
// Return decrypted string.
return plainText;
}
}

最佳答案

您对 GetBytes 和 GetString 使用了不同的编码:

ASCIIEncoding.Unicode.GetBytes(originalText);

然后

Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)

尝试对两个操作使用同一个。

克里斯

关于c# - AES 字符串加密/解密字符被隔开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7645931/

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