在TripleDES中实现Rfc2898DeriveBytes时的有线输出

时间:2014-06-08 21:28:59

标签: c# 3des pbkdf2

这是一个简单的代码,但需要花费数小时才能找出我输出错误的原因。我似乎无法找到问题所在。一切都是特别的Rfc2898DeriveBytes实施吗? 我需要帮助来找出导致错误输出的内容,它在哪里以及如何解决它以使此代码工作。

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(); 
    }

这是我输入的内容:

enter image description here

还有一件我想知道的事情,Rfc2898DeriveBytes(string a, byte[] salt, int iteration)Rfc2898DeriveBytes( byte[] a , byte[] salt, int iteration)之间有什么区别?哪一个最好用?他们提供相同的输出吗?

1 个答案:

答案 0 :(得分:0)

您正在使用原始(加密器)tripledes实例,而不是解密器实例tripledes1来解密。