Generate X509Certificate from byte[]?

2022-08-31 16:59:05

Is there a possibility to generate an java.security.cert.X509Certificate from an byte[]?


答案 1

Sure.

The certificate objects can be created by an instance of CertificateFactory - in particular, one configured to create X509 certificates. This can be created like so:

CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

Then you need to pass it an InputStream containing the bytes of the certificate. This can be achieved by wrapping your byte array in a ByteArrayInputStream:

InputStream in = new ByteArrayInputStream(bytes);
X509Certificate cert = (X509Certificate)certFactory.generateCertificate(in);

答案 2

You can do something like:

X509Certificate certificate = signature.getKeyInfo().getX509Datas().get(0).getX509Certificates().get(0);

String lexicalXSDBase64Binary = certificate.getValue();
byte[] decoded = DatatypeConverter.parseBase64Binary(lexicalXSDBase64Binary);


CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(decoded));

推荐