Security and Cryptography with Python

Python is one of the famous programming langauges among users due to its vast applications and libraries.
Python has a great potential in security and cryptography.
Let us explore different cryptographic features and implementation in python and its uses in computer and network security to hashing and encryption/decryption algorithms.


Secure password Hashing:

To perform secure password hashing we can used hashlib library that provides the PBKDF2(Password Based Key Derivation Function 2) algorithm.
PBKDF2 is vulnerable to brute-force attacks, but generating original password from stored hash can be expensive.
we can use any digest algorithm with PBKDF2, SHA256 is usually recommended.
A random salt is stored along with hashed password in order to compare entered password to stored hash.


import hashlib as hl
import os
salt = os.urandom(10)
hash = hl.pbkdf2_hmac('sha256', b'password', salt, 10000)
#To get hash in hexadecimal
import binascii as ba
hexhash = ba.hexlify(hash)

bcrpyt and scrpyt are considered stronger against brute-force attacks in comparison to pbkdf2.

Secure password hashing with bcrpyt:

import bcrypt
password = b"super secret password"
# Hash a password for the first time, with a randomly-generated salt
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
# Check that an unhashed password matches one that has previously been
# hashed
if bcrypt.checkpw(password, hashed):
print("It Matches!")
print("It Does not Match :(")


Calculating a Message Digest:

We can use generators provided by hashlib module to convert an arbitrary string into a fixed-length digest. A new method is used as generator.


import hashlib as hl
h ='sha256')
h.update(b'May the Force be with you !')
#for hexdigest


new() requires name of algorithm to produce generator. To find out all available algorithms use below:



File Hashing:

Hashing files is advantageous for many reasons. We can use hashes to check if files are identical or if content of files have been modified. A hash function converts a variable length sequence of bytes to a fixed length sequence.


import hashlib as hl
h ='sha256')
with open('testfile', 'r' ) as f:
        rr =
print h.hexdigest()
# for larger files
size = 66666
h ='sha256')
with open('testfile','r') as f:
       rr =
       while len(rr) > 0:
                rr =



More on upcoming posts.

Hope It Helps !

Happy Learning 🙂

Leave a Reply

Up ↑

%d bloggers like this: