Kamran Bajwa
Kamran Bajwa

Reputation: 39

Weak Key error in C# while trying to implement TripleDES

whenever I try to run this code I get this error: 'Specified key is a known weak key for 'TripleDES' and cannot be used.' Can someone please help me solve this issue? I would be really grateful. Thanks.

using System.Security.Cryptography;


    String Data = EncryptDES("041205FFFBA666CF");


static string EncryptDES(string InputText)
{
    byte[] key = new byte[] { 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02 };
    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;

}

Upvotes: 0

Views: 551

Answers (1)

stratov
stratov

Reputation: 406

You can check your key with TripleDES.IsWeakKey(Byte[]) method.

As the error speaks for itself, the key you provided is weak. Since all the bytes in the array are equal. Simply, just change the key.

For additional information, you may check TripleDES.IsWeakKey(Byte[]) Method and weak key

Upvotes: 0

Related Questions