Search code examples
c#3despbkdf2

Having wired outputs while Rfc2898DeriveBytes implementation in TripleDES


This is a simple code but its taking hours to find out why am I getting wrong output. I can't seem to find the problem. Is everything okey specially with Rfc2898DeriveBytes implementation? I need help to find out whats causing wrong output, where is it and how to solve it to make this code work.

static void Main(string[] args)
    {
        string data = "welcome to the jungle";
        string pass = "monkey";
        string salt = "12345678";
        byte[] textdata = Encoding.UTF8.GetBytes(data);
        byte[] password = Encoding.UTF8.GetBytes(pass);
        byte[] saltbyte = Encoding.UTF8.GetBytes(salt);
        Rfc2898DeriveBytes keyGenerate = new Rfc2898DeriveBytes(password ,saltbyte ,1000);
        Rfc2898DeriveBytes keyGenerate1 = new Rfc2898DeriveBytes(password, saltbyte, 1000);
        byte[] key1 = keyGenerate.GetBytes(16);
        byte[] key2 = keyGenerate1.GetBytes(16);
        Console.WriteLine("Plaintext: " + data);
  
        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        tdes.BlockSize = 64;
        tdes.KeySize = 128;
        tdes.Key = key1;
        tdes.IV = saltbyte;
        tdes.Mode = CipherMode.CBC;
        tdes.Padding = PaddingMode.PKCS7;
        ICryptoTransform tripledes = tdes.CreateEncryptor();
        byte[] een = tripledes.TransformFinalBlock(textdata, 0, textdata.Length);
        string een1 = Convert.ToBase64String(een);
        Console.WriteLine("Encrypted Data: " +een1);

        TripleDESCryptoServiceProvider tdes1 = new TripleDESCryptoServiceProvider();
        tdes1.BlockSize = 64;
        tdes1.KeySize = 128;
        tdes1.Key = key2;
        tdes1.IV = saltbyte;
        tdes1.Mode = CipherMode.CBC;
        tdes1.Padding = PaddingMode.PKCS7;
        ICryptoTransform tripledes1 = tdes1.CreateDecryptor();
        byte[] en1 = tripledes.TransformFinalBlock(een, 0, een.Length);
        string en11 = Encoding.UTF8.GetString(en1); ;
        Console.WriteLine("Decrypted Data: " +en11);
        Console.ReadLine(); 
    }

This is what I get in as output:

enter image description here

And one more thing that I want to know, what is the difference between Rfc2898DeriveBytes(string a, byte[] salt, int iteration) and Rfc2898DeriveBytes( byte[] a , byte[] salt, int iteration) ? and which one is best for use? Do they give same output?


Solution

  • You're using the original (encryptor) tripledes instance, rather than the decryptor instance tripledes1 to decrypt.