How to extract RSA public-key from x509 certificate in python

6.9k views Asked by At

I have the following script. It connects to a TLS server and extracts X509 certificate public-key:

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)

The problem is that the returned public-key. I need it in hexadecimal format. How to solve this issue?

This is the output I am getting:

<OpenSSL.crypto.PKey object at 0x0000019EBFDF73C8>
2

There are 2 answers

2
Coder-256 On

I'm not exactly sure what you're asking for. It would be helpful to paste in the output you received (it looks like you forgot to). This may not bee what you're looking for, but it's worth a try (untested, also you must import binascii):

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

You should modify the encoding and format to fit your needs.

EDIT: I think I understand what you're trying to do now. You may want to change the encoding to Encoding.PKCS1.

0
Jake  Lee On
#pk = x509.get_pubkey() # from your code.
IntPk = pk.to_cryptography_key().public_numbers()
print(IntPk.n)# modulus
print(IntPk.e)# exponent

In python3, arbitrary-precision arithmetic is default. so decryption is possible like below:

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