Question

I am trying to make an encrypt/decrypt code for 3DES using C# built in 3Des. I am configuring it like this:

    this.tDes = new TripleDESCryptoServiceProvider ();
    this.tDes.Key = new byte[]{97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112};
    this.tDes.IV = new byte[8];
    this.tDes.Mode = CipherMode.CBC;

And this is my decript function:

    public string Decrypt(string CipherText)
    {
        byte[] cipherData = System.Text.Encoding.UTF8.GetBytes(CipherText);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, this.tDes.CreateDecryptor(), CryptoStreamMode.Write);
        cs.Write(cipherData, 0, cipherData.Length);
        cs.FlushFinalBlock();
        byte[] ClearBytes = ms.ToArray();
        ms.Close();
        cs.Close();
        string decriptedData = Convert.ToBase64String(ClearBytes);
        return decriptedData;
    }

This is my encrypt function:

public string Encrypt(string InputText)
{
    byte[] clearData = System.Text.Encoding.UTF8.GetBytes(InputText);
    MemoryStream ms = new MemoryStream();
    CryptoStream cs = new CryptoStream(ms, this.tDes.CreateEncryptor(), 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;
}

But when trying to decrypt it, C# throws an error in the line "cs.FlushFinalBlock();" saying incorrect length. What should be the correct size? What is the problem?

Was it helpful?

Solution

You need to decode the base 64 before decrypting it (so assign it to cipherData). Then clearBytes should be decoded using UTF8 and assigned to decriptedData.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top