0

实际上,我正在解密我在 c# 中使用 powershell 创建的字符串。

我使用以下 Powershell 命令创建 SecureString:

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

我使用以下 C# 代码解密 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]);
            }

        }

这在两个方向上都可以正常工作,但现在我使用自己的密钥文件在 Powershell 中创建 SecureString:

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

任何想法我必须在 c# 代码中更改以使用特定的密钥文件?

4

1 回答 1

0

指定密钥时,PowerShell 使用System.Security.Cryptography.Aes-class 而不是 进行加密ProtectedData,因此您需要进行大量更改。

如果使用 Key 或 SecureKey 参数指定加密密钥,则使用高级加密标准 (AES) 加密算法。指定密钥的长度必须为 128、192 或 256 位,因为这些是 AES 加密算法支持的密钥长度。如果未指定密钥,则使用 Windows 数据保护 API (DPAPI) 对标准字符串表示进行加密。

ConvertFrom-SecureString @ TechNet

就个人而言,我会ConvertTo-SecureString在 C# 中使用 -cmdlet 来避免重新发明轮子。

请参阅Aes Constructor @ MSDN和 this previous SO-question for C#-solution。

于 2016-09-04T09:41:53.047 回答