将 PEM 格式的字符串转换为 java.security.cert.X509Certificate
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9739121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a PEM-formatted String to a java.security.cert.X509Certificate
提问by Jeffrey Chung
How does one create a java.security.cert.X509Certificate
instance from a PEM-formatted String? The PEM-formatted String is a HTTP request "SSL_CLIENT_CERT" header value.
如何java.security.cert.X509Certificate
从 PEM 格式的字符串创建实例?PEM 格式的字符串是 HTTP 请求“SSL_CLIENT_CERT”标头值。
ANSWER: Based on mgaert's answer, here's what I wrote in Scala:
回答: 根据 mgaert 的回答,这是我在 Scala 中写的:
val cert = factory.generateCertificate(
new ByteArrayInputStream(
Base64.decodeBase64(
cert.stripPrefix("-----BEGIN CERTIFICATE-----").stripSuffix("-----END CERTIFICATE-----")
)
).asInstanceOf[X509Certificate]
采纳答案by mgaert
Decode the Base64 to binary, with some InputStream reading it, then try
将 Base64 解码为二进制,用一些 InputStream 读取它,然后尝试
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(is);
回答by simonC
I have a similar problem, I'm pasting also here the java code that worked for me in case anyone neaded it :
我有一个类似的问题,我也在此处粘贴了对我有用的 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));
}
回答by Balaji Boggaram Ramanarayan
The steps in conversion of PEM formatted String is opposite of how (x509 -> String) took place.
PEM 格式字符串的转换步骤与 (x509 -> String) 发生的方式相反。
Sample PEM Formatted String :
示例 PEM 格式字符串:
-----BEGIN CERTIFICATE-----
MIIEczCCA1ugAwIBAgIBADANBgkqhkiG9w0BAQQFAD..AkGA1UEBhMCR0Ix
EzARBgNVBAgTClNvbWUtU3RhdGUxFDASBgNVBAoTC0..0EgTHRkMTcwNQYD
VQQLEy5DbGFzcyAxIFB1YmxpYyBQcmltYXJ5IENlcn..XRpb24gQXV0aG9y
aXR5MRQwEgYDVQQDEwtCZXN0IENBIEx0ZDAeFw0wMD..TUwMTZaFw0wMTAy
MDQxOTUwMTZaMIGHMQswCQYDVQQGEwJHQjETMBEGA1..29tZS1TdGF0ZTEU
MBIGA1UEChMLQmVzdCBDQSBMdGQxNzA1BgNVBAsTLk..DEgUHVibGljIFBy
aW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxFD..AMTC0Jlc3QgQ0Eg
THRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCg..Tz2mr7SZiAMfQyu
vBjM9OiJjRazXBZ1BjP5CE/Wm/Rr500PRK+Lh9x5eJ../ANBE0sTK0ZsDGM
ak2m1g7oruI3dY3VHqIxFTz0Ta1d+NAjwnLe4nOb7/..k05ShhBrJGBKKxb
8n104o/5p8HAsZPdzbFMIyNjJzBM2o5y5A13wiLitE..fyYkQzaxCw0Awzl
kVHiIyCuaF4wj571pSzkv6sv+4IDMbT/XpCo8L6wTa..sh+etLD6FtTjYbb
rvZ8RQM1tlKdoMHg2qxraAV++HNBYmNWs0duEdjUbJ..XI9TtnS4o1Ckj7P
OfljiQIDAQABo4HnMIHkMB0GA1UdDgQWBBQ8urMCRL..5AkIp9NJHJw5TCB
tAYDVR0jBIGsMIGpgBQ8urMCRLYYMHUKU5AkIp9NJH..aSBijCBhzELMAkG
A1UEBhMCR0IxEzARBgNVBAgTClNvbWUtU3RhdGUxFD..AoTC0Jlc3QgQ0Eg
THRkMTcwNQYDVQQLEy5DbGFzcyAxIFB1YmxpYyBQcm..ENlcnRpZmljYXRp
b24gQXV0aG9yaXR5MRQwEgYDVQQDEwtCZXN0IENBIE..DAMBgNVHRMEBTAD
AQH/MA0GCSqGSIb3DQEBBAUAA4IBAQC1uYBcsSncwA..DCsQer772C2ucpX
xQUE/C0pWWm6gDkwd5D0DSMDJRqV/weoZ4wC6B73f5..bLhGYHaXJeSD6Kr
XcoOwLdSaGmJYslLKZB3ZIDEp0wYTGhgteb6JFiTtn..sf2xdrYfPCiIB7g
BMAV7Gzdc4VspS6ljrAhbiiawdBiQlQmsBeFz9JkF4..b3l8BoGN+qMa56Y
It8una2gY4l2O//on88r5IWJlm1L0oA8e4fR2yrBHX..adsGeFKkyNrwGi/
7vQMfXdGsRrXNGRGnX+vWDZ3/zWI0joDtCkNnqEpVn..HoX
-----END CERTIFICATE-----
Here are the steps :
以下是步骤:
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
Sample Code to do above (with PEM Writer):
上面要做的示例代码(使用 PEM Writer):
/**
* 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;
}
回答by Zeigeist
Another sample,
另一个样本,
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;
}
回答by shuyu
Tried to follow @Balaji Boggaram Ramanarayan code but IDE keep on throwing Exception. Instead i convert the string to bytes and it works perfectly.
试图遵循@Balaji Boggaram Ramanarayan 代码,但 IDE 继续抛出异常。相反,我将字符串转换为字节,它完美地工作。
private X509Certificate convertStringToX509Cert(String certificate) throws Exception{
InputStream targetStream = new ByteArrayInputStream(certificate.getBytes());
return (X509Certificate) CertificateFactory
.getInstance("X509")
.generateCertificate(targetStream);
}
Not to mentions, this method doesn't need to remove .pem header and footer (-----BEGIN PRIVATE KEY----- and -----END PRIVATE KEY-----)
更不用说,这种方法不需要删除 .pem 页眉和页脚(-----BEGIN PRIVATE KEY----- 和 -----END PRIVATE KEY-----)