Windows 上的 PowerShell : "Windows Data Protection API (DPAPI) is not supported on this platform."

标签 powershell

我需要在 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/

相关文章:

powershell - 使用Powershell从纯文本文件中提取表

powershell - powershell控制台:从键盘快捷方式调用命令的任何方式?

powershell - 如何删除Powershell中的第一行和最后一行

powershell - 将控制台输出写入文件 - 文件意外为空

xml - Powershell 编辑 Xml 导致 Visual Studio 报告行尾不一致

powershell - 获取 ADComputer 和 MemberOf

powershell - 如何阻止 PowerShell SqlCommand 回显参数

powershell - 基本循环帮助 - Powershell

powershell - 修剪角色右侧

c# - "Cannot Invoke this function because the current host does not implement it"