The problem you are running into is you are never making sure the text in
Genkey.Text
is padded or truncated to the correct size. Your key needs to be 32 bytes while your IV needs to be 16 bytes (based on your 256 bit key and 128 bit block). If you look at my code, you will see how I handle this using the
PadLeft
method.
You can plug the following code into a console application to test, just make sure you have the input file created.
static void Main(string[] args)
{
string keyText = "Test";
byte[] keyBytes = ASCIIEncoding.ASCII.GetBytes(keyText.PadLeft(32));
byte[] ivBytes = ASCIIEncoding.ASCII.GetBytes(keyText.PadLeft(16));
Console.WriteLine("Key Length: {0}", keyBytes.Length);
string inputFile = @"C:\TestFiles\Input.txt";
string encryptedFile = @"C:\TestFiles\Output.enc";
string decryptedFile = @"C:\TestFiles\Decrypted.txt";
using (FileStream inputFileStream = File.Open(inputFile, FileMode.Open))
using (FileStream outputFileStream = File.Open(encryptedFile, FileMode.Create))
{
using (AesCryptoServiceProvider aesCryptoServiceProvider = new AesCryptoServiceProvider())
{
aesCryptoServiceProvider.KeySize = 256;
aesCryptoServiceProvider.BlockSize = 128;
aesCryptoServiceProvider.Key = keyBytes;
aesCryptoServiceProvider.IV = ivBytes;
ICryptoTransform cryptoTransform = aesCryptoServiceProvider.CreateEncryptor();
using (CryptoStream cryptoStream = new CryptoStream(outputFileStream, cryptoTransform, CryptoStreamMode.Write))
{
byte[] buffer = new byte[inputFileStream.Length];
inputFileStream.Read(buffer, 0, buffer.Length);
cryptoStream.Write(buffer, 0, buffer.Length);
}
}
}
using (FileStream inputFileStream = File.Open(encryptedFile, FileMode.Open))
using (FileStream outputFileStream = File.Open(decryptedFile, FileMode.Create))
{
using (AesCryptoServiceProvider aesCryptoServiceProvider = new AesCryptoServiceProvider())
{
aesCryptoServiceProvider.KeySize = 256;
aesCryptoServiceProvider.BlockSize = 128;
aesCryptoServiceProvider.Key = keyBytes;
aesCryptoServiceProvider.IV = ivBytes;
ICryptoTransform cryptoTransform = aesCryptoServiceProvider.CreateDecryptor();
using (CryptoStream cryptoStream = new CryptoStream(outputFileStream, cryptoTransform, CryptoStreamMode.Write))
{
byte[] buffer = new byte[inputFileStream.Length];
inputFileStream.Read(buffer, 0, buffer.Length);
cryptoStream.Write(buffer, 0, buffer.Length);
}
}
}
}