将存储在文本文件中的 SecureString 转换回可读字符串

use*_*331 3 .net security string powershell securestring

我在将以前存储的 SecureString 转换回其原始字符串时遇到问题。我这样做是因为我相信最初输入密码时可能存在拼写错误。

SecureString 最初是使用以下命令创建并存储在文本文件中的:

$SecurePassword = Read-Host -Prompt "Enter password" -AsSecureString
$SecurePassword | ConvertFrom-SecureString > C:\TEMP\TEST_Secure.txt
Run Code Online (Sandbox Code Playgroud)

对于我选择的应用程序(Veeam 备份),我读取包含加密密码的文件并将其反馈回应用程序

$SecurePasswordPath = "C:\TEMP\TEST_Secure.txt"
$EncryptionKey = cat $SecurePasswordPath | ConvertTo-SecureString
Run Code Online (Sandbox Code Playgroud)

Veeam备份脚本实际上是按如下方式读取的:

$EncryptionKey = Add-VBREncryptionKey -Password (cat $SecurePasswordPath | ConvertTo-SecureString)
Run Code Online (Sandbox Code Playgroud)

我已尝试以下方法来尝试恢复密钥:

$new1 = cat $SecurePasswordPath | ConvertTo-SecureString

$Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($new1)
$result = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr)
Run Code Online (Sandbox Code Playgroud)

结果通常是一个空白字段。

我也尝试过更推荐的方法:

$new1 = cat $SecurePasswordPath | ConvertTo-SecureString
[System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($new1))
Run Code Online (Sandbox Code Playgroud)

每一个结果都不会真正返回任何内容。

我担心我在创建时没有遵循正确的语法,并且无法恢复原始密钥,因此无法恢复我的备份。

到这里就绝望了!任何帮助将不胜感激!!

Bil*_*art 6

以下是如何提示输入 aSecureString并将其作为加密标准字符串写入文本文件:

Read-Host "Enter password" -AsSecureString | 
  ConvertFrom-SecureString |
  Out-File "D:\Path\EncryptedStandardString.txt"
Run Code Online (Sandbox Code Playgroud)

要反转这个并获取一个SecureString对象:

$secureString = Get-Content "D:\Path\EncryptedStandardString.txt" |
  ConvertTo-SecureString
Run Code Online (Sandbox Code Playgroud)

如果要使用 AES 而不是 DPAPI,还需要向和cmdlet 提供-Key或参数。-SecureKeyConvertFrom-SecureStringConvertTo-SecureString

如果想将a解密SecureStringString对象,可以使用以下函数:

function ConvertTo-String {
  param(
    [Security.SecureString]
    $secureString
  )
  try {
    $bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureString)
    [Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)
  }
  finally {
    if ( $bstr -ne [IntPtr]::Zero ) {
      [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

警告:如果您使用此功能,您将绕过对象提供的保护SecureString

  • @TesselttingHeckler - 不 - `Export-CliXml` 的便利之处在于它存储一个 `PSCredential` 对象而不仅仅是一个 `SecureString`。但它不支持 AES。 (2认同)