利用openssl 生成p12文件,
生成密钥对 openssl genrsa -out private.key 2048
证书申请 openssl req -new -out root.csr -key private.key
自签署证书 openssl x509 -req -in root.csr -out cert.pem -signkey private.key -days 3650
其它证书用CA来签署 openssl x509 -req -in root.csr -out cert.pem -CA cert.pem -CAkey private.key -CAcreateserial -days 3650
合成p12文件 openssl pkcs12 -export -clcerts -in cert.pem -inkey private.key -out root.p12
利用openssl生成pfx文件
openssl genrsa -out private.key 2048
openssl req -new -x509 -days 3650 -key private.key -out ca.crt
生成pfx文件 openssl pkcs12 -export -out server.pfx -inkey private.key -in ca.crt
package com.test;
import java.io.File;
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 PfxTest {
@SuppressWarnings("resource")
public static void main(String[] args) {
try{
String pfxFileName = "/home/yunix/keytest1/server.pfx";
String keyStorePwd = "111111";
File fpkcs12 = null;
if(pfxFileName !=null) {
fpkcs12 = new File(pfxFileName);
}
FileInputStream fis = new FileInputStream(fpkcs12);
KeyStore keyStore = null;
try{
keyStore = KeyStore.getInstance("PKCS12");
}catch(Exception ex) {
ex.printStackTrace();
throw new Exception("exception");
}
keyStore.load(fis, keyStorePwd.toCharArray());
Enumeration<String> e = keyStore.aliases();
String keyAlias = null;
if (e.hasMoreElements()) // we are readin just one certificate.
{
keyAlias = (String)e.nextElement();
System.out.println("alias=[" + keyAlias + "]");
}
PrivateKey prikey = (PrivateKey)keyStore.getKey("1",keyStorePwd.toCharArray());
System.out.println(prikey);
Certificate cert = keyStore.getCertificate("1");
PublicKey pubkey = cert.getPublicKey();
System.out.println(pubkey);
}catch(Exception e) {
e.printStackTrace();
}
}
}