PowerShell в Windows: «API защиты данных Windows (DPAPI) не поддерживается на этой платформе». - PullRequest
1 голос
/ 16 октября 2019

Мне нужно использовать API защиты данных в Windows, но 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?

1 Ответ

0 голосов
/ 16 октября 2019

Я понял это. Причина, по которой это не сработало в 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...