Forked from lkdocs/Python PyCrypto: Sign Data Example.py
Last active
May 12, 2018 04:32
-
-
Save muttiopenbts/48e1699faab0c6b57ff3d9a17a8f7fd5 to your computer and use it in GitHub Desktop.
RSA sign and verify functions
This file contains 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
''' | |
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