算法学习|【Python】采用rsa实现简单的文本加密代码

采用rsa实现简单的文本加密代码,思路比较简单,直接采用rsa加密包实现,详细代码如下:

# coding: utf8 """ # rsa加密算法及加解密时间统计 #2020-03-07 #Mayongdong """ import rsa import datetimedef rsaEncrypt(str): # 生成公钥、私钥 (pubkey, privkey) = rsa.newkeys(512) print(pubkey, privkey) # 明文编码格式 content = str.encode('utf-8') # 公钥加密 crypto = rsa.encrypt(content, pubkey) return (crypto, privkey)# rsa解密 def rsaDecrypt(str, pk): # 私钥解密 content = rsa.decrypt(str, pk) con = content.decode('utf-8') return conif __name__ == '__main__': # rsa加密 startTime1 = datetime.datetime.now() str, pk = rsaEncrypt("人生怎能没有挫折,有挫折战胜它")# 原始文 print('加密后密文:', str) print(pk) end_time = datetime.datetime.now() - startTime1 print("rsa_encrypt_cost_time:", end_time)# rsa解密 startTime2 = datetime.datetime.now() content = rsaDecrypt(str, pk) print('解密后明文:', content) end_time = datetime.datetime.now() - startTime2 print("rsa_decrypt_cost_time:", end_time)

【算法学习|【Python】采用rsa实现简单的文本加密代码】运行结果:
PublicKey(11131718635291684274117869901086512417811976195186919753594551576361121776227962431382187081832008891400394217732815931514574474177793288106567878235695507, 65537) PrivateKey(11131718635291684274117869901086512417811976195186919753594551576361121776227962431382187081832008891400394217732815931514574474177793288106567878235695507, 65537, 9409909095551509968203152303587176525425080202227067982195372954673026626266753180099183434000578447231005187827328044517125648932297348534874846313804673, 7173012914231738958698457657873207228612981272344868111341345507151117956420389803, 1551888832265394018794725130010816643763228679549877901335773156420579769) 加密后密文: b'\x1d\x7f"\xf2`\xbb(\xdb\xf3w\x8cU\xf7\xd3\xab\x94\x1e3c\x05\x86\xfc\xfc\\\xd70\xf52\xbe\x83z\xfd\xc0\xdc\xc9{\x03\x02qxae\xb0jG\x983\xd39\x9b\xd9\x9f\x12W\xd7\xd2\x95\x8c!\xe5cz1F' PrivateKey(11131718635291684274117869901086512417811976195186919753594551576361121776227962431382187081832008891400394217732815931514574474177793288106567878235695507, 65537, 9409909095551509968203152303587176525425080202227067982195372954673026626266753180099183434000578447231005187827328044517125648932297348534874846313804673, 7173012914231738958698457657873207228612981272344868111341345507151117956420389803, 1551888832265394018794725130010816643763228679549877901335773156420579769) rsa_encrypt_cost_time: 0:00:00.015958 解密后明文: 人生怎能没有挫折,有挫折战胜它 rsa_decrypt_cost_time: 0:00:00.001995

整体来说加密是时间要长于解密时间。
rsa每次加密对文本长度有限制,不能超过53 bytes,如果超过会报错,例如:
str, pk = rsaEncrypt("人生怎能没有挫折,有挫折战胜它,那才叫人生!")# 原始文

这个文本的长度为64 bytes,我们点击运行后,会提示错误。
算法学习|【Python】采用rsa实现简单的文本加密代码
文章图片

    推荐阅读