1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
| '''
@Author: MetaNetworks
@Date: 2020-05-23 14:04:58
@LastEditors: MetaNetworks
@LastEditTime: 2020-05-23 15:15:00
@Description: MetaNetworks' Code
'''
#rsa 公钥与私钥示例
import rsa
import base64
import time
#生成公钥与私钥
t1 = time.time()
(public_key, private_key) = rsa.newkeys(3072) # RSA加密
print("生成KEY耗费",time.time()-t1)
def rsaEncryption(public_key, cleartext):
try:
t1 = time.time()
result = rsa.encrypt(cleartext.encode(), public_key)
return base64.encodebytes(result)
finally:
t2 = time.time()
print("加密耗时",t2-t1)
# RSA解密
def rsaDecryption(public_key, ciphertext):
try:
t1 = time.time()
result = rsa.decrypt(base64.decodebytes(ciphertext), private_key)
return result.decode() #输出公钥、私钥
finally:
t2 = time.time()
print("解密耗时",t2-t1)
print(public_key.save_pkcs1())
print(private_key.save_pkcs1())
cleartext : str
with open("origin_text.txt",'r') as txt:
cleartext = txt.read()
ciphertext = rsaEncryption(public_key, cleartext)
print("密文:")
print(ciphertext)
with open("encrypted_text.txt",'w') as txt:
txt.write(ciphertext.decode("utf-8"))
decipher = rsaDecryption(private_key, ciphertext)
print("明文:")
print(decipher)
with open("decrypted_text.txt",'w') as txt:
txt.write(str(decipher))
|