python实现RSA加密和签名以及分段加解密的方案(3)

from Crypto.Hash import SHA from Crypto.Signature import PKCS1_v1_5 as Sig_pk from Crypto.PublicKey import RSA import base64 ​ # 待签名内容 name = "musen" # 获取私钥 key = open('private.pem', 'r').read() rsakey = RSA.importKey(key) # 根据sha算法处理签名内容 (此处的hash算法不一定是sha,看开发) data = SHA.new(name.encode()) # 私钥进行签名 sig_pk = Sig_pk.new(rsakey) sign = sig_pk.sign(data) # 将签名后的内容,转换为base64编码 result = base64.b64encode(sign) # 签名结果转换成字符串 data = result.decode() print(data)

2、公钥验签

from Crypto.Hash import SHA from Crypto.Signature import PKCS1_v1_5 as Sig_pk from Crypto.PublicKey import RSA import base64 ​ ​ # 签名之前的内容 name = "musen"# 签名数据 data="X3Gg+wd7UDh4X8ra+PGCyZFUrG+6jDeQt6ajMA0EjwoDwxlddLzYoS4dtjQ2q5WCcRhxcp8fjEyoPXBmJE9rMKDjEIeE/VO0sskbJiO65fU8hgcqdWdgbVqRryhOw+Kih+I6RIeNRYnOB8GkGD8Qca+n9JlOELcxLRdLo3vx6dw=" # base64解码 data = base64.b64decode(data) # 获取公钥 key = open('public.pem').read() rsakey = RSA.importKey(key) # 将签名之前的内容进行hash处理 sha_name = SHA.new(name.encode()) # 验证签名 signer = Sig_pk.new(rsakey) result = signer.verify(sha_name, data) # 验证通过返回True 不通过返回False print(result)

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/6d233a4b6b4087d83c84b8be2b074a20.html