Skip to content

Instantly share code, notes, and snippets.

@radupotop
Created June 5, 2023 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save radupotop/c7c06056b1965e3202465831bde430ad to your computer and use it in GitHub Desktop.
Save radupotop/c7c06056b1965e3202465831bde430ad to your computer and use it in GitHub Desktop.
from Crypto.PublicKey import RSA
from Crypto.Signature.pkcs1_15 import PKCS115_SigScheme
from Crypto.Hash import SHA256
import binascii
# Generate 1024-bit RSA key pair (private + public key)
keyPair = RSA.generate(bits=1024)
pubKey = keyPair.publickey()
# Sign the message using the PKCS#1 v1.5 signature scheme (RSASP1)
msg = b'Message for RSA signing'
hash = SHA256.new(msg)
signer = PKCS115_SigScheme(keyPair)
signature = signer.sign(hash)
print("Signature:", binascii.hexlify(signature))
# Verify valid PKCS#1 v1.5 signature (RSAVP1)
msg = b'Message for RSA signing'
hash = SHA256.new(msg)
verifier = PKCS115_SigScheme(pubKey)
try:
verifier.verify(hash, signature)
print("Signature is valid.")
except:
print("Signature is invalid.")
# Verify invalid PKCS#1 v1.5 signature (RSAVP1)
msg = b'A tampered message'
hash = SHA256.new(msg)
verifier = PKCS115_SigScheme(pubKey)
try:
verifier.verify(hash, signature)
print("Signature is valid.")
except:
print("Signature is invalid.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment