RijndaelManaged ложный результат расшифровки - PullRequest
0 голосов
/ 18 сентября 2018

У меня проблема, я пытался ее исправить сам, но не могу.Моя программа ищет ALT. TXT файлы из каталога.Затем он читает файлы, шифрует каждый файл и перезаписывает старый файл.Это отлично работает.Теперь я хочу расшифровать текстовые файлы, происходит следующее:

Здесь вы можете увидеть зашифрованный текст и расшифрованный текст

Итак, проблема в том,TXT-файл становится зашифрованным, и дешифрование тоже работает, но когда я расшифровываю, исходный текст не появляется.Вы можете видеть это на картинке, там идут только проводные письма.Я не могу понять, почему, я использую ту же соль и тот же пароль.

Вот мой код:

Первые 3 фрагмента для шифрования, остальные 3 для дешифрования.

foreach (var file in d2.GetFiles("*.txt"))
{
    Console.WriteLine(file.FullName, file.Name);
    string temppfad = file.FullName;
    StreamReader sr = new StreamReader(temppfad);
    string Inhalt = sr.ReadToEnd();
    Console.WriteLine(Inhalt + "\n");
    string Verschlüsselterinhalt = Verschlüsseln(Password, Inhalt);
    sr.Close();
    File.WriteAllText(temppfad, Verschlüsselterinhalt);
}

Эти части все еще работают, просто загрузите их, чтобы лучше их понять.

Детали шифрования:

static string Verschlüsseln(string PW, string original)
{
    using (RijndaelManaged myRijndael = new RijndaelManaged())
    {
        myRijndael.GenerateKey();
        myRijndael.GenerateIV();

        byte[] salt = Encoding.ASCII.GetBytes("0PQUX76U0adfaDADFexA888887Dz3J3X");
        Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(PW, salt);
        myRijndael.Key = key.GetBytes(myRijndael.KeySize / 8);
        myRijndael.IV = key.GetBytes(myRijndael.BlockSize / 8);

        // Encrypt the string to an array of bytes.
        byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);

        StringBuilder s = new StringBuilder();
        foreach (byte item in encrypted)
        {
            s.Append(item.ToString("X2") + " ");
        }
        Console.WriteLine("Encrypted:   " + s + "\n\n");
        return s.ToString();
    }
}

static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
{
    // Check arguments.
    if (plainText == null || plainText.Length <= 0)
        throw new ArgumentNullException("plainText");
    if (Key == null || Key.Length <= 0)
        throw new ArgumentNullException("Key");
    if (IV == null || IV.Length <= 0)
        throw new ArgumentNullException("Key");
    byte[] encrypted;
    // Create an RijndaelManaged object
    // with the specified key and IV.
    using (RijndaelManaged rijAlg = new RijndaelManaged())
    {
        rijAlg.Key = Key;
        rijAlg.IV = IV;
        rijAlg.Mode = CipherMode.CBC;
        rijAlg.Padding = PaddingMode.Zeros;

        // Create a decrytor to perform the stream transform.
        ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);

        // Create the streams used for encryption.
        using (MemoryStream msEncrypt = new MemoryStream())
        {
            using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            {
                using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                {

                    //Write all data to the stream.
                    swEncrypt.Write(plainText);
                }
                encrypted = msEncrypt.ToArray();
            }
        }
    }
    // Return the encrypted bytes from the memory stream.
    return encrypted;
}

Я думаю, что к этому моменту все в порядке, сейчас я опубликую детали для расшифровки.

foreach (var file in d2.GetFiles("*.txt"))
{
    Console.WriteLine(file.FullName, file.Name);
    string temppfad = file.FullName;
    StreamReader sr = new StreamReader(temppfad);
    string Inhalt = sr.ReadToEnd();
    Console.WriteLine("Inhalt: " + Inhalt + "\n");
    string Entschlüsselterinhalt = Entschlüsseln(Password, Inhalt);
    sr.Close();
    File.WriteAllText(temppfad, Entschlüsselterinhalt);
}

static string Entschlüsseln(string PW, string original)
{
    using (RijndaelManaged myRijndael = new RijndaelManaged())
    {
        myRijndael.GenerateKey();
        myRijndael.GenerateIV();

        byte[] salt = Encoding.ASCII.GetBytes("0PQUX76U0adfaDADFexA888887Dz3J3X");
        Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(PW, salt);
        myRijndael.Key = key.GetBytes(myRijndael.KeySize / 8);
        myRijndael.IV = key.GetBytes(myRijndael.BlockSize / 8);

        // Decrypt the bytes to a string.
        byte[] originalbytes = Encoding.ASCII.GetBytes(original);
        string decrypted = DecryptStringFromBytes(originalbytes, myRijndael.Key, myRijndael.IV);

        //Display the original data and the decrypted data.
        Console.WriteLine("Decrypted:    " + decrypted);
        return decrypted;
    }
}

static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
    // Check arguments.
    if (cipherText == null || cipherText.Length <= 0)
        throw new ArgumentNullException("cipherText");
    if (Key == null || Key.Length <= 0)
        throw new ArgumentNullException("Key");
    if (IV == null || IV.Length <= 0)
        throw new ArgumentNullException("Key");

    // Declare the string used to hold
    // the decrypted text.
    string plaintext = null;

    // Create an RijndaelManaged object
    // with the specified key and IV.
    using (RijndaelManaged rijAlg = new RijndaelManaged())
    {
        rijAlg.Key = Key;
        rijAlg.IV = IV;
        rijAlg.Mode = CipherMode.CBC;
        rijAlg.Padding = PaddingMode.Zeros;

        // Create a decrytor to perform the stream transform.
        ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

        // Create the streams used for decryption.
        using (MemoryStream msDecrypt = new MemoryStream(cipherText))
        {
            using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
            {
                using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                {

                    // Read the decrypted bytes from the decrypting stream
                    // and place them in a string.
                    plaintext = srDecrypt.ReadToEnd();
                }
            }
        }
    }
    return plaintext;
}

Я был бы очень рад, если бы кто-нибудь мог мне помочь.

ОБНОВЛЕНИЕ !!!

Я отредактировал теперь мой код, теперь он выглядит так:

                foreach (var file in d2.GetFiles("*.txt"))
                {
                    Console.WriteLine(file.FullName, file.Name);
                    string temppfad = file.FullName;
                    StreamReader sr = new StreamReader(temppfad);
                    string Inhalt = sr.ReadToEnd();
                    Console.WriteLine(Inhalt + "\n");
                    byte[] Verschlüsselterinhalt = Verschlüsseln(Password, Inhalt);
                    sr.Close();
                    File.WriteAllBytes(temppfad, Verschlüsselterinhalt);
                }



    static byte[] Verschlüsseln(string PW, string original)
    {
        using (RijndaelManaged myRijndael = new RijndaelManaged())
        {

            byte[] salt = Encoding.ASCII.GetBytes("0PQUX76U0adfaDADFexA888887Dz3J3X");
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(PW, salt);
            myRijndael.Key = key.GetBytes(myRijndael.KeySize / 8);
            myRijndael.IV = key.GetBytes(myRijndael.BlockSize / 8);

            // Encrypt the string to an array of bytes.
            byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);
            return encrypted;
        }
    }

Я думаю, что часть в порядке, теперь при расшифровке я получаю ошибку

                foreach (var file in d2.GetFiles("*.txt"))
                {
                    Console.WriteLine(file.FullName, file.Name);
                    string temppfad = file.FullName;
                    StreamReader sr = new StreamReader(temppfad);
                    string Inhalt = sr.ReadToEnd();
                    Console.WriteLine("Inhalt: " + Inhalt + "\n");
                    string Entschlüsselterinhalt = Entschlüsseln(Password, Inhalt);
                    sr.Close();
                    File.WriteAllText(temppfad, Entschlüsselterinhalt);
                }

   static string Entschlüsseln(string PW, string original)
    {
        using (RijndaelManaged myRijndael = new RijndaelManaged())
        {

            byte[] salt = Encoding.ASCII.GetBytes("0PQUX76U0adfaDADFexA888887Dz3J3X");
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(PW, salt);
            myRijndael.Key = key.GetBytes(myRijndael.KeySize / 8);
            myRijndael.IV = key.GetBytes(myRijndael.BlockSize / 8);

            // Decrypt the bytes to a string.
            byte[] originalbytes = Encoding.ASCII.GetBytes(original);
            string decrypted = DecryptStringFromBytes(originalbytes, myRijndael.Key, myRijndael.IV);

            //Display the original data and the decrypted data.
            Console.WriteLine("Decrypted:    " + decrypted);
            return decrypted;
        }
    }

Ошибка появляется здесь:

Сообщение об ошибке

Здесь есть полный код:

static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
    {
        // Check arguments.
        if (cipherText == null || cipherText.Length <= 0)
            throw new ArgumentNullException("cipherText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("Key");

        // Declare the string used to hold
        // the decrypted text.
        string plaintext = null;

        // Create an RijndaelManaged object
        // with the specified key and IV.
        using (RijndaelManaged rijAlg = new RijndaelManaged())
        {
            rijAlg.Key = Key;
            rijAlg.IV = IV;
            rijAlg.Mode = CipherMode.CBC;
            rijAlg.Padding = PaddingMode.Zeros;

            // Create a decrytor to perform the stream transform.
            ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

            // Create the streams used for decryption.
            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {

                        // Read the decrypted bytes from the decrypting stream
                        // and place them in a string.
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }

        }

        return plaintext;
    }

Привет

Ответы [ 2 ]

0 голосов
/ 19 сентября 2018

решено

Спасибо за вашу большую помощь, моя последняя ошибка была довольно легкой, просто небольшая ошибка, вот решение части, где была ошибка:

                    foreach (var file in d2.GetFiles("*.txt"))
                {
                    Console.WriteLine(file.FullName, file.Name);
                    string temppfad = file.FullName;
                    byte[] Inhaltsbyte = File.ReadAllBytes(temppfad);
                    string Entschlüsselterinhalt = Entschlüsseln(Password, Inhaltsbyte);
                    File.WriteAllText(temppfad, Entschlüsselterinhalt);
                }
0 голосов
/ 18 сентября 2018

Проблема в том, что вы возитесь с зашифрованным текстом, выполняя это

StringBuilder s = new StringBuilder();
foreach (byte item in encrypted)
{
    s.Append(item.ToString("X2") + " ");
}

Как упоминал Дэмиен, вы должны вернуть байтовый массив из static string Verschlüsseln(string PW, string original) и использовать File.WriteAllBytes для записи его в файл.Затем вы можете использовать File.ReadAllBytes, чтобы прочитать его из файла и передать байт [] в метод расшифровки, и вам не нужно ничего делать с кодировкой.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...