Python crypto toolkit, hashing and encryption

In this exercise we look at the python crypto toolkit, what it is, how it works and how it can be used.

If you need help with python refer to Python tutorial (2.7 is installed in 6218 as default python, there is also 3.2). See also:

If you feel that there is some other language that you master better, e.g., C we are not going to restrict this. With C you can use the libssl and libcrypto APIs. See also

man evp

but you will not get any ready answers, however, the assistant can help you.

Hashing

  1. Get familiar with Python Cryptography Toolkit that contains tools for encrypting, hashing and verifying information.
  2. Create a small python application that calculates MD5-hash from the inputted file and outputs the MD5 hash to stdout, e.g.
    user@computer$ python md5calculator.py file_to_be_hashed.txt
    11a5385d40feaed451aef9bd1b48f9a3 file_to_be_hashed.txt
  3. Create a small python application that can be used to verify an MD5 hash. It should accept the file name as input and the second parameter is the hash value, e.g.
    user@computer$ python md5verify.py file_to_be_hashed.txt 11a5385d40feaed451aef9bd1b48f9a3
    MD5 checksum is correct
  4. Change the applications to calculate SHA-1 value for the file (or add a new parameter that can be used to change the hash type). What changes were needed?

Examples

Example code that calculates both MD5 and SHA checksums from given file: hash.py

Usage:

python hash.py file_to_be_hashed

Example code that calculates the MD5 hash from given file and compares it to given checksum (MD5 only): verify.py

Usage:

python verify.py file_to_be_hashed 11a5385d40feaed451aef9bd1b48f9a3

Where 11a5385d40feaed451aef9bd1b48f9a3 is the previously calculated MD5 checksum.

Encryption

  1. Create a small python application that can encrypt the given file using AES (select the lenght yourself).
    1. Application accepts only filename as parameter
    2. Application asks the user for password that is used for encryption (note the length of the password)
    3. Write the length of the original file into the beginning of the encrypted file.
    4. Read and encrypt the file piece by piece and save the results as encrypted file. You have to note the length of the encrypted block.
  2. Create another application that can decrypt the file using the user provided password.

Examples

Example code that encrypts given file with user provided password (16/24/32 bytes) using AES with CBC without any IV (the default: 16 x 0x00) encrypt.py

Usage:

python encrypt.py file_to_be_encrypted

This results in a file with name file_to_be_encrypted.enc.

Example code that decrypts the given file using the user provided password: decrypt.py

Usage:

python decrypt.py file_to_be_encrypted.enc

This results in a file with name file_to_be_encrypted.org.

All examples

All python examples in one tar.gz, to unpack:

tar xzf netsec_a4_examples.tar.gz
Last modified: 2014/02/04 15:53