瀏覽代碼

增加域名证书过期时间查询方法

tags/24080901
WendyYang 8 月之前
父節點
當前提交
6f1f356fb0
共有 1 個檔案被更改,包括 67 行新增0 行删除
  1. +67
    -0
      hz-pm-api/src/main/java/com/hz/pm/api/common/util/SSLCertExpiryUtil.java

+ 67
- 0
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;

/**
* <p>
* SSLCertExpiryUtil
* </p>
*
* @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"));
}


}

Loading…
取消
儲存