網(wǎng)站首頁 編程語言 正文
前言
- 加密技術(shù)在數(shù)據(jù)安全存儲(chǔ),數(shù)據(jù)傳輸中發(fā)揮著重要作用,能夠保護(hù)用戶隱私數(shù)據(jù)安全,防止信息竊取。RSA是一種非對稱加密技術(shù),在軟件、網(wǎng)頁中已得到廣泛應(yīng)用。本文將介紹RSA加密解密在python中的實(shí)現(xiàn)。
- 原則:公鑰加密,私鑰解密
- 解釋:具體過程的解釋請見代碼前的注釋
如果本文對您有幫助,不妨點(diǎn)贊、收藏、關(guān)注喲!您的支持和關(guān)注是博主創(chuàng)作的動(dòng)力!
一、安裝模塊
pip install pycryptodome
二、生成密鑰對
- 密鑰對文件生成和讀取
- 代碼:
from Crypto.PublicKey import RSA
def create_rsa_pair(is_save=False):
'''
創(chuàng)建rsa公鑰私鑰對
:param is_save: default:False
:return: public_key, private_key
'''
f = RSA.generate(2048)
private_key = f.exportKey("PEM") # 生成私鑰
public_key = f.publickey().exportKey() # 生成公鑰
if is_save:
with open("crypto_private_key.pem", "wb") as f:
f.write(private_key)
with open("crypto_public_key.pem", "wb") as f:
f.write(public_key)
return public_key, private_key
def read_public_key(file_path="crypto_public_key.pem") -> bytes:
with open(file_path, "rb") as x:
b = x.read()
return b
def read_private_key(file_path="crypto_private_key.pem") -> bytes:
with open(file_path, "rb") as x:
b = x.read()
return b
三、加密
- 流程:輸入文本(str)→字符串編碼(默認(rèn)utf-8)(bytes)→rsa加密(bytes)→base64編碼(bytes)→解碼為字符串(str)
代碼:
import base64
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
def encryption(text: str, public_key: bytes):
# 字符串指定編碼(轉(zhuǎn)為bytes)
text = text.encode('utf-8')
# 構(gòu)建公鑰對象
cipher_public = PKCS1_v1_5.new(RSA.importKey(public_key))
# 加密(bytes)
text_encrypted = cipher_public.encrypt(text)
# base64編碼,并轉(zhuǎn)為字符串
text_encrypted_base64 = base64.b64encode(text_encrypted ).decode()
return text_encrypted_base64
if __name__ == '__main__':
public_key = read_public_key()
text = '123456'
text_encrypted_base64 = encryption(text, public_key)
print('密文:',text_encrypted_base64)
四、解密
- 說明:解密流程與加密流程相反(按照加密流程逆序解密)
- 流程:輸入文本(str)→字符串編碼(默認(rèn)utf-8)(bytes)→base64解碼(bytes)→rsa解密(bytes)→解碼為字符串(str)
- 代碼:
import base64
from Crypto.Cipher import PKCS1_v1_5
from Crypto import Random
from Crypto.PublicKey import RSA
def decryption(text_encrypted_base64: str, private_key: bytes):
# 字符串指定編碼(轉(zhuǎn)為bytes)
text_encrypted_base64 = text_encrypted_base64.encode('utf-8')
# base64解碼
text_encrypted = base64.b64decode(text_encrypted_base64 )
# 構(gòu)建私鑰對象
cipher_private = PKCS1_v1_5.new(RSA.importKey(private_key))
# 解密(bytes)
text_decrypted = cipher_private.decrypt(text_encrypted , Random.new().read)
# 解碼為字符串
text_decrypted = text_decrypted.decode()
return text_decrypted
if __name__ == '__main__':
# 生成密文
public_key = read_public_key()
text = '123456'
text_encrypted_base64 = encryption(text, public_key)
print('密文:',text_encrypted_base64)
# 解密
private_key = read_private_key()
text_decrypted = decryption(text_encrypted_base64, private_key)
print('明文:',text_decrypted)
五、完整代碼
import base64
from Crypto.Cipher import PKCS1_v1_5
from Crypto import Random
from Crypto.PublicKey import RSA
# ------------------------生成密鑰對------------------------
def create_rsa_pair(is_save=False):
'''
創(chuàng)建rsa公鑰私鑰對
:param is_save: default:False
:return: public_key, private_key
'''
f = RSA.generate(2048)
private_key = f.exportKey("PEM") # 生成私鑰
public_key = f.publickey().exportKey() # 生成公鑰
if is_save:
with open("crypto_private_key.pem", "wb") as f:
f.write(private_key)
with open("crypto_public_key.pem", "wb") as f:
f.write(public_key)
return public_key, private_key
def read_public_key(file_path="crypto_public_key.pem") -> bytes:
with open(file_path, "rb") as x:
b = x.read()
return b
def read_private_key(file_path="crypto_private_key.pem") -> bytes:
with open(file_path, "rb") as x:
b = x.read()
return b
# ------------------------加密------------------------
def encryption(text: str, public_key: bytes):
# 字符串指定編碼(轉(zhuǎn)為bytes)
text = text.encode('utf-8')
# 構(gòu)建公鑰對象
cipher_public = PKCS1_v1_5.new(RSA.importKey(public_key))
# 加密(bytes)
text_encrypted = cipher_public.encrypt(text)
# base64編碼,并轉(zhuǎn)為字符串
text_encrypted_base64 = base64.b64encode(text_encrypted).decode()
return text_encrypted_base64
# ------------------------解密------------------------
def decryption(text_encrypted_base64: str, private_key: bytes):
# 字符串指定編碼(轉(zhuǎn)為bytes)
text_encrypted_base64 = text_encrypted_base64.encode('utf-8')
# base64解碼
text_encrypted = base64.b64decode(text_encrypted_base64)
# 構(gòu)建私鑰對象
cipher_private = PKCS1_v1_5.new(RSA.importKey(private_key))
# 解密(bytes)
text_decrypted = cipher_private.decrypt(text_encrypted, Random.new().read)
# 解碼為字符串
text_decrypted = text_decrypted.decode()
return text_decrypted
if __name__ == '__main__':
# 生成密鑰對
# create_rsa_pair(is_save=True)
# public_key = read_public_key()
# private_key = read_private_key()
public_key, private_key = create_rsa_pair(is_save=False)
# 加密
text = '123456'
text_encrypted_base64 = encryption(text, public_key)
print('密文:', text_encrypted_base64)
# 解密
text_decrypted = decryption(text_encrypted_base64, private_key)
print('明文:', text_decrypted)
運(yùn)行:
原文鏈接:https://juejin.cn/post/7083429856330907685
相關(guān)推薦
- 2023-06-17 Python結(jié)合Sprak實(shí)現(xiàn)計(jì)算曲線與X軸上方的面積_python
- 2022-08-18 C++詳解如何實(shí)現(xiàn)單鏈表_C 語言
- 2022-10-31 Kotlin定義其他類的實(shí)現(xiàn)詳解_Android
- 2023-06-13 C語言中求余運(yùn)算符的使用解讀_C 語言
- 2022-03-27 C++浮點(diǎn)數(shù)在內(nèi)存中的存儲(chǔ)詳解_C 語言
- 2022-09-07 Go編寫定時(shí)器與定時(shí)任務(wù)詳解(附第三方庫gocron用法)_Golang
- 2022-08-21 Android實(shí)現(xiàn)動(dòng)態(tài)曲線繪制_Android
- 2023-10-24 記ElementUI內(nèi)置的$confirm確認(rèn)消息彈框方法
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支