2.8. Cryptographic Hash Functions#
A cryptographic hash function is a special type of hash function designed for security applications. Cryptographic hash functions are widely used in security protocols because they provide a way to verify the integrity of data without revealing the original content. We’ll see this in the next lesson.
Like hash functions we’ve seen so far, the hash values are fixed length and are deterministic, meaning that for a given input they produce the same output.
Unlike general hash functions however, cryptographic hash functions must meet strict security properties which are explained below.
2.8.1. Preimage Resistance#
Given a hash value \(h(s)\), it should be infeasible to determine the original input data.
This ensures that sensitive data cannot be recovered from their hash.
2.8.2. Collision Resistance#
It should be infeasible to search through all possible inputs to find pairs that generate the same hash value.
This ensures that:
an attack cannot create two inputs with the same hash, which is useful to prevent malicious data substitution
an attacker cannot modify data while keeping the same hash, which is critical for digital signatures and file integrity checks.
2.8.3. Recommended Video#
Code Challenge: Secure Hash Algorithm (SHA)
SHA-256 is a common and secure cryptographic hash function.
Using hashlib write a python script that:
asks the user to enter a message
calculates the SHA-256 hash of the message
prints the hash in hexadecimal format
Example
Enter your message to hash: hello world
Hex of SHA-256 Hash:
b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
Using hashlib
The hashlib.sha256 function accepts byte valued data, not strings. So you’ll need to convert the entered string into bytes e.g.
bytes = "hello world".encode("utf-8")
h = hashlib.sha256(bytes)
The result h from hashlib is a Hash type object. To get the hexadecimal representation of the hash you can use the hexdigest method of this object.
hex_hash = h.hexdigest()
Solution
Solution is locked