jonjayallday
jonjayallday

Reputation: 23

tripleDES decryption c#

I am given a tripleDES encrypted and encoded base 64 string:

ABvAsOKcGXqc5uQ4O5Z53isJaH31Pa8+PeddljE4mSU=

I am also given:

key size = 128;

key = 0123456789ABCDEF

iv = ABCDEFGH

I have written out the following code. I keep on getting an exception thrown at me saying "Bad PKCS7 padding. Invalid length 31" I am losing a byte somewhere I think. Can anyone please tell me what I am doing wrong.

string base64Encoded = "ABvAsOKcGXqc5uQ4O5Z53isJaH31Pa8+PeddljE4mSU="; // 
string ASCIIkey = "0123456789ABCDEF";
string ASCIIiv = "ABCDEFGH";


TripleDESCryptoServiceProvider tDES = new TripleDESCryptoServiceProvider();
tDES.KeySize = 128;
tDES.BlockSize = 64;
tDES.Padding = PaddingMode.PKCS7;
tDES.Mode = CipherMode.ECB;
tDES.Key = Encoding.ASCII.GetBytes(ASCIIkey);
tDES.IV = Encoding.ASCII.GetBytes (ASCIIiv);
byte[] encryptedData = Convert.FromBase64String(base64Encoded);
ICryptoTransform transform = tDES.CreateDecryptor();
byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
string message = System.Text.Encoding.ASCII.GetString(plainText);
Console.Write (message);

Upvotes: 1

Views: 1114

Answers (1)

AlexD
AlexD

Reputation: 32596

With

tDES.Mode = CipherMode.CBC;

and using as a reference HashAlgorithm.TransformBlock sample (see PrintHashMultiBlock)

int offset = 0;
while(encryptedData.Length - offset >= size)
    offset += transform.TransformBlock(encryptedData, offset,
                                       encryptedData.Length - offset,
                                       outputBuffer, offset);

I was able to get a known phrase

All Your Base Are Belong To Us!!


However a better way is just to change two lines

tDES.Padding = PaddingMode.None;  // instead of PaddingMode.PKCS7
tDES.Mode = CipherMode.CBC;       // instead of CipherMode.ECB

This is suggested by @MaartenBodewes here.

So feel free to unaccept the answer, and delete the duplicate :-).

Upvotes: 1

Related Questions