RSA讀取公鑰/私鑰

1、首先創建一個接口類IKeyReader

public interface IKeyReader {
    /**
     * 從keystore文件裏讀取公鑰
     * @param kstorefile keystore文件
     * @param kstoretype keystore文件類型,一般爲JKS 
     * @param kstorepwd keystore文件密碼
     * @param alias 密鑰別名
     * @return 公鑰
     */    
    public PublicKey getPublicKey(String kstorefile, String kstoretype, String kstorepwd, String alias);
    
    /**
     * 從keystore文件裏讀取私鑰
     * @param kstorefile keystore文件
     * @param kstoretype keystore文件類型,一般爲JKS 
     * @param kstorepwd keystore文件密碼
     * @param alias 密鑰別名
     * @param keypwd 密鑰密碼
     * @return 私鑰
     */
    public PrivateKey getPrivateKey(String kstorefile, String kstoretype, String kstorepwd, String alias,String keypwd);
    /**
     * 從DER編碼公鑰文件裏讀取公鑰
     * @param CRTfile DER編碼公鑰文件
     * @return 公鑰
     */
    public PublicKey getPublickey(String CRTfile);
    /**
     * 從DER編碼私鑰文件裏讀取私鑰
     * @param DERfile DER編碼私鑰文件
     * @return  私鑰
     */
    public PrivateKey getPrivatekey(String DERfile);
    /**
     * 從keystore文件裏讀取公鑰內容,以Base64編碼輸出
     * @param kstorefile keystore文件
     * @param kstoretype keystore文件類型,一般爲JKS 
     * @param kstorepwd keystore文件密碼
     * @param alias 密鑰別名
     * @return  公鑰內容(經Base64編碼)
     */
    public String getCert(String kstorefile, String kstoretype, String kstorepwd, String alias);


2、創建一個接口實現類

public class KeyReader implements IKeyReader {

    private static final Logger log = LoggerFactory.getLogger(KeyReader.class);

    public KeyReader() {
        log.info("構造函數=====555555555555555555555555555555555");
    }

    /**
     * 從密鑰文件中讀取公鑰
     *
     * @param kstorefile 密鑰文件
     * @param kstoretype 密鑰文件類型,例如:JKS
     * @param kstorepwd 密鑰文件訪問密碼
     * @param alias 別名
     * @return 公鑰
     */
    @Override
    public PublicKey getPublicKey(String kstorefile, String kstoretype, String kstorepwd, String alias) {

        try {
            KeyStore ks;
            try (FileInputStream in = new FileInputStream(kstorefile)) {
                ks = KeyStore.getInstance(kstoretype);
                ks.load(in, kstorepwd.toCharArray());
            }
            if (!ks.containsAlias(alias)) {
                log.warn("No such alias in the keystore.");
                return null;
            }
            Certificate cert = ks.getCertificate(alias);
            return cert.getPublicKey();
        } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException ex) {
            log.warn("getPublicKey failure.", ex);
            return null;
        } catch (FileNotFoundException ex) {
            log.warn("getPublicKey failure.", ex);
            return null;
        } catch (IOException ex) {
            log.warn("getPublicKey failure.", ex);
            return null;
        }
    }

    /**
     * 從密鑰文件中讀取私鑰
     *
     * @param kstorefile 密鑰文件
     * @param kstoretype 密鑰文件類型,例如:JKS
     * @param kstorepwd 密鑰文件訪問密碼
     * @param alias 別名
     * @return 私鑰
     */
    @Override
    public PrivateKey getPrivateKey(String kstorefile, String kstoretype, String kstorepwd, String alias, String keypwd) {
        try {
            KeyStore ks;
            try (FileInputStream in = new FileInputStream(kstorefile)) {
                ks = KeyStore.getInstance(kstoretype);
                ks.load(in, kstorepwd.toCharArray());
            }
            if (!ks.containsAlias(alias)) {
                log.warn("No such alias in the keystore.");
                return null;
            }
            return (PrivateKey) ks.getKey(alias, keypwd.toCharArray());
        } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException ex) {
            log.warn("getPrivateKey failure.", ex);
            return null;
        } catch (FileNotFoundException ex) {
            log.warn("getPrivateKey failure.", ex);
            return null;
        } catch (IOException ex) {
            log.warn("getPrivateKey failure.", ex);
            return null;
        }
    }

    @Override
    public String getCert(String kstorefile, String kstoretype, String kstorepwd, String alias) {
        try {
            KeyStore ks;
            try (FileInputStream in = new FileInputStream(kstorefile)) {
                ks = KeyStore.getInstance(kstoretype);
                ks.load(in, kstorepwd.toCharArray());
            }
            if (!ks.containsAlias(alias)) {
                log.warn("No such alias in the keystore.");
                return null;
            }
            X509Certificate cert = (X509Certificate) ks.getCertificate(alias);

            return Base64.encodeBase64String(cert.getEncoded());
        } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException ex) {
            log.warn("getPublicKey failure.", ex);
            return null;
        } catch (FileNotFoundException ex) {
            log.warn("getPublicKey failure.", ex);
            return null;
        } catch (IOException ex) {
            log.warn("getPublicKey failure.", ex);
            return null;
        }
    }

    @Override
    public PrivateKey getPrivatekey(String DERfile) {
        PrivateKey privateKey = null;
        try {
            InputStream in = null;
            byte[] key = new byte[2048];
            in = new FileInputStream(DERfile);
            in.read(key);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
            return privateKey;
        } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
            log.error("私鑰證書文件格式錯誤",ex);
        } catch (IOException ex) {
            log.error(ex.getMessage(),ex);
        } 
        return privateKey;
    }

    @Override
    public PublicKey getPublickey(String CRTfile) {
        try {
            CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
            FileInputStream bais = new FileInputStream(CRTfile);
            X509Certificate Cert = (X509Certificate) certificatefactory.generateCertificate(bais);
            return Cert.getPublicKey();
        } catch (CertificateException | FileNotFoundException ex) {
            log.warn("getPublicKey failure", ex);
        }
        return null;
    }

    private byte[] getPemFileBytes(String fileName) {
        BufferedReader br;
        byte[] key = null;
        try {
            br = new BufferedReader(new FileReader(fileName));
            String s = br.readLine();
            String str = "";
            s = br.readLine();
            while (s.charAt(0) != '-') {
                str += s + "\r";
                s = br.readLine();
            }
            key = Base64.decodeBase64(str);
        } catch (Exception ex) {
            log.warn("read pem file failure.", ex);
        }

        return key;
    }



發佈了75 篇原創文章 · 獲贊 8 · 訪問量 35萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章