AesManaged - заполнение недействительно и не может быть удалено - чтение из .Txt файла - PullRequest
1 голос
/ 21 мая 2019

Я пытаюсь сохранить зашифрованные данные в текстовый файл, а затем открыть и расшифровать его.Когда я пытаюсь расшифровать его, я получаю сообщение об ошибке «Заполнение недействительно и не может быть удалено».Я использую пример кода непосредственно от 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);

            }

Вот методы шифрования и дешифрования:

        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;

    }

1 Ответ

1 голос
/ 22 мая 2019

Извините, я удалил свой комментарий (в этом контексте это было неправильно), но я переработал ваш пример, чтобы иметь немного меньший шаблон и иметь возможность шифровать и дешифровать должным образом.Проблема в том, что вы генерируете новую и отличную пару ключ / 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);

и вот немного переработанные тяжелые методы, которые будут немного более компактными:

    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();
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...