gpt4 book ai didi

c# - 如何正确且一致地从字符串中获取字节以进行 AES 加密?

转载 作者:太空狗 更新时间:2023-10-29 18:16:02 25 4
gpt4 key购买 nike

我目前正在使用 C# 实现 AES。加密方法有两个参数:一个字符串和一个密码。我正在获取提供的字符串并将其转换为字节数组,以便稍后使用它通过 BinaryWriter 将数据写入流。

问题是,当我使用 Convert.FromBase64String(string) 时,我得到 FormatException: Invalid length. 并且当我使用 Encoding.UTF8.GetBytes( string) 我的解密方法抛出无效 PKCS7.Padding 异常。

最近几天我一直在努力解决这个问题。我在 stackoverflow.com 和其他网站上阅读了近乎无限的问题,但我仍然不知道解决这个问题的最可靠方法是什么。

将在此程序中使用的字符串仅限于句子(例如“要加密的东西”)和数字(例如“12345”)。

提前谢谢你,这是我此时的代码:

    public class AESProvider {

public byte[] EncryptStringToBytes_Aes(string plainText, string Key)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
byte[] plainTextInBytes = Convert.FromBase64String(plainText);
byte[] encrypted;

//Create an Aes object
//with the specified key and IV.

using (Aes aesAlg = Aes.Create())
{
aesAlg.GenerateIV();
byte[] IV = aesAlg.IV;
//The Salt will be the first 8 bytes of the IV.
byte[] theSalt = new byte[8];
Array.Copy(IV,theSalt,8);
//A key for AES is generated by expanding the password using the following method.
Rfc2898DeriveBytes keyGen = new Rfc2898DeriveBytes(Key,theSalt);
byte[] aesKey = keyGen.GetBytes(16);
aesAlg.Key = aesKey;

// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, IV);

// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (BinaryWriter swEncrypt = new BinaryWriter(csEncrypt))
{

//Write all data to the stream.
swEncrypt.Write(plainTextInBytes);
}
encrypted = msEncrypt.ToArray();
}
}
// Prepend the IV to the ciphertext so it can be used in the decryption process.
using (MemoryStream ivPlusCipher = new MemoryStream())
{
using (BinaryWriter tBinaryWriter = new BinaryWriter(ivPlusCipher))
{
tBinaryWriter.Write(IV);
tBinaryWriter.Write(encrypted);
tBinaryWriter.Flush();
}
return ivPlusCipher.ToArray();
}
}
}

public byte[] DecryptStringFromBytes_Aes(byte[] cipherText, string Key)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
// Declare the string used to hold
// the decrypted text.
byte[] decrypted;

// Create an Aes object
// with the specified key and IV.

// Create the streams used for decryption.

using (Aes aesAlg = Aes.Create())
{
aesAlg.Mode = CipherMode.CBC;
aesAlg.Padding = PaddingMode.PKCS7;
//Grab IV from ciphertext
byte[] IV = new byte[16];
Array.Copy(cipherText,0,IV,0,16);
//Use the IV for the Salt
byte[] theSalt = new byte[8];
Array.Copy(IV,theSalt,8);
Rfc2898DeriveBytes keyGen = new Rfc2898DeriveBytes(Key,theSalt);
byte[] aesKey = keyGen.GetBytes(16);
aesAlg.Key = aesKey;

// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, IV);

using (MemoryStream msDecrypt = new MemoryStream())
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write))
{
using (BinaryWriter srDecrypt = new BinaryWriter(csDecrypt))
{
//Decrypt the ciphertext
srDecrypt.Write(cipherText, IV.Length, (cipherText.Length - IV.Length));
}
decrypted = msDecrypt.ToArray();
return decrypted;
}
}
}
}
}

最佳答案

您需要在加密/解密前后进行字节和字符串之间的转换。这不是同一个操作,你不应该使用同一个方法。

加密时,您从任意字符串开始。使用 Encoding.UTF8.GetBytes() 将其转换为 byte[]。加密它。现在可以使用 Convert.ToBase64String() 将生成的 byte[] 转换为字符串。

解密时,您现在从 Base64 编码的字符串开始。使用 Convert.FromBase64String() 将其解码为 byte[]。解密它。您现在拥有原始字符串的 UTF-8 编码,您可以使用 Encoding.UTF8.GetString() 对其进行解码。

记住:

  • Encoding.UTF8 可将任意字符串转换为字节数组(但它只能将包含实际 UTF8 编码的字节数组转换回来)。
  • Convert.[To/From]Base64String 可将任意字节数组转换为字符串(但它只能将包含实际 Base64 编码的字符串转换回来)。

关于c# - 如何正确且一致地从字符串中获取字节以进行 AES 加密?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26471791/

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