如何从十六进制格式的PEM证书中提取公钥

时间:2016-12-21 12:41:54

标签: python x509 public-key pem

我有这个脚本提取证书公钥,但它不是十六进制格式。如何以十六进制格式提取公钥?

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

这是我得到的输出:

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 个答案:

答案 0 :(得分:0)

就这样做:

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

这将为您提供二进制格式,然后只转换为十六进制。