Extract Publickey from Privatekey input using Python

自古美人都是妖i 提交于 2019-12-11 05:58:51

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/39074253/extract-publickey-from-privatekey-input-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!