BouncyHsm.Client 1.1.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package BouncyHsm.Client --version 1.1.0                
NuGet\Install-Package BouncyHsm.Client -Version 1.1.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="BouncyHsm.Client" Version="1.1.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add BouncyHsm.Client --version 1.1.0                
#r "nuget: BouncyHsm.Client, 1.1.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install BouncyHsm.Client as a Cake Addin
#addin nuget:?package=BouncyHsm.Client&version=1.1.0

// Install BouncyHsm.Client as a Cake Tool
#tool nuget:?package=BouncyHsm.Client&version=1.1.0                

BouncyHsm Client

A REST API client for BouncyHSM that allows you to manage BouncyHSM programmatically using code. This package is recommended for use in unit tests.

This package contains native PKCS#11 libraries for:

  • Windows x86
  • Windows x64
  • Linux x64 (for Debian based distributions)

this allows this nuget to be added to the BouncyHsm tests available on localhost to be used immediately.

See more https://github.com/harrison314/BouncyHsm.

Exanple unit test

A new empty slot and token is created in InitializerTest, it is deleted after the end of testing. In AesExampleTests, a new AES key is created via the REST API, then the data is encrypted and decrypted using the PKCS#11 library.

Test uses Pkcs11Interop library.

internal static class BchClient
{
    private static HttpClient httpClient = new HttpClient();

    private const string BouncyhsmEndpoint = "https://localhost:7007/";

    public static IBouncyHsmClient Client
    {
        get => new BouncyHsmClient(BouncyhsmEndpoint, httpClient);
    }
}

[TestClass]
public class InitializerTest
{
    public static int? SlotId
    {
        get;
        private set;
    }

    public static string P11LibPath
    {
        get
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                return "BouncyHsm.Pkcs11Lib.dll";
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                return "" + "./BouncyHsm.Pkcs11Lib-x64.so";
            }

            throw new PlatformNotSupportedException();
        }
    }

    public static string? TokenSerialNumber
    {
        get;
        private set;
    }

    public static string LoginPin
    {
        get;
        private set;
    } = default!;

    [AssemblyInitialize]
    public static async Task Initialize(TestContext testContext)
    {
        LoginPin = "123456";
        try
        {
            string runId = Guid.NewGuid().ToString();
            CreateSlotResultDto information = await BchClient.Client.CreateSlotAsync(new CreateSlotDto()
            {
                Description = $"Integration Test Slot - {runId}",
                IsHwDevice = true,
                Token = new CreateTokenDto()
                {
                    Label = $"IntegrationTestSlot-{runId}",
                    SerialNumber = null,
                    SimulateHwMechanism = true,
                    SimulateHwRng = true,
                    SimulateProtectedAuthPath = false,
                    SimulateQualifiedArea = false,
                    SpeedMode = SpeedMode.WithoutRestriction,
                    SignaturePin = null,
                    SoPin = "12345678",
                    UserPin = LoginPin
                }
            });

            SlotId = information.SlotId;
            TokenSerialNumber = information.TokenSerialNumber;
        }
        catch (Exception ex)
        {
            testContext.WriteLine(ex.ToString());
            throw;
        }
    }

    [AssemblyCleanup]
    public static async Task Cleanup()
    {
        if (SlotId.HasValue)
        {
            await BchClient.Client.DeleteSlotAsync(SlotId.Value);
        }
    }
}


[TestClass]
public class AesExampleTests
{
    [TestMethod]
    public async Task AesExample_Encrypt()
    {
        (string label, byte[] ckId) = await this.InitializeAesKey();

        byte[] plainText = new byte[16 * 8];
        Random.Shared.NextBytes(plainText);

        Pkcs11InteropFactories factories = new Pkcs11InteropFactories();
        using IPkcs11Library library = factories.Pkcs11LibraryFactory.LoadPkcs11Library(factories,
            InitializerTest.P11LibPath,
            AppType.SingleThreaded);

        List<ISlot> slots = library.GetSlotList(SlotsType.WithTokenPresent);
        ISlot slot = slots.First();

        using ISession session = slot.OpenSession(SessionType.ReadOnly);
        session.Login(CKU.CKU_USER, InitializerTest.LoginPin);


        List<IObjectAttribute> keyAttributes = new List<IObjectAttribute>()
        {
             session.Factories.ObjectAttributeFactory.Create(CKA.CKA_LABEL, label),
            session.Factories.ObjectAttributeFactory.Create(CKA.CKA_ID, ckId),
        };

        IObjectHandle key = session.FindAllObjects(keyAttributes).Single();

        byte[] iv = session.GenerateRandom(16);

        using IMechanism mechanism = session.Factories.MechanismFactory.Create(CKM.CKM_AES_CBC_PAD, iv);
        byte[] cipherText = session.Encrypt(mechanism, key, plainText);
        byte[] decrypted = session.Decrypt(mechanism, key, cipherText);

        Assert.AreEqual(Convert.ToHexString(plainText), Convert.ToHexString(decrypted));
    }

    private async Task<(string label, byte[] ckId)> InitializeAesKey()
    {
        string label = $"AES-{DateTime.UtcNow}-{Random.Shared.Next(100, 999)}";
        byte[] ckId = RandomNumberGenerator.GetBytes(32);

        _ = await BchClient.Client.GenerateAesKeyAsync(InitializerTest.SlotId!.Value, new GenerateAesKeyRequestDto()
        {
            Size = 32,
            KeyAttributes = new GenerateKeyAttributesDto()
            {
                CkaId = ckId,
                CkaLabel = label,
                Exportable = false,
                ForDerivation = false,
                ForEncryption = true,
                ForSigning = false,
                ForWrap = false,
                Senzitive = true
            }
        });

        return (label, ckId);
    }
}
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.2.0 28 12/17/2024
1.1.1 96 11/18/2024
1.1.0 102 10/21/2024
1.0.1 103 10/9/2024