There are several objects in the softhsm as bellow.
$ sudo pkcs11-tool --module /usr/lib/softhsm/libsofthsm2.so --list-objects -l
Using slot 0 with a present token (0x74a6136e)
Logging in to "token-label".
Please enter User PIN:
Private Key Object; RSA
label: foo
ID: 1001
Usage: decrypt, sign, signRecover, unwrap
Access: sensitive, always sensitive, never extractable, local
Public Key Object; RSA 2048 bits
label: foo
ID: 1001
Usage: encrypt, verify, verifyRecover, wrap
Access: local
Private Key Object; EC
label: key-label
ID: 1001
Usage: decrypt, sign, signRecover, unwrap, derive
Access: sensitive, always sensitive, never extractable, local
Private Key Object; RSA
label: test
ID: 01
Usage: decrypt, sign, signRecover, unwrap
Access: sensitive, always sensitive, never extractable, local
Public Key Object; EC EC_POINT 256 bits
EC_POINT: 044104677475aed10d3447f451513be316e97a12089c2c8fbb0b9a2f6baaaee341781b2dcf695d84e1b74452f194d97d904b1c5a92750764aaba08c59ebe7f8f189f74
EC_PARAMS: 06082a8648ce3d030107 (OID 1.2.840.10045.3.1.7)
label: key-label
ID: 1001
Usage: encrypt, verify, verifyRecover, wrap, derive
Access: local
Public Key Object; RSA 2048 bits
label: test
ID: 01
Usage: encrypt, verify, verifyRecover, wrap
Access: local
However when I tried to create a CSR and sign it with the key in softhsm2, it cannot load the private key
$ OPENSSL_CONF=engine.conf sudo openssl req -new -subj '/CN=test/' -sha256 -engine pkcs11 -keyform engine -key 01 > my-request.csr
Engine "pkcs11" set.
Failed to enumerate slots
PKCS11_get_private_key returned NULL
Could not read private key from org.openssl.engine:pkcs11:01
40772E3E8E7F0000:error:40000067:pkcs11 engine:ERR_ENG_error:invalid parameter:eng_back.c:603:
40772E3E8E7F0000:error:13000080:engine routines:ENGINE_load_private_key:failed loading private key:../crypto/engine/eng_pkey.c:79:
I have updated the pkcs11 path but everything else is the same, running the commands by hand it works to register the engine but attempting to sign fails.
Solution:
With the -key
instead of using keyid 01, the input should adhere PKCS11 URI:
"pkcs11:model=SoftHSM%20v2;token=token-label;object=test;type=private"