利用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))
版权声明:本文为qq_42450533原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。