【问题标题】:How to extract RSA public-key from x509 certificate in python如何从 python 中的 x509 证书中提取 RSA 公钥
【发布时间】:2017-05-03 03:04:30
【问题描述】:

我有以下脚本。它连接到 TLS 服务器并提取 X509 证书公钥:

import socket, ssl
import OpenSSL

hostname='www.google.com'
port=443

context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = context.wrap_socket(s, server_hostname=hostname)
ssl_sock.connect((hostname, port))
ssl_sock.close()
print("ssl connection Done")

cert = ssl.get_server_certificate((hostname, port))
# OpenSSL
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
pk = x509.get_pubkey()
print(pk)

问题是返回的公钥。我需要它的十六进制格式。如何解决这个问题?

这是我得到的输出:

<OpenSSL.crypto.PKey object at 0x0000019EBFDF73C8>

【问题讨论】:

标签: python ssl cryptography x509


【解决方案1】:
#pk = x509.get_pubkey() # from your code.
IntPk = pk.to_cryptography_key().public_numbers()
print(IntPk.n)# modulus
print(IntPk.e)# exponent

在 python3 中,任意精度算术是默认的。 所以可以解密如下:

pow(signature, e, n))# (a**b)%c is by pow(a, b, c)

【讨论】:

    【解决方案2】:

    我不确定您要的是什么。粘贴您收到的输出会很有帮助(看起来您忘记了)。这可能不是你要找的东西,但值得一试(未经测试,你也必须import binascii):

    print(binascii.hexlify(pk.to_cryptography_key().public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo))
    

    您应该修改编码和格式以满足您的需要。

    编辑:我想我明白你现在想要做什么。您可能需要将编码更改为Encoding.PKCS1

    【讨论】:

    • 我添加了输出。但我正在寻找长的十六进制格式。例如,从浏览器中,我发现 google 的公钥类似于:b3 37 8b a7 5e d2 f3 b2 77 90 9e 05 a3 a4 a8 df 99 f0 98 61 f3 95 73 75 9e 6e 11 00 33 7f 5e 23 d1 88 79 eb db c1 04 11 70 e8 5b ee ce a1 5a 90 eb 18 36 5a 48 54 19 e7 8a 7a 92 ec a9 c5 5c 98 ..etc
    • 您的线路不工作。例如,Encoding 未解析。
    猜你喜欢
    • 2017-06-13
    • 1970-01-01
    • 2018-01-27
    • 2012-07-17
    • 1970-01-01
    • 2014-06-23
    • 2016-01-07
    • 2018-08-03
    • 2013-03-10
    相关资源
    最近更新 更多