Python初学RAS库实现加密,解密,签名,验签【python学习笔记】

最近看了很多资料,用python的写了RSA非对称加密,给IQ星友们分享一下我的学习成果,嘿嘿!

467470c533153726

RSA实例1.1生产秘钥.py

import rsa
import time
 
v_秘钥强度 = 128
v_开始时间 = time.time()
(v_公钥, v_私钥) = rsa.newkeys(v_秘钥强度 * 8)
print('耗时:', time.time() - v_开始时间)
with open('公钥.pem', 'w+') as f:
    f.write(v_公钥.save_pkcs1().decode())
with open('私钥.pem', 'w+') as f:
    f.write(v_私钥.save_pkcs1().decode())

RSA实例1.2公钥加密信息.py

import rsa
 
with open('公钥.pem', 'r') as f:
    v_公钥 = rsa.PublicKey.load_pkcs1(f.read().encode())
 
v_需要加密的数据 = input('输入要加密的内容:')
print(f'需要加密的原始内容:{v_需要加密的数据}')
 
# 公钥加密
v_密文 = rsa.encrypt(v_需要加密的数据.encode(), v_公钥)
 
print(f'加密后的密文:{v_密文}')
 
# 保存密文
with open('密文.b', mode='wb') as f:
    f.write(v_密文)

RSA实例1.3私钥解密信息.py

import rsa
 
# 读取私钥
with open(file='私钥.pem', mode='r') as f:
    v_私钥 = rsa.PrivateKey.load_pkcs1(f.read().encode())
 
# 读取密文
with open(file='密文.b', mode='rb') as f:
    v_密文 = f.read()
 
# 解密明文
v_解密明文 = rsa.decrypt(v_密文, v_私钥).decode()
print(f'解密后的明文:{v_解密明文}')

RSA实例1.4私钥签名信息.py

import rsa
 
# 读取私钥
with open(file='私钥.pem', mode='r') as f:
    v_私钥 = rsa.PrivateKey.load_pkcs1(f.read().encode())
 
v_需要签名的信息 = input('输入要签名的消息:')
v_签名数据 = rsa.sign(v_需要签名的信息.encode(), v_私钥, 'SHA-1')
 
with open(file='签名内容.txt', mode='w+') as f:
    f.write(v_需要签名的信息)
 
with open(file='签名.b', mode='wb') as f:
    f.write(v_签名数据)
 
print(f'私钥签名数据:{v_签名数据}')

RSA实例1.5公钥验证签名.py

import rsa
 
with open('公钥.pem', 'r') as f:
    v_公钥 = rsa.PublicKey.load_pkcs1(f.read().encode())
 
with open(file='签名内容.txt', mode='r') as f:
    v_签名数据 = f.read()
 
with open(file='签名.b', mode='rb') as f:
    v_签名 = f.read()
 
print(v_签名数据)
try:
    xx = rsa.verify(v_签名数据.encode(), v_签名, v_公钥)
    if xx=='SHA-1':
        print('签名正确')
except BaseException as e:
    print('签名错误')

用python实现了RSA的加密,解密,签名,验签,星友们就可以做更多事啦!

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享
屁屁酱的头像 - IQ星球
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情图片