Ключ ошибки ProtectedData недопустим для использования в указанном состоянии - PullRequest
0 голосов
/ 06 июня 2019

Моя цель - написать простое консольное приложение, которое может зашифровать пароль, записать его в файл.Затем прочитайте файл (с зашифрованным паролем) и расшифруйте текст, чтобы получить пароль. Я следую этой статье и приведенному там примеру C #: https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.protecteddata?view=netframework-4.8

Код, который я использую:

using System;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;


namespace CreatePasswordFile
{
    class CreatePasswordFile
    {

        static string PasswordFilePath;
        static byte[] s_aditionalEntropy = { 1,2,3,4,5,6,7,8,9,10 };


        static void Main(string[] args)
        {
            string plainPassword;
            string PasswordFilePath = @"D:\PasswordFiles\Password.txt";
            string PasswordFileEncryptedPath = @"D:\PasswordFiles\EncryptedPassword.txt";

            using (StreamReader sr = new StreamReader(PasswordFilePath))
            {
                plainPassword = sr.ReadLine();
            }

            var passwordbytes = plainPassword.ToCharArray().Select(c => Convert.ToByte(c)).ToArray();

            byte[] encryptedBytes1 = Protect(passwordbytes);

            var encryptedString = Encoding.Unicode.GetString(encryptedBytes1);

            WriteToFile(PasswordFileEncryptedPath, encryptedString);


            string encryptedText = ReadEnryptedFile(PasswordFileEncryptedPath);

            byte[] encryptedBytes2 = Encoding.Unicode.GetBytes(encryptedText);

            byte[] originalPlainPassword = UnProtect(encryptedBytes2);


        }

        private static byte[] UnProtect(byte[] secret)
        {
            return ProtectedData.Unprotect(secret, s_aditionalEntropy, DataProtectionScope.CurrentUser);
        }

        private static string ReadEnryptedFile(string passwordFileEncryptedPath)
        {
            string returnValue = string.Empty;
            using (StreamReader sr = new StreamReader(passwordFileEncryptedPath))
            {
                returnValue = sr.ReadLine();
            }

            return returnValue;
        }

        private static void WriteToFile(string passwordFileEncryptedPath, string encryptedSecret)
        {
            using (StreamWriter sw = new StreamWriter(passwordFileEncryptedPath))
            {
                sw.WriteLine(encryptedSecret);
            }
        }


        private static byte[] Protect(byte[] passwordBytes)
        {
            return ProtectedData.Protect(passwordBytes, s_aditionalEntropy, DataProtectionScope.CurrentUser);

        }
    }
}

Я получаю следующее исключение: необработанное исключение типа 'System.Security.Cryptography.CryptographicException' произошло в сообщении System.Security.dll: {"Ключ недопустим для использования в указанном состоянии. \ R \ n"}

Исключение возникает в этом методе:

private static byte[] UnProtect(byte[] secret)
{
    return ProtectedData.Unprotect(secret, s_aditionalEntropy, DataProtectionScope.CurrentUser);
}

Есть идеи, почему это происходит?Примечание. Я запускаю эту программу из Visual Studio, поэтому DataProtectionScope.CurrentUser всегда должен указывать на мою учетную запись (если я не ошибаюсь).

...