天天看點

Android 生成PKCS12并導入證書

Android 生成PKCS12并導入證書

引入三方jar包

// 這個是加解密相關的包
implementation group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.62'
// 主要用到這個
implementation group: 'org.bouncycastle', name: 'bcpkix-jdk15on', version: '1.62'
           

上回寫到生成pkcs10證書傳到背景,這篇主要寫将簽名後的證書導入到PKCS12中去

// 生成KeyPair
    public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        return keyPairGenerator.genKeyPair();

    }

 // 合成p12證書
    public static void storeP12(PrivateKey pri, String p7, String p12Path, String p12Password) throws Exception {

        CertificateFactory factory = CertificateFactory.getInstance("X509");
        //初始化證書鍊
        X509Certificate p7X509 = (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(p7.getBytes()));
        Certificate[] chain = new Certificate[]{p7X509};
        // 生成一個空的p12證書
        KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
        ks.load(null, null);
        // 将伺服器傳回的證書導入到p12中去
        ks.setKeyEntry("client", pri, p12Password.toCharArray(), chain);
        // 加密儲存p12證書
        FileOutputStream fOut = new FileOutputStream(p12Path);
        ks.store(fOut, p12Password.toCharArray());
    }
           

代碼收錄

https://github.com/ddssingsong/AnyTool

cipher子產品

繼續閱讀