Thursday, January 31, 2013

Simple Python Encryption and Decryption

The following is a just an example of how to encrypt and decrypt a message with Python Crypto. It could be simple but took me some time to learn how to do it.

-------------------------- encrypt.py -------------------------------
#!/usr/bin/python

from Crypto.Cipher import AES
from Crypto import Random
import hashlib

# This is the password to be used
password = raw_input("Enter password: ")

# This create a 256 bit hash from the password.
key = hashlib.sha256(password).digest()

# Plain text to be encrypted
plaintext = raw_input("Enter Message: ")

# create a random iv.
iv = Random.new().read(AES.block_size)

# Create a aes object.
encobj = AES.new(key, AES.MODE_CFB, iv)

# String with iv and encrypted message
ciphertext = iv + encobj.encrypt(plaintext)

# Resulting ciphertext in hex
# Print hex because is cleaner in the terminal screen.
print ciphertext.encode('hex')

------------------------ decrypt.py ----------------------------------------

#!/usr/bin/python

from Crypto.Cipher import AES
from Crypto import Random
import hashlib

# Password to be used
password = raw_input("Enter password: ")

# Create a 256 bit hash from the password
key = hashlib.sha256(password).digest()

# Encoded message to be decrypted
cipher_msg = raw_input("Enter Cipher: ").decode('hex')

# Get iv from the first 16 charecter in the message
iv = cipher_msg[:16]
# Get the message to be decrypted
cipher = cipher_msg[16:]

# Create the AES object
encobj = AES.new(key, AES.MODE_CFB, iv)

# Decrypt the message
plaintext = encobj.decrypt(cipher)

print plaintext