Skip to content

Instantly share code, notes, and snippets.

@Gr3yR0n1n
Forked from alairock/rsa.py
Created July 2, 2022 05:15
Show Gist options
  • Save Gr3yR0n1n/40b707b5fb7bec95f363bc8a5f299a97 to your computer and use it in GitHub Desktop.
Save Gr3yR0n1n/40b707b5fb7bec95f363bc8a5f299a97 to your computer and use it in GitHub Desktop.
Simplify RSA encode and decode messages with the python rsa library.
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'))
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment