07.07.2023 Views

Implementing-cryptography-using-python

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 3 ■ Classical Cryptography 67

Hashing Passwords

Python, like many other languages, provides you a way to call hashing functions

that accept a message of any length and return a fixed-length result that is

referred to as a message digest or hash code. Hashing functions use specific hashing

algorithms but do not use secret keys. If the exact message is entered into

a hashing function, the same hash code will be produced.

There are several reasons to use hash codes in communications. They can

assist in ensuring the confidentiality and the integrity of the message. You can

use a number of hashing algorithms, including MD5, SHA-3, SHA-512, HAVAL,

and RIPEMD-160, just to name a few. The most important properties of hash

algorithms are that the output is not predictable, different messages do not

produce the same hash code, messages are not reversible, and given the same

value, a hash algorithm should always produce the same result.

The following example shows the SHA-512 hash values for the words password

and Password. Notice that even though only the first letter was capitalized, the

entire message digest is different.

Here is the hash value for password:

b109f3bbbc244eb82441917ed06d618b9008dd09b3befd1b5e07394c706a8bb980b1d778

5e5976ec049b46df5f1326af5a2ea6d103fd07c95385ffab0cacbc86

Here is the hash value for Password:

e6c83b282aeb2e022844595721cc00bbda47cb24537c1779f9bb84f04039e1676e6ba857

3e588da1052510e3aa0a32a9e55879ae22b0c2d62136fc0a3e85f8bb

To examine the hashed password using SHA-512, type the following into

Python:

import hashlib

plaintext_password = b'Password'

hashed_sha512 = hashlib.sha512(plaintext_password).hexdigest()

print(hashed_sha512)

There are two primary ways to attack hash functions: through cryptanalysis

and through brute force. Storing passwords in the database in their hash code

form still offers malicious users a way to figure out passwords. A rainbow table,

which is a precomputed table for reversing cryptographic hash functions, can

be used to crack password hashes. Rainbow tables are used in recovering a

plaintext password up to a certain length consisting of a limited set of characters.

This is where salting and stretching come in.

Salting Passwords

You have learned that you need to use cryptographic hashing to minimize

readability when storing passwords, but just hashing alone isn’t enough. Salting

is the process of adding or concatenating a random chunk of bits to the end of

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!