.crt证书转成.pem格式
先解释一下.crt 和 .pem是什么,看下图
图是网上找到, 链接: https://www.zhihu.com/question/29620953
.crt 和 .pem 后缀的都是指证书,只是需要用不同的工具才能查看里面的内容,理解是不同的编码方式。
比如.crt需要系统自带的证书工具就能打开,.pem需要做Base64解码才能查看。
有个需要是要在JAVA的项目内将.crt转成.pem这种格式,通过Linux的openssl工具,或者keytool工具(JDK中的工具)都能很方便的做转换,JAVA其实也可以,也非常简单 示例代码如下。
// 博客原文地址:https://www.cnblogs.com/mysticbinary/p/16932466.html
String certpath = "E:\\mysticbinary\\mysticbinary.crt";
CertificateFactory cf = CertificateFactory.getInstance("X.509");
FileInputStream in1 = new FileInputStream(certpath);
Certificate c = cf.generateCertificate(in1);
X509Certificate x509Cert = (X509Certificate) c;
// 获取 .pem 格式 证书
System.out.println(X509Factory.BEGIN_CERT);
byte[] encoded = x509Cert.getEncoded();
BASE64Encoder encoder = new BASE64Encoder();
String publicKeyBase64 = encoder.encodeBuffer(encoded);
System.out.print(publicKeyBase64);
System.out.println(X509Factory.END_CERT);
publicKeyBase64 = "-----BEGIN CERTIFICATE-----\n" + publicKeyBase64 + "-----END CERTIFICATE-----";
System.out.println("pblicKeyBase64: "+publicKeyBase64);
当然也可以使用在线工具转换:
https://redkestrel.co.uk/products/decoder/
提取证书里面RSA公钥的长度
// 博客原文地址:https://www.cnblogs.com/mysticbinary/p/16932466.html
String certpath = "E:\\mytestsdk\\2022-11-09-15-48-10-444-123123.crt";
CertificateFactory cf = CertificateFactory.getInstance("X.509");
FileInputStream in1 = new FileInputStream(certpath);
Certificate c = cf.generateCertificate(in1);
X509Certificate x509Cert = (X509Certificate) c;
RSAPublicKey rsaPublicKey = (RSAPublicKey) x509Cert.getPublicKey();
Integer pklength = rsaPublicKey.getModulus().bitLength();
参考:
https://blog.csdn.net/weixin_42209368/article/details/101679681