Python的hashlib模块用于数据加密和验证。哈希加密可以把任意长度的数据转换成固定长度的字符串,这个字符串就像数据的"指纹"一样。
哈希加密有这些特点:
相同输入永远产生相同输出
不同输入产生不同输出
无法从输出反推输入
很小的输入变化会导致输出巨大变化
import hashlibimport hashlib
# 创建MD5哈希对象
md5_hash = hashlib.md5()
# 添加要加密的数据
md5_hash.update(b"Hello World")
# 获取加密结果
result = md5_hash.hexdigest()
print(f"MD5加密结果: {result}")输出结果:
MD5加密结果: b10a8db164e0754105b7a99be72e3fe5import hashlib
# 一步完成加密
text = "Python编程"
md5_result = hashlib.md5(text.encode()).hexdigest()
print(f"文本'{text}'的MD5值: {md5_result}")import hashlib
# SHA-256加密
text = "安全密码"
sha256_hash = hashlib.sha256(text.encode())
print(f"SHA-256: {sha256_hash.hexdigest()}")import hashlib
# SHA-512加密
text = "重要数据"
sha512_hash = hashlib.sha512(text.encode())
print(f"SHA-512: {sha512_hash.hexdigest()}")import hashlib
# 使用new函数创建哈希对象
algorithms = ['md5', 'sha1', 'sha256', 'sha512']
text = "测试数据"
for algo in algorithms:
hash_obj = hashlib.new(algo)
hash_obj.update(text.encode())
print(f"{algo:>8}: {hash_obj.hexdigest()}")对于大文件,可以分块读取和加密:
import hashlib
def hash_file(filename, algorithm='sha256'):
"""计算文件的哈希值"""
hash_obj = hashlib.new(algorithm)
try:
with open(filename, 'rb') as file:
# 分块读取文件,避免内存不足
while True:
chunk = file.read(4096) # 每次读取4KB
if not chunk:
break
hash_obj.update(chunk)
return hash_obj.hexdigest()
except FileNotFoundError:
return "文件不存在"
# 使用示例
file_hash = hash_file('example.txt')
print(f"文件哈希值: {file_hash}")哈希加密常用于密码存储:
import hashlib
import os
def hash_password(password):
"""对密码进行加密"""
# 添加随机盐值,增加安全性
salt = os.urandom(32)
password_hash = hashlib.pbkdf2_hmac(
'sha256',
password.encode(),
salt,
100000 # 迭代次数
)
return salt + password_hash
def verify_password(password, stored_hash):
"""验证密码"""
salt = stored_hash[:32] # 提取盐值
stored_password = stored_hash[32:]
new_hash = hashlib.pbkdf2_hmac(
'sha256',
password.encode(),
salt,
100000
)
return new_hash == stored_password
# 使用示例
password = "user_password123"
hashed = hash_password(password)
print(f"加密后的密码长度: {len(hashed)} 字节")
# 验证密码
is_correct = verify_password("user_password123", hashed)
print(f"密码验证结果: {is_correct}")
is_wrong = verify_password("wrong_password", hashed)
print(f"错误密码验证: {is_wrong}")哈希常用于检查文件是否被修改:
import hashlib
def create_file_hash(filepath):
"""创建文件的哈希值"""
hasher = hashlib.sha256()
with open(filepath, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b""):
hasher.update(chunk)
return hasher.hexdigest()
def verify_file_integrity(filepath, expected_hash):
"""验证文件完整性"""
actual_hash = create_file_hash(filepath)
return actual_hash == expected_hash
# 使用示例
file_path = "important_document.pdf"
# 首次计算哈希值
original_hash = create_file_hash(file_path)
print(f"文件原始哈希: {original_hash}")
# 后续验证
is_unchanged = verify_file_integrity(file_path, original_hash)
print(f"文件是否未被修改: {is_unchanged}")import hashlib
# 查看所有可用算法
print("保证可用的算法:")
for algo in sorted(hashlib.algorithms_guaranteed):
print(f" - {algo}")
print("\n当前系统支持的算法:")
for algo in sorted(hashlib.algorithms_available):
print(f" - {algo}")import hashlib
text = "哈希测试"
# 十六进制输出
md5_hex = hashlib.md5(text.encode()).hexdigest()
print(f"十六进制: {md5_hex}")
# 二进制输出
md5_binary = hashlib.md5(text.encode()).digest()
print(f"二进制: {md5_binary}")
# 字节长度
print(f"MD5输出长度: {len(md5_binary)} 字节")import hashlib
import os
class FileDeduplicator:
def __init__(self):
self.file_hashes = {}
def find_duplicates(self, directory):
"""查找重复文件"""
duplicates = {}
for root, dirs, files in os.walk(directory):
for filename in files:
filepath = os.path.join(root, filename)
try:
file_hash = self._calculate_file_hash(filepath)
if file_hash in self.file_hashes:
if file_hash not in duplicates:
duplicates[file_hash] = [self.file_hashes[file_hash]]
duplicates[file_hash].append(filepath)
else:
self.file_hashes[file_hash] = filepath
except (IOError, OSError):
continue
return duplicates
def _calculate_file_hash(self, filepath):
"""计算文件哈希值"""
hasher = hashlib.sha256()
with open(filepath, 'rb') as f:
for chunk in iter(lambda: f.read(8192), b""):
hasher.update(chunk)
return hasher.hexdigest()
# 使用示例
deduplicator = FileDeduplicator()
# duplicates = deduplicator.find_duplicates('/path/to/directory')import hashlib
class DataValidator:
@staticmethod
def create_checksum(data):
"""创建数据校验和"""
if isinstance(data, str):
data = data.encode()
return hashlib.sha256(data).hexdigest()
@staticmethod
def validate_data(data, expected_checksum):
"""验证数据完整性"""
actual_checksum = DataValidator.create_checksum(data)
return actual_checksum == expected_checksum
# 使用示例
original_data = "这是一段重要数据"
checksum = DataValidator.create_checksum(original_data)
print(f"数据校验和: {checksum}")
# 验证数据
is_valid = DataValidator.validate_data(original_data, checksum)
print(f"数据验证通过: {is_valid}")
# 修改数据后验证
modified_data = "这是一段被修改的数据"
is_valid_modified = DataValidator.validate_data(modified_data, checksum)
print(f"修改后验证通过: {is_valid_modified}")import hashlib
def secure_hash(data, algorithm='sha256'):
"""使用安全算法进行哈希"""
secure_algorithms = ['sha256', 'sha384', 'sha512', 'sha3_256', 'sha3_512']
if algorithm not in secure_algorithms:
print(f"警告: {algorithm} 可能不安全,建议使用 {secure_algorithms}")
algorithm = 'sha256'
hasher = hashlib.new(algorithm)
hasher.update(data.encode() if isinstance(data, str) else data)
return hasher.hexdigest()
# 安全使用示例
data = "敏感信息"
secure_hash_value = secure_hash(data, 'sha256')
print(f"安全哈希: {secure_hash_value}")import hashlib
import secrets
def secure_password_hash(password):
"""安全的密码哈希方法"""
# 生成随机盐值
salt = secrets.token_hex(16)
# 组合密码和盐值
salted_password = password + salt
# 多次哈希增加安全性
hash_value = hashlib.sha256(salted_password.encode()).hexdigest()
for _ in range(1000):
hash_value = hashlib.sha256(hash_value.encode()).hexdigest()
return f"{salt}${hash_value}"
def verify_secure_password(password, stored_hash):
"""验证安全哈希密码"""
salt, expected_hash = stored_hash.split('$')
salted_password = password + salt
hash_value = hashlib.sha256(salted_password.encode()).hexdigest()
for _ in range(1000):
hash_value = hashlib.sha256(hash_value.encode()).hexdigest()
return hash_value == expected_hash
# 使用示例
user_password = "my_secure_password"
stored_hash = secure_password_hash(user_password)
print(f"存储的哈希: {stored_hash}")
is_valid = verify_secure_password(user_password, stored_hash)
print(f"密码验证: {is_valid}")import hashlib
import time
def benchmark_algorithms():
"""比较不同哈希算法的性能"""
test_data = "a" * 1000000 # 1MB数据
algorithms = ['md5', 'sha1', 'sha256', 'sha512']
print("哈希算法性能比较:")
print("-" * 50)
for algo in algorithms:
start_time = time.time()
hasher = hashlib.new(algo)
hasher.update(test_data.encode())
result = hasher.hexdigest()
end_time = time.time()
duration = (end_time - start_time) * 1000 # 毫秒
print(f"{algo:>8}: {duration:6.2f} ms - {result[:16]}...")
# 运行性能测试
benchmark_algorithms()Python hashlib 模块中常见的哈希算法及其含义:
| 算法名称 | 摘要长度(位) | 输出长度(字节) | 安全性 | 用途 |
|---|---|---|---|---|
| md5 | 128 | 16 | 不安全 | 数据完整性验证、密码存储等 |
| sha1 | 160 | 20 | 不安全 | 数据完整性验证、密码存储等 |
| sha224 | 224 | 28 | 低 | 数据完整性验证、数字签名等 |
| sha256 | 256 | 32 | 中等 | 数据完整性验证、数字签名等 |
| sha384 | 384 | 48 | 高 | 数字签名、加密算法等 |
| sha512 | 512 | 64 | 高 | 数字签名、加密算法等 |
| sha3_224 | 224 | 28 | 高 | 未来标准的 SHA-3 家族成员,适用于数字签名等 |
| sha3_256 | 256 | 32 | 高 | 未来标准的 SHA-3 家族成员,适用于数字签名等 |
| sha3_384 | 384 | 48 | 高 | 未来标准的 SHA-3 家族成员,适用于数字签名等 |
| sha3_512 | 512 | 64 | 高 | 未来标准的 SHA-3 家族成员,适用于数字签名等 |
| shake_128 | 可变 | 可变 | 高 | SHAKE 系列是 SHA-3 家族的可变长度版本,适用于各种应用 |
| shake_256 | 可变 | 可变 | 高 | SHAKE 系列是 SHA-3 家族的可变长度版本,适用于各种应用 |
说明:
hashlib模块提供了强大的哈希加密功能:
数据完整性验证:检查文件或数据是否被修改
密码安全存储:安全地存储用户密码
数据去重:通过哈希值识别重复数据
数字指纹:为数据创建唯一标识
重要提醒:
MD5和SHA-1已经不安全,不建议用于安全敏感场景
对于密码存储,使用加盐和多次哈希
选择SHA-256或SHA-3等安全算法
大文件要分块处理,避免内存问题
更多哈希加密的高级用法可以在fly63网站的Python安全编程教程中找到。在实际应用中,要根据具体需求选择合适的算法和安全措施。
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!