Encryption AES托管-填充无效且无法删除-从.Txt文件读取

Encryption AES托管-填充无效且无法删除-从.Txt文件读取,encryption,Encryption,我试图将加密数据保存到文本文件中,然后打开并解密它。当我尝试解密它时,我收到错误“填充无效且无法删除”。我使用的是直接来自Microsoft的示例代码进行加密和解密 以下是我加密和保存文件的代码: string json = JsonConvert.SerializeObject(credentials); using (AesManaged myAes = new AesManaged())

我试图将加密数据保存到文本文件中,然后打开并解密它。当我尝试解密它时,我收到错误“填充无效且无法删除”。我使用的是直接来自Microsoft的示例代码进行加密和解密

以下是我加密和保存文件的代码:

                    string json = JsonConvert.SerializeObject(credentials);
                    using (AesManaged myAes = new AesManaged())
                    {

                        byte[] encrypted = ControlHelperscs.EncryptStringToBytes_Aes(json, myAes.Key, myAes.IV);
                        File.WriteAllBytes(subPath, encrypted);
                    }
以下是我检索和解密文件的代码:

                using (AesManaged myAes = new AesManaged())
            {

                    byte[] file = File.ReadAllBytes(subPath);

                    string decrypt = ControlHelperscs.DecryptStringFromBytes_Aes(file, myAes.Key, myAes.IV);
                    credentials = JsonConvert.DeserializeObject<LoginModel>(decrypt);

            }
使用(AesManaged myAes=new AesManaged())
{
byte[]file=file.ReadAllBytes(子路径);
string decrypt=ControlHelperscs.DecryptStringFromBytes_Aes(文件,myAes.Key,myAes.IV);
凭据=JsonConvert.DeserializeObject(解密);
}
以下是加密和解密方法:

        public static byte[] EncryptStringToBytes_Aes(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("IV");
        byte[] encrypted;

        // Create an AesManaged object
        // with the specified key and IV.
        using (AesManaged aesAlg = new AesManaged())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;

            // Create an encryptor to perform the stream transform.
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.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;

    }

    public static string DecryptStringFromBytes_Aes(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("IV");

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

        // Create an AesManaged object
        // with the specified key and IV.
        using (AesManaged aesAlg = new AesManaged())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;

            // Create a decryptor to perform the stream transform.
            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.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;

    }
公共静态字节[]EncryptStringToBytes_Aes(字符串明文,字节[]键,字节[]IV)
{
//检查参数。

如果(plainText==null | | plainText.Length很抱歉,我删除了我的评论(在该上下文中是错误的),但我修改了您的示例,使其少了一点样板文件,并且能够正确地加密和解密。问题是,您正在生成一个新的、不同的密钥/IV对,以从您用于加密的密钥/IV对中进行解密。当然,它将无法解密。因此,下面是使其正常工作的部分:

        byte[] key;
        byte[] iv;

        string json = JsonConvert.SerializeObject(credentials);
        using (AesManaged myAes = new AesManaged())
        {
            key = myAes.Key;
            iv = myAes.IV;
            byte[] encrypted = ControlHelperscs.EncryptStringToBytes_Aes(json, key, iv);
            File.WriteAllBytes(subPath, encrypted);
        }

        byte[] file = File.ReadAllBytes(subPath);

        string decrypt = ControlHelperscs.DecryptStringFromBytes_Aes(file, key, iv);
        credentials = JsonConvert.DeserializeObject<LoginModel>(decrypt);

看起来您使用的是固定的IV-这在很大程度上违背了CBC模式的观点。它是不安全的。实际上,我从Microsoft获得了该代码。这就是为什么我不理解它为什么不能正常工作的原因。@Jesse C.Slicer(收到错误:“在加密流上调用了两次FlushFinalBlock()方法。它只能调用一次。”感谢您的帮助,这里的问题是,用户永远不会以保存文本文件的相同方法打开保存的文本文件,因此无法使用相同的密钥。我需要一种方法来知道解密时的密钥是什么。因此,这些密钥必须保存到文件系统。我将尝试将密钥保存到文本文件a第二个开始,看看是否有效。非常感谢!我真的非常感谢你的帮助。
    public static byte[] EncryptStringToBytes_Aes(string plainText, byte[] key, byte[] iv)
    {
        // Check arguments.
        if (plainText is null)
        {
            throw new ArgumentNullException(nameof(plainText));
        }

        if (plainText.Length == 0)
        {
            throw new ArgumentOutOfRangeException(nameof(plainText), plainText, "length cannot be zero");
        }

        if (key is null)
        {
            throw new ArgumentNullException(nameof(key));
        }

        if (key.Length == 0)
        {
            throw new ArgumentOutOfRangeException(nameof(key), key, "length cannot be zero");
        }

        if (iv is null)
        {
            throw new ArgumentNullException(nameof(iv));
        }

        if (iv.Length == 0)
        {
            throw new ArgumentOutOfRangeException(nameof(iv), iv, "length cannot be zero");
        }

        // Create an AesManaged object
        // with the specified key and IV.
        // Create an encryptor to perform the stream transform.
        // Create the streams used for encryption.
        using (SymmetricAlgorithm aesAlg = new AesManaged { Key = key, IV = iv })
        using (ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV))
        using (MemoryStream msEncrypt = new MemoryStream())
        using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
        using (TextWriter swEncrypt = new StreamWriter(csEncrypt))
        {
            // Write all data to the stream.
            swEncrypt.Write(plainText);
            swEncrypt.Flush();
            csEncrypt.FlushFinalBlock();

            // Return the encrypted bytes from the memory stream.
            return msEncrypt.ToArray();
        }
    }

    public static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] key, byte[] iv)
    {
        // Check arguments.
        if (cipherText is null)
        {
            throw new ArgumentNullException(nameof(cipherText));
        }

        if (cipherText.Length ==  0)
        {
            throw new ArgumentOutOfRangeException(nameof(cipherText), cipherText, "length cannot be zero");
        }

        if (key is null)
        {
            throw new ArgumentNullException(nameof(key));
        }

        if (key.Length == 0)
        {
            throw new ArgumentOutOfRangeException(nameof(key), key, "length cannot be zero");
        }

        if (iv is null)
        {
            throw new ArgumentNullException(nameof(iv));
        }

        if (iv.Length == 0)
        {
            throw new ArgumentOutOfRangeException(nameof(iv), iv, "length cannot be zero");
        }

        // Create an AesManaged object
        // with the specified key and IV.
        // Create a decryptor to perform the stream transform.
        // Create the streams used for decryption.
        using (SymmetricAlgorithm aesAlg = new AesManaged { Key = key, IV = iv })
        using (ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV))
        using (Stream msDecrypt = new MemoryStream(cipherText))
        using (Stream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
        using (TextReader srDecrypt = new StreamReader(csDecrypt))
        {
            // Read the decrypted bytes from the decrypting stream
            // and place them in a string.
            return srDecrypt.ReadToEnd();
        }
    }