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)
python 签名加密 解密 验签
最新推荐文章于 2024-05-01 08:51:56 发布