Python 中从 PrivateKey/CertificateRequest/Certificate 中提取公钥模数,格式与 OpenSSL 相同

Jon*_*sco 5 python openssl pycrypto

使用 OpenSSL,我可以使用以下命令从各种对象中提取公钥的模数:

openssl rsa -noout -modulus -in {KEY}
openssl req -noout -modulus -in {CSR}
openssl x509 -noout -modulus -in {CERT}
Run Code Online (Sandbox Code Playgroud)

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

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

小智 6

密码学中的课程RSAPublicNumbers链接)有您正在寻找的内容。您可以使用pyopenssl 中类的to_cryptography_key方法(link)获取它PKey

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

Run Code Online (Sandbox Code Playgroud)