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();
}
}
}