方式1:使用javax.security.cert.X509Certificate进行解析
[java] view plain copy
- URL url = Demo.class.getClassLoader().getResource(“C000024.crt”); //证书路径
- System.out.println(“公钥所在路径:”+url.getFile());
- X509Certificate cert = X509Certificate.getInstance(new FileInputStream(url.getFile()));
- PublicKey publicKey = cert.getPublicKey();
- BASE64Encoder base64Encoder=new BASE64Encoder();
- String publicKeyString = base64Encoder.encode(publicKey.getEncoded());
- System.out.println(“—————–公钥——————–“);
- System.out.println(publicKeyString);
- System.out.println(“—————–公钥——————–“);
方式2:使用java.security.cert.X509Certificate进行解析
[java] view plain copy
- URL url = Demo.class.getClassLoader().getResource(“C000024.crt”); //证书路径
- System.out.println(“公钥所在路径:”+url.getFile());
- CertificateFactory cf = CertificateFactory.getInstance(“X.509”);
- X509Certificate cert = (X509Certificate)cf.generateCertificate(new FileInputStream(url.getFile()));
- PublicKey publicKey = cert.getPublicKey();
- BASE64Encoder base64Encoder=new BASE64Encoder();
- String publicKeyString = base64Encoder.encode(publicKey.getEncoded());
- System.out.println(“—————–公钥——————–“);
- System.out.println(publicKeyString);
- System.out.println(“—————–公钥——————–“);
[java] view plain copy
说明:因为只做示例,没有进行异常处理和流的释放,方式1的代码可能少点,方式2需要强转,美观上可能方式1更好看点,但方式1的实质还是调用的方式2,方式2内部有实现缓存策略.更多可以参考下api文档,文档上有提供示例.
版权声明:本文为hejjiiee原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。