Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save RevenueGitHubAdmin/2e149d08dc79f496ee552c605eb08fe2 to your computer and use it in GitHub Desktop.
Save RevenueGitHubAdmin/2e149d08dc79f496ee552c605eb08fe2 to your computer and use it in GitHub Desktop.
[Java] How to retrieve the certificate and the private key from the KeyStore.
/*
* The following snippet retrieves, from an already loaded keystore, the certificate and the
* private key used to sign the requests. It takes as assumption that the keystore contains
* only one certificate.
*
* Gists provided for illustrative purposes only. Developers can use these as a support tool
* but the Office of the Revenue Commissioners (Revenue) does not provide any warranty with
* these gists.
*/
public void getCertificateAndKeyFromKeyStore(KeyStore keyStore, String encodedPassword) throws KeyStoreException, UnrecoverableEntryException, NoSuchAlgorithmException {
// Retrieving the certificate.
String certificateAlias = keyStore.aliases().nextElement();
X509Certificate certificate = (X509Certificate)keyStore.getCertificate(certificateAlias);
// Retrieving the private key.
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(
certificateAlias,
new KeyStore.PasswordProtection(encodedPassword.toCharArray())
);
PrivateKey privateKey = privateKeyEntry.getPrivateKey();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment