国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python rsa 加密解密

2019-11-25 16:18:18
字體:
供稿:網(wǎng)友

最近有需求,需要研究一下RSA加密解密安全;在網(wǎng)上百度了一下例子文章,很少有文章介紹怎么保存、傳輸、打印加密后的文本信息,都是千篇一律的。直接在一個腳本,加密后的文本信息賦于變量,然后立馬調(diào)用解密。仔細想了一下RSA加密解密的過程,確定有二端,一端為:加密端,一端為解密端,一般不在同一臺機器。在這里,我只模擬了保存在文件,然后再讀出來;關于怎以通過網(wǎng)絡傳輸,也是大同小異。

用RSA加密后的密文,是無法直接用文本顯示,因為存在一些無法用文本信息編碼顯示的二進制數(shù)據(jù)。對于保存,網(wǎng)絡傳輸,打印不亂碼,需要通base64編碼進行轉(zhuǎn)換;base64編解碼能把一些無法直接用文件本信息編碼的二進制數(shù)據(jù),轉(zhuǎn)換成常規(guī)的二進制數(shù)據(jù)。

 #/usr/bin/env python# -*- coding: utf-8 -*-import rsaimport sysimport base64# 打印 python 版本 與 windows 系統(tǒng)編碼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'))

以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持武林網(wǎng)!

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 临江市| 新巴尔虎左旗| 通城县| 姚安县| 宝清县| 大悟县| 类乌齐县| 伊宁市| 华坪县| 长子县| 宜宾市| 临沂市| 普宁市| 汽车| 南昌县| 双流县| 会东县| 惠东县| 张家口市| 镶黄旗| 剑川县| 安国市| 高陵县| 博野县| 全椒县| 昭苏县| 台北县| 崇义县| 凤凰县| 溧水县| 南木林县| 秦皇岛市| 新绛县| 林周县| 上饶县| 砚山县| 新营市| 岫岩| 东港市| 日照市| 邻水|