powershell

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


I need to use the Data Protection API on Windows, but PowerShell does not seem to be able to. When I run this script:

$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

I get this output:

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

When I create a console application and do the same thing in C#, it works perfectly. Why does it not work in PowerShell?

Edit: This does work on PowerShell Core. Why not on the classic PowerShell?


Solution

  • I figured it out. The reason this didn't work in PowerShell but in PowerShell Core was that I actually loaded the wrong assembly in PowerShell.

    As soon as I loaded the correct assembly for .net 4.6.1 it worked.

    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