PyCrypto has no function, which can manage RSA passphrase.
Instead, You can use ezPyCrypto (homepage) module, which is built top of PyCrypto module. It has simpler interface and lets you:
- Generate, export and import public and private keys
- Encrypt and decrypt strings with ease
- Optionally create encrypted data as email-friendly text
- Sign and verify strings (incl. documents)
- Protect your private key with a passphrase
- Create 'streams', for sending data through secured sockets
- Choose any public key size you like (2048-bit recommended)
- Choose between RSA and ElGamal for public key, and IDEA, DES3, Blowfish, ARC4, IDEA for session key
- Rest in the comfort of security, with 256-bit session keys and defences against common RSA and ElGamal attacks, which will painfully frustrate anyone seeking to violate your privacy.
Usage:
"""
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)
Build it
If you look into ezCryptoPy source,then you'll see key is actually encrypted/decrypted by using BlueFish algorithm:
# 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]
That means, you can write your own passphrase handler by using previous code example without installing ezPyCrypto. Here can you find many code examples, how do to it yourself:
Nullege code search
My first and alternative solution:
You can use python exec() function and commandline function "ssh-keygen"(doc):
ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]
.