from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
def generate_signature(message, private_key):
private_key_obj = RSA.import_key(private_key)
h = SHA256.new(message.encode())
signature = pkcs1_15.new(private_key_obj).sign(h)
return signature
def verify_signature(message, signature, public_key):
public_key_obj = RSA.import_key(public_key)
h = SHA256.new(message.encode())
try:
pkcs1_15.new(public_key_obj).verify(h, signature)
return True
except (ValueError, TypeError):
return False
key_pair = RSA.generate(2048)
private_key = key_pair.export_key()
public_key = key_pair.publickey().export_key()
message = "blast.hk"
signature = generate_signature(message, private_key)
verified = verify_signature(message, signature, public_key)
print(f"verified: {verified}") # verified: True