如何用Python打开带密码保护的.pem私钥与证书文件?
读取带密码保护的OpenSSL私钥与证书(Python)
问题背景
你通过以下OpenSSL命令生成了带AES256加密的私钥、公钥及证书:
openssl genrsa -aes256 -passout pass:password -out key.pem 4096 && openssl rsa -in key.pem -passin pass:password -pubout -out pukey.pub
生成证书的命令:
openssl req -new -key key.pem -passin pass:password -x509 -out keycert.pem -days 365000 -subj '/CN=localhost'
当前直接读取文件内容的代码:
with open('../key.pem', 'rb') as f: private_key = f.read() with open('../keycert.pem', 'rb') as f: certificate_chain = f.read()
运行后报错:
E1117 13:57:03.515461744 70812 ssl_transport_security.cc:854] Invalid private key.
该错误的核心原因是:私钥文件被密码加密,直接读取的字节内容未经过解密,无法被SSL相关模块识别。
解决方案
使用cryptography库解密私钥,证书无需密码可直接读取。
步骤1:安装依赖
pip install cryptography
步骤2:解密私钥并读取证书
from cryptography.hazmat.primitives import serialization from cryptography.hazmat.backends import default_backend # 读取并解密私钥 with open('../key.pem', 'rb') as f: private_key = serialization.load_pem_private_key( f.read(), password=b'password', # 注意密码需传入字节类型 backend=default_backend() ) # 读取证书(无需密码) with open('../keycert.pem', 'rb') as f: certificate = serialization.load_pem_x509_certificate( f.read(), backend=default_backend() ) # 若需将解密后的私钥转为无加密的PEM字节(适配gRPC等场景) private_key_pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption() )
关键说明
load_pem_private_key会自动处理加密的PEM私钥,传入对应密码即可完成解密,得到可直接使用的私钥对象。- 证书文件本身未加密,可直接加载为证书对象,或保留原始字节内容(根据后续业务场景选择)。
内容的提问来源于stack exchange,提问作者sama
相关产品推荐
相关产品推荐

