Last active
May 28, 2018 23:02
-
-
Save bhavincb/6108c9ff31b21da91f42ecc1b24462ea to your computer and use it in GitHub Desktop.
python pycrypto pyopenssl sign data from private key
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
def sign(private_key_loc, policyText): | |
''' | |
param: private_key_loc Path to your private key | |
param: package PolicyText to be signed | |
return: base64 encoded signature | |
''' | |
from Crypto.PublicKey import RSA | |
from Crypto.Signature import PKCS1_v1_5 | |
from Crypto.Hash import SHA256 | |
from OpenSSL import crypto | |
from base64 import b64encode, b64decode | |
key = open(private_key_loc, "rb").read() | |
p12 = crypto.load_pkcs12(key, "notasecret") | |
pem = crypto.dump_privatekey(crypto.FILETYPE_PEM, p12.get_privatekey()) | |
rsakey = RSA.importKey(pem) | |
signer = PKCS1_v1_5.new(rsakey) | |
digest = SHA256.new() | |
# It's being assumed the data is plain text, so it's encoded before updating the digest | |
digest.update(b64encode(policyText)) | |
sign = signer.sign(digest) | |
verifier = PKCS1_v1_5.new(rsakey.publickey()) | |
verified = verifier.verify(digest, sign) | |
print verified | |
return b64encode(sign) | |
def signUsingJson(json_loc, policyText): | |
''' | |
param: private_key_loc Path to your private JSON key | |
param: package PolicyText to be signed | |
return: base64 encoded signature | |
''' | |
from oauth2client.service_account import ServiceAccountCredentials | |
from base64 import b64encode, b64decode | |
creds = ServiceAccountCredentials.from_json_keyfile_name(json_loc) | |
# It's being assumed the data is plain text, so it's encoded before updating the digest | |
signature = creds.sign_blob(b64encode(policyText))[1] | |
return b64encode(signature) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment