From 6f1f356fb0053418e6dc392ec94bff3c828919f5 Mon Sep 17 00:00:00 2001 From: WendyYang Date: Fri, 8 Mar 2024 17:35:26 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=9F=9F=E5=90=8D=E8=AF=81?= =?UTF-8?q?=E4=B9=A6=E8=BF=87=E6=9C=9F=E6=97=B6=E9=97=B4=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../hz/pm/api/common/util/SSLCertExpiryUtil.java | 67 ++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 hz-pm-api/src/main/java/com/hz/pm/api/common/util/SSLCertExpiryUtil.java diff --git a/hz-pm-api/src/main/java/com/hz/pm/api/common/util/SSLCertExpiryUtil.java b/hz-pm-api/src/main/java/com/hz/pm/api/common/util/SSLCertExpiryUtil.java new file mode 100644 index 0000000..d9f0116 --- /dev/null +++ b/hz-pm-api/src/main/java/com/hz/pm/api/common/util/SSLCertExpiryUtil.java @@ -0,0 +1,67 @@ +package com.hz.pm.api.common.util; + +import cn.hutool.core.date.DateUnit; +import cn.hutool.core.date.DateUtil; +import lombok.extern.slf4j.Slf4j; + +import javax.net.ssl.HttpsURLConnection; +import java.net.URL; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.Date; + +/** + *

+ * SSLCertExpiryUtil + *

+ * + * @author WendyYang + * @since 14:40 2024/3/8 + */ +@Slf4j +public class SSLCertExpiryUtil { + + private SSLCertExpiryUtil() { + } + + /** + * 获取域名的剩余有效期(单位:天) + * + * @param httpUrl \ + * @return 剩余有效期 + */ + public static Long getLeftValidityPeriod(String httpUrl) { + Long leftDays = null; + try { + URL url = new URL("https://" + httpUrl); + HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); + connection.connect(); + // 获取服务器证书链 + Certificate[] certificates = connection.getServerCertificates(); + for (Certificate certificate : certificates) { + if (certificate instanceof X509Certificate) { + X509Certificate x509cert = (X509Certificate) certificate; + // 获取证书的主题 + String subject = x509cert.getSubjectDN().getName(); + if (subject.endsWith(httpUrl)) { + // 获取证书的有效期结束时间 + Date expiryDate = x509cert.getNotAfter(); + leftDays = DateUtil.between(new Date(), expiryDate, DateUnit.DAY); + break; + } + } + } + connection.disconnect(); + return leftDays; + } catch (Exception e) { + log.error("获取域名有效期失败:", e); + return leftDays; + } + } + + public static void main(String[] args) { + System.out.println(getLeftValidityPeriod("zuche.ningdatech.com")); + } + + +}