Receiving error when trying to use System.Security.Cryptography.ProtectedData in a C# Powershell Cmdlet Module

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:

  1. Why does it work in one and not the other?
  2. 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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

Receiving error when trying to use System.Security.Cryptography.ProtectedData in a C# Powershell Cmdlet Module

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:

  1. Why does it work in one and not the other?
  2. 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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

Receiving error when trying to use System.Security.Cryptography.ProtectedData in a C# Powershell Cmdlet Module

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:

  1. Why does it work in one and not the other?
  2. 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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật