如何解密通过PowerShell加密的C#中的字符串

Sar*_*mar 7 .net c# encryption powershell securestring

是否可以解密通过PowerShell加密的C#中的字符串以及如何?

该字符串通过PowerShell加密,如下所示:

$pw = read-host "Enter Password" –AsSecureString

ConvertFrom-SecureString $pw | out-file "C:\file.txt"
Run Code Online (Sandbox Code Playgroud)

要使用PowerShell将其转换回来,我可以使用这些调用C#类的命令System.Runtime.InteropServices.Marshal.

$pwdSec = Get-Content "C:\file.txt" | ConvertTo-SecureString

$bPswd = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwdSec)

$pswd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bPswd)
Run Code Online (Sandbox Code Playgroud)

文件包含已转换为加密标准的字符串string("hello").

因此,如果打开file.txt文件,它看起来类似于:

01000000d08c9ddf0115d1118c7a00c04fc297eb0100000052ded6c2db80e748933432e19b9de8b10000
000002000000000003660000c00000001000000016dc35885d76d07bab289eb9927cfc1e000000000480
0000a0000000100000003106cde553f45b08d13d89d11336170b280000005cc865c1ee1b57e84ed3d1a2
d3f2d0ec0f189b532e61c18d1f31444d6f119a1e8368477fd2d81f54140000000cb0262e58b08ae14f37
22c14c69684841b6b21c
Run Code Online (Sandbox Code Playgroud)

Mar*_*ryl 7

ConvertFrom-SecureString您拥有的输出文件是一个UTF-16(密码)字符串,受ProtectedData.Protect存储为十六进制转储保护.

请恢复编码使用:

// Read file to string
string exportedData = File.ReadAllText(@"file.txt");

// 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);
}

// Decrypt the byte array to Unicode byte array
byte[] data =
    ProtectedData.Unprotect(encryptedData, (byte[])null, DataProtectionScope.CurrentUser);

// Convert Unicode byte array to string
string password = Encoding.Unicode.GetString(data);
Run Code Online (Sandbox Code Playgroud)

上面的代码工作,当你没有指定-KeyConvertFrom-SecureString.然后使用Windows Data Protection API(DPAPI)保护安全字符串.因此,字符串必须在相同的机器和帐户上进行解码,因为它是编码的.