數字證書中讀取PublicKey


1. 讀取https簽發證書中的key

 1) 在下面的代碼中,是實現讀取證書字符串來讀取key的,CERTIFICATE 就是一個證書的字符串, 而方法cf.generateCertificate() 接受的是一個InputStream 流,當然這個地方也可以讀取一個文件 new FileInputSream("file path")即可!

public String getCertificateKey() {
        CertificateFactory cf = null;
        PublicKey publicKey = null;
        try {
            cf = CertificateFactory.getInstance("X.509");
            //DataInputStream  di = new DataInputStream("");
            X509Certificate cert = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(CERTIFICATE.getBytes()));
            publicKey = cert.getPublicKey();
        } catch (Exception e) {
            e.printStackTrace();
        }
        byte[] publicKeyString = Base64.encode(publicKey.getEncoded(), Base64.DEFAULT);
        String publickey = new String(publicKeyString);
        System.out.println("-----------------公鑰--------------------");
        System.out.println(publickey);
        System.out.println("-----------------公鑰--------------------");
        return publickey;
    }

 2) 這里的 X509Certificate 文件是 import java.security.cert.X509Certificate; 包路徑下的, 

 

 

 

public String getCertificateKey() {
CertificateFactory cf = null;
PublicKey publicKey = null;
try {
cf = CertificateFactory.getInstance("X.509");
//DataInputStream di = new DataInputStream("");
X509Certificate cert = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(CERTIFICATE.getBytes()));
publicKey = cert.getPublicKey();
} catch (Exception e) {
e.printStackTrace();
}
byte[] publicKeyString = Base64.encode(publicKey.getEncoded(), Base64.DEFAULT);
String publickey = new String(publicKeyString);
System.out.println("-----------------公鑰--------------------");
System.out.println(publickey);
System.out.println("-----------------公鑰--------------------");
return publickey;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM