Loading

python实现RSA加密解密方法

python3.5 安装pip

 

1 安装rsa
2 python -m pip install rsa

 

我们可以生成RSA公钥和密钥,也可以load一个.pem文件进来

 1 # -*- coding: utf-8 -*-
 2 import rsa
 3  
 4 # 先生成一对密钥,然后保存.pem格式文件,当然也可以直接使用
 5 (pubkey, privkey) = rsa.newkeys(1024)
 6  
 7 pub = pubkey.save_pkcs1()
 8 pubfile = open('public.pem','w+')
 9 pubfile.write(pub)
10 pubfile.close()
11  
12 pri = privkey.save_pkcs1()
13 prifile = open('private.pem','w+')
14 prifile.write(pri)
15 prifile.close()
16  
17 # load公钥和密钥
18 message = 'lovesoo.org'
19 with open('public.pem') as publickfile:
20     p = publickfile.read()
21     pubkey = rsa.PublicKey.load_pkcs1(p)
22  
23 with open('private.pem') as privatefile:
24     p = privatefile.read()
25     privkey = rsa.PrivateKey.load_pkcs1(p)
26  
27 # 用公钥加密、再用私钥解密
28 crypto = rsa.encrypt(message, pubkey)
29 message = rsa.decrypt(crypto, privkey)
30 print message
31  
32 # sign 用私钥签名认证、再用公钥验证签名
33 signature = rsa.sign(message, privkey, 'SHA-1')
34 rsa.verify('lovesoo.org', signature, pubkey)

持续更新

posted @ 2016-08-13 20:49  王树燚  阅读(6242)  评论(0编辑  收藏  举报