Message Signing with Private Key and SHA256

  • Share this:

Code introduction


This function uses the cryptography library to sign a given message. It first loads the private key from a PEM file, then calculates the hash of the message, and finally signs the hash with the private key using the PKCS1v15 padding and SHA256 hash algorithm.


Technology Stack : cryptography, hashes, padding, serialization, default_backend, Encoding, Format, NoEncryption, load_pem_private_key, Hash, finalize, sign, PKCS1v15, SHA256

Code Type : The type of code

Code Difficulty : Advanced


                
                    
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
from cryptography.hazmat.primitives.serialization import Encoding
from cryptography.hazmat.primitives.serialization import Format
from cryptography.hazmat.primitives.serialization import NoEncryption

def sign_data(private_key_path, message):
    # 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()
        )
    
    # Create a hash of the message
    message_hash = hashes.Hash(hashes.SHA256(), backend=default_backend())
    message_hash.update(message.encode('utf-8'))
    message_hash_value = message_hash.finalize()
    
    # Sign the hash of the message with the private key
    signature = private_key.sign(
        message_hash_value,
        padding.PKCS1v15(),
        hashes.SHA256()
    )
    
    return signature