Rijndael管理的错误解密结果

时间:2018-09-18 13:36:21

标签: c# encryption

我有一个问题,我试图自己修复它,但我不能。 我的程序搜索目录中的.txt文件。然后,它读取文件并加密每个文件并覆盖旧文件。很好现在我想解密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;
        }
    }

错误出现在这里:

Errormessage

这里有完整的代码:

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 :(得分:1)

问题是您这样做搞乱了加密的文本

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

如Damien所述,您应该从static string Verschlüsseln(string PW, string original)返回一个字节数组,并使用File.WriteAllBytes将其写入文件。然后,您可以使用File.ReadAllBytes从文件中读取它,并将byte []传递到您的解密方法中,而无需进行任何编码操作。

答案 1 :(得分:0)

已解决

谢谢您的帮助,我的最后一个错误很简单,只是一个小错误,这是错误所在部分的解决方案:

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