Расшифровать SecureString с помощью специального ключа

На самом деле я расшифровываю строки, созданные с помощью powershell в С#.

Я создаю SecureString с помощью следующей команды Powershell:

ConvertTo-SecureString -String "TopSecret" -AsPlainText -Force | ConvertFrom-SecureString

Я расшифровываю SecureString с помощью следующего кода С#:

        string exportedData = string.Empty;
        bool SecureStringOK = true;

        try
        {
            // Read args[0] to string
            exportedData = args[0];
        }
        catch (System.IndexOutOfRangeException)
        {
            Console.WriteLine("NO_SECURESTRING");
            Debug.WriteLine("NO_SECURESTRING");
            SecureStringOK = false;
        }

        if (SecureStringOK)
        {

            // Decrypt the byte array to Unicode byte array
            try
            {
                // Remove all new-lines
                exportedData = exportedData.Replace(Environment.NewLine, "");

                // Convert the hex dump to byte array
                int length = exportedData.Length / 2;
                byte[] encryptedData = new byte[length];
                for (int index = 0; index < length; ++index)
                {
                    encryptedData[index] = byte.Parse(exportedData.Substring(2 * index, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
                }

                byte[] data = ProtectedData.Unprotect(encryptedData, (byte[])null, DataProtectionScope.CurrentUser);

                // Convert Unicode byte array to string
                string password = Encoding.Unicode.GetString(data);

                // Write Output
                Console.WriteLine(password);
                Debug.WriteLine(password);
            }
            catch (System.Security.Cryptography.CryptographicException)
            {
                Console.WriteLine("WRONG_SECURESTRING: " + args[0]);
                Debug.WriteLine("WRONG_SECURESTRING: " + args[0]);
            }
            catch (System.FormatException)
            {
                Console.WriteLine("WRONG_SECURESTRING_FORMAT: " + args[0]);
                Debug.WriteLine("WRONG_SECURESTRING_FORMAT: " + args[0]);
            }

        }

Это прекрасно работает в обоих направлениях, но теперь я создаю SecureString в Powershell со своим собственным файлом ключа:

ConvertTo-SecureString -String "TopSecret" -AsPlainText -Force | ConvertFrom-SecureString -Key $KeyPath

Любые идеи, что я должен изменить в коде С#, чтобы использовать определенный ключевой файл?


person BetaWayOfLife    schedule 03.09.2016    source источник


Ответы (1)


При указании ключа PowerShell шифрует с использованием класса System.Security.Cryptography.Aes вместо ProtectedData, поэтому вам нужно внести довольно много изменений.

Если ключ шифрования указан с помощью параметров Key или SecureKey, используется алгоритм шифрования Advanced Encryption Standard (AES). Указанный ключ должен иметь длину 128, 192 или 256 бит, так как эти длины ключей поддерживаются алгоритмом шифрования AES. Если ключ не указан, API защиты данных Windows (DPAPI) используется для шифрования стандартного строкового представления.

ConvertFrom-SecureString @ TechNet

Лично я бы использовал ConvertTo-SecureString-командлет в C#, чтобы не изобретать велосипед.

См. Aes Constructor @ MSDN и этот предыдущий SO-вопрос для C#-решения.

person Frode F.    schedule 04.09.2016