Java根据域名获取证书颁发日期,截止日期,到期天数
以下提供参考工具类和运行效果截图:
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import javax.net.ssl.HttpsURLConnection;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.URL;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;
@Slf4j
public class DomainExpiryCheckerUtil {
/**
* 根据域名获取证书:颁发日期,截止日期,到期天数
*
* @param domainName 域名,例如:baidu.com
* @return com.alibaba.fastjson2.JSONObject
* @date 2024/7/3 下午2:11
*/
public static JSONObject getDomainCertificateInfo(String domainName) {
try {
InetAddress address = InetAddress.getByName(domainName);
log.info("IP地址: {}", address.getHostAddress());
if (address instanceof Inet4Address) {
log.info("IPv4 Address");
} else if (address instanceof Inet6Address) {
log.info("IPv6 Address");
}
// 建立HTTPS连接以获取SSL证书
URL url = new URL("https://" + domainName);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.connect();
// 从HTTPS连接获取证书
Certificate[] certs = conn.getServerCertificates();
// 获取证书的有效期
X509Certificate cert = (X509Certificate) certs[0];
Date notBefore = cert.getNotBefore();
Date notAfter = cert.getNotAfter();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String BeforeStr = sdf.format(notBefore);
log.info("证书颁发日期: {}", BeforeStr);
String afterStr = sdf.format(notAfter);
log.info("证书截止日期: {}", afterStr);
// 计算到期前的时间
Date now = new Date();
long diff = notAfter.getTime() - now.getTime();
long daysUntilExpiration = diff / (1000 * 60 * 60 * 24);
log.info("证书到期天数: {}", daysUntilExpiration);
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
JSONObject info = getDomainCertificateInfo("baidu.com");
System.out.println(JSONObject.toJSONString(info));
}
}
代码运行结果:
浏览器查看百度证书日期:验证一致