Search code examples
pythondigital-signature

How to generate a digital signature of a string in Python?


I have a string and I need to generate a digital signature for it using my private key? How can I do it in Python?


Solution

  • You could use the Cryptography module to generate a private key then sign your string using RSA:

    # Generate a private key   
    >>> from cryptography.hazmat.backends import default_backend
    >>> from cryptography.hazmat.primitives.asymmetric import rsa
    >>> private_key = rsa.generate_private_key(
    ...     public_exponent=65537,
    ...     key_size=2048,
    ...     backend=default_backend()
    ... )
    
    # Sign a message using the key
    >>> from cryptography.hazmat.primitives import hashes
    >>> from cryptography.hazmat.primitives.asymmetric import padding
    >>> message = b"A message I want to sign"
    >>> signature = private_key.sign(
    ...     message,
    ...     padding.PSS(
    ...         mgf=padding.MGF1(hashes.SHA256()),
    ...         salt_length=padding.PSS.MAX_LENGTH
    ...     ),
    ...     hashes.SHA256()
    ... )
    

    If you already have a private key that you want to use, then you can load it rather than generating a new one.