Sobes.tech
Junior — Middle

Could you explain what is meant by a digital signature in cryptography?

sobes.tech AI

Answer from AI

A digital signature is a cryptographic mechanism that allows verifying the authenticity and integrity of an electronic message or document. It is created using the sender's private key and can be verified with the corresponding public key.

Working principle:

  1. The sender creates a hash of the message (a short, unique representation of the data).
  2. The hash is encrypted with the private key — resulting in a digital signature.
  3. The recipient decrypts the signature with the sender's public key and compares it with the hash of the received message.

If they match, it means the message has not been altered and is indeed from the sender.

Example in Python using the cryptography library:

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization

# Key generation
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = private_key.public_key()

message = b"Example message"

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

# Verify the signature
try:
    public_key.verify(
        signature,
        message,
        padding.PSS(
            mgf=padding.MGF1(hashes.SHA256()),
            salt_length=padding.PSS.MAX_LENGTH
        ),
        hashes.SHA256()
    )
    print("Signature is valid")
except Exception:
    print("Signature is invalid")