java读取证书公钥

方式1:使用javax.security.cert.X509Certificate进行解析

        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进行解析

        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("-----------------公钥--------------------");
 
  
 
  

说明:因为只做示例,没有进行异常处理和流的释放,方式1的代码可能少点,方式2需要强转,美观上可能方式1更好看点,但方式1的实质还是调用的方式2,方式2内部有实现缓存策略.更多可以参考下api文档,文档上有提供示例.

你可能感兴趣的:(java)