使用 Python 从私钥输入中提取公钥 [英] Extract Publickey from Privatekey input using Python

查看:82
本文介绍了使用 Python 从私钥输入中提取公钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要像我们在 sshgen 中所做的那样,从没有临时位置的本地私钥生成公钥.所以我使用这个.在这里,我将我的私钥作为输入传递,就像这样(在执行时):

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-----"

我的代码(codekey.py):

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

错误:

      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

动态地我需要在执行我的python脚本时传递如上所示的键值,并从中生成公钥.是否可能??,我不需要在本地存储,因为为了特权和关键证券,不想要破解.

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.

推荐答案

您可以这样做:

如果您已经拥有私钥,您基本上可以用它创建一个私钥对象,然后简单地使用 as 从中提取公钥:

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

假设 private_key 是您的私钥对象.

assuming that private_key is your private key object.

如果您没有此对象,则从 PEM 编码 (PKCS#1) 私钥文件(如您在上面的问题中给出)获取它的一种方法如下:

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

然后一旦您在 private_key 对象中拥有私钥,请执行以下操作:

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

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

这篇关于使用 Python 从私钥输入中提取公钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆