3

Want to create a CSR file in java, when the private/public key pair are getting generated in HSM(Hardware Security Module).

On trying out the examples in Bouncy Castle, the generation of CSR requires both the private key and public key.As the generation of keys is happening in HSM, i have only the public key and the private key sham object. Can i generate CSR in java without having the private key?

Please find the code sample i was trying.

 KeyPair pair = generateKeyPair();
    PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(
        new X500Principal("CN=Requested Test Certificate"), pair.getPublic());
    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
    ContentSigner signer = csBuilder.build(pair.getPrivate());
    PKCS10CertificationRequest csr = p10Builder.build(signer);

I am pretty new to HSM, and any input or reference will be helpful.

Manu
  • 1,379
  • 6
  • 24
  • 53

1 Answers1

3

You can generate a CSR without having the value of the private key. You do need a reference to the private key, and the key must be capable of signing. References to private keys are just special versions of classes that implement PrivateKey. They don't contain the data, just the reference. Calling getEncoded or retrieving a private exponent of an RSA key will however (usually - it may depend on the key generation parameters and PKCS#11 middleware) fail with an exception.

The way these keys can be used is by just providing them to an init method of a newly generated Signature instance. The Java runtime will then search for the right SignatureSpi implementation in the right provider (the one for your HSM). This is called delayed provider selection as it only searches for an implementation after the init method is called. Of course in your case this will all happen out of sight by the ContentSigner.

The private key data should not leave your HSM at any time, unless wrapped for backup or sharing between HSM's.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
  • thanks Maarten for response. you said that "You do need a reference to the private key, and the key must be capable of signing. References to private keys are just special versions of classes that implement PrivateKey" can you explain that how to implement in java? – mehrdad eilbeygi Jun 12 '23 at 05:26