Java examples for Security:Key
get Public Key from file
//package com.java2s; import java.io.FileInputStream; import java.security.KeyStore; import java.security.PublicKey; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; public class Main { public static void main(String[] argv) throws Exception { String certificatePath = "java2s.com"; System.out.println(getPublicKey(certificatePath)); }/*w w w. j a v a2s. co m*/ public static final String KEY_STORE = "JKS"; public static final String X509 = "X.509"; private static PublicKey getPublicKey(String certificatePath) throws Exception { Certificate certificate = getCertificate(certificatePath); PublicKey publicKey = certificate.getPublicKey(); return publicKey; } private static Certificate getCertificate(String certificatePath) throws Exception { CertificateFactory certificateFactory = CertificateFactory .getInstance(X509); FileInputStream in = new FileInputStream(certificatePath); Certificate certificate = certificateFactory .generateCertificate(in); in.close(); return certificate; } private static Certificate getCertificate(String keyStorePath, String alias, String password) throws Exception { KeyStore keyStore = getKeyStore(keyStorePath, password); Certificate certificate = keyStore.getCertificate(alias); return certificate; } private static KeyStore getKeyStore(String keyStorePath, String password) throws Exception { FileInputStream in = new FileInputStream(keyStorePath); KeyStore keyStore = KeyStore.getInstance(KEY_STORE); keyStore.load(in, password.toCharArray()); in.close(); return keyStore; } }