在第二功能中使用安全字符串

时间:2015-12-09 19:41:06

标签: security powershell

在函数一中,我从一行读取一个对象并将其存储在一个安全的字符串中。用户永远不能确定字符串中的内容,实际值将用于第二个函数。

$read_servername = ConvertTo-SecureString Read-File $file -AsPlainText -Force

这成为对象System.Security.SecureString。当我将安全字符串传递给下一个函数时,它不能使用安全字符串的实际文本。在搜索中,我没有找到在第二个函数中解密此安全字符串的方法,但是我需要第二个函数才能使用它的值而不会损坏字符串。

请注意ConvertFrom-SecureString似乎没有解密它;例如,“C:\ Location \”的值不会被解密使用。

谢谢!

1 个答案:

答案 0 :(得分:0)

解密SecureString并不像创建SecureString那么容易。您可以使用以下方法执行此操作:

[System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.Inter‌​opServices.marshal]::SecureStringToBSTR($read_servername))

如果超长单线是令人生畏的,你可以分两步:

$BSTR = [System.Runtime.Inter‌​opServices.marshal]::SecureStringToBSTR($read_servername)
$PlainText = [System.Runtime.InteropServices.marshal]::PtrToStringAuto($BSTR)