一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

python rsa 加密解密

时间:2017-07-10 编辑:简简单单 来源:一聚教程网

最近有需求,需要研究一下RSA加密解密安全;在网上百度了一下例子文章,很少有文章介绍怎么保存、传输、打印加密后的文本信息,都是千篇一律的。直接在一个脚本,加密后的文本信息赋于变量,然后立马调用解密。仔细想了一下RSA加密解密的过程,确定有二端,一端为:加密端,一端为解密端,一般不在同一台机器。在这里,我只模拟了保存在文件,然后再读出来;关于怎以通过网络传输,也是大同小异。

用RSA加密后的密文,是无法直接用文本显示,因为存在一些无法用文本信息编码显示的二进制数据。对于保存,网络传输,打印不乱码,需要通base64编码进行转换;base64编解码能把一些无法直接用文件本信息编码的二进制数据,转换成常规的二进制数据。

 

 代码如下复制代码

#/usr/bin/env python

# -*- coding: utf-8 -*-

importrsa

importsys

importbase64

# 打印 python 版本 与 windows 系统编码

print("---- 1 ----")

print(sys.version)

print(sys.getdefaultencoding())

print(sys.getfilesystemencoding())

# 先生成一对密钥,然后保存.pem格式文件,当然也可以直接使用

print("---- 2 ----")

(pubkey, privkey)=rsa.newkeys(1024)

pub=pubkey.save_pkcs1()

print(type(pub))

pubfile=open('public.pem','w+')

pubfile.write(pub.decode('utf-8'))

pubfile.close()

print("---- 3 ----")

pri=privkey.save_pkcs1()

print(type(pri))

prifile=open('private.pem','w+')

prifile.write(pri.decode('utf-8'))

prifile.close()

# load公钥和密钥

print("---- 4 ----")

message='dPabdbGDpFTrwwgydVafdlsadlfsal%46645645s'

print('message:',type(message))

withopen('public.pem') as publickfile:

 p=publickfile.read()

 print(type(p))

 pubkey=rsa.PublicKey.load_pkcs1(p.encode('utf-8'))

withopen('private.pem') as privatefile:

 p=privatefile.read()

 print(type(p))

 privkey=rsa.PrivateKey.load_pkcs1(p.encode('utf-8'))

# 用公钥加密、再用私钥解密

crypto=rsa.encrypt(message.encode('utf-8'),pubkey)

print(crypto)

print("---- 5 ----")

print('crypto:',type(crypto))

print('cry_base64:',base64.encodestring(crypto))

print('cry_base64_utf8:',base64.encodestring(crypto).decode('utf-8'))

# 保存到本地文件

cry_file=open('cry_file.txt','w+')

cry_file.write(base64.encodestring(crypto).decode('utf-8'))

cry_file.close()

print("---- 6 ----")

# 从本地文件读取

cry_file=open('cry_file.txt','r')

cry_text=''

foriincry_file.readlines():

 cry_text+=i

print('cry_text_type:',type(cry_text))

print('cry_text:',cry_text)

print('cry_base64:',cry_text.encode('utf-8'))

crypto_tra=base64.decodestring(cry_text.encode('utf-8'))

print("---- 7 ----")

assertcrypto==crypto_tra

print(crypto)

print("---- 8 ----")

plaintext=rsa.decrypt(crypto,privkey)

assertmessage==plaintext.decode('utf-8')

print(plaintext.decode('utf-8'))

 

热门栏目