2

I'm trying to encrypt a string and decript it using AES. The encryption worked fine but I'm getting an error of The input data is not a complete block for the decryption. Is there an issue with my padding?

var aes = System.Security.Cryptography.Aes.Create();
aes.GenerateKey();
aes.GenerateIV();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;

var desEncrypter = aes.CreateEncryptor();
var buffer = System.Text.ASCIIEncoding.ASCII.GetBytes(text);

finalV = Convert.ToBase64String(desEncrypter.TransformFinalBlock(buffer, 0, buffer.Length));

var desDecrypter = aes.CreateDecryptor();
var buff = System.Text.Encoding.ASCII.GetBytes(finalV);

var origValue = desDecrypter.TransformFinalBlock(buff , 0, buff .Length);
mysticalstick
  • 2,479
  • 5
  • 16
  • 21

1 Answers1

8

You're creating finalV by converting bytes to Base64. In order to turn that back into bytes, you need to call Convert.FromBase64String(finalV).

You're calling ASCII.GetBytes(finalV), which gets you the bytes representing that Base64 text, rather than the original bytes.

EDIT

Not sure where you're getting stuck, but here is working code that is based on yours, so you can diff this out and see where you're getting the error:

string text = "ABC";

var aes = System.Security.Cryptography.Aes.Create();
aes.GenerateKey();
aes.GenerateIV();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;

var desEncrypter = aes.CreateEncryptor();
var buffer = System.Text.ASCIIEncoding.ASCII.GetBytes(text);

var finalV = Convert.ToBase64String(desEncrypter.TransformFinalBlock(buffer, 0, buffer.Length));

var desDecrypter = aes.CreateDecryptor();
var buff = Convert.FromBase64String(finalV);

var origValue = desDecrypter.TransformFinalBlock(buff, 0, buff.Length);
string result = Encoding.ASCII.GetString(origValue);
Console.WriteLine(result);
Joe Enos
  • 39,478
  • 11
  • 80
  • 136
  • Thank you I have fixed this. Now I can convert the decrypted value to a `byte[]`. I cannot seem to convert this into a `string` though. I tried calling `System.Text.Encoding.UTF8.GetString()` which should take in a `byte[]` yet I'm still getting this error. – mysticalstick Feb 03 '17 at 19:56
  • Your `buff` doesn't have any meaning as a string. It's the encypted text. Assuming your encryption code is ok, then `origValue` represents your decrypted value. Assuming that was originally a string, that's the one you need to call: `string decryptedText = Encoding.UTF8.GetString(origValue)`. – Joe Enos Feb 03 '17 at 19:59
  • 1
    yes I have tried this but I get the message `cannot implicitly convert from string to byte[]`. I printed the type of `origValue` to verify before and it is `System.byte[]` I don't know where the type error might be coming from. – mysticalstick Feb 03 '17 at 20:02
  • Also, I'd look [here](http://stackoverflow.com/a/2006922/111266) for better code for simple encryption of a string. – Joe Enos Feb 03 '17 at 20:11