How to extract public-key from PEM certificate in hexadecimal format

2.6k views Asked by At

I have this script which extracts the certificate public-key but it is not in a hexadecimal format. How can I extract the public-key in hexadecimal format?

import socket, ssl
import OpenSSL
#import binascii

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)

print (OpenSSL.crypto.dump_publickey(OpenSSL.crypto.FILETYPE_PEM,x509.get_pubkey()))

This is the output I am getting:

b'-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvLyy8xoWO8b2nSjh746S\nmxOyrntQj/C04DaNCQDkhFFXf2w5ZfChIMk3NmThBmTydm4rl0r7TlqoNfkNc8Xr\n/P+WJtDku8ai2R/usFWPrayZZGtlWd6BpBfI5jVuIaHyStLZw7+IMhtHfQDo1wsw\nmPx0sxmAOqEeoXcX45x5G8LKT1n78r0NX8bjAM0upk5dseg3QCVKNSPgVUueIAM3\nt/5B6GpqL0R2cjp+HadsJAr93l0buBIfGU911k4ntuY3JzYUEbQ7warZT7bBT1FI\nX6J0RpFDaIxiIhS+lHZHziKP5pb+QUGFnakQmglu/L1D+k3Go1WangeL+bEeztEi\nSQIDAQAB\n-----END PUBLIC KEY-----\n'
1

There are 1 answers

2
Raskayu On

Just do that:

RSA.publickey().exportKey("DER")

This will give you der format that is in binary, then just convert to hex.