from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
import base64
# 私钥
private_key = '''-----BEGIN RSA PRIVATE KEY-----
5353dfggd
-----END RSA PRIVATE KEY-----
'''
# 公钥
public_key = '''-----BEGIN PUBLIC KEY-----
hfgghftetet
-----END PUBLIC KEY-----'''
def rsa_sign(plaintext, hash_algorithm=Crypto.Hash.MD5):
"""RSA 数字签名,私钥进行签名"""
signer = Signature_pkcs1_v1_5.new(RSA.importKey(private_key))
# hash算法必须要pycrypto库里的hash算法,不能直接用系统hashlib库,pycrypto是封装的hashlib
hash_value = hash_algorithm.new(plaintext.encode('utf-8'))
signature = signer.sign(hash_value)
signature = base64.b64encode(signature)
return signature.decode()
def rsa_verify(sign, plaintext, hash_algorithm=Crypto.Hash.MD5):
"""校验RSA 数字验签,公钥进行验签"""
sign = base64.b64decode(sign)
hash_value = hash_algorithm.new(plaintext.encode('utf-8'))
verifier = Signature_pkcs1_v1_5.new(RSA.importKey(public_key))
return verifier.verify(hash_value, sign)
python 实现RSA数字签名的相关教程结束。