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'))
原文地址:https://www.cnblogs.com/52python/p/6589869.html