Невозможно расшифровать обычный текст с помощью TripleDESCryptoServiceProvider.

Я пытаюсь зашифровать и расшифровать текст, используя TripleDESCryptoServiceProvider.

Мое требование - одинаковый открытый текст, зашифрованный текст не должен быть одинаковым, для этого я создал разные вектор каждый раз.

Это код для шифрования и расшифровки текста.

public string EncryptString(string PlainText)
        {
            GenerateIV();
            GenerateKey();
            if (PlainText == null || PlainText.Length <= 0)
            {
                throw new ArgumentNullException("Invalid Plaintext.");
            }

            if (Key == null || Key.Length <= 0)
            {
                throw new ArgumentNullException("Key Can Not Be Null Or Empty.");
            }

            if (IV == null || IV.Length <= 0)
            {
                throw new ArgumentNullException("Vector Can Not Be Null Or Empty.");
            }

            byte[] encryptedText;

            using (TripleDESCryptoServiceProvider tdsObj = new TripleDESCryptoServiceProvider())
            {
                if (!isKeyStrengthChecked)
                {
                    bool isWeekKey = TripleDESCryptoServiceProvider.IsWeakKey(Key);
                    if (isWeekKey)
                    {
                        throw new Exception("Weak Key.");
                    }
                    else
                    {
                        isKeyStrengthChecked = true;
                    }
                }
                tdsObj.Key = Key;
                tdsObj.IV = IV;
                tdsObj.Mode = CipherMode.CBC;
                tdsObj.Padding = PaddingMode.PKCS7;
                ICryptoTransform encryptor = tdsObj.CreateEncryptor(tdsObj.Key, tdsObj.IV);
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter srEncrypt = new StreamWriter(csEncrypt))
                        {
                            srEncrypt.Write(PlainText);
                        }
                        encryptedText = msEncrypt.ToArray();
                    }
                }
            }
            return Convert.ToBase64String(encryptedText);
        }

        public string DecryptString(string cipherText)
        {
            GenerateIV();
            GenerateKey();
            if (cipherText == null || cipherText.Length <= 0)
            {
                throw new ArgumentNullException("Invalid CipherText.");
            }

            if (Key == null || Key.Length <= 0)
            {
                throw new ArgumentNullException("Key Can Not Be Null Or Empty.");
            }

            if (IV == null || IV.Length <= 0)
            {
                throw new ArgumentNullException("Vector Can Not Be Null Or Empty.");
            }

            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            string PlainText = null;
            using (TripleDESCryptoServiceProvider tdsDecrypt = new TripleDESCryptoServiceProvider())
            {
                tdsDecrypt.Key = Key;
                tdsDecrypt.IV = IV;
                tdsDecrypt.Mode = CipherMode.CBC;
                tdsDecrypt.Padding = PaddingMode.PKCS7;
                ICryptoTransform decrytor = tdsDecrypt.CreateDecryptor(Key, IV);
                using (MemoryStream msDecrypt = new MemoryStream(cipherBytes))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decrytor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            PlainText = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }
            return PlainText;
        }

Мой полный код находится здесь .Net Fiddle

Но когда я расшифровываю текст, я не получаю такой же простой текст. Что не так я сделал.


person Amit Kumar    schedule 02.10.2015    source источник


Ответы (2)


Вы создаете новый IV и ключ с вызовом расшифровки

public string DecryptString(string cipherText)
    {
        GenerateIV();
        GenerateKey();
        if (cipherText == null || cipherText.Length <= 0)

Вы должны использовать один и тот же IV и ключ как для шифрования, так и для расшифровки.

person Ebbe M. Pedersen    schedule 02.10.2015
comment
Я использую один и тот же ключ, но другой вектор, потому что я не хочу генерировать один и тот же зашифрованный текст для одного и того же простого текста. - person Amit Kumar; 02.10.2015
comment
Да, вы должны использовать новый IV при каждом шифровании... но вам нужно использовать правильный IV при расшифровке... а не просто генерировать новый. - person Ebbe M. Pedersen; 02.10.2015
comment
Если вы закомментируете GenerateIV() и GenerateKey() в методе DecryptString, программа вернет Hello Amit - person Ebbe M. Pedersen; 02.10.2015
comment
Это означает, что мне нужно хранить каждый Vector для каждого зашифрованного текста в Db, чтобы при расшифровке текста с сохраненным Vector - person Amit Kumar; 02.10.2015
comment
Да, вам нужен IV, используемый при шифровании. Это не секрет или что-то в этом роде. Люди часто добавляют зашифрованное поле к IV. - person Ebbe M. Pedersen; 02.10.2015
comment
Есть ли другой лучший способ сделать это вместо добавления Vector. - person Amit Kumar; 02.10.2015
comment
IV необходимо хранить вместе с зашифрованными данными. Я предпочитаю использовать его в начале. - person Ebbe M. Pedersen; 02.10.2015

Попробуй это

Демонстрация скрипта Dotnet

Комментарий // GenerateIV(); GenerateKey(); к функциям EncryptString и DecryptString

        string plainText1 = "Hello Amit";
        string plainText2 = "Hello Amit";
        Helper helper = new Helper();

        helper.GenerateIV();
        helper.GenerateKey();
        string encryptedData1 = helper.EncryptString(plainText1);
        string encryptedData2 = helper.EncryptString(plainText2);
        string getBackText = helper.DecryptString(encryptedData1);
        Console.WriteLine(getBackText);
        Console.ReadLine();
person SimarjeetSingh Panghlia    schedule 02.10.2015
comment
Но если комментарий GenerateIV(), то я получу тот же зашифрованный текст для того же простого текста. - person Amit Kumar; 02.10.2015