Reputation: 688
I wrote what was supposed to be a simple encrypt/decrypt application to familiarize myself with the AesCryptoServiceProvider and I am receiving an error. The error is "The input data is not a complete block." Here is the code:
static void Main(string[] args)
{
Console.WriteLine("Enter string to encrypt:");
string userText = Console.ReadLine();
byte[] key;
byte[] IV;
using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
{
key = aes.Key;
IV = aes.IV;
}
byte[] encryptedText = EncryptString(userText, key, IV);
Console.WriteLine(Convert.ToBase64String(encryptedText));
string decryptedText = DecryptString(encryptedText, key, IV);
Console.WriteLine(decryptedText);
Console.ReadLine();
}
private static byte[] EncryptString(string encryptText, byte[] key, byte[] IV)
{
using (AesCryptoServiceProvider symAlg = new AesCryptoServiceProvider())
{
symAlg.Key = key;
symAlg.IV = IV;
ICryptoTransform ct = symAlg.CreateEncryptor(symAlg.Key, symAlg.IV);
byte[] encryptTextBytes = UnicodeEncoding.ASCII.GetBytes(encryptText);
byte[] encryptedText = ct.TransformFinalBlock(encryptTextBytes, 0, encryptTextBytes.Length);
return encryptTextBytes;
}
}
private static string DecryptString(byte[] decryptText, byte[] key, byte[] IV)
{
using (AesCryptoServiceProvider symAlg = new AesCryptoServiceProvider())
{
symAlg.Key = key;
symAlg.IV = IV;
ICryptoTransform ct = symAlg.CreateDecryptor(symAlg.Key, symAlg.IV);
byte[] decryptedUserText = ct.TransformFinalBlock(decryptText, 0, decryptText.Length);
return Convert.ToBase64String(decryptedUserText);
}
}
I can find results for this error online but they are all related to writing to a memory stream for encryption, which is not really what I am doing. Can someone help point out what I am doing wrong here?
Upvotes: 1
Views: 5702
Reputation: 949
Ha, found it!
Look at what you return in your encrypt function:
byte[] encryptTextBytes = UnicodeEncoding.ASCII.GetBytes(encryptText);
byte[] encryptedText = ct.TransformFinalBlock(encryptTextBytes, 0, encryptTextBytes.Length);
return encryptTextBytes;
Tip: it is not the encrypted stuff.
Upvotes: 2