Data Signing with SHA256 using Cryptography Library

  • Share this:

Code introduction


This function uses the hashing, signing, and key loading functionalities from the cryptography library to sign data. It first loads the private and public keys, then hashes the input data using SHA256, and finally signs the hash result with the private key.


Technology Stack : cryptography

Code Type : Function

Code Difficulty : Intermediate


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

def sign_data(data, private_key_path, public_key_path):
    # Load private key
    with open(private_key_path, "rb") as key_file:
        private_key = load_pem_private_key(key_file.read(), password=None, backend=default_backend())

    # Load public key
    with open(public_key_path, "rb") as key_file:
        public_key = load_pem_public_key(key_file.read(), backend=default_backend())

    # Create a hash of the data
    hash_obj = hashes.Hash(hashes.SHA256(), backend=default_backend())
    hash_obj.update(data)
    digest = hash_obj.finalize()

    # Sign the digest
    signature = private_key.sign(
        digest,
        padding.PSS(
            mgf=padding.MGF1(hashes.SHA256()),
            salt_length=padding.PSS.MAX_LENGTH
        ),
        hashes.SHA256()
    )

    return signature                
              
Tags: