Generate Hash with Private Key for Data Integrity and Authenticity

  • Share this:

Code introduction


This function uses a private key to sign the data, generating a hash value for verifying the integrity and authenticity of the data.


Technology Stack : cryptography

Code Type : Encryption function

Code Difficulty : Intermediate


                
                    
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.serialization import load_pem_private_key
from cryptography.hazmat.backends import default_backend

def generate_hash(data, private_key_path):
    # Load the private key from a PEM file
    with open(private_key_path, 'rb') as key_file:
        private_key = load_pem_private_key(key_file.read(), password=None, backend=default_backend())

    # Generate a hash of the data using the private key
    hash_value = private_key.sign(
        data.encode('utf-8'),
        padding.PSS(
            mgf=padding.MGF1(hashes.SHA256()),
            salt_length=padding.PSS.MAX_LENGTH
        ),
        hashes.SHA256()
    )

    return hash_value                
              
Tags: