Sign Data with PEM Private Key

  • Share this:

Code introduction


This function uses the cryptography library to sign the given data. It accepts a path to a PEM encoded private key file and the data to be signed as input, and returns the signature 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

def sign_data(private_key_path, data):
    """
    Sign the given data using a private key.

    Args:
        private_key_path (str): The path to the PEM encoded private key file.
        data (bytes): The data to be signed.

    Returns:
        bytes: The signature of the data.
    """
    with open(private_key_path, 'rb') as key_file:
        private_key = load_pem_private_key(key_file.read(), password=None)
    
    signature = private_key.sign(
        data,
        padding.PSS(
            mgf=padding.MGF1(hashes.SHA256()),
            salt_length=padding.PSS.MAX_LENGTH
        ),
        hashes.SHA256()
    )
    
    return signature                
              
Tags: