I have a GO Application, that stores it's certificate to a HSM via opencryptoki (pkcs11) in a softwaretoken. But it's not a go question, more a general pkcs11 question I think.
I set my certificates and privatekey like this:
certTemplate := []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_CERTIFICATE),
pkcs11.NewAttribute(pkcs11.CKA_CERTIFICATE_TYPE, pkcs11.CKC_X_509),
pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),
pkcs11.NewAttribute(pkcs11.CKA_VALUE, certBytes),
pkcs11.NewAttribute(pkcs11.CKA_SUBJECT, template.SubjectKeyId),
pkcs11.NewAttribute(pkcs11.CKA_ID, pkcs11KeyID),
}
privateKeyTemplate := []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PRIVATE_KEY),
pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_ECDSA),
pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),
pkcs11.NewAttribute(pkcs11.CKA_ID, pkcs11KeyID),
pkcs11.NewAttribute(pkcs11.CKA_EC_PARAMS, []byte{0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07}),
pkcs11.NewAttribute(pkcs11.CKA_VALUE, ecdsaPrivKeyD),
}
ctx.CreateObject(session, certTemplate)
ctx.CreateObject(session, privateKeyTemplate)
This works perfectly. I can also get the Certificate via
findTemplate := []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),
pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_CERTIFICATE),
pkcs11.NewAttribute(pkcs11.CKA_CERTIFICATE_TYPE, pkcs11.CKC_X_509),
}
ctx.FindObjectsInit(session, findTemplate);
objs, b, err := ctx.FindObjects(session, numSlots)
But I cannot get my public key, as I expected
findTemplate := []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),
pkcs11.NewAttribute(pkcs11.CKA_ID, pkcs11KeyID),
pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PUBLIC_KEY),
}
ctx.FindObjectsInit(session, findTemplate);
obj, _, err := ctx.FindObjects(session, 1)
There is no error, just that there are no keys in the hsm store.
Although the public key is part of the certificate, the CKO_PUBLIC_KEY
object may not be separately available, and there isn't a CKA_PUBLIC
attribute either for certificates.
To get to the public key you'll have to retrieve the CKA_VALUE
of the certificate and parse it using your favorite X.509v3 certificate parser. The result will undoubtedly return either the encoded public key value or a public key as structure in your favorite runtime.
As you have already written in your question, you have created/imported only two persistent token objects - certificate object (CKA_CLASS = CKO_CERTIFICATE
) and private key object (CKA_CLASS = CKO_PRIVATE_KEY
) - so naturally you can find only these two objects by calling FindObjectsInit
and FindObjects
.
If you want to find also a public key object (CKA_CLASS = CKO_PUBLIC_KEY
) then you will need to create/import it first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With