'How to store only public key in keystore using java code with corresponding alias?
I had created keystore ,i want to store only publickey in keystore , and don't want to store private key.because private key will be in client device and he will share public key using rest API.
Also how should i keep multiple public key in one keystore.with different aliases
If some one has sample code,or sample link it will be great helpful for me.
Solution 1:[1]
It can't be done, at least not in the format of a raw java.security.PublicKey. You can only store 3 types of entries in a JKS keystore: PrivateKeyEntry (for asymmetrical private keys), SecretKey (for symmetrical secret keys) and TrustedCertificateEntry (for "public" keys). They all implement the java.security.KeyStore.Entry interface.
The bottom line is: you need to associate your public key with a certificate, which you can create, and then store the certificate in the keystore as a separate entry.
Creating certificates is a bit tricky, but an example can be found here: Creating an X509 Certificate in Java without BouncyCastle?
Solution 2:[2]
This may be closer to what you are looking for to call a REST web service with SSL taken from here Importing PEM certificate into Java KeyStore programmatically :
private static SSLContext createSSLContext(String certString) throws IOException {
try {
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
ByteArrayInputStream inStream = new ByteArrayInputStream(certString.getBytes(StandardCharsets.UTF_8));
X509Certificate cert = (X509Certificate) certFactory.generateCertificate(inStream);
KeyStore store = KeyStore.getInstance("JKS");
store.load(null);
store.setCertificateEntry("certificate", cert);
SSLContext sslContext = SSLContexts.custom()
.loadKeyMaterial(store, "".toCharArray())
.build();
return sslContext;
} catch (IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException |
KeyManagementException | UnrecoverableKeyException e) {
throw new IOException(e);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
| Solution 2 | Randy |
