python rsa加密解密和base64编解码介绍

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

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

#/usr/bin/env python# -*- coding: utf-8 -*-import rsaimport sysimport 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 += iprint('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_traprint(crypto)print("---- 8 ----")plaintext = rsa.decrypt(crypto,privkey)assert  message == plaintext.decode('utf-8')print(plaintext.decode('utf-8'))

登录后复制

以上就是python rsa加密解密和base64编解码介绍的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2275918.html

(0)
上一篇 2025年2月27日 14:52:30
下一篇 2025年2月18日 15:48:47

AD推荐 黄金广告位招租... 更多推荐

发表回复

登录后才能评论