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 );
    
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值