Python使用cryptography加载OpenSSL生成的x509证书报错如何解决
你遇到的TypeError: from_buffer() cannot return the address of a unicode object报错,是因为x509.load_pem_x509_certificate()方法要求传入证书的二进制内容,你当前直接传入了字符串类型的文件路径,或者读取证书时没有使用二进制模式拿到了Unicode字符串,不符合接口参数要求。
正确使用流程
1. 生成证书(你的OpenSSL命令无需修改,本身是正确的)
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout test.key -out test.cert
执行过程中按提示填写证书信息即可,生成的test.cert为PEM格式证书文件,test.key为对应的私钥文件。
2. Python 3.8+ 加载证书的正确代码
from cryptography import x509 # 以二进制模式读取证书文件 with open("test.cert", "rb") as cert_file: cert_bytes = cert_file.read() # 传入二进制内容加载证书 cert = x509.load_pem_x509_certificate(cert_bytes)
3. 常用证书操作示例
- 查看证书生效、失效时间:
print("证书生效时间:", cert.not_valid_before) print("证书失效时间:", cert.not_valid_after)
- 读取证书主体信息:
from cryptography.x509.oid import NameOID # 读取通用名(CN) common_name = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value print("证书通用名:", common_name)
- 加载对应私钥:
from cryptography.hazmat.primitives import serialization with open("test.key", "rb") as key_file: private_key = serialization.load_pem_private_key( key_file.read(), password=None # 生成证书时使用了-nodes参数,私钥无密码 )
注意事项
- Python 3默认字符串为Unicode类型,所有密码学相关的文件操作都要使用二进制模式(
rb读/wb写),避免编码转换破坏文件内容 - 如果是从接口、缓存等位置获取的证书内容,直接使用bytes类型即可,不要调用
decode()方法转成字符串
内容的提问来源于stack exchange,提问作者user3732793
相关产品推荐
相关产品推荐

