跳至页脚内容
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 是一个功能强大的 PDF 生成库,适用于 Python,让开发人员能够轻松创建、编辑和操作 PDF 文档。 它提供了广泛的功能,从将 HTML 转换为 PDF 到合并多个 PDF,使其成为自动化文档工作流程的理想选择。 结合 PyCryptodome 这一强大的加密操作库,开发人员可以向他们的 PDF 文档添加安全功能,如加密和数字签名。 这种集成对于需要高安全性和数据完整性的应用特别有用,如金融、法律或机密环境。

要安装 IronPDF,可以使用 pip,Python 的包管理器。 以下是开始工作的方法:

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 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。