python rsa 加密解密 (編解碼,base64編解碼)


  最近有需求,需要研究一下RSA加密解密安全;在網上百度了一下例子文章,很少有文章介紹怎么保存、傳輸、打印加密后的文本信息,都是千篇一律的。直接在一個腳本,加密后的文本信息賦於變量,然后立馬調用解密。仔細想了一下RSA加密解密的過程,確定有二端,一端為:加密端,一端為解密端,一般不在同一台機器。在這里,我只模擬了保存在文件,然后再讀出來;關於怎以通過網絡傳輸,也是大同小異。

  用RSA加密后的密文,是無法直接用文本顯示,因為存在一些無法用文本信息編碼顯示的二進制數據。對於保存,網絡傳輸,打印不亂碼,需要通base64編碼進行轉換;base64編解碼能把一些無法直接用文件本信息編碼的二進制數據,轉換成常規的二進制數據。

 

 

 1 #/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 import rsa
 4 import sys
 5 import base64
 6 
 7 # 打印 python 版本 與 windows 系統編碼
 8 print("---- 1 ----")
 9 print(sys.version)
10 print(sys.getdefaultencoding())
11 print(sys.getfilesystemencoding())
12 
13 # 先生成一對密鑰,然后保存.pem格式文件,當然也可以直接使用
14 print("---- 2 ----")
15 (pubkey, privkey) = rsa.newkeys(1024)
16 pub = pubkey.save_pkcs1()
17 print(type(pub))
18 pubfile = open('public.pem','w+')
19 pubfile.write(pub.decode('utf-8'))
20 pubfile.close()
21 
22 print("---- 3 ----")
23 pri = privkey.save_pkcs1()
24 print(type(pri))
25 prifile = open('private.pem','w+')
26 prifile.write(pri.decode('utf-8'))
27 prifile.close()
28 
29 # load公鑰和密鑰
30 print("---- 4 ----")
31 message = 'dPabdbGDpFTrwwgydVafdlsadlfsal%46645645s'
32 print('message:',type(message))
33 with open('public.pem') as publickfile:
34     p = publickfile.read()
35     print(type(p))
36     pubkey = rsa.PublicKey.load_pkcs1(p.encode('utf-8'))
37 with open('private.pem') as privatefile:
38     p = privatefile.read()
39     print(type(p))
40     privkey = rsa.PrivateKey.load_pkcs1(p.encode('utf-8'))
41 
42 # 用公鑰加密、再用私鑰解密
43 crypto = rsa.encrypt(message.encode('utf-8'),pubkey)
44 print(crypto)
45 
46 print("---- 5 ----")
47 print('crypto:',type(crypto))
48 print('cry_base64:',base64.encodestring(crypto))
49 print('cry_base64_utf8:',base64.encodestring(crypto).decode('utf-8'))
50 # 保存到本地文件
51 cry_file = open('cry_file.txt','w+')
52 cry_file.write(base64.encodestring(crypto).decode('utf-8'))
53 cry_file.close()
54 
55 print("---- 6 ----")
56 # 從本地文件讀取
57 cry_file = open('cry_file.txt','r')
58 cry_text = ''
59 for i in cry_file.readlines():
60     cry_text += i
61 
62 print('cry_text_type:',type(cry_text))
63 print('cry_text:',cry_text)
64 print('cry_base64:',cry_text.encode('utf-8'))
65 crypto_tra = base64.decodestring(cry_text.encode('utf-8'))
66 
67 print("---- 7 ----")
68 assert crypto == crypto_tra
69 print(crypto)
70 
71 print("---- 8 ----")
72 plaintext = rsa.decrypt(crypto,privkey)
73 assert  message == plaintext.decode('utf-8')
74 print(plaintext.decode('utf-8'))

 


免責聲明!

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



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