说明:本人是一个人python新手,近期想用python3做一个校验证书文件是否到期的功能,所以搜了很多资料,包括但不限于AI,baidu,google等。然后发现没有一个没有一个适用当下的方法。
从搜索结果来看,都是推荐使用OpenSSL.crypto.loads_pkcs12,但是这个方法在我本机上一直无法找到。我开始怀疑是不是我本地的版本问题,但是当我将pyopenssl升级到24.0.0最新版以后依旧无法验证。然后我就去看依赖包的源码介绍。
然后就发现了,在pyopenssl的首页介绍说明,23.3.0 (2023-10-25)版本删除了已弃用 3 年的OpenSSL.crypto.loads_pkcs7和OpenSSL.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("证书已过期。")
接上代码