不想存储p12证书内容,只想存储证书密钥,可通过以下2種方式实现
一、通過java读取证书的密钥出来:
package com.zat.ucop.service.util; import org.apache.commons.codec.binary.Base64; import java.io.FileInputStream;
import java.io.IOException;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.util.Enumeration; /**
* 读取P12格式证书的密钥.
*
* @author weixiong.cao
* @date 2019/4/3
*/
public class ReadP12Demo { public static void main(String[] args) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException {
String keyStorePath = "E:/client_01.p12";
String password = "123456"; // 实例化密钥库,默认JKS类型
KeyStore ks = KeyStore.getInstance("PKCS12");
// 获得密钥库文件流
FileInputStream is = new FileInputStream(keyStorePath);
// 加载密钥库
ks.load(is, password.toCharArray());
// 关闭密钥库文件流
is.close(); //私钥
Enumeration aliases = ks.aliases();
String keyAlias = null;
if (aliases.hasMoreElements()){
keyAlias = (String)aliases.nextElement();
System.out.println("p12's alias----->"+keyAlias);
}
PrivateKey privateKey = (PrivateKey) ks.getKey(keyAlias, password.toCharArray());
String privateKeyStr = Base64.encodeBase64String(privateKey.getEncoded());
System.out.println("私钥------------->" + privateKeyStr); //公钥
Certificate certificate = ks.getCertificate(keyAlias);
String publicKeyStr = Base64.encodeBase64String(certificate.getPublicKey().getEncoded());
System.out.println("公钥------------->"+publicKeyStr);
}
}
二、通過openssl命令讀取
進入linux控制臺,輸入以下命令
openssl pkcs12 -in ./client_01.p12 -nocerts -nodes -out ./priKey.prikey
會在指定目錄下生成1個priKey.prikey,我們在提取裏面的內容: