Skip to content

Instantly share code, notes, and snippets.

@luismoramedina
Created January 30, 2017 10:11
Show Gist options
  • Save luismoramedina/735617e06fa1e59cdc3fb4b6830c0a2d to your computer and use it in GitHub Desktop.
Save luismoramedina/735617e06fa1e59cdc3fb4b6830c0a2d to your computer and use it in GitHub Desktop.
Extract public key from x509 certificate
String cer = "/home/luis/Downloads/APImIntranet.cer";
FileInputStream fileInputStream = new FileInputStream(cer);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate)cf.generateCertificate(fileInputStream);
PublicKey publicKey = cert.getPublicKey();
byte[] encoded = publicKey.getEncoded();
byte[] b64key = Base64.getEncoder().encode(encoded);
System.out.println("b64key = " + new String(b64key));
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(encoded);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey key = keyFactory.generatePublic(x509EncodedKeySpec);
System.out.println("x509EncodedKeySpec = " + new String(key.getEncoded()));
@thecoder8890
Copy link

Can you please provide the complete class?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment