From my security team, they want me to use AES256 key strength and CBC mode. My code only works when I enter a input plaintext of 32 letters in length now after changing to 256 CBC and block size to 128.
If I enter "This is a test" (not 32 characters long), I receive:
System.Security.Cryptography.CryptographicException: The input data is not a complete block.
If I enter: " ABCDEFGHIJKLMNOPQRSTUVWXYZ000000", works!
What code do I need to make this work with "This is a test" as input.
Code Below:
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;
}
AES is a block cipher, so it only works on plaintexts that have exactly the size of one block. A mode of operation like CBC enables you to encrypt plaintexts that are a multiple of the block size. To encrypt plaintexts of arbitrary length a padding mode must be used.
A common mode used for block ciphers is PKCS#5/PKCS#7:
aes.Padding = PaddingMode.PKCS7;
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments