python 验证pfx,p12,pem,crt等证书文件有效期

说明:本人是一个人python新手,近期想用python3做一个校验证书文件是否到期的功能,所以搜了很多资料,包括但不限于AI,baidu,google等。然后发现没有一个没有一个适用当下的方法。

从搜索结果来看,都是推荐使用OpenSSL.crypto.loads_pkcs12,但是这个方法在我本机上一直无法找到。我开始怀疑是不是我本地的版本问题,但是当我将pyopenssl升级到24.0.0最新版以后依旧无法验证。然后我就去看依赖包的源码介绍。

然后就发现了,在pyopenssl的首页介绍说明,23.3.0 (2023-10-25)版本删除了已弃用 3 年的OpenSSL.crypto.loads_pkcs7OpenSSL.crypto.loads_pkcs12 ,其实pyopenssl在20.0.0 (2020-11-27) 版本就已经启用了该方法。然后我就开始对比,19.1.0 (2019-11-18) 和24.0.0文档中是否有替代方案。最后在文档首页看到了这样一段话。

Note: The Python Cryptographic Authority strongly suggests the use of pyca/cryptography where possible. If you are using pyOpenSSL for anything other than making a TLS connection you should move to cryptography and drop your pyOpenSSL dependency.

到此其实差不多已经真相了,openssl推荐我们使用cryptography。

from cryptography.hazmat.backends import default_backend
from cryptography import x509
from cryptography.hazmat.primitives.serialization import pkcs12
from datetime import datetime

def check_certificate(file_path,password):

    with open(file_path, "rb") as cert_file:
        cert_data = cert_file.read()

    if file_path.lower().endswith((".pfx",".p12")):
       pkcs = pkcs12.load_pkcs12(cert_data,password.encode("utf-8") )
       certificate = pkcs.cert.certificate
    elif file_path.lower().endswith((".cet", ".pem", ".crt",".cer")):
       certificate = x509.load_pem_x509_certificate(cert_data, default_backend())
    else:
        raise ValueError("不支持的证书文件格式")
     # 打印证书的开始时间和结束时间
    valid_from = certificate.not_valid_before
    valid_to = certificate.not_valid_after

    # 获取当前时间
    current_time = datetime.now()
    # print("当前时间:",current_time)
    

    # 检查证书是否在有效期内
    if valid_from <= current_time <= valid_to:
        print("证书在有效期内。")
    else:
        print("证书已过期。")

接上代码

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值