iT邦幫忙

2024 iThome 鐵人賽

DAY 9
0
Security

網路安全基礎概念與實作系列 第 9

Day 9: 使用 Python 實作 RSA 加密與解密

  • 分享至 

  • xImage
  •  

1. 安裝PyCryptodome

跟 Day 7 實作AES加密與解密一樣要先安裝 PyCryptodome,才能夠生成 RSA 金鑰並進行加密解密,因為上次講過如何安裝,今天就先省略安裝的說明!

2. 實作 RSA 金鑰生成

以下程式碼會生成一對 RSA 公開金鑰和私密金鑰:

from Crypto.PublicKey import RSA

key = RSA.generate(2048)# 生成 2048 位的 RSA 金鑰

private_key = key.export_key()# 匯出私密金鑰
with open("private.pem", "wb") as private_file:
    private_file.write(private_key)


public_key = key.publickey().export_key()# 匯出公開金鑰
with open("public.pem", "wb") as public_file:
    public_file.write(public_key)

print("RSA 金鑰生成完成!")

3. 加密與解密的實作

生成完金鑰後,我們就可以使用這些金鑰進行加密和解密操作。

加密:
我們使用接收者的公開金鑰進行加密,這樣只有擁有對應私密金鑰的人才能解密。

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import base64

with open("public.pem", "rb") as public_file:# 載入公開金鑰
    public_key = RSA.import_key(public_file.read())


message = "這是一個機密訊息"
cipher = PKCS1_OAEP.new(public_key)# 使用公開金鑰進行加密
cipher_text = cipher.encrypt(message.encode())

cipher_text_base64 = base64.b64encode(cipher_text)# 將加密後的密文轉換成 base64 格式
print(f"加密後的訊息: {cipher_text_base64.decode()}")

解密:
接收者使用自己的私密金鑰來解密收到的密文。

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import base64

with open("private.pem", "rb") as private_file:# 載入私密金鑰
    private_key = RSA.import_key(private_file.read())

cipher = PKCS1_OAEP.new(private_key)# 使用私密金鑰進行解密
cipher_text = base64.b64decode(cipher_text_base64)  # 將 base64 轉回原本的密文
message = cipher.decrypt(cipher_text)

print(f"解密後的訊息: {message.decode()}")

4. 測試流程

  1. 生成金鑰:先執行金鑰生成程式碼,來生成公開與私密金鑰檔案。
  2. 加密訊息:使用公開金鑰來加密一段訊息。
  3. 解密訊息:使用私密金鑰來解密加密後的訊息。

上一篇
Day 8: 常用的非對稱加密 : RSA
下一篇
Day 10: 密碼攻擊手法概論
系列文
網路安全基礎概念與實作26
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言