Reputation: 49
I am trying to write a code which would decrypt a text which was encrypted with AES-128-ECB and represented in Base64. The key is known (it's a task for educational purposes) and presented in ASCII (for example, YELLOW SUBMARINE).
Here is the code:
private void button6_Click(object sender, EventArgs e)
{
string CTChar = Funcs.BitsToChar(Funcs.B64ToBits(textBox1.Text));
Byte[] CTBytes = new Byte[CTChar.Length];
for (int iCounter = 0; iCounter < CTChar.Length; iCounter++)
{
CTBytes[iCounter] = Convert.ToByte(CTChar[iCounter]%256);
}
string KeyBits = Funcs.CharToBits(textBox2.Text);
Byte[] KeyBytes = new Byte[textBox2.TextLength];
string PlainText = null;
Aes Decryptor = Aes.Create();
Decryptor.BlockSize = 128;
for (int iCounter = 0; iCounter < textBox2.Text.Length; iCounter++)
{
KeyBytes[iCounter] = Convert.ToByte(textBox2.Text[iCounter]);
}
Decryptor.KeySize = textBox2.TextLength * 8;
Decryptor.Key = KeyBytes;
Decryptor.Mode = CipherMode.ECB;
ICryptoTransform Decr = Decryptor.CreateDecryptor();
using (MemoryStream msDecrypt = new MemoryStream(CTBytes))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, Decr, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
PlainText = srDecrypt.ReadToEnd();
}
}
}
textBox3.Text = PlainText;
}
When running it and trying to decrypt a text, an error occurs: The input data is not a complete block (Cryptographic Exception was unhandled). What am I doing wrong?
Upvotes: 0
Views: 1305
Reputation: 93988
You should convert base 64 - which seems to be the format of the input ciphertext - directly to a Byte[]. You are currently converting it to bits, then to characters, then to bytes. Base 64 has been defined to encode bytes (or octets) to text.
Converting bytes with a random value to/from text will get you in trouble; it is one of the reasons why base 64 exists in the first place. Try and find a correct base 64 implementation for your platform, there should be plenty, even in the standard API.
Upvotes: 2