Extract Publickey from Privatekey input using Python

Doefi picture Doefi · Aug 22, 2016 · Viewed 12.9k times · Source

I need to generate publickey from a private key without temporary location locally like we do in sshgen.So i use this.Here iam passing my private key as input like this(while executing):

python codekey.py "-----BEGIN RSA PRIVATE KEY-----\nMIhhhhhhhhhhhhhhhh......Bidqt/YS3/0giWrtv+rMkJtv8n\nmirJ+16SZodI5gMuknvZG....................n-----END RSA PRIVATE KEY-----"

My code (codekey.py):

import sys
import io
from twisted.conch.ssh import keys
k = sys.argv[1]
rsa = keys.RSA.importKey(k)
key = keys.Key(rsa)
ssh_public = key.public().toString("openssh")
print ssh_public

error:

      Traceback (most recent call last):
    File "codekey.py", line 7, in <module>
     rsa = keys.RSA.importKey(k)
    File "/usr/lib/python2.7/dist-packages/Crypto/PublicKey/RSA.py", line                638, in importKey
     if lines[1].startswith(b('Proc-Type:4,ENCRYPTED')):
       IndexError: list index out of range

Dyanamically i need to pass key value as shown above while executing my python script and from that it will generate public key .Whether it is possible ??,i dont need to store locally,since for priveleges and key securities,dont want to hack.

Answer

qre0ct picture qre0ct · Jun 24, 2017

Here's how you can do it :

If you already have the private key you can basically make a private key object with it and then simply extract the public key from it using as :

public_key = private_key.publickey().exportKey('PEM')

assuming that private_key is your private key object.

In case you do not have this object, one way of obtaining it from the PEM encoded (PKCS#1) private key file (as you have given in your question above) would be like this :

from Crypto.PublicKey import RSA
from base64 import b64decode
pem_key = b'your private key in PEM'
key = b64decode(pem_key)
keyPriv = RSA.importKey(key)
# key now has all the components of the private 
print keyPriv.keydata
modulusN = keyPriv.n
pubExpE = keyPriv.e
priExpD = keyPriv.d
primeP = keyPriv.p
primeQ = keyPriv.q
private_key = RSA.construct((modulusN, pubExpE, priExpD, primeP, primeQ))

and then once you have the private key in the private_key objectdo the :

public_key = private_key.publickey().exportKey('PEM')