python 签名加密 解密 验签

import base64
import rsa
from time import time
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5

class EncryptedSignature(object):
    def __init__(self):
        self.PUB_KEY=open('public.pem', 'r').read()
        self.PRI_KEY = open('private.pem', 'r').read()


    def make_pem(self,public_path="public.pem",private_path="private.pem"):
        (pubkey, privkey) = rsa.newkeys(1024)
        # 生成公钥
        pub = pubkey.save_pkcs1()
        pubfile = open(public_path, 'wb')
        pubfile.write(pub)
        pubfile.close()
        # 生成私钥
        pri = privkey.save_pkcs1()
        prifile = open(private_path, 'wb')
        prifile.write(pri)
        prifile.close()

    def encrypt(self,message,length=100):
        rsakey = RSA.importKey(self.PUB_KEY)
        cipher = Cipher_pkcs1_v1_5.new(rsakey)
        cipher_text = base64.b64encode(cipher.encrypt(message.encode("utf8")))
        return cipher_text.decode()

    def decrypt(self,data,length=100):
        rsakey = RSA.importKey(self.PRI_KEY)
        cipher = Cipher_pkcs1_v1_5.new(rsakey)
        text = cipher.decrypt(base64.b64decode(data), 0)
        return text.decode()

    def signer(self,message):
        rsakey = RSA.importKey(self.PRI_KEY)
        signers = PKCS1_v1_5.new(rsakey)
        digest = SHA.new()
        digest.update(message.encode())
        sign = signers.sign(digest)
        signature = base64.b64encode(sign)
        return signature.decode()

    def verify_sign(self,sign, message):
        """
         unsign: 签名
         raw_sign: 待验证签名
        """
        rsakey = RSA.importKey(self.PUB_KEY)
        verifier = PKCS1_v1_5.new(rsakey)
        digest = SHA.new()
        # Assumes the data is base64 encoded to begin with
        digest.update(message.encode())
        is_verify = verifier.verify(digest, base64.b64decode(sign))
        return is_verify
if __name__ == '__main__':
    messge="khgkhjgKGHKkjlahdlkh.1638249910"
    #**********签名-加密********
    ec=EncryptedSignature()
    sig=ec.signer(messge)
    enc=ec.encrypt(messge)
    print("签名内容:",sig)
    print("加密内容:",enc)
    #*********解密-验签**********
    text=ec.decrypt(enc)

    unsign=ec.verify_sign(sig,text)
    print("解密结果:",text)
    print("验签结果:",unsign)
    tt=text.rsplit('.',1)[1]
    tt=int(tt)
    now_time=time()
    print(now_time-tt)






  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值