3

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.

Mayur Shah
  • 1,009
  • 11
  • 16

2 Answers2

7

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?

Community
  • 1
  • 1
Daniel
  • 4,033
  • 4
  • 24
  • 33
0

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);
    }
}
Randy
  • 729
  • 5
  • 14