• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

python 搞代码 4年前 (2022-01-09) 43次浏览 已收录 0个评论

最近有需求,需要研究一下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_<b style="color:transparent">本文来源gao@!dai!ma.com搞$$代^@码网*</b>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编解码介绍的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python rsa加密解密和base64编解码介绍
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址