如何从SSLContext获取SSL证书到期日期?



我目前正在从Java程序中的pem文件中读取证书和密钥,并使用它来构造SSLContext对象,如下所示 -

final SslContext _sslContext = SslContextBuilder.forClient().ciphers(ciphers)
.sslProvider(sslProvider).trustManager(_trustedCerts).keyManager(_cert, _key, pwd).build();

_cert,_key是文件。

有什么方法可以使用此 SSLContext 对象来获取证书到期日期和 DN?

我能够直接从 pem 文件中获取证书信息。这就是我在 Java 中以编程方式做到这一点的方式 -

CertificateFactory fact = null;
try {
fact = CertificateFactory.getInstance("X.509");
} catch (CertificateException e) {
e.printStackTrace();
}
FileInputStream is = null;
try {
is = new FileInputStream(_cert);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
X509Certificate cer = null;
try {
cer = (X509Certificate) fact.generateCertificate(is);
log.info("Cer Not Before - {} ", cer.getNotBefore());
log.info("Cer Not After - {} ", cer.getNotAfter());
log.info("Cer Issuer DN - {} ",cer.getIssuerDN());
} catch (CertificateException e) {
e.printStackTrace();
}

这个堆栈溢出答案帮助我解决了如何从 pem 文件加载公共证书?。

您可以通过以下方式找到在握手期间发送到对等方的 SSL 证书 (X509Certificate( 的到期日期:

public Map<BigInteger, CertificateInfo> getCertificatesExpiryDatesAndDistinguishedNames(SslContext context) {
SSLSessionContext sessionContext = context.sessionContext();
return Collections.list(sessionContext.getIds()).stream()
.map(sessionContext::getSession)
.map(SSLSession::getLocalCertificates) // certificate(s) that were sent to the peer during handshaking
.map(Stream::of)
.map(streamOfCertificates -> streamOfCertificates.map(X509Certificate.class::cast))
.flatMap(Function.identity())
.collect(toMap(X509Certificate::getSerialNumber, this::convertToCertificateInfo));
}
private CertificateInfo convertToCertificateInfo(final X509Certificate certificate) {
return new CertificateInfo(certificate.getIssuerX500Principal(), certificate.getNotAfter());
}

这将返回证书序列号和证书信息的映射(颁发者可分辨名称和有效期的结束日期(:

public class CertificateInfo {
private final X500Principal x500Principal;
private final Date endDateOfValidityPeriod;
public CertificateInfo(X500Principal x500Principal, Date endDateOfValidityPeriod) {
this.x500Principal = x500Principal;
this.endDateOfValidityPeriod = endDateOfValidityPeriod;
}
public X500Principal getX500Principal() {
return x500Principal;
}
public Date getEndDateOfValidityPeriod() {
return endDateOfValidityPeriod;
}
}

最新更新