0
X509Certificate2 _HsmserverCertificate = null;

string pkcs11LibraryPath = "C:\\Program Files (x86)\\nCipher\\nfast\\toolkits\\pkcs11\\cknfast-64.dll";

Pkcs11InteropFactories factories = new Pkcs11InteropFactories();

using (IPkcs11Library pkcs11Library = factories.Pkcs11LibraryFactory.LoadPkcs11Library(factories, pkcs11LibraryPath, AppType.MultiThreaded))
{
    ISlot slot = HelpersMethods.GetUsableSlot(pkcs11Library);

    using (Net.Pkcs11Interop.HighLevelAPI.ISession session = slot.OpenSession(SessionType.ReadWrite))
    {
        session.Login(CKU.CKU_USER, @"1234");

        CngKey cngKey;

        cngKey = CngKey.Open("mykeyname");

        RSACng rsaKey = new RSACng(cngKey)
        {
            KeySize = 2048
        };

        RSAParameters pub = rsaKey.ExportParameters(false);
        RSAParameters prv = rsaKey.ExportParameters(true);

        RSACng rsaPrv = new RSACng();
        rsaPrv.ImportParameters(prv);

        RSACng rsaPub = new RSACng();
        rsaPub.ImportParameters(pub);
        
        //get certificate from HSM
        var certificate = ReadCertificates(slot, session)[0];

        _HsmserverCertificate = new X509Certificate2(certificate.CkaValue, "1234", X509KeyStorageFlags.Exportable);

        // In this line I get error:
        // The provided key does not match the public key for this
        // certificate. Parameter name: privateKey'
        X509Certificate2 certWithKey = _HsmserverCertificate.CopyWithPrivateKey(rsaPrv);
        
        session.Logout();
    }
}
Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
TBT
  • 55
  • 1
  • 1
  • 4
  • Well? Seems like a clear error message. You just get the list of certs and then get the first one, and hope for the best? But please first explain what you are trying to do. You are using CNG and PKCS#11 at the same time, and then use an X509Certificate2 constructor that assumes PKCS#12 key store. You've lost me. By the way: always check the format of your question and indicate a programming environment. – Maarten Bodewes Nov 01 '22 at 20:58
  • Thanks. Actually my certificate is located in HSM and also in the certificate I dont have private key. My private key is exists in HSM too which is not extractable. I need this certificate for AuthenticateAsServer which should have privatekey in it. In order to get private key I have used CNG. I have used pkcs11 to get my certificate from HSM and tried to add private key to it. I am newbie to this subject and exactly dont know what should I do. Please help me if you know anything thanks. – TBT Nov 02 '22 at 02:19
  • Don't set the `KeySize` property when opening an existing key. If you set it to the size of the existing key it has no effect, and if you set it to some other value then the object forgets the existing key and generates a random one of the correct size. So that line is either redundant, or the source of your key mismatch exception. – bartonjs Nov 28 '22 at 17:09

0 Answers0