本文来源公众号“python”,仅用于学术分享,侵权删,干货满满。
原文链接:Github 3.1k star,一个有趣的 Python 库--pycryptodome!
大家好,今天为大家分享一个有趣的 Python 库 - pycryptodome。
Github地址:https://github.com/Legrandin/pycryptodome
pycryptodome是一个功能强大的Python密码学库,是pycrypto库的现代化替代品。它提供了全面的密码学功能,包括对称加密、非对称加密、哈希算法、数字签名等。该库具有良好的性能、安全性和易用性,广泛应用于网络安全、数据保护、身份验证等领域。
安装
1、安装命令
pip install pycryptodome
2、验证安装
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
# 验证安装成功
print("pycryptodome安装成功!")
print(f"随机生成的密钥: {get_random_bytes(16).hex()}")
只要特性
-
全面的加密算法支持:包括AES、DES、RSA、ECC等主流加密算法
-
高性能实现:核心算法用C语言实现,执行效率高
-
现代化设计:采用安全的默认参数,避免常见的安全陷阱
-
丰富的哈希算法:支持SHA系列、MD5、BLAKE2等哈希函数
-
数字签名功能:提供完整的数字签名和验证机制
-
跨平台兼容:支持Windows、Linux、macOS等主流操作系统
基本功能
1、对称加密(AES)
AES是目前最广泛使用的对称加密算法,适用于大量数据的快速加密。以下示例展示了如何使用AES-GCM模式进行安全加密,该模式不仅提供保密性,还能验证数据完整性。
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
# 生成密钥和明文
key = get_random_bytes(32) # 256位密钥
plaintext = b"这是需要加密的敏感数据"
# 创建AES密码器
cipher = AES.new(key, AES.MODE_GCM)
# 加密数据
ciphertext, tag = cipher.encrypt_and_digest(plaintext)
print(f"加密后的数据: {ciphertext.hex()}")
print(f"验证标签: {tag.hex()}")
# 解密数据
cipher_dec = AES.new(key, AES.MODE_GCM, nonce=cipher.nonce)
decrypted = cipher_dec.decrypt_and_verify(ciphertext, tag)
print(f"解密后的数据: {decrypted.decode()}")
2、哈希算法
哈希算法用于生成数据的数字指纹,常用于密码存储、数据完整性校验等场景。在用户注册系统中,通常使用SHA-256对密码进行哈希处理后存储,而不是直接存储明文密码。
from Crypto.Hash import SHA256, SHA3_256
# 创建待哈希的数据
data = b"用户密码123456"
# SHA-256哈希
hash_sha256 = SHA256.new(data)
print(f"SHA-256哈希值: {hash_sha256.hexdigest()}")
# SHA-3哈希
hash_sha3 = SHA3_256.new(data)
print(f"SHA-3哈希值: {hash_sha3.hexdigest()}")
3、随机数生成
密码学中的随机数生成是安全的基础,用于生成密钥、初始化向量、盐值等。在实际应用中,随机数常用于生成会话密钥、防止重放攻击的随机令牌等安全机制。
from Crypto.Random import get_random_bytes, random
# 生成随机字节
random_key = get_random_bytes(32)
print(f"随机密钥: {random_key.hex()}")
# 生成随机整数
random_int = random.randint(1000, 9999)
print(f"随机验证码: {random_int}")
高级功能
1、RSA非对称加密
在HTTPS协议中,RSA用于安全地交换对称加密密钥。以下示例展示了完整的RSA密钥生成、加密和解密过程,这在构建安全通信系统时非常有用。
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
# 生成RSA密钥对
key = RSA.generate(2048)
private_key = key
public_key = key.publickey()
# 要加密的数据
message = b"这是通过RSA加密的机密消息"
# 使用公钥加密
cipher_rsa = PKCS1_OAEP.new(public_key)
encrypted_message = cipher_rsa.encrypt(message)
print(f"RSA加密后: {encrypted_message.hex()[:50]}...")
# 使用私钥解密
cipher_rsa_dec = PKCS1_OAEP.new(private_key)
decrypted_message = cipher_rsa_dec.decrypt(encrypted_message)
print(f"RSA解密后: {decrypted_message.decode()}")
2、数字签名
通过私钥对数据进行签名,任何人都可以使用对应的公钥来验证签名的有效性,从而确保数据未被篡改且来源可信。
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
# 使用之前生成的RSA密钥
message = b"需要签名的重要文档内容"
# 创建消息哈希
hash_obj = SHA256.new(message)
# 使用私钥签名
signature = pkcs1_15.new(private_key).sign(hash_obj)
print(f"数字签名: {signature.hex()[:50]}...")
# 使用公钥验证签名
try:
pkcs1_15.new(public_key).verify(hash_obj, signature)
print("签名验证成功,数据完整且来源可信")
except:
print("签名验证失败,数据可能被篡改")
实际应用场景
1、用户密码安全存储
在Web应用开发中,用户密码的安全存储是基础安全要求。使用盐值和多轮哈希可以有效防止彩虹表攻击和暴力破解。
from Crypto.Hash import SHA256
from Crypto.Random import get_random_bytes
import time
def hash_password(password, salt=None):
if salt isNone:
salt = get_random_bytes(16)
# 多轮哈希增加破解难度
hash_obj = SHA256.new(password.encode() + salt)
for _ in range(10000): # 10000轮哈希
hash_obj = SHA256.new(hash_obj.digest())
return salt + hash_obj.digest()
# 模拟用户注册
user_password = "mySecurePassword123"
hashed_password = hash_password(user_password)
print(f"存储的密码哈希: {hashed_password.hex()}")
# 模拟用户登录验证
login_password = "mySecurePassword123"
stored_salt = hashed_password[:16]
if hash_password(login_password, stored_salt) == hashed_password:
print("密码验证成功")
else:
print("密码错误")
2、文件加密工具
文件加密是保护敏感数据的重要手段,特别适用于需要在不安全环境中存储或传输文件的场景。通过AES加密,可以确保只有拥有正确密钥的用户才能访问文件内容。
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import os
def encrypt_file(file_path, password):
# 生成密钥
key = SHA256.new(password.encode()).digest()
# 读取文件内容
with open(file_path, 'rb') as f:
file_data = f.read()
# 加密文件
cipher = AES.new(key, AES.MODE_GCM)
ciphertext, tag = cipher.encrypt_and_digest(file_data)
# 保存加密文件
encrypted_file = file_path + '.encrypted'
with open(encrypted_file, 'wb') as f:
f.write(cipher.nonce + tag + ciphertext)
return encrypted_file
# 使用示例
# encrypted_file = encrypt_file('important_document.pdf', 'myPassword123')
# print(f"文件已加密保存为: {encrypted_file}")
总结
pycryptodome库是Python生态系统中最优秀的密码学库之一,提供了完整的密码学功能实现。通过本文的介绍,分享了安装配置、核心特性,以及在对称加密、哈希计算、随机数生成、非对称加密和数字签名等方面的应用。该库不仅功能强大,而且易于使用,无论是简单的密码哈希还是复杂的加密系统构建,都能很好地满足需求。在实际开发中,合理使用pycryptodome可以大大提升应用程序的安全性,保护用户数据和系统资源。
THE END !
文章结束,感谢阅读。您的点赞,收藏,评论是我继续更新的动力。大家有推荐的公众号可以评论区留言,共同学习,一起进步。

921

被折叠的 条评论
为什么被折叠?



