PyCrypto 没有可以管理 RSA 密码的功能。
相反,您可以使用构建在 PyCrypto 模块之上的 ezPyCrypto (homepage) 模块。它具有更简单的界面,让您:
- 生成、导出和导入公钥和私钥
- 轻松加密和解密字符串
- 可选择将加密数据创建为电子邮件友好文本
- 签署和验证字符串(包括文档)
- 使用密码保护您的私钥
- 创建“流”,用于通过安全套接字发送数据
- 选择您喜欢的任何公钥大小(推荐 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]
这意味着,您可以使用前面的代码示例编写自己的密码处理程序,而无需安装 ezPyCrypto。在这里你可以找到很多代码示例,如何自己做:
Nullege code search
我的第一个替代解决方案:
可以使用pythonexec()函数和命令行函数“ssh-keygen”(doc):
ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]。