2

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>
Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
user2192774
  • 3,807
  • 17
  • 47
  • 62
  • Possible duplicate of [extracting public key from certificate and encrypting data](http://stackoverflow.com/questions/5789193/extracting-public-key-from-certificate-and-encrypting-data) – Maarten Bodewes Dec 18 '16 at 00:11
  • Currently you're just getting the handle to the public key. Have you looked at `OpenSSL.crypto.dump_publickey(type, pkey)`? – Maarten Bodewes Dec 18 '16 at 00:14

2 Answers2

1

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.

Coder-256
  • 5,212
  • 2
  • 23
  • 51
  • I added the output. But I am llooking for the long hexadecimal format. For example, from the browser, I find that google's public-key is something like: `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` – user2192774 Dec 17 '16 at 14:39
  • You line is not working. For example, `Encoding` is unresolved. – user2192774 Dec 17 '16 at 14:44
0
#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)
Jake Lee
  • 1
  • 2