-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.py
36 lines (27 loc) · 998 Bytes
/
test.py
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
import rsa
(publickey, privatekey) = rsa.newkeys(1000) # 对数字1000加密得到公钥和私钥
pub = publickey.save_pkcs1() # 获取公钥
# 将公钥保存到文件*************
filepub = open("public.pem", 'wb+')
filepub.write(pub)
filepub.close()
pri = privatekey.save_pkcs1() # 获取私钥
# 将私钥保存到文件***********
filepri = open('private.pem', 'wb+')
filepri.write(pri)
filepri.close()
string = "laomomoblog" # 待加密的字符串
# 取出公钥
with open('public.pem', 'r') as file_pub:
f_pub = file_pub.read()
pubkey = rsa.PublicKey.load_pkcs1(f_pub)
# 取出私钥
with open('private.pem', 'r') as file_pri:
f_pri = file_pri.read()
prikey = rsa.PrivateKey.load_pkcs1(f_pri)
# 加密字符串string
crypt = rsa.encrypt(string.encode('utf-8'), pubkey) # 使用公钥去加密字符串
# 解密
de_crypt = rsa.decrypt(crypt, prikey) # 用私钥去解密
# 解出来的de_crypt与string应该是相等的,判断一下
assert string, de_crypt