| by Arround The Web | No comments

Python Hashlib SHA256

The “Secure Hash Algorithms” (SHA) are a type of encryption technique that converts data into a unique string of characters. These algorithms are utilized for different purposes, including protecting passwords and ensuring data security. The SHA256 algorithm is applied/executed to the particular string or files and generates encoded data.

This Python write-up will present a detailed guide on Python hashlib sha256 using various examples. To get started, follow the below contents:

What is SHA256 Hashing Algorithm?

The “SHA256”, which is also known as “Secure Hash Algorithm 256-bit”, is a cryptographic hash function. This function belongs to the “SHA-2” family and is widely utilized in different applications, including password storage,  signing things digitally, and others.

The “SHA256” algorithm is applied to the string or file and generates a fixed-size output of “256” bits which is commonly known as a hash value.

How to Implement a Python SHA256 Algorithm?

To execute the “sha256” algorithm in Python, the “hashlib.sha256()” constructor method of the “hashlib” module is used in Python. This constructor method accepts the byte-like values and retrieves the hash value. Because it takes only byte-like objects that is why the input string is encoded into byte using the “encode()” method. The “hexdigest()” method can also be utilized with this constructor method to convert the output into the hexadecimal format.

Let’s look at the examples below to get a better understanding.

Example 1: Implement SHA256 For Single String Using Python “hashlib” Module

In the following code, the “hashlib” module is imported, and the string is defined. The “hashlib.sha256()” method takes the bytes data, which is converted from string using the “encode()” method. The “hashlib.sha256()” method output is used along with the “hexdigest()” method to retrieve the hexadecimal object:

import hashlib
str1 = 'Hello and Welcome to Python Guide!'
print(str1, '\n')
output = hashlib.sha256(str1.encode('utf-8'))
print(output.hexdigest())

The above code execution retrieves the following output:

Example 2: Implement SHA256 For Input User String Using Python “hashlib” Module

We can also implement the “sha256” to the user input string. Here in the below code, the “hashlib.sha256()” takes the encoded version of the input string and retrieves the hexadecimal value:

import hashlib
str1 = input('Enter String: ')
output = hashlib.sha256(str1.encode('utf-8'))
print(output.hexdigest())

The above code successfully implements the sha256 on user input:

Example 3: Implement SHA256 For Entire File Using Python “hashlib” Module

We can also implement sha256 for the entire file using the “hashlib.sha256()” method of the “hashlib” module. Here is the content of the file, along with its name:

Now, in the below code, the “hashlib” module is imported, and the specified text file is opened in binary “rb” mode using the “with open()” function. The “for” loop is used to iterate over the file object and implement the sha256 algorithm to the entire file using the “hashlib.sha256()” method:

import hashlib
with open(r'C:\Users\p\Documents\program\sample.txt', 'rb') as f:
    for line in f:
        res = hashlib.sha256(line.rstrip())
        print(res.hexdigest())

The sha256 has been implemented into an entire file:

Example 4: Implement SHA256 for the List of Strings Using Python “hashlib” Module

We can also hash the list of strings using the “hashlib.sha256()” method. In the below code, the “hashlib” module is imported, and the list of strings is initialized in the program. Next, an empty string is declared, and the for-loop loops/iterates over the list of strings. For each iteration, the “hashlib.sha256()” method is applied to the individual string in the list of strings and retrieves the hash value. The “append()” method is used to combine all the hash values and store them in an empty string “new_str1”:

import hashlib
str1 = ['Python Guide', 'Linux Guide', 'Java Guide']
new_str1 = []
for string in str1:
    new_str1.append(hashlib.sha256(string.encode('utf-8')).hexdigest())
print(new_str1)

The hash value of the input list of strings has been retrieved successfully:

Example 5: Implement SHA256 for Pandas DataFrame Columns Using Python “hashlib” Module

We can also implement the sha256 algorithm on the specified columns of the Pandas DataFrame using the “hashlib.sha256()” constructor method. In the below code, we defined the function that retrieves the hash value. The DataFrame is created, and the “apply()” function is used to apply this hash function to the specified DataFrame columns:

import hashlib
import pandas
def hashfunc(str1):
    return hashlib.sha256(str1.encode('utf-8')).hexdigest()

df = pandas.DataFrame.from_dict({
    'Id_no': [45, 55, 65],
    'String': ['Java48', 'Linux%2', 'Python43']})
print(df, '\n')

df['Hashed String'] = df['String'].apply(hashfunc)
print(df)

The sha256 has been implemented into a DataFrame specific column:

Conclusion

In Python, the sha256 algorithm is implemented to strings, a list of strings, files, and Pandas DataFrame columns using the hashlib.sha256() constructor method. This method is used along with the encode() and the “hexdigest()” method to encode the strings into a byte object and retrieve the hexadecimal format value. This guide presented a detailed tutorial on the “hashlib.sha256()” method of the “hashlib” module using numerous examples.

Share Button

Source: linuxhint.com

Leave a Reply