2012-03-16 72 views
18

如何從PEM格式的字符串創建java.security.cert.X509Certificate實例? PEM格式的字符串是HTTP請求「SSL_CLIENT_CERT」標頭值。將PEM格式的字符串轉換爲java.security.cert.X509Certificate

答案基於mgaert的答案,這是我在斯卡拉寫道:

val cert = factory.generateCertificate(
    new ByteArrayInputStream(
     Base64.decodeBase64(
     cert.stripPrefix("-----BEGIN CERTIFICATE-----").stripSuffix("-----END CERTIFICATE-----") 
    ) 
    ).asInstanceOf[X509Certificate] 
+4

沒有必要解碼它。直接支持PEM base64編碼格式,如[本答案](http://stackoverflow.com/a/9739366/822870)。再次: CertificateFactory cFactory = CertificateFactory.getInstance(「X.509」); X509Certificate cert =(X509Certificate)cFactory.generateCertificate(getInputStream(of_the_original_unmodified_certificate_file)); – 2015-05-21 15:08:28

+1

似乎沒有必要去除前綴/後綴 – lznt 2017-10-18 22:27:42

回答

27

解碼的Base64編碼到二進制,讀取某些InputStream它,然後嘗試

CertificateFactory cf = CertificateFactory.getInstance("X.509"); 
Certificate cert = cf.generateCertificate(is); 
12

我有一個類似的問題,我粘貼也在這裏的Java代碼,爲我工作,如果有人掛了它:

import java.util.Base64; 

public static X509Certificate parseCertificate(String _headerName, HttpServletRequest _request) throws CertificateException { 
    String certStr = _request.getHeader("x-clientcert"); 
    //before decoding we need to get rod off the prefix and suffix 
    byte [] decoded = Base64.getDecoder().decode(certStr.replaceAll(X509Factory.BEGIN_CERT, "").replaceAll(X509Factory.END_CERT, "")); 

    return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(decoded)); 
} 
6

PEM格式化字符串轉換的步驟與(x509 - >字符串)發生方式相反。

樣品PEM格式的字符串:

-----BEGIN CERTIFICATE----- 
MIIEczCCA1ugAwIBAgIBADANBgkqhkiG9w0BAQQFAD..AkGA1UEBhMCR0Ix 
EzARBgNVBAgTClNvbWUtU3RhdGUxFDASBgNVBAoTC0..0EgTHRkMTcwNQYD 
VQQLEy5DbGFzcyAxIFB1YmxpYy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SD6Kr 
XcoOwLdSaGmJYslLKZB3ZIDEp0wYTGhgteb6JFiTtn..sf2xdrYfPCiIB7g 
BMAV7Gzdc4VspS6ljrAhbiiawdBiQlQmsBeFz9JkF4..b3l8BoGN+qMa56Y 
It8una2gY4l2O//on88r5IWJlm1L0oA8e4fR2yrBHX..adsGeFKkyNrwGi/ 
7vQMfXdGsRrXNGRGnX+vWDZ3/zWI0joDtCkNnqEpVn..HoX 
-----END CERTIFICATE----- 

步驟如下:

1. Remove headers from PEM formatted String 
Headers are : ---- BEGIN CERTIFICATE ----- and ----- END CERTIFICATE ------ 
2. Decode the rest of the part using Base64 to byte array 
3. Then you can use CertificateFactory to convert byte stream to x509Certificate object 

示例代碼以上做(與PEM作家):

/** 
    * Converts a PEM formatted String to a {@link X509Certificate} instance. 
    * 
    * @param pem PEM formatted String 
    * @return a X509Certificate instance 
    * @throws CertificateException 
    * @throws IOException 
    */ 
    public X509Certificate convertToX509Certificate(String pem) throws CertificateException, IOException { 
     X509Certificate cert = null; 
     StringReader reader = new StringReader(pem); 
     PEMReader pr = new PEMReader(reader); 
     cert = (X509Certificate)pr.readObject(); 
     return cert; 
    } 
+1

請注意,PEMReader是Bouncy Castle Crypto API的一部分,請參閱https://www.bouncycastle.org/。 @mgaert編寫的代碼無需外部庫。 – 2016-11-16 14:46:37

1

另一個樣品,

public static X509Certificate convertToX509Cert(String certificateString) throws CertificateException { 
    X509Certificate certificate = null; 
    CertificateFactory cf = null; 
    try { 
     if (certificateString != null && !certificateString.trim().isEmpty()) { 
      certificateString = certificateString.replace("-----BEGIN CERTIFICATE-----\n", "") 
        .replace("-----END CERTIFICATE-----", ""); // NEED FOR PEM FORMAT CERT STRING 
      byte[] certificateData = Base64.getDecoder().decode(certificateString); 
      cf = CertificateFactory.getInstance("X509"); 
      certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateData)); 
     } 
    } catch (CertificateException e) { 
     throw new CertificateException(e); 
    } 
    return certificate; 
}