Youssef
Youssef

Reputation: 728

TripleDES Encryption in C#

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

Upvotes: 4

Views: 8601

Answers (3)

Youssef
Youssef

Reputation: 728

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

A copy paste issue. :(

Thanks for help, guys

Upvotes: 8

sep332
sep332

Reputation: 1049

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)

Upvotes: 0

Quintin Robinson
Quintin Robinson

Reputation: 82325

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.

Upvotes: 0

Related Questions