首页 > 解决方案 > RijndaelManaged false 解密结果

问题描述

我有一个问题,我试图自己解决它,但我不能。我的程序从目录中搜索 als .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;
        }
    }

错误出现在这里:

错误信息

这里有完整的代码:

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

问候

标签: c#encryption

解决方案


问题是您这样做会弄乱加密文本

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[] 传递给您的解密方法,并且您不需要对编码做任何事情。


推荐阅读