读取Cert格式证书的密钥

时间:2020-12-04 09:00:49

不想存储Cert证书内容,只想存储证书密钥,可通过以下2種方式实现

一、通過java读取证书的密钥出来:

 package com.zat.ucop.service.util;

 import sun.misc.BASE64Encoder;

 import java.io.FileInputStream;
import java.security.PublicKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate; /**
* 读取cert格式证书的密钥.
*
* @author weixiong.cao
* @date 2019/4/3
*/
public class ReadCerDemo {
public static void main(String[] args) throws Exception {
String keyStorePath = "E:/mpay公钥/client_02.cer"; CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(new FileInputStream(keyStorePath));
PublicKey publicKey = cert.getPublicKey();
BASE64Encoder base64Encoder = new BASE64Encoder();
String publicKeyString = base64Encoder.encode(publicKey.getEncoded());
System.out.println("-----------------公钥--------------------");
System.out.println(publicKeyString);
System.out.println("-----------------公钥--------------------");
}
}

二、通過openssl命令讀取

進入linux控制臺,輸入以下命令:

openssl x509 -in ./client_02.cer -pubkey -noout > ./mpayPubKey.pubkey

以上命令會將證書內容生成到一個 mpayPubKey.pubkey 文件,文件內容如下:

读取Cert格式证书的密钥