I’ve created a simple c# Powershell cmdlet project to replicate my issue. The cmdlet uses System.Security.Cryptography.ProtectedData.Protect()
. When running in Xunit, the cmdlet runs successfully, but when importing the module in pwsh console the System.Security.Cryptography.ProtectedData
assembly cannot be found.
Import-Module .TestProtectedDataPowershell.dll
Test-ProtectData -NotSecret "some text here"
Throws exception
Exception :
Type : System.IO.FileNotFoundException
Message : Could not load file or assembly 'System.Security.Cryptography.ProtectedData, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.
FileName : System.Security.Cryptography.ProtectedData, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
TargetSite :
Name : Protect
DeclaringType : [TestProtectedDataPowershell.DataProtectionUsingDPAPI]
MemberType : Method
Module : TestProtectedDataPowershell.dll
Source : TestProtectedDataPowershell
HResult : -2147024894
StackTrace :
at TestProtectedDataPowershell.DataProtectionUsingDPAPI.Protect(String unencryptedString)
at TestProtectedDataPowershell.TestProtectDataCmdlet.BeginProcessing() in c:tempTestProtectedDataTestProtectedDataTestProtectedDataPowershellTestProtectDataCmdlet.cs:line 19
at System.Management.Automation.Cmdlet.DoBeginProcessing()
at System.Management.Automation.CommandProcessorBase.DoBegin()
CategoryInfo : NotSpecified: (:) [Test-ProtectData], FileNotFoundException
FullyQualifiedErrorId : System.IO.FileNotFoundException,TestProtectedDataPowershell.TestProtectDataCmdlet
InvocationInfo :
MyCommand : Test-ProtectData
ScriptLineNumber : 1
OffsetInLine : 1
HistoryId : 10
Line : Test-ProtectData -NotSecret "some text here"
Statement : Test-ProtectData -NotSecret "some text here"
PositionMessage : At line:1 char:1
+ Test-ProtectData -NotSecret "some text here"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
InvocationName : Test-ProtectData
CommandOrigin : Internal
ScriptStackTrace : at <ScriptBlock>, <No file>: line 1
However in Xunit tests the cmdlet works as expected. The below unit test works
[Fact]
public void TestProtectDataCmdlet()
{
// Create a runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
// Set the execution policy within the runspace
//runspace.SessionStateProxy.SetVariable("ExecutionPolicy", ExecutionPolicy.Unrestricted);
using (PowerShell powershell = PowerShell.Create())
{
powershell.Runspace = runspace;
// Import module
powershell.AddScript(@"Import-Module 'C:tempTestProtectedDataTestProtectedDataTestProtectedDataPowershellbinDebugnet8.0TestProtectedDataPowershell.dll'");
powershell.Invoke();
// Execute cmdlet
powershell.AddCommand("Test-ProtectData").AddParameter("NotSecret", "My not yet secret text");
var results = powershell.Invoke();
foreach (var item in results)
{
Debug.Print(item.ToString());
}
Assert.NotEmpty(results);
}
runspace.Close();
runspace.Dispose();
}
I’ve verified that Xunit is using Powershell version 7.4.6 which is the same version that I’m running in console.
Questions:
- Why does it work in one and not the other?
- How can I get it to work in console? Do I need a psd1 file and to specify in it that System.Security.Crptography.ProtectedData is required? I’ve seen conflicting information saying that as long as it is referenced in my project (the required ProtectedData nuget package is installed), that a manifest specifying anything additional for this is not needed.
I’ve also tried including System.Security.Cryptography.ProtectedData.dll in the output directory along side my own dll but this also does not work. I’ve done with with other modules like Oracle.ManagedDataAccess.dll which has worked.
I don’t think it has anything to do with the cmdlet code but here is the sample code just in case:
using System.Management.Automation;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Text;
namespace TestProtectedDataPowershell
{
[SupportedOSPlatform("windows")]
[Cmdlet(VerbsDiagnostic.Test, "ProtectData")]
public class TestProtectDataCmdlet : PSCmdlet
{
[Parameter(Position = 0, Mandatory = true)]
public string NotSecret { get; set; }
protected override void BeginProcessing()
{
if (NotSecret != null)
WriteObject(DataProtectionUsingDPAPI.Protect(NotSecret));
}
}
[SupportedOSPlatform("windows")]
[Cmdlet(VerbsDiagnostic.Test, "UnprotectData")]
public class TestUnprotectDataCmdlet : PSCmdlet
{
[Parameter(Position = 0, Mandatory = true)]
public string Secret { get; set; }
protected override void BeginProcessing()
{
if (Secret != null)
WriteObject(DataProtectionUsingDPAPI.Unprotect(Secret));
}
}
[SupportedOSPlatform("windows")]
public static class DataProtectionUsingDPAPI
{
private static readonly byte[] _additionalEntropy = { 99, 208, 37, 234, 65, 88, 45, 33, 66, 23, 88, 23, 45, 192 };
public static string Protect(string unencryptedString)
{
try
{
// Encrypt the data using DataProtectionScope.CurrentUser.
// The result can be decrypted only by the same current user.
var unencryptedBytes = Encoding.UTF8.GetBytes(unencryptedString);
var encryptedBytes = System.Security.Cryptography.ProtectedData.Protect(unencryptedBytes, _additionalEntropy, DataProtectionScope.CurrentUser);
return Convert.ToBase64String(encryptedBytes);
}
catch (CryptographicException e)
{
Console.WriteLine("Data was not encrypted. An error occurred.");
Console.WriteLine(e.ToString());
throw;
}
}
public static string Unprotect(string encryptedString)
{
try
{
// Decrypt the data using DataProtectionScope.CurrentUser.
var encryptedBytes = Convert.FromBase64String(encryptedString);
var decryptedBytes = ProtectedData.Unprotect(encryptedBytes, _additionalEntropy, DataProtectionScope.CurrentUser);
return Encoding.UTF8.GetString(decryptedBytes);
}
catch (CryptographicException e)
{
Console.WriteLine("Data was not decrypted. An error occurred.");
Console.WriteLine(e.ToString());
throw;
}
}
}
}
Also, I should mention that I’m targeting net8.0
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Management.Automation" Version="7.4.6" />
<PackageReference Include="System.Security.Cryptography.ProtectedData" Version="9.0.0" />
</ItemGroup>
</Project>
Strangely, direct usage of [System.Security.Cryptography.ProtectedData]
works perfectly fine in pwsh so maybe there is a conflict between the assembly my project wants to use and the one that Powershell is using in console?
$unecrpytedText = "Some text I want to encrypt"
$unencrytedBytes = [System.Text.Encoding]::UTF8.GetBytes($unecrpytedText)
$currentUser = [System.Security.Cryptography.DataProtectionScope]::CurrentUser
$encryptedBytes = [System.Security.Cryptography.ProtectedData]::Protect($unencrytedBytes, $null, $currentUser)
$decryptedBytes = [System.Security.Cryptography.ProtectedData]::Unprotect($encryptedBytes, $null, $currentUser)
$result = [System.Text.Encoding]::UTF8.GetString($decryptedBytes)
$result
Some text I want to encrypt
After lots of swapping of versions, building, rebuilding, publishing and testing I finally found a working solution in both Powershell 5.1 and 7.4
So first, to target and test PS5.1 I changed framework to netstandard2.0 (I decided that I wanted the cmdlet to work there as well)
I then published the solution which compiled it including the needed assemblies which also included System.Security.Cryptography.ProtectedData.dll Using v9.0 of ProtectedData worked with PS5.1 but would not work with PS7
I found that PS7 is using v8.0 so not sure if that has something to do with it not working
[System.Security.Cryptography.ProtectedData] | select Assembly
Assembly
--------
System.Security.Cryptography.ProtectedData, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
Updating the project to use version 8.0 System.Security.Cryptography.ProtectedData, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
is working with both 5.1 and 7.4
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="PowerShellStandard.Library" Version="5.1.1" />
<PackageReference Include="System.Security.Cryptography.ProtectedData" Version="8.0.0" />
</ItemGroup>
</Project>
1