如何从python中的x509证书中提取公钥?

mug*_*gzi 5 python cryptography azure x509certificate jwt

下面显示了我遵循的代码示例,但是我得到了错误响应 - “无法加载证书”。

from cryptography.x509 import load_pem_x509_certificate
from cryptography.hazmat.backends import default_backend

cert_str = '-----BEGIN CERTIFICATE----- MIIDBTCCAe2gAwIBAgIQEsuEXXy6BbJCK3bMU6GZ/TANBgkqhkiG9w0BAQsFADAt... -----END CERTIFICATE-----';

cert_obj = load_pem_x509_certificate(str.encode(cert_str), default_backend())
public_key = cert_obj.public_key();
Run Code Online (Sandbox Code Playgroud)

错误响应

Traceback (most recent call last):
  File "C:\xampp1\htdocs\TestWorkPlace\TestPython\src\test1.py", line 10, in <module>
    cert_obj = load_pem_x509_certificate(str.encode(cert_str), default_backend())
  File "C:\Program Files (x86)\Python\lib\site-packages\cryptography\x509\base.py", line 43, in load_pem_x509_certificate
    return backend.load_pem_x509_certificate(data)
  File "C:\Program Files (x86)\Python\lib\site-packages\cryptography\hazmat\backends\multibackend.py", line 341, in load_pem_x509_certificate
    return b.load_pem_x509_certificate(data)
  File "C:\Program Files (x86)\Python\lib\site-packages\cryptography\hazmat\backends\openssl\backend.py", line 1175, in load_pem_x509_certificate
    raise ValueError("Unable to load certificate")
ValueError: Unable to load certificate
Run Code Online (Sandbox Code Playgroud)

请帮我解决这个问题。

Pau*_*rer 6

X509 证书中不包含私钥,仅包含公钥。要提取公钥,您已获得正确的代码,但您的证书将无法加载,因为它不是正确的 PEM 格式。

PEM 格式的证书具有-----BEGIN CERTIFICATE----------END CERTIFICATE-----分隔符以及其间的 base64 编码数据,但每行最多需要 64 个字符(最初在RFC 1421中定义,但也出现在RFC 7468中)。

有些软件比规范更宽容,但pyca/cryptography(OpenSSL 或 LibreSSL)的底层库要求它以这种方式格式化。