最近学习RSA非对称加密,找了很多资料。发一下学习成果
RSA实例1.1生产秘钥.py
[Python] 纯文本查看 复制代码 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
[Python] 纯文本查看 复制代码 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
[Python] 纯文本查看 复制代码 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
[Python] 纯文本查看 复制代码 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
[Python] 纯文本查看 复制代码 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('签名错误')
简单的实现了加密,解密,签名,验签。然后就可以做很多事情了。
|