Friday, May 15, 2015

Cryptography with Python 3

In 2012 I posted a post on using PyCrypto with Python 3 and some AES and RSA examples. Now, I usually use the cryptography Python library (implemented for both Python 2 and 3). I have ported all my PyCrypto examples from 2012 (see the README file) to the cryptography library. / [src] is a small example using AES to encrypt and decrypt a text:

> python3

The example includes two versions, one using the high level Fernet class and the other using the more low level hazmat functions. In [src] the second version is implemented using CBC mode (where padding is necessary):

> python3 / /

An example with three programs. [src] is used to generatea RSA key-pair. To generate an RSA key pair stored in the file k1 and protected with the password "passwd" is done with the following command (the public key is stored in the file):

> python3 k1 "passwd" [src] generates an AES key and use this key to encrypt plaintext data read from stdin (README in the example below). The ciphertext is written to stdout (CIPHER in the example below). The AES key is encrypted using the public RSA key generated above and then saved to file k2 (no password needed since the public key is not password protected):

> python3 k2 < README > CIPHER [src] reads the encrypted AES key k2 end decrypts it using the RSA key k1 (k1 is protected with the password "passwd"). It then use the AES key to decrypt the ciphertext data read from stdin (CIPHER in the example below). The plaintext is written to stdout:

> python3 k1 k2 "passwd" < CIPHER /

An example with two programs, a server [src] and a client [src]. The example demonstrates secure communication using AES. The shared key is generated from a password (the shared secret). We are using CTR mode, and the initial value (for the counter) is sent first in the first message. First start the server then the client:

> python3 localhost 3456 "mypass" &
> python3 localhost 3456 "mypass"

These two programs are using the tcp module from NOOP project (currently, only a few of the modules from the NOOP project are released, May 2015). /

An example with two programs, a sender [src] and a receiver [src]. The example demonstrates secure communication using a combination of RSA and AES. The sender use the public RSA key of the receiver to encrypt the first message sent to the receiver. This message contains the shared secret AES key of the session. Then the sender sends a message encrypted with this key. First start the receiver then the sender:

> python3 k1 localhost 3456 "passwd" &
> python3 localhost 3456

These two programs are also using the tcp module from NOOP project.


This code is not meant to be robust. All error checking is ignored.