Java根据域名获取证书颁发日期 截止日期 到期天数

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));
    }
}

代码运行结果:
在这里插入图片描述

浏览器查看百度证书日期:验证一致
在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柳落青

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值