如何读取 Java 中 .pfx 文件的内容?

2022-09-04 02:28:47

我有文件,也有私钥。如何用 Java 读取证书?file.pfxfile.pfx

我用过这个代码:

import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateException;
import javax.crypto.SecretKey;
import javax.security.auth.callback.*;
//These packages I have used.

public String readFile(String fn) { 
  String thisLine, ret = ""; 
  KeyStore ks = KeyStore.getInstance("pkcs12", "SunJSSE"); 
  ks.load(new FileInputStream(fn),"password".toCharArray()); 
  try { 
    Key key = ks.getKey("1", "password".toCharArray());
    Certificate[] cc = ks.getCertificateChain("1");
    X509Certificate certificate1 = (X509Certificate) cc[0];//Here it throws  java.lang.NullPointerException 
    ret += certificate1.getNotAfter(); 
    ret += certificate1.getNotBefore(); 
  } catch(Exception e) { 
    ret = "Cannot load, exception!";
  } 
  return ret; 
}

答案 1

试试这个代码来读取.pfx文件:-

  public void checkExpire() {

        try {
            KeyManagerFactory kmf = javax.net.ssl.KeyManagerFactory.getInstance("SunX509");
            KeyStore keystore = KeyStore.getInstance("PKCS12");
            char[] password= "yourfilepassword".toCharArray();

            keystore.load(new FileInputStream("filepath\filename.pfx"),password);
            //keystore.load(new FileInputStream(certificate), password);
            kmf.init(keystore, psswd);
            Enumeration<String> aliases = keystore.aliases();
            while(aliases.hasMoreElements()){
                String alias = aliases.nextElement();
                if(keystore.getCertificate(alias).getType().equals("X.509")){
                Date expDate = ((X509Certificate) keystore.getCertificate(alias)).getNotAfter();
                Date fromDate= ((X509Certificate) keystore.getCertificate(alias)).getNotBefore();
        System.out.println("Expiray Date:-"+expDate );
        System.out.println("From Date:-"+fromDate);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

答案 2

您收到异常是因为您的密钥库(即 PKCS #12 文件)不包含具有您提供的别名的证书链。

Key key = ks.getKey("1", "shalimar1234".toCharArray());
Certificate[] cc = ks.getCertificateChain("1"); // this is returning null

你的对象也很合理,但你似乎根本没有使用这个对象。keynull

要了解文件中有哪些别名可用,请尝试查看从 KeyStore.aliases() 返回的字符串。


推荐