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)

持續更新


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM