从 Python 中的 PrivateKey/CertificateRequest/Certificate 中提取 public-key 模数,格式与 OpenSSL 相同

Extract public-key modulus from PrivateKey/CertificateRequest/Certificate in Python , with the same format as OpenSSL

使用 OpenSSL,我可以使用这些命令从各种对象中提取 public 密钥的模数:

openssl rsa -noout -modulus -in {KEY}
openssl req -noout -modulus -in {CSR}
openssl x509 -noout -modulus -in {CERT}

我正在尝试使用 cryptographypyopenssl 包在 python 中复制它。

我可以从 Python 中的所有这些对象中提取 public 密钥,但我不知道如何对模数进行编码以匹配 OpenSSL 命令行输出——这似乎是我无法从 3 个项目中的任何一个的文档或源代码中找出格式的 base64 编码版本。

pyopenssl中PKeyclassRSAPublicNumbersclass(link) in cryptography has what you are looking for. You can get it using to_cryptography_key method (link)

from OpenSSL.crypto import load_certificate
from OpenSSL.crypto import FILETYPE_PEM

with open(certfile, 'rb') as fp:
    cert = load_certificate(FILETYPE_PEM, fp.read())

# This gives you the modulus in integer form
modn = cert.get_pubkey().to_cryptography_key().public_numbers().n

# Convert it to hex
print('{:X}'.format(modn))