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!") else: 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 = hl.new('sha256') h.update(b'May the Force be with you !') h.digest() #for hexdigest h.hexdigest()
new() requires name of algorithm to produce generator. To find out all available algorithms use below:
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 = hl.new('sha256') with open('testfile', 'r' ) as f: rr = f.read() h.update(rr) print h.hexdigest() # for larger files size = 66666 h = hl.new('sha256') with open('testfile','r') as f: rr = f.read(size) while len(rr) > 0: h.update(rr) rr = f.read(size) print(h.hexdigest())
More on upcoming posts.
Hope It Helps !
Happy Learning 🙂