Python is one of the famous programming languages among users due to its vast applications and libraries.
Python has 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 use Hashlib library that provides the PBKDF2(Password-Based Key Derivation Function 2) algorithm.
PBKDF2 is vulnerable to brute-force attacks, but generating the original password from the stored hash can be expensive.
we can use any digest algorithm with PBKDF2, SHA256 is usually recommended.
A random salt is stored along with the hashed password in order to compare entered password to the 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 a 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 the name of the algorithm to produce the 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 the content of files has 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 🙂