Python
from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives.serialization import load_pem_public_key def verify_signature(public_key_path, message, signature): with open(public_key_path, 'rb') as key_file: public_key = load_pem_public_key(key_file.read()) 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.") return True except Exception: print("Signature is invalid.") return False # Usage example public_key_path = 'public_key.pem' message = b'This is the message that was signed.' signature = b'\x00\x11\x22...' # Replace with the actual signature verify_signature(public_key_path, message, signature)
Here's how you can use the code:
- Replace
'public_key.pem'
with the path to your public key file. Make sure the key is in PEM format. - Replace
message
with the message that was signed. - Replace
signature
with the actual signature you want to verify.
When you run the code, it will load the public key from the specified file, verify the signature against the message, and print whether the signature is valid or invalid.
Make sure you have the cryptography
library installed before running the code. You can install it using pip:
pip install cryptography
Note that this code assumes you have a public key and a signature in hand. If you need to generate keys and sign messages as well, let me know, and I can provide additional code for that.