跳過到頁腳內容
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 的簡單集成。 其全面的功能集,包括對認證加密模式、對稱和非對稱加密、哈希和密鑰衍生的支持,滿足了需要強大安全措施的現代應用的需求。 它的易用性、積極的維護和獨立性質使其成為在各種情境下實現安全數據處理的不可或缺工具,從密碼管理到安全文檔生成和加密,確保數據在日益數位化的世界中的完整性和機密性。

有關 IronPDF 許可的詳細信息,請參見 IronPDF 許可頁面。 若要進一步探索,請查看我們關於將 HTML 轉換為 PDF 的完整教程。

Curtis Chau
技術作家

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

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