How to add / change password for RSA private key using PyCrypto

Maybe someone can help me. I use PyCrypto to generate an RSA key pair. Public key and private key. I am trying to add / change a password to a private key, and I do not know how to do this.

This is part of my code.

#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 

In M2Crypt, the function generates a pair key. RSA.gen_key accepts a function callback argument, and I can return my own password.

 #example in M2Crypt: from M2Crypto import RSA key = RSA.gen_key(1024, 6528, lambda pass:'my_password') 

How to do it in PyCrypto. thanks for the answer

+6
source share
2 answers

PyCrypto does not have a function that can manage the RSA passphrase.

Instead, you can use ezPyCrypto ( homepage ), which is built on top of the PyCrypto module. It has a simpler interface and allows you to:

  • Generate, export, and import public and private keys
  • Easy to encrypt and decrypt strings
  • It is possible to create encrypted data in the form of text, convenient for e-mail.
  • Sign and verify the lines (including documents)
  • Protect your private key with a passphrase
  • Create "streams" to send data through secure sockets
  • Choose any public key size you like (2048 bit recommended)
  • Choose between RSA and ElGamal for the public key, as well as IDEA, DES3, Blowfish, ARC4, IDEA for the session key.
  • Rest in safety, with 256-bit session keys and protection against common RSA and ElGamal attacks, which will painfully upset anyone who wants to violate your privacy.

Application:

 """ 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 plunder dec2 = k2.decString(enc) 

Build it

If you look at the source of ezCryptoPy, you will see that the key is actually encrypted / decrypted using the 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] 

This means that you can write your own passphrase processor using the previous code example without installing ezPyCrypto. Here you can find many code examples on how to do it yourself: Search for a zero word

My first and alternative solution:

You can use the python function exec () and the command line function "ssh-keygen" ( doc ):

ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile] .

+2
source

To download a key with a phrase, see the RSA module description

ImportKey Description

importKey(externKey, passphrase=None)

Import an RSA key (public or private half) encoded in standard form.

See RSAImplementation.importKey.

Options:

  • externKey (string) - The RSA key to import, encoded as a string.

    The RSA public key can be in any of the following formats:

    • X.509 subjectPublicKeyInfo DER SEQUENCE (binary or PEM encoding)
    • PKCS # 1 RSAPublicKey DER SEQUENCE (binary or PEM encoding)
    • OpenSSH (text public key only)

    The RSA private key can be in any of the following formats:

    • PKCS # 1 RSAPrivateKey DER SEQUENCE (binary or PEM encoding)
    • PKCS # 8 PrivateKeyInfo DER SEQUENCE (binary or PEM encoding)
    • OpenSSH (text public key only)

    For more information on PEM encoding, see RFC1421 / RFC1423.

    In the case of PEM encryption, the private key can be encrypted using DES or 3TDES according to a specific phrase. Only OpenSSL compatible passwords are supported.

  • passphrase (string). In the case of an encrypted PEM key, this is the pass phrase, from which the encryption key is derived.

Return:

RSA Key Object (_RSAobj).

Raises:

  • ValueError / IndexError / TypeError . If the given key cannot be analyzed (possibly because the wrong phrase is incorrect).

Example:

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

To save a key with a phrase, see the description of the _RSAobj object .

Description of exportKey

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

Export this RSA key.

Options:

  • format (string) - the format used to wrap the key.
    • 'DER'. Binary encoding, always unencrypted.
    • 'PEM'. Text encoding in accordance with RFC1421 / RFC1423. Unencrypted (default) or> encrypted.
    • 'OpenSSH'. Text encoding performed in accordance with the OpenSSH specification. Available only for public keys (not private keys).
  • passphrase (string) - in the case of PEM, the phrase to get the encryption key.
  • pkcs (integer) - The PKCS standard for key assembly. You have two options:

    • with 1, the public key is embedded in the X.509 SubjectPublicKeyInfo DER SEQUENCE. The private key is built into PKCS # 1 RSAPrivateKey DER SEQUENCE. This mode is the default.
    • Since 8, the private key is embedded in PKCS # 8 PrivateKeyInfo DER SEQUENCE. This mode is not available for public keys. PKCS standards are not OpenSSH format.

Return:

A string of bytes with an encoded public or private half.

Raises:

  • ValueError . If the format is unknown.

Example:

 from Crypto.PublicKey import RSA with open("key.pem", "r") as privatekey: encryptor = RSA.importKey(privatekey, passphrase="my secret") 
+1
source

All Articles