Skip to content

Instantly share code, notes, and snippets.

@cimnine
Last active May 5, 2016 06:55
Show Gist options
  • Save cimnine/5472913 to your computer and use it in GitHub Desktop.
Save cimnine/5472913 to your computer and use it in GitHub Desktop.

Adding a Certificate to a Key Store

// This method adds a certificate with the specified alias to the specified keystore file.
public static void addToKeyStore(File keystoreFile, char[] keystorePassword,
  String alias, java.security.cert.Certificate cert) {
    try {
        // Create an empty keystore object
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());

        // Load the keystore contents
        FileInputStream in = new FileInputStream(keystoreFile);
        keystore.load(in, keystorePassword);
        in.close();

        // Add the certificate
        keystore.setCertificateEntry(alias, cert);

        // Save the new keystore contents
        FileOutputStream out = new FileOutputStream(keystoreFile);
        keystore.store(out, keystorePassword);
        out.close();
    } catch (java.security.cert.CertificateException e) {
    } catch (NoSuchAlgorithmException e) {
    } catch (FileNotFoundException e) {
        // Keystore does not exist
    } catch (KeyStoreException e) {
    } catch (IOException e) {
    }
}

Retrieving the Certification Path of an SSL Server

This example implements a client that connects to an SSL server and retrieves the server's certificates.

try {
    // Create the client socket
    int port = 443;
    String hostname = "hostname";
    SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory();
    SSLSocket socket = (SSLSocket)factory.createSocket(hostname, port);

    // Connect to the server
    socket.startHandshake();

    // Retrieve the server's certificate chain
    java.security.cert.Certificate[] serverCerts =
        socket.getSession().getPeerCertificates();

    // Close the socket
    socket.close();
} catch (SSLPeerUnverifiedException e) {
} catch (IOException e) {
} catch (java.security.cert.CertificateEncodingException e) {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment