python实验之数字签名的产生和验证

利用Python实现DSA或者RSA数字签名的产生和验证过程。
任务1:准备一个私钥文件,一个公钥文件,一个数据文件;
任务2:定义一个函数,能够使用指定的私钥对数据文件进行签名,并将签名结果输出到文件返回;
任务3:定义一个函数,能够使用指定的公钥对任务2中的签名文件进行验证,返回验证结果;
任务4:利用任务1中的文件对任务2和3中的函数进行测试。

实验步骤:在项目中新建一个 string.txt 文件,里面写入待签名数据,然后运行实验
实验结果:
在这里插入图片描述
以及生成了 file_sign.txt , prive.pem , public.pem 三个文件,其中 file_sign.txt保存了签名后的数据。

from Crypto.Hash import MD5
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto import Random
import base64


def product_key():
	# 生成一个公私钥并写入文件
    string=''
    random_rsa=Random.new().read#创建一个随机数
    prive_key=RSA.generate(1024,random_rsa)# new a price key
    public_key=prive_key.publickey()# new a public key
    with open('public.pem','w+') as file_public:
        file_public.write(str(public_key.exportKey(),'utf-8'))
    with open('prive.pem','w+') as file_prive:
        file_prive.write(str(prive_key.exportKey(),'utf-8'))

	# 从文件中读取公私钥
    # read public_key from file
    with open('public.pem', 'r+') as file_public:
        public_pem = bytes(file_public.read(), 'utf-8')
        public_key = RSA.importKey(public_pem)
    # read prive_key from file
    with open('prive.pem', 'r+') as file_prive:
        prive_pem = bytes(file_prive.read(), 'utf-8')
        prive_key = RSA.importKey(prive_pem)
    #read string from file
    with open('string.txt', 'r+') as file_txt:
        string = file_txt.read()

    return string, prive_key, public_key


def sign(message, prive_key):
    digest = MD5.new(message.encode('utf-8'))  # 生成摘要
    cipher = PKCS1_v1_5.new(prive_key)
    signature = base64.b64encode(cipher.sign(digest))  # 对摘要加密并进行base64编码
    # put the result into a file
    with open('file_sign.txt','w+') as file_sign:
        file_sign.write(str(signature, 'utf-8'))
    return


def unsign(message, public_key):
    # read signature from file
    with open('file_sign.txt', 'r+') as file_sign:
        signature=file_sign.read()
    signature = base64.b64decode(signature)
    cipher = PKCS1_v1_5.new(public_key)
    digest = MD5.new(message.encode('utf-8'))  # 生成摘要
    return cipher.verify(digest, signature)  # 摘要解密并比对摘要


[string, prive_key, public_key] = product_key()
sign(string, prive_key)
print(unsign(string, public_key))


  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值