python 实现RSA数字签名


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)

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM