[python]Code snippet to encrypt and decrypt password.

This is a code snippet which i want to use to store a password input by user, and encrypt it. My intention is to test this code snippet so that I can store the ciphertext in a file, and decrypt the cipher text file by python

import os
from getpass import getpass as GP
from Crypto.Cipher import AES
from Crypto import Random

#Prompts password, the default prompt if not specified is Password:
#When use in terminal, password entered by user will not be echoed.
password = GP(prompt='Enter password:',stream=None)

#use os.urandom() method to create a random 16 bytes string
#convert to bytes. On this example I want to use AES-128 hence 16bytes key.
#16, 24, 32bytes are AES-128,192 and 256 bits respectively.
key = bytes(os.urandom(16))

#To generate an initializing vector, fixed block size is 16 bytes.
iv = Random.new().read(AES.block_size)

#Create a cipher to use for encryption
cipher = AES.new(key,AES.MODE_CFB,iv)

#encrypts the password entered by user
ciphertext = cipher.encrypt(password)

#ciphertext is in bytes, so i open create a file - password.enc
#write the bytes into this file
with open('password.enc', 'wb') as file:


#Create a decipher to decrypt the ciphertext
decipher = AES.new(key,AES.MODE_CFB,iv)

#read byte from file
with open('password.enc', 'rb') as file:
    ctext = file.read()
#decrypt the ciphertext
plaintext = decipher.decrypt(ctext)

#To convert the plaintext in bytes to string, use decode "utf-8"
This entry was posted in Python, Scripting and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s