Last active
July 2, 2022 05:15
-
-
Save alairock/8cea6861e4ab803f5f4d96cdeb0ae639 to your computer and use it in GitHub Desktop.
Simplify RSA encode and decode messages with the python rsa library.
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
import base64 | |
import os | |
import rsa | |
def load_priv_key(path): | |
path = os.path.join(os.path.dirname(__file__), path) | |
with open(path, mode='rb') as privatefile: | |
keydata = privatefile.read() | |
return rsa.PrivateKey.load_pkcs1(keydata) | |
def load_pub_key(path): | |
path = os.path.join(os.path.dirname(__file__), path) | |
with open(path, mode='rb') as pubfile: | |
keydata = pubfile.read() | |
return rsa.PublicKey.load_pkcs1(keydata) | |
def verify(message, signature, pubkey): | |
signature = base64.b64decode(signature) | |
return rsa.verify(message, signature, pubkey) | |
def sign(message, privkey): | |
signature = rsa.sign(message, privkey, 'SHA-1') | |
return base64.b64encode(signature) | |
def create_keys(): | |
(pubkey, privkey) = rsa.newkeys(512, True, 8) | |
with open("id_rsa.pub", "w") as text_file: | |
text_file.write(pubkey.save_pkcs1().decode('ascii')) | |
with open("id_rsa", "w") as text_file: | |
text_file.write(privkey.save_pkcs1().decode('ascii')) |
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
from . import rsa | |
# create keys (saved in same dir) | |
rsa.create_keys() | |
message = 'Go left at the blue tree'.encode('utf-8') | |
privkey = rsa.load_priv_key('id_rsa') | |
pubkey = rsa.load_pub_key('id_rsa.pub') | |
# sign message | |
signature = rsa.sign(message, privkey) | |
# verify signature | |
is_verified = rsa.verify(message, signature, pubkey) | |
print(is_verified) |
👍
Great
Saved me a few hours - thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cool!