java pfx 证书_java 读取.pfx证书文件公钥私钥字符串

该博客介绍了如何使用Java从.pfx文件中读取证书,包括设置证书路径和密码,加载PKCS12密钥库,获取证书别名,以及提取私钥和公钥的Base64编码。
摘要由CSDN通过智能技术生成

import cn.hutool.core.codec.Base64Encoder;

import java.io.FileInputStream;

import java.security.KeyStore;

import java.security.PrivateKey;

import java.security.PublicKey;

import java.security.cert.Certificate;

import java.util.Enumeration;

public class ReadP12Cert

{

public static void main(String[] args)

{

//证书路径

final String KEYSTORE_FILE = "D:\\123.pfx";

//证书密码

final String KEYSTORE_PASSWORD = "111111";

try

{

//获取PKCS12密钥库

KeyStore ks = KeyStore.getInstance("PKCS12");

FileInputStream fis = new FileInputStream(KEYSTORE_FILE);

// If the keystore password is empty(""), then we have to set

// to null, otherwise it won't work!!!

char[] nPassword = null;

if ((KEYSTORE_PASSWORD == null) || KEYSTORE_PASSWORD.trim().equals(""))

{

nPassword = null;

}

else

{ //把密码字符串转为字符数组

nPassword = KEYSTORE_PASSWORD.toCharArray();

}

//将.pfx证书信息加载密钥库

ks.load(fis, nPassword);

fis.close();

//证书类型

System.out.println("keystore type=" + ks.getType());

Enumeration enum1 = ks.aliases();

String keyAlias = null;

if (enum1.hasMoreElements())

{ //获取证书别名

keyAlias = (String)enum1.nextElement();

System.out.println("alias=[" + keyAlias + "]");

}

System.out.println("is key entry=" + ks.isKeyEntry(keyAlias));

PrivateKey prikey = (PrivateKey) ks.getKey(keyAlias, nPassword);

Certificate cert = ks.getCertificate(keyAlias);

PublicKey pubkey = cert.getPublicKey();

System.out.println("cert class = " + cert.getClass().getName());

System.out.println("cert = " + cert);

System.out.println("public key = " + Base64Encoder.encode(pubkey.getEncoded()));

System.out.println("private key = " + Base64Encoder.encode(prikey.getEncoded()));

}

catch (Exception e)

{

e.printStackTrace();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值