跳至頁尾內容
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 自包含的特性,安裝過程非常簡單。 它可以通過 pip, Python的套件安裝器,使用以下命令安裝:

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 (How It Works For Developers): 圖 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 (How It Works For Developers): 圖 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 (How It Works For Developers): 圖 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 (How It Works For Developers): 圖 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 (How It Works For Developers): 圖 5 - 密碼保護輸出

IronPDF for Python

IronPDF 是一個強大的為 Python 提供 PDF 生成的程式庫,讓開發者能夠輕鬆建立、編輯和操作 PDF 文件。 它提供了一系列功能,從將 HTML 轉換為 PDF 到合併多個 PDF,使其成為自動化文件工作流程的理想選擇。 當與 PyCryptodome 結合使用時,這個強大的加密運算程式庫,開發者可以在其 PDF 文件中新增安全功能,例如加密和數位簽名。 這種整合對於需要高安全性和資料完整性的應用特別有用,如財務、法律或機密環境。

要安裝 IronPDF,您可以使用 pip, Python 的套件管理器。 以下是開始使用的方法:

pip install ironpdf

PyCryptodome (How It Works For Developers): Figure 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 (How It Works For Developers): 圖 7 - 加密文件輸出

結論

總結來說,PyCryptodome 是一個強大且多功能的 Python 程式庫,顯著增強了開發者的加密運算,提供多種類的算法和易於與其他工具整合,如 IronPDF。 PyCryptodome 以其全面的功能集,包括對認證加密模式、對稱和非對稱加密、雜湊和密鑰派生的支持,滿足了需要強大安全措施的現代應用需求。 其易用性、積極維護和自包含的特性,讓其成為實現各種情境中安全資料處理的不可缺少工具,從密碼管理到安全文件生成和加密,確保資料完整性和機密性在日益數位化的世界中。

有關 IronPDF 授權的詳細資訊,請參閱 IronPDF 授權頁面。 要進一步探索,可以查看我們的詳細教學,瞭解如何將 HTML 轉換為 PDF。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話