Java 读取p12 证书私钥

    /**
     * 获取  p12证书 私钥
     * @param p12FilePath p12证书文件路径
     * @param p12Pswd p12 证书密码
     */
    public String getRsaPriKeyByP12(String p12FilePath, String p12Pswd) throws KeyStoreException, NoSuchProviderException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        InputStream fis = new FileInputStream(p12FilePath);

        KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");

        keyStore.load(fis, p12Pswd.toCharArray());

        Enumeration<String> aliases = keyStore.aliases();
        String keyAlias = null;
        if (aliases.hasMoreElements()) {
            keyAlias = (String) aliases.nextElement();
            System.out.println("p12's alias----->" + keyAlias);
        }
        // 完整 私钥对象
        PrivateKey priKey = (PrivateKey) (keyStore.getKey(keyAlias, null));
        System.out.println("私钥:\n" + priKey);
        
        // 私钥RSA字符串
        String rsaBase64Prikey = Base64.encodeToString(priKey.getEncoded());
        System.out.println("私钥RSA:\n" + rsaBase64Prikey);
        return rsaBase64Prikey;
    }
    

    /**
     * 获取 cer证书公钥
     * @param cerFilePath cer文件路径
     */
    public String getRsaPublicKeyByCer(String cerFilePath) throws CertificateException, FileNotFoundException {
        // public key
        InputStream is = new FileInputStream(cerFilePath);
        CertificateFactory cf = CertificateFactory.getInstance("x509");
        Certificate cerCert = cf.generateCertificate(is);
        // 获取 公钥对象
        PublicKey publicKey = cerCert.getPublicKey();
        // 获取  公钥RSA 公钥字符串
        String rsaBase64publickey = Base64.encodeToString(publicKey.getEncoded());

        System.out.println("public key:\n" + rsaBase64publickey);
        return rsaBase64publickey;
    }


测试

    @Test
    public void test() throws UnrecoverableKeyException, CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException, NoSuchProviderException {
        String PayP12FilePath = "E:\\pay.p12";
        
		String PayCerFilePath = "E:\\pay.cer";
        String PayP12Password = "a123456";
        

        getRsaPriKeyByP12(PayP12FilePath, PayP12Password);
		getRsaPublicKeyByCer(PayCerFilePath );
    

你可能感兴趣的:(java,java,开发语言,后端)