开发者

How to read public key from PFX file in java

开发者 https://www.devze.com 2023-01-31 23:34 出处:网络
I am able to read private key from PFX file but not public key. I am using following code to read public key.

I am able to read private key from PFX file but not public key. I am using following code to read public key.

InputStream inStream = new FileInputStream(certFile); 
CertificateFactory cf = CertificateFactory.getInstance("X.509"); 
BufferedInputStream bis = new BufferedInputStream(inStream);
// if (bis.available() > 0) {
java.security.cert.Ce开发者_如何学Pythonrtificate cert = cf.generateCertificate(bis);
System.out.println("This part is not getting printed in case of PFX file");
// }
puk = (PublicKey) cert.getPublicKey();

This code is working properly when i read from .cer file. Please help


Use the KeyStore class and treat the file as a PKCS#12 KeyStore. Use KeyStore.getInstance("PKCS12") to get an instance of a PKCS12 keystore.

The Javadocs for KeyStore contain sample code.


Use the following code snippet to get Public and Private Keys of the Certificate, with extensions like *.jks, *.p12, *.pfx:

public static HashMap<String, Object> getCertKeys(InputStream cerFileStream, String password) throws Exception {
    HashMap<String, Object> keyPair = new HashMap<String, Object>();
    
    KeyStore keyStore = KeyStore.getInstance("PKCS12"); //, "BC");
    keyStore.load(cerFileStream, password.toCharArray());
    
    Enumeration<String> keyStoreAliasEnum = keyStore.aliases();
    String alias = null;
    while ( keyStoreAliasEnum.hasMoreElements() ) {
        alias = keyStoreAliasEnum.nextElement();
        if (password != null) {
            PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());
            
            X509Certificate x509Certificate = (X509Certificate) keyStore.getCertificate(alias);
            PublicKey publicKey = x509Certificate.getPublicKey();
            
            keyPair.put("Alias", alias);
            keyPair.put("PublicKey", publicKey);
            keyPair.put("PrivateKey", privateKey);
            keyPair.put("X509Certificate", x509Certificate);
        }
    }
    return keyPair;
}

Use the following code snippet to read Public Key from the *.cer file. Keytool Export Certificate formats X.509[.cer], PKCS#7[.p7b], PKI PAth[.pkipath], SPC[.spc]

public static X509Certificate loadPublicKeyX509(InputStream cerFileStream) throws CertificateException, NoSuchProviderException {
    CertificateFactory  certificateFactory = CertificateFactory.getInstance("X.509", "BC");
    X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(cerFileStream);
    return x509Certificate;
}

Full Example with Test Certificates: Baeldung.cer, Baeldung.p12

public class CertificaeKeys {
    static {
        addBCProvider();
    }
    
    public static void main(String[] args) throws Exception {
        
        String CertWithKeyPair = "C:/Yash/SOAP/Baeldung.p12", certPassword = "password";
        String CertWithKey = "C:/Yash/SOAP/Baeldung.cer";
        
        File securityFileKeyPair = new File(CertWithKeyPair);
        File securityFileKey = new File(CertWithKey);
        
        InputStream cerFileStream = new FileInputStream(securityFileKey);
        X509Certificate loadPublicKeyX509 = loadPublicKeyX509(cerFileStream);
        PublicKey publicKeyCert = loadPublicKeyX509.getPublicKey();
        System.out.println("LoadPublicKey : "+ publicKeyCert);
        
        InputStream pkcs_FileStream = new FileInputStream(securityFileKeyPair);
        HashMap<String, Object> keyPair = getCertKeys(pkcs_FileStream, certPassword);
        
        String alias = (String) keyPair.get("Alias");
        PublicKey publicKey = (PublicKey) keyPair.get("PublicKey");
        PrivateKey privateKey = (PrivateKey) keyPair.get("PrivateKey");
        X509Certificate x509Certificate = (X509Certificate) keyPair.get("X509Certificate");
        
        System.out.println("alias: "     +alias);
        System.out.println("publicKey: " +publicKey);
        System.out.println("privateKey: "+privateKey);
        System.out.println("x509Certificate: "+x509Certificate);
        
        if (publicKeyCert.equals(publicKey)) {
            System.out.println("Both public key are equal.");
        }
        
    }
    
    public static X509Certificate loadPublicKeyX509(InputStream cerFileStream) throws CertificateException, NoSuchProviderException {
        CertificateFactory  certificateFactory = CertificateFactory.getInstance("X.509", "BC");
        X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(cerFileStream);
        return x509Certificate;
    }
    public static HashMap<String, Object> getCertKeys(InputStream cerFileStream, String password) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, NoSuchProviderException {
        HashMap<String, Object> keyPair = new HashMap<String, Object>();
        // ...
        return keyPair;
    }
    
    public static void addBCProvider() {
        // java.security.NoSuchProviderException: no such provider: BC
        if (Security.getProvider(org.bouncycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME) == null) {
            System.out.println("JVM Installing BouncyCastle Security Providers to the Runtime");
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        } else {
            System.out.println("JVM Installed with BouncyCastle Security Providers");
        }
        
        configure_JCE_UnlimitedStrength();
    }
    public static void configure_JCE_UnlimitedStrength() {
        System.out.println("Java Cryptography Extension Unlimited Strength Jurisdiction Policy Files");
        try {
            int maxKeySize = javax.crypto.Cipher.getMaxAllowedKeyLength("AES");
            System.out.println("Max Key Size for AES : " + maxKeySize); // Default-128
            if (maxKeySize == 128) { // For java versio less than 9
                System.out.println("Link: http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html");
                System.out.println("Download these jars(local_policy.jar,US_export_policy.jar) and replace in {JAVA_HOME}/lib/security.");
            }
            // For java 9 - Added Encryption policy(local or USExport).
            Security.setProperty("crypto.policy", "unlimited");
        } catch (java.security.NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
}


Security.addProvider(new BouncyCastleProvider()); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream("G:\certificate\pkcs7\src\main\resources\certificates\UTKS0000001_1092020T20308.pfx"),"12345678".toCharArray()); KEY_ALIAS_IN_KEYSTORE=keyStore.aliases().nextElement(); Certificate[] certchain = (Certificate[]) keystore.getCertificateChain(KEY_ALIAS_IN_KEYSTORE);

    final List<Certificate> certlist = new ArrayList<Certificate>();

    for (int i = 0, length = certchain == null ? 0 : certchain.length; i < length; i++) {
        certlist.add(certchain[i]);
    }

    Store certstore = new JcaCertStore(certlist);

    Certificate cert = keystore.getCertificate(KEY_ALIAS_IN_KEYSTORE);
    publicKey = cert.getPublicKey();
    System.out.println("*************************"+publicKey);
0

精彩评论

暂无评论...
验证码 换一张
取 消