我需要在 Windows 上使用数据保护 API,但 PowerShell 似乎无法使用。当我运行这个脚本时:
$scope = [System.Security.Cryptography.DataProtectionScope]::CurrentUser
$ciphertext = [System.Text.Encoding]::UTF8.GetBytes("hallo welt")
$protected = [System.Security.Cryptography.ProtectedData]::Protect($ciphertext, $null, $scope)
$unprotected = [System.Security.Cryptography.ProtectedData]::Unprotect($protected, $null, $scope)
$text = [System.Text.Encoding]::UTF8.GetString($unprotected)
Write-Output $text
我得到这个输出:
Exception calling "Protect" with "3" argument(s): "Windows Data Protection API (DPAPI) is not supported on this platform."
At line:3 char:1
+ $protected = [System.Security.Cryptography.ProtectedData]::Protect($c ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : PlatformNotSupportedException
当我创建一个控制台应用程序并在 C# 中做同样的事情时,它工作得很好。为什么它在 PowerShell 中不起作用?
编辑: 这确实适用于 PowerShell Core。为什么不使用经典的 PowerShell?
最佳答案
我想通了。这在 PowerShell 中不起作用但在 PowerShell Core 中不起作用的原因是我实际上在 PowerShell 中加载了错误的程序集。
一旦我为 .net 4.6.1 加载了正确的程序集,它就开始工作了。
Add-Type -Path "D:\_packages\System.Security.Cryptography.ProtectedData.4.6.0\lib\net461\System.Security.Cryptography.ProtectedData.dll"
$scope = [System.Security.Cryptography.DataProtectionScope]::CurrentUser
$ciphertext = [System.Text.Encoding]::UTF8.GetBytes("hallo welt")
$protected = [System.Security.Cryptography.ProtectedData]::Protect($ciphertext, $null, $scope)
$unprotected = [System.Security.Cryptography.ProtectedData]::Unprotect($protected, $null, $scope)
$text = [System.Text.Encoding]::UTF8.GetString($unprotected)
Write-Output $text
关于Windows 上的 PowerShell : "Windows Data Protection API (DPAPI) is not supported on this platform.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58411318/