我的安全团队希望我使用 AES256 密钥强度和 CBC 模式。我的代码只有在更改为 256 CBC 和块大小为 128 后现在输入长度为 32 个字母的输入明文时才有效。
如果我输入“这是一个测试”(不是 32 个字符长),我会收到:
System.Security.Cryptography.CryptographicException:输入数据不是一个完整的块。
如果我输入:“ABCDEFGHIJKLMNOPQRSTUVWXYZ000000”,就可以了!
我需要什么代码才能使用“这是一个测试”作为输入来完成这项工作。
下面的代码:
public byte[] EncryptStringToByte(string plainText, byte[] key, byte[] vector)
{
byte[] encrypted;
using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
{
aes.BlockSize = 128;
aes.KeySize = 256;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.None;
aes.Key = key;
aes.IV = vector;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
// Create the streams used for encryption.
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(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}