AES and RSA PyCrypto examples with Python 3
Earlier today I wrote about installing PyCrypto for Python 3 on OS X 10.8. I will use the opportunity to provide a few examples using PyCrypto to do AES and RSA encryption and decryption. I have created 3 programs. The first one, pycrypto-mkkey.py [src], generates an RSA key and saves it in two different files. One including the private key and one with only the public key (using the .pub extension). The stored private key is password protected with the given password. The program is used like this:
python3 pycrypto-mkkey.py rsa-key "passwd"
The second program, pycrypto-encrypt.py [src], use the public RSA key to encrypt a file. Actually, the file is encrypted using AES, and the AES key is then encrypted with RSA. First the program generates a new fresh AES key and saves it to disk encrypted with the RSA key. Then it uses this AES key to encrypt the file (from stdin) and write the encrypted data to stdout. The program is used like this:
python3 pycrypto-encrypt.py rsa-key.pub aes-key < plain > cipher
The third program, pycrypto-decrypt.py [src], use the private RSA key to decrypt the file. Actually, the file is decrypted using AES, and the AES key is decrypted using RSA. First the program decrypts the AES key with the private RSA key. Then it uses this AES key to decrypt the file (from stdin) and write the decrypted data to stdout. The program is used like this:
python3 pycrypto-decrypt.py rsa-key aes-key "passwd" < cipher
Se also the README file distributed together with the programs.
Note: PyCrypto is not maintained and should not be used. Consider Cryptography (for new projects) or PyCryptodome (as a replacement for PyCrypto) instead.