views:

1457

answers:

3

I'm trying TripleDES Encryption with ECB mode. My code looks like that:

public static string EncryptDES(string InputText)
        {
            byte[] key = new byte[] { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48 };
            byte[] clearData = System.Text.Encoding.UTF8.GetBytes(InputText);
            MemoryStream ms = new MemoryStream();
            TripleDES alg = TripleDES.Create();
            alg.Key = key;
            alg.Mode = CipherMode.ECB;
            CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(clearData, 0, clearData.Length);
            cs.FlushFinalBlock();
            byte[] CipherBytes = ms.ToArray();
            ms.Close();
            cs.Close();
            string EncryptedData = Convert.ToBase64String(CipherBytes);
            return EncryptedData;

        }

When I run a test I got an exception that the "Length of Data to decrypt is invalid."

Does anyone knows what I'm doing wrong?

Thank you in advance.

Update

My bad ! I found my problem Instead of using alg.CreateEncryptor() I was using alg.CreateDecyptor().

A copy paste issue. :(

Thanks for help, guys

A: 

It sounds like your encryption method is using a different key/salt combo than the decryption method and it can't decrypt the data.

During debugging it might be benefical to convert your key & salt to readable strings and waste the cycle's converting them to bytes.. at least for readability.

Quintin Robinson
A: 

This could be an encoding problem. Make sure it's in UTF-8 or something sane. Maybe something like this:

Public Shared DefaultEncoding As Text.Encoding = _System.Text.Encoding.GetEncoding("Unicode")

(Reference: codeproject.com)

sep332
+3  A: 

My bad ! I found my problem Instead of using alg.CreateEncryptor() I was using alg.CreateDecyptor().

A copy paste issue. :(

Thanks for help, guys

Youssef
Heh good catch.. I skipped right over that, glad you fixed your issue!
Quintin Robinson
Thanks CQ for your help. Actually, your suggestion inspired me to find the problem.
Youssef