get Public Key from path - Java Security

Java examples for Security:Key

Description

get Public Key from path

Demo Code


//package com.java2s;
import java.io.FileInputStream;
import java.io.IOException;

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 cerPath = "java2s.com";
        System.out.println(getPublicKey(cerPath));
    }/*  w w w.j  a v a 2s.c o m*/

    public static final String KEY_STORE = "JKS";
    public static final String X509 = "X.509";

    public static PublicKey getPublicKey(String cerPath) {
        Certificate cer = getCertificate(cerPath);
        return cer.getPublicKey();
    }

    public static PublicKey getPublicKey(String keyStorePath, String alias,
            String passwd) {
        try {
            KeyStore ks = getKeyStore(keyStorePath, passwd);
            if (ks.containsAlias(alias)) {
                return ks.getCertificate(alias).getPublicKey();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Certificate getCertificate(String cerPath) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(cerPath);
            CertificateFactory factory = CertificateFactory
                    .getInstance(X509);
            return factory.generateCertificate(fis);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static Certificate getCertificate(String keyStorePath,
            String alias, String passwd) {
        try {
            KeyStore ks = getKeyStore(keyStorePath, passwd);
            if (ks.containsAlias(alias)) {
                return ks.getCertificate(alias);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static KeyStore getKeyStore(String keyStorePath, String passwd) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(keyStorePath);
            KeyStore ks = KeyStore.getInstance(KEY_STORE);
            ks.load(fis, passwd.toCharArray());
            return ks;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

Related Tutorials