RSA digital singnature schem
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes
class RSA_Signature:
def init(self):
# Generate RSA key pair
self.private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
self.public_key = self.private_key.public_key()
def sign(self, message):
# Ensure the message is in bytes
if isinstance(message, str):
message = message.encode() # Convert string to bytes if needed
# Sign the message
signature = self.private_key.sign(
message,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
return signature
def verify(self, signature, message):
# Ensure the message is in bytes
if isinstance(message, str):
message = message.encode() # Convert string to bytes if needed
# Verify the signature
try:
self.public_key.verify(
signature,
message,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
return True
except Exception as e:
print("Signature verification failed:", e)
return False
Example usage:
if name == "main":
# Initialize RSA signature object
rsa_signature = RSA_Signature()
# Data to sign
message = "Hello, world!" # You can use a string directly here
# Sign the message
signature = rsa_signature.sign(message)
print("Digital Signature:", signature)
# Verify the signature
is_verified = rsa_signature.verify(signature, message)
print("Signature verified:", is_verified)