【问题标题】:PowerShell on Windows: "Windows Data Protection API (DPAPI) is not supported on this platform."Windows 上的 PowerShell:“此平台不支持 Windows 数据保护 API (DPAPI)。”
【发布时间】:2019-10-16 10:37:13
【问题描述】:

我需要在 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 Core 吗?
  • 这适用于我在 Windows 10(64 位和 32 位版本)上的 PowerShell 5.1 以及 ISE 中。事实上,很难想象这会如何失败,因为它调用了非托管代码。 [System.Reflection.Assembly]::LoadWithPartialName("System.Security") 是否生成正确的程序集?
  • 对我也很好。经典 PowerShell 5.1
  • 什么 Windows 版本?
  • 绝对支持我的平台和我的 Windows 版本,因为如果我在 .net 核心或 .net 框架控制台应用程序中使用 DPAPI,这将非常有效。我认为它以某种方式弄错了组件。

标签: powershell


【解决方案1】:

我想通了。这在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-14
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2016-06-20
    相关资源
    最近更新 更多