Reputation: 21
Using Java API, I am trying to access Public key stored in Luna HSM. Even though I am able to print the corresponding public key label name, but when I am trying to get the public key, I am not able to get the reference to that public key. Here is the code snippet:
KeyStore ks = KeyStore.getInstance("Luna");
ks.load(null, null);
lunaProvider = ks.getProvider();
publicKey = (PublicKey) ks.getKey(alipayImpl.getHsmKeyStorePublicEntryName(), null);
// ****************************************************************************
// ** If the private keystore is not found, return original barcode string. **
// ****************************************************************************
if (publicKey == null) {
throw new Exception("Unable to acquire the Public Key " + alipayImpl.getHsmKeyStorePublicEntryName() + ", Hash will not be verified.");
}
// ***********************************************************
// ** Create a Signature Object and sign the encrypted text **
// ***********************************************************
Signature signatureObject = Signature.getInstance(alipayImpl.getAlipaySignAlgorithm(), lunaProvider);
signatureObject.initVerify(publicKey);
signatureObject.update(signedMessage
.getBytes(AlipayConstants.INPUT_CHARSET_VALUE));
isValidSign = signatureObject.verify(Base64.decode(hash));
I am logging to HSM properly. While Accessing Private Key, I didnt have any issues. Is there any restriction on Luna HSM that access to public key is given only through Certificates?
Thanks in advance.
Upvotes: 2
Views: 2900
Reputation: 86
In Java keystore there is no PublicKeyEntry and that's the reason why you're not able to access your public key.
https://docs.oracle.com/javase/8/docs/api/java/security/KeyStore.Entry.html
Java's KeyStore.KeyEntry interface has three implementing classes.
Java expects you to get retrieve a public key out of your certificate. Sebastien Vanmechelen has given you the perfect example on how to do that.
If by any chance, your Luna HSM partition does not have a X509 certificate then using LunaKey is the only alternative.
Upvotes: 0
Reputation: 51
The correct answer is >
LunaKey lk= LunaKey.LocateKeyByAlias("publicKeyName");
But it is advisable to make the key persistent before querying HSM.
Upvotes: 1
Reputation: 574
Did you try something like this :
final KeyStore keyStore = KeyStore.getInstance("Luna");
keyStore.load(null, null);
final Certificate certificate = keyStore.getCertificate(alias);
if (certificate == null) {
throw new IllegalArgumentException(String.format("Certificate '%s' does not exists", alias));
}
final PublicKey publicKey = certificate.getPublicKey();
// TODO Working with the public key...
Upvotes: 0