python rsa 加密解密

yipeiwu_com5年前Python基础

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

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

 #/usr/bin/env python
# -*- coding: utf-8 -*-
import rsa
import sys
import base64
# 打印 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))
with open('public.pem') as publickfile:
 p = publickfile.read()
 print(type(p))
 pubkey = rsa.PublicKey.load_pkcs1(p.encode('utf-8'))
with open('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 = ''
for i in cry_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 ----")
assert crypto == crypto_tra
print(crypto)
print("---- 8 ----")
plaintext = rsa.decrypt(crypto,privkey)
assert message == plaintext.decode('utf-8')
print(plaintext.decode('utf-8'))

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持【听图阁-专注于Python设计】!

相关文章

python groupby 函数 as_index详解

在官方网站中对as_index有以下介绍: as_index : boolean, default True For aggregated output, return object w...

查看python安装路径及pip安装的包列表及路径

查看python安装路径及pip安装的包列表及路径

一、Linux系统 查看Python路径 whereis python 此命令将会列出系统所安装的所有版本的Python的路径效果如下:  使用以下命令可分别查看Pytho...

Random 在 Python 中的使用方法

Random 在 Python 中的使用方法

1.random.random(): 会随机生成0-1之间的小数 例如: 2.random.uniform(min,max): 会随机生成 min - max 之间的小数,其中min...

python 获取字符串MD5值方法

工作中用到了MD5值来进行对文件校验,MD5本身就是一个很出色的算法,一定程度上解决了hash散列的冲突,关于MD5的内容网上也有很多,这里只要是进行一个实验,验证一下文件校验方面的工作...

centos 下面安装python2.7 +pip +mysqld

python2.7 复制代码 代码如下: wget http://www.python.org/ftp/python/2.7.6/Python-2.7.6.tar.xz yum inst...