简体   繁体   English

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

[英]How to extract public key from a x509 certificate in python?

Below shows the code example I followed, However I got error response as - "Unable to load certificate". 下面显示了我遵循的代码示例,但是我得到了错误响应 - “无法加载证书”。

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();

Error response 错误响应

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

Please help me to sort this issue. 请帮我解决这个问题。

Private keys are not contained within X509 certificates, only public keys. 私钥不包含在X509证书中,只包含公钥。 To extract the public key you've got the correct code, but your certificate will not load because it isn't in proper PEM format. 要提取公钥,您已获得正确的代码,但您的证书将无法加载,因为它不是正确的PEM格式。

A PEM formatted certificate has the -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- delimiters and base64 encoded data in between, but it also needs to be a maximum of 64 characters per line (originally defined in RFC 1421 but also present in RFC 7468 ). PEM格式的证书之间有-----BEGIN CERTIFICATE----------END CERTIFICATE-----分隔符和base64编码数据,但它最多也需要64个字符每行(最初在RFC 1421中定义,但也存在于RFC 7468中 )。

Some software is more forgiving than the specification, but the underlying library for pyca/cryptography (OpenSSL or LibreSSL) requires that it be formatted in this fashion. 有些软件比规范更宽容,但pyca/cryptography (OpenSSL或LibreSSL)的底层库要求以这种方式进行格式化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM