【问题标题】:Converting SecureString stored in text file back to readable string将存储在文本文件中的 SecureString 转换回可读字符串
【发布时间】:2018-09-01 09:23:47
【问题描述】:

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

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

$SecurePassword = Read-Host -Prompt "Enter password" -AsSecureString
$SecurePassword | ConvertFrom-SecureString > C:\TEMP\TEST_Secure.txt

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

$SecurePasswordPath = "C:\TEMP\TEST_Secure.txt"
$EncryptionKey = cat $SecurePasswordPath | ConvertTo-SecureString

Veeam 备份脚本实际上是这样读取的:

$EncryptionKey = Add-VBREncryptionKey -Password (cat $SecurePasswordPath | ConvertTo-SecureString)

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

$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)

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

我也试过比较推荐的方法:

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

这些中的每一个都不会真正返回任何内容。

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

在这里绝望!任何帮助将不胜感激!

【问题讨论】:

  • SecureString 最初是在您尝试解密它的同一台计算机上加密的吗?
  • 是的。同一台机器。
  • 和同一个用户帐号?
  • 最初可能使用了不同的用户帐户。我的问题是,我可以逐步完成上述步骤,但仍然无法产生所需的输出。因此,我可以在同一台机器、同一用户上重新创建一个新的 SecureString 文本文件,并运行这两种方法来尝试检索密码,但它仍然失败,结果相同。这就是为什么我质疑我是否正确设置它。
  • ConvertTo-SecureString 仅适用于使用 DPAPI 的同一台计算机和同一用户帐户(即,没有 -Key-SecureKey 参数)。

标签: .net string powershell security securestring


【解决方案1】:

以下是提示输入SecureString 并将其作为加密标准字符串写入文本文件的方法:

Read-Host "Enter password" -AsSecureString | 
  ConvertFrom-SecureString |
  Out-File "D:\Path\EncryptedStandardString.txt"

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

$secureString = Get-Content "D:\Path\EncryptedStandardString.txt" |
  ConvertTo-SecureString

如果您想使用 AES 而不是 DPAPI,您还需要为 ConvertFrom-SecureStringConvertTo-SecureString cmdlet 提供 -Key-SecureKey 参数。

如果要将SecureString解密为String对象,可以使用以下函数:

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

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

【讨论】:

  • 这与使用Export-CliXml 有显着不同吗?Export-CliXml 使用 DPAPI 将凭据存储在磁盘上,但无需执行任何 ConvertTo 或 ConvertFrom?
  • @TessellatingHeckler - 不 - Export-CliXml 的便利之处在于它存储了一个 PSCredential 对象,而不仅仅是一个 SecureString。但是它不支持 AES。
猜你喜欢
  • 2021-09-15
  • 2015-06-30
  • 1970-01-01
  • 2013-04-08
  • 1970-01-01
  • 2014-03-25
  • 2023-03-07
  • 2014-03-30
  • 1970-01-01
相关资源
最近更新 更多