from base64 import b64encode, b64decode
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
def private_key_signature(message, privatefile):
#use private key certificate to signature
privatekey = RSA.importKey(_read_file(privatefile))
signer = PKCS1_v1_5.new(privatekey)
return b64encode(signer.sign(SHA.new(message)))
def public_key_verify(message, sign, publicfile):
#use public key certificate to verify
publickey = RSA.importKey(_read_file(publicfile))
verifier = PKCS1_v1_5.new(publickey)
return verifier.verify(SHA.new(message), b64decode(sign))
def _read_file(file_path):
with open(file_path, 'rb') as fp:
return fp.read()
结果如下:
In [2]: sign = private_key_signature('123456', 'private.pem')
In [3]: sign
Out[3]: 'Uwa55Oa+ru/QbWBnax7jtjKKNbPHk2Nhe1m8BeS2JmDmd0zHQ0oKq6QJ4A23bG51R/kDhz9J/ipsIPpI7lCWzyM7O91SuSAlnq19XpywOB+uk/4RT/Q8AAndbhPlvP0gYxIkd6BKeWckfjvoBvN0fnM17fHpLo0LJwbYrr6zB6g='
In [6]: result = public_key_verify('123456', sign, 'public.pem')
In [7]: result
Out[7]: True
网友评论