Python 如何使用PyCrypto添加/更改RSA私钥的密码

Python 如何使用PyCrypto添加/更改RSA私钥的密码,python,cryptography,rsa,Python,Cryptography,Rsa,也许有人能帮我。 我正在使用PyCrypto生成一对RSA密钥。公钥和 私钥。 我尝试向私钥添加/更改密码,但我不知道如何 去做吧 这是我的一段代码 #encoding:utf-8 from Crypto.PublicKey import RSA pass_alice='ala' private_alice_key = RSA.generate(1024) public_alice_key = private_alice_key.publickey() str_priv = private

也许有人能帮我。 我正在使用PyCrypto生成一对RSA密钥。公钥和 私钥。 我尝试向私钥添加/更改密码,但我不知道如何 去做吧

这是我的一段代码

#encoding:utf-8
from Crypto.PublicKey import RSA

pass_alice='ala'
private_alice_key = RSA.generate(1024)
public_alice_key  = private_alice_key.publickey()

str_priv = private_alice_key.exportKey()
str_pub  = public_alice_key.exportKey()

print str_priv
print str_pub

# HOW ADD OR CHANGE PASSWORD FOR private_alice_key
在M2Crypt中,函数generate pair key RSA.gen_key take give函数回调参数,我可以返回自己的密码

#example in M2Crypt:
from M2Crypto import RSA
key = RSA.gen_key(1024, 6528, lambda pass:'my_password')
如何在PyCrypto中执行此操作。
感谢您的回复

PyCrypto没有可以管理RSA密码的功能

相反,您可以使用构建在PyCrypto模块之上的ezPyCrypto()模块。它具有更简单的界面,并允许您:

  • 生成、导出和导入公钥和私钥
  • 轻松加密和解密字符串
  • 可以选择将加密数据创建为电子邮件友好文本
  • 签署并验证字符串(包括文件)
  • 使用密码短语保护您的私钥
  • 创建“流”,用于通过安全套接字发送数据
  • 选择您喜欢的任意公钥大小(建议2048位)
  • 选择RSA和ElGamal作为公钥,选择IDEA、DES3、Blowfish、ARC4和IDEA作为会话密钥
  • 使用256位会话密钥和针对常见RSA和ElGamal攻击的防御措施,您可以放心地休息,这会让任何试图侵犯您隐私的人感到痛苦
用法:

"""
example7.py
Demonstrate the use of passphrases with private keys
"""
import ezPyCrypto

mysecret = "Don't look at this!!!"
raw = "Here is a string to encrypt"

# Create a key object
k = ezPyCrypto.key(passphrase=mysecret)

# Export public/private key
publicAndPrivateKey = k.exportKeyPrivate()

# Encrypt against this keypair
enc = k.encString(raw)

# Create a new key object, and import keys (with passphrase)
k1 = ezPyCrypto.key(publicAndPrivateKey, passphrase=mysecret)

# Decrypt text
dec = k.decString(enc)

# test
if dec == raw:
    print "Successful decryption using correct passphrase"
else:
    print "Failed somewhere"

print "Trying now with a bad passphrase"
try:
    k2 = ezPyCrypto.key(publicAndPrivateKey, passphrase="cracking attempt")
except ezPyCrypto.CryptoKeyError:
    print "Oops - our feeble cracking attempt failed (which is a good thing)."
else:
    print "Cracking attempt succeeded - we're not safe"
    # We're in - let's plunder
    dec2 = k2.decString(enc)
构建它

如果查看ezCryptoPy源代码,您将看到密钥实际上是使用BlueFish算法加密/解密的:

   # decrypt against passphrase
        blksiz = 8 # lazy of me

        # create temporary symmetric cipher object for passphrase - 
        #hardwire to Blowfish
        ppCipher = Blowfish.new(passphrase,
                                Blowfish.MODE_CFB,
                                self._passIV[0:blksiz])
        enclen = len(keyobj)
        decpriv = ''
        i = 0
        while i < enclen:
            decbit = ppCipher.decrypt(keyobj[i:i+blksiz])
            decpriv += decbit
            i += blksiz
        keyobj = decpriv[0:size]
#根据密码短语解密
blksiz=8#我真懒
#为密码短语创建临时对称密码对象-
#硬接线到河豚
ppCipher=Blowfish.new(密码短语,
Blowfish.MODE_循环流化床,
self._被动[0:blksiz])
enclen=len(keyobj)
decpriv=''
i=0
而我
这意味着,您可以使用前面的代码示例编写自己的密码短语处理程序,而无需安装ezPyCrypto。在这里,您可以找到许多代码示例,您自己如何操作:

我的第一个备选解决方案:

"""
example7.py
Demonstrate the use of passphrases with private keys
"""
import ezPyCrypto

mysecret = "Don't look at this!!!"
raw = "Here is a string to encrypt"

# Create a key object
k = ezPyCrypto.key(passphrase=mysecret)

# Export public/private key
publicAndPrivateKey = k.exportKeyPrivate()

# Encrypt against this keypair
enc = k.encString(raw)

# Create a new key object, and import keys (with passphrase)
k1 = ezPyCrypto.key(publicAndPrivateKey, passphrase=mysecret)

# Decrypt text
dec = k.decString(enc)

# test
if dec == raw:
    print "Successful decryption using correct passphrase"
else:
    print "Failed somewhere"

print "Trying now with a bad passphrase"
try:
    k2 = ezPyCrypto.key(publicAndPrivateKey, passphrase="cracking attempt")
except ezPyCrypto.CryptoKeyError:
    print "Oops - our feeble cracking attempt failed (which is a good thing)."
else:
    print "Cracking attempt succeeded - we're not safe"
    # We're in - let's plunder
    dec2 = k2.decString(enc)
您可以使用python exec()函数和命令行函数“ssh keygen”():


ssh-keygen-p[-p旧密码短语][-N新密码短语][-f密钥文件]

用于加载带有短语look-at的键

导入密钥的描述
importKey(externKey,passphrase=None)

导入以标准格式编码的RSA密钥(公共或私有的一半)

请参阅rsaemplementation.importKey

参数:
  • externKey(字符串)-要导入的RSA密钥,编码为字符串

    RSA公钥可以采用以下任意格式:

    • X.509主题公钥信息序列(二进制或PEM编码)
    • PKCS#1 rs公钥序列(二进制或PEM编码)
    • OpenSSH(仅文本公钥)
    RSA私钥可以采用以下任意格式:

    • PKCS#1 RSAPrivateKey DER序列(二进制或PEM编码)
    • PKCS#8 PrivateKeyInfo序列(二进制或PEM编码)
    • OpenSSH(仅文本公钥)
    有关PEM编码的详细信息,请参阅RFC1421/RFC1423

    在PEM编码的情况下,可以根据特定的密码短语使用DES或3TDES对私钥进行加密。仅支持与OpenSSL兼容的密码短语

  • 密码短语(字符串)-对于加密的PEM密钥,这是导出加密密钥的密码短语

返回: RSA密钥对象(_RSAobj)

提出:
  • ValueError/IndexError/TypeError-无法解析给定键时(可能是因为密码短语错误)
例如:

from Crypto import RSA

key = RSA.generate(1024)
exportedKey = key.exportKey('PEM', 'my secret', pkcs=1)
from Crypto.PublicKey import RSA

with open("key.pem", "r") as privatekey:
    encryptor = RSA.importKey(privatekey, passphrase="my secret")
要使用短语保存密钥,请参见

exportKey的说明
exportKey(self,format='PEM',passphrase=None,pkcs=1)

导出此RSA密钥

参数:
  • 格式(字符串)-用于包装键的格式。
    • “德”。二进制编码,始终未加密
    • “PEM”。文本编码,根据RFC1421/RFC1423完成。未加密(默认)或>加密
    • “OpenSSH”。文本编码,根据OpenSSH规范完成。仅适用于公钥(非私钥)
  • 密码短语(字符串)-对于PEM,用于导出加密密钥的密码短语
  • pkcs(整数)-组装钥匙时要遵循的pkcs标准。你有两个选择:

    • 对于1,公钥嵌入到X.509 SubjectPublicKeyInfo序列中。私钥嵌入到PKCS#1 RSAPrivateKey DER序列中。此模式为默认模式
    • 对于8,私钥嵌入到PKCS#8 PrivateKeyInfo序列中。此模式不适用于公钥。 PKCS标准与OpenSSH格式无关
返回: 带有编码的公共或私有半字节的字节字符串

提出:
  • ValueError-格式未知时
例如:

from Crypto import RSA

key = RSA.generate(1024)
exportedKey = key.exportKey('PEM', 'my secret', pkcs=1)
from Crypto.PublicKey import RSA

with open("key.pem", "r") as privatekey:
    encryptor = RSA.importKey(privatekey, passphrase="my secret")

这似乎是ezPyCrypto的链接现在重定向到一些美味的垃圾邮件的副本;我认为这个答案无论如何都应该被认为是过时的,因为它是在2011年第一次被回应的,很快在将近7年前,现在应该有更好的图书馆;