Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muttiopenbts/48e1699faab0c6b57ff3d9a17a8f7fd5 to your computer and use it in GitHub Desktop.
Save muttiopenbts/48e1699faab0c6b57ff3d9a17a8f7fd5 to your computer and use it in GitHub Desktop.
RSA sign and verify functions
'''
pip uninstall crypto
pip install pycrypto
Tested using python 3
'''
def sign_data(private_key_loc, data, pass_phrase=None):
'''
param: private_key_loc Path to your private key
param: data, plain text data to be signed
param: pass_phrase if private key is protected
return: base64 encoded signature
'''
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
from base64 import b64encode, b64decode
key = open(private_key_loc, "r").read()
rsakey=RSA.importKey(key,passphrase=pass_phrase)
signer = PKCS1_v1_5.new(rsakey)
digest = SHA256.new()
# It's being assumed the data is base64 encoded, so it's decoded before updating the digest
digest.update(data.encode('utf-8'))
sign = signer.sign(digest)
return b64encode(sign)
def verify_sign(public_key_loc, signature, data):
'''
Verifies with a public key from whom the data came that it was indeed
signed by their private key
param: public_key_loc Path to public key
param: signature String signature to be verified
param: data, plain text data from which signature is derived from
return: Boolean. True if the signature is valid; False otherwise.
'''
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
from base64 import b64decode
pub_key = open(public_key_loc, "r").read()
rsakey = RSA.importKey(pub_key)
signer = PKCS1_v1_5.new(rsakey)
digest = SHA256.new()
# Assumes the data is base64 encoded to begin with
digest.update(data.encode('utf-8'))
if signer.verify(digest, b64decode(signature)):
return True
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment