跳過到頁腳內容
PYTHON 幫助

在 Python 中使用 PyCryptodome 进行加密

在數位轉型時代,強大的加密機制的重要性怎麼強調都不為過。 密碼學確保資料在通過各種網路和系統傳輸時的安全性和隱私性。 PyCryptodome 是一個在加密領域脫穎而出的 Python 庫,它提供了大量功能來促進安全的資料處理,例如經過身份驗證的加密模式(GCM、CCM、EAX、SIV、OCB)和具有一流支援的加速 AES。 本文深入探討了 PyCryptodome 的最後一個官方版本,探索了其功能、用例、簡化的安裝過程,以及如何在各種應用程式中有效地利用它。 我們還將使用單獨的 C# 庫 IronPDF 和 PyCryptodome 建立加密的 PDF 檔案。

PyCryptodome 概述

PyCryptodome 是一個獨立的 Python 套件,包含底層密碼學原語。 它被設計成舊版 PyCrypto 庫的直接替代品,解決了它的許多限制並擴展了它的功能。 它提供了廣泛的加密演算法和協議,對於需要在應用程式中實現安全功能的開發人員來說,這是一個非常寶貴的工具。

主要功能

1.廣泛的演算法支援:PyCryptodome 支援一系列全面的加密演算法,包括 AES、RSA、DSA 等。 這種廣泛的支援確保開發人員能夠找到滿足各種加密需求的必要工具。 2.易用性:此程式庫的設計以使用者友善為目標,具有清晰簡潔的 API,即使是密碼學知識有限的人也能有效地實現安全功能。 3.積極維護:與前身 PyCrypto 不同,PyCryptodome 會進行積極維護,定期更新和改進,確保與最新的 Python 版本和安全標準相容。 4.自包含:PyCryptodome 不需要任何外部依賴項,因此可以輕鬆地在不同環境中安裝和使用。 5.與現有庫的整合:PyCryptodome 可以與其他 Python 庫和框架無縫集成,增強其在各種應用程式中的實用性。

安裝

由於 PyCryptodome 的獨立性,安裝過程非常簡單。 可以透過 Python 的套件安裝程式pip安裝,使用以下命令:

pip install pycryptodome
pip install pycryptodome
SHELL

核心概念和模組

PyCryptodome 由多個模組組成,每個模組都針對密碼學的不同面向。 理解這些模組對於有效利用該程式庫至關重要。

哈希

雜湊函數是密碼學的基礎,它提供了一種從任意資料產生固定大小雜湊的方法。 PyCryptodome 透過Crypto.Hash模組支援各種雜湊演算法。

SHA-256 雜湊函數的使用範例

from Crypto.Hash import SHA256

# Create a new SHA-256 hash object
hash_object = SHA256.new(data=b'Hello, PyCryptodome!')

# Output the hexadecimal digest of the hash
print(hash_object.hexdigest())
from Crypto.Hash import SHA256

# Create a new SHA-256 hash object
hash_object = SHA256.new(data=b'Hello, PyCryptodome!')

# Output the hexadecimal digest of the hash
print(hash_object.hexdigest())
PYTHON

PyCryptodome(開發者使用指南):圖 1 - 雜湊輸出

對稱加密

對稱加密使用同一個金鑰進行加密和解密。 PyCryptodome 的Crypto.Cipher模組支援多種對稱加密演算法,包括 AES、DES 等。

AES加密和解密範例

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

# Generate a random AES key
key = get_random_bytes(16)  # 16 bytes for AES-128

# Create a new AES cipher in EAX mode for encryption
cipher = AES.new(key, AES.MODE_EAX)
data = b'Secret Message'

# Encrypt the data and get the nonce, ciphertext and tag
nonce = cipher.nonce
ciphertext, tag = cipher.encrypt_and_digest(data)

# Create a new AES cipher in EAX mode for decryption
cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
plaintext = cipher.decrypt(ciphertext)

# Verify the authenticity of the message
try:
    cipher.verify(tag)
    print("The message is authentic:", plaintext)
except ValueError:
    print("Key incorrect or message corrupted")
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

# Generate a random AES key
key = get_random_bytes(16)  # 16 bytes for AES-128

# Create a new AES cipher in EAX mode for encryption
cipher = AES.new(key, AES.MODE_EAX)
data = b'Secret Message'

# Encrypt the data and get the nonce, ciphertext and tag
nonce = cipher.nonce
ciphertext, tag = cipher.encrypt_and_digest(data)

# Create a new AES cipher in EAX mode for decryption
cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
plaintext = cipher.decrypt(ciphertext)

# Verify the authenticity of the message
try:
    cipher.verify(tag)
    print("The message is authentic:", plaintext)
except ValueError:
    print("Key incorrect or message corrupted")
PYTHON

PyCryptodome(開發者使用指南):圖 2 - AES 輸出

非對稱加密

非對稱加密使用一對金鑰:用於加密的公鑰和用於解密的私鑰。 PyCryptodome 的Crypto.PublicKey模組提供對 RSA、DSA 和 ECC(橢圓曲線密碼學)的支援。

RSA加密和解密範例

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

# Generate an RSA key pair
key = RSA.generate(2048)
public_key = key.publickey()

# Encrypt the message using the public key
cipher = PKCS1_OAEP.new(public_key)
ciphertext = cipher.encrypt(b'Secret Message')

# Decrypt the message using the private key
cipher = PKCS1_OAEP.new(key)
plaintext = cipher.decrypt(ciphertext)
print(plaintext)
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP

# Generate an RSA key pair
key = RSA.generate(2048)
public_key = key.publickey()

# Encrypt the message using the public key
cipher = PKCS1_OAEP.new(public_key)
ciphertext = cipher.encrypt(b'Secret Message')

# Decrypt the message using the private key
cipher = PKCS1_OAEP.new(key)
plaintext = cipher.decrypt(ciphertext)
print(plaintext)
PYTHON

PyCryptodome(開發者使用指南):圖 3 - RSA 輸出

關鍵推導

金鑰派生函數根據密碼或口令產生加密金鑰。 這在基於密碼的加密中尤其有用。 PyCryptodome 支援 PBKDF2、scrypt 和其他金鑰派生演算法。

PBKDF2 的使用範例

from Crypto.Protocol.KDF import PBKDF2
from Crypto.Random import get_random_bytes

# Define a password and generate a salt
password = b'my secret password'
salt = get_random_bytes(16)

# Derive a key from the password and salt using PBKDF2
key = PBKDF2(password, salt, dkLen=32, count=1000000)
print(key)
from Crypto.Protocol.KDF import PBKDF2
from Crypto.Random import get_random_bytes

# Define a password and generate a salt
password = b'my secret password'
salt = get_random_bytes(16)

# Derive a key from the password and salt using PBKDF2
key = PBKDF2(password, salt, dkLen=32, count=1000000)
print(key)
PYTHON

PyCryptodome(開發者使用指南):圖 4 - PBKDF2 輸出

使用案例

密碼管理

密碼管理器可以利用 PyCryptodome 的金鑰派生功能安全地儲存和檢索使用者密碼。 透過使用像 PBKDF2 這樣的強大金鑰派生演算法,開發人員可以確保儲存的密碼能夠抵禦暴力破解攻擊。

密碼安全範例

from Crypto.Protocol.KDF import PBKDF2
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES

# Derive a strong key from a password
password = b'user_password'
salt = get_random_bytes(16)
key = PBKDF2(password, salt, dkLen=32, count=1000000)

# Encrypt the password before storing
cipher = AES.new(key, AES.MODE_EAX)
stored_password = b'ActualPassword'
nonce = cipher.nonce
ciphertext, tag = cipher.encrypt_and_digest(stored_password)

# Store ciphertext, nonce, salt, and tag securely
password_data = {
    'ciphertext': ciphertext,
    'nonce': nonce,
    'salt': salt,
    'tag': tag
}

# Decrypt the password when needed
key = PBKDF2(password, password_data['salt'], dkLen=32, count=1000000)
cipher = AES.new(key, AES.MODE_EAX, nonce=password_data['nonce'])
plaintext = cipher.decrypt(password_data['ciphertext'])

# Verify the authenticity of the password
try:
    cipher.verify(password_data['tag'])
    print("The stored password is authentic:", plaintext)
except ValueError:
    print("Key incorrect or password corrupted")
from Crypto.Protocol.KDF import PBKDF2
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES

# Derive a strong key from a password
password = b'user_password'
salt = get_random_bytes(16)
key = PBKDF2(password, salt, dkLen=32, count=1000000)

# Encrypt the password before storing
cipher = AES.new(key, AES.MODE_EAX)
stored_password = b'ActualPassword'
nonce = cipher.nonce
ciphertext, tag = cipher.encrypt_and_digest(stored_password)

# Store ciphertext, nonce, salt, and tag securely
password_data = {
    'ciphertext': ciphertext,
    'nonce': nonce,
    'salt': salt,
    'tag': tag
}

# Decrypt the password when needed
key = PBKDF2(password, password_data['salt'], dkLen=32, count=1000000)
cipher = AES.new(key, AES.MODE_EAX, nonce=password_data['nonce'])
plaintext = cipher.decrypt(password_data['ciphertext'])

# Verify the authenticity of the password
try:
    cipher.verify(password_data['tag'])
    print("The stored password is authentic:", plaintext)
except ValueError:
    print("Key incorrect or password corrupted")
PYTHON

PyCryptodome(開發者使用指南):圖 5 - 保護密碼輸出

IronPDF for Python

IronPDF 是一個功能強大的 Python PDF 生成庫,它允許開發人員輕鬆建立、編輯和操作 PDF 文件。 它提供了廣泛的功能,從將 HTML 轉換為 PDF 到合併多個 PDF,使其成為自動化文件工作流程的理想選擇。 結合強大的加密操作庫 PyCryptodome,開發人員可以為其 PDF 文件添加安全功能,例如加密和數位簽章。 這種整合對於需要高安全性和資料完整性的應用尤其有用,例如金融、法律或機密環境。

若要安裝 IronPDF,您可以使用 Python 套件管理器pip 。 以下是如何開始:

pip install ironpdf
pip install ironpdf
SHELL

PyCryptodome(開發者使用指南):圖 6 - IronPDF

安裝完成後,即可開始使用 IronPDF 建立和編輯 PDF 檔案。 下面這個簡單的範例示範如何使用 IronPDF 建立 PDF 文件,然後使用 PyCryptodome 來加密:

from ironpdf import ChromePdfRenderer
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
import os

# Create a new PDF renderer
renderer = ChromePdfRenderer()

# Render a URL as a PDF and save it
pdfFromUrl = renderer.RenderUrlAsPdf("https://ironpdf.com/")
pdfFromUrl.SaveAs("output.pdf")

# Function to encrypt a file using AES
def encrypt_file(file_name, key):
    cipher = AES.new(key, AES.MODE_CBC)  # Use AES in CBC mode
    iv = cipher.iv
    with open(file_name, 'rb') as f:
        data = f.read()
    encrypted_data = iv + cipher.encrypt(pad(data, AES.block_size))
    with open(file_name + '.enc', 'wb') as f:
        f.write(encrypted_data)

# Example usage
key = os.urandom(16)  # AES key must be either 16, 24, or 32 bytes long
encrypt_file("output.pdf", key)
from ironpdf import ChromePdfRenderer
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
import os

# Create a new PDF renderer
renderer = ChromePdfRenderer()

# Render a URL as a PDF and save it
pdfFromUrl = renderer.RenderUrlAsPdf("https://ironpdf.com/")
pdfFromUrl.SaveAs("output.pdf")

# Function to encrypt a file using AES
def encrypt_file(file_name, key):
    cipher = AES.new(key, AES.MODE_CBC)  # Use AES in CBC mode
    iv = cipher.iv
    with open(file_name, 'rb') as f:
        data = f.read()
    encrypted_data = iv + cipher.encrypt(pad(data, AES.block_size))
    with open(file_name + '.enc', 'wb') as f:
        f.write(encrypted_data)

# Example usage
key = os.urandom(16)  # AES key must be either 16, 24, or 32 bytes long
encrypt_file("output.pdf", key)
PYTHON

該腳本示範如何使用 IronPDF 建立簡單的 PDF,然後使用 PyCryptodome 中的 AES 對其進行加密,為建立更複雜、更安全的 PDF 處理應用程式奠定基礎。

PyCryptodome(開發者使用指南):圖 7 - 加密檔案輸出

結論

總而言之,PyCryptodome 是一個功能強大且用途廣泛的 Python 庫,它顯著增強了開發人員的加密操作能力,提供了廣泛的演算法,並且可以輕鬆地與其他工具(如 IronPDF)整合。 PyCryptodome 具有全面的功能集,包括支援認證加密模式、對稱和非對稱加密、雜湊和金鑰派生,能夠滿足需要強大安全措施的現代應用程式的需求。 其易用性、主動維護性和獨立性使其成為在各種場景中實施安全資料處理的不可或缺的工具,從密碼管理到安全性文件產生和加密,確保在日益數位化的世界中資料的完整性和機密性。

有關 IronPDF 許可的詳細信息,請參閱 IronPDF 許可頁面。 如需了解更多信息,請查看我們關於將 HTML 轉換為 PDF 的詳細教程。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。