Python: Code Snippets - Encryption

Friday 21st July 2017 1:00pm

This code snippet will encrypt and decrypt any message.

To run this script copy the code below and save to a file called encryption.py

encryption.py

#!/usr/bin/env python

# Encryption
# A quick way to encrypt and decrypt using AES
# and displays results in base 64

# Date: 07 March 2016
# Written By: Phantom Raspberry Blower

import base64
from Crypto.Cipher import AES

class Encryption():

    # Initialize
    def __init__(self, key):
        # Pad with leading zeros to ensure key length = 16
        self.key = key.zfill(16)
        self.iv = 'PRB StrikesAgain'

    # Encrypt message
    def encrypt_msg(self, msg):
        objAES = AES.new(self.key, AES.MODE_CFB, self.iv)
        cipher_txt = objAES.encrypt(msg)
        return base64.b64encode(cipher_txt)

    # Decrypt message
    def decrypt_msg(self, msg):
        objAES = AES.new(self.key, AES.MODE_CFB, self.iv)
        cipher_txt = base64.b64decode(msg)
        return objAES.decrypt(cipher_txt)

# Check if running stand-alone or imported
if __name__ == '__main__':
    from encryption import Encryption
    try:
        key = raw_input('Enter the key to encrypt: ')
        encryption = Encryption(key)
        while True:
            # Prompt user encryption passphrase
            passphrase = raw_input('Enter the passphrase to encrypt: ')
            if passphrase:
                print ''
                # Enctrypt the passhrase
                encrypt = encryption.encrypt_msg(passphrase)
                print 'Encrypted: %s' % encrypt
                # Decrypt the encrypted passphrase
                decrypt = encryption.decrypt_msg(encrypt)
                print 'Decrypted: %s' % decrypt
                print ''
            else:
                print "\nQuit"
                break
    except KeyboardInterrupt:
        print "\nQuit"

Output:

python encryption.py
Enter the key to encrypt: PRB Woz Ere
Enter the passphrase to encrypt: A message to you Rudy!

Encrypted: y1ATFeZ3qT/EzGc8Qhb0rTd4u1+TFA==
Decrypted: A message to you Rudy!

Enter the passphrase to encrypt:

Quit

 

FB Like & Share