Last active
February 9, 2022 02:20
-
-
Save cbscribe/1cf127d0791c7cdfe409e296cabcc018 to your computer and use it in GitHub Desktop.
Python RSA tools
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Run `pip install pycryptodome` to install Crypto library | |
| from Crypto.PublicKey import RSA | |
| from Crypto.Signature import pss | |
| from Crypto.Hash import SHA256 | |
| import base64 | |
| def sign(): | |
| with open("private.key", "r") as file: | |
| data = file.read() | |
| private_key = RSA.import_key(data) | |
| msg = input("Message: ").encode() | |
| hashed = SHA256.new(msg) | |
| signature = pss.new(private_key).sign(hashed) | |
| with open("signed_message.txt", "w") as output: | |
| output.write(msg.decode()) | |
| output.write("\n--\n") | |
| output.write(base64.b64encode(signature).decode()) | |
| # print(base64.b64encode(signature).decode()) | |
| def verify(): | |
| keyfile = input("Public key: ") | |
| with open(keyfile, "r") as f: | |
| data = f.read() | |
| public_key = RSA.import_key(data) | |
| msg = input("Message: ").encode() | |
| signature = input("Signature: ").encode() | |
| signature = base64.b64decode(signature) | |
| hashed = SHA256.new(msg) | |
| try: | |
| pss.new(public_key).verify(hashed, signature) | |
| print("Verified") | |
| except: | |
| print("Verification failed") | |
| choice = input("(S)ign or (V)erify: ").lower() | |
| if choice == "s": | |
| sign() | |
| elif choice == "v": | |
| verify() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment