Python3入门指南Python语言的特点和实际应用Python3环境搭建配置VSCode进行Python开发Python基础语法Python变量与数据类型Python数据类型转换Python解释器使用Python注释使用Python运算符Python数字类型Python字符串操作Python列表操作Python元组使用Python字典使用Python集合使用Python条件控制详解Python循环语句详解Python编程入门实践Python推导式详解Python迭代器和生成器Python with语句详解Python函数详解Python lambda(匿名函数)Python装饰器Python数据结构Python模块和包使用Python中__name__和__main__的用法Python输入输出:从基础到文件操作Python文件操作Python OS模块使用Python错误和异常处理Python面向对象编程Python命名空间和作用域Python虚拟环境:venv详细教程Python类型注解Python标准库常用模块Python正则表达式Python CGI编程Python MySQL(mysql-connector驱动)Python MySQL(PyMySQL驱动)Python网络编程Python发送邮件Python多线程编程Python XML解析Python JSON解析Python日期和时间处理Python操作MongoDBPython urllib库使用Python uWSGI 安装与配置Python pip包管理工具Python operator模块Python math模块Python requests模块HTTP请求Python random模块Python OpenAI库Python AI绘画制作Python statistics模块Python hashlib模块:哈希加密Python量化交易Python pyecharts数据可视化Python Selenium网页自动化Python BeautifulSoup网页数据提取Python Scrapy爬虫框架Python Markdown转HTMLPython sys模块Python Pickle模块:数据存储Python subprocess模块Python queue队列模块Python StringIO内存文件操作Python logging日志记录Python datetime日期时间处理Python re正则表达式Python csv表格数据处理Python threading 多线程编程Python asyncio 异步编程Python PyQt 图形界面开发Python 应用方向和常用库框架

Python hashlib模块:哈希加密

Python的hashlib模块用于数据加密和验证。哈希加密可以把任意长度的数据转换成固定长度的字符串,这个字符串就像数据的"指纹"一样。


什么是哈希加密

哈希加密有这些特点:

  • 相同输入永远产生相同输出

  • 不同输入产生不同输出

  • 无法从输出反推输入

  • 很小的输入变化会导致输出巨大变化


导入hashlib模块

import hashlib


基本使用方法

使用MD5算法

import hashlib

# 创建MD5哈希对象
md5_hash = hashlib.md5()

# 添加要加密的数据
md5_hash.update(b"Hello World")

# 获取加密结果
result = md5_hash.hexdigest()
print(f"MD5加密结果: {result}")

输出结果:

MD5加密结果: b10a8db164e0754105b7a99be72e3fe5

直接加密字符串

import hashlib

# 一步完成加密
text = "Python编程"
md5_result = hashlib.md5(text.encode()).hexdigest()
print(f"文本'{text}'的MD5值: {md5_result}")


常用哈希算法

SHA-256加密

import hashlib

# SHA-256加密
text = "安全密码"
sha256_hash = hashlib.sha256(text.encode())
print(f"SHA-256: {sha256_hash.hexdigest()}")

SHA-512加密

import hashlib

# SHA-512加密
text = "重要数据"
sha512_hash = hashlib.sha512(text.encode())
print(f"SHA-512: {sha512_hash.hexdigest()}")

使用new函数选择算法

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 模块中常见的哈希算法及其含义:

算法名称摘要长度(位)输出长度(字节)安全性用途
md512816不安全数据完整性验证、密码存储等
sha116020不安全数据完整性验证、密码存储等
sha22422428数据完整性验证、数字签名等
sha25625632中等数据完整性验证、数字签名等
sha38438448数字签名、加密算法等
sha51251264数字签名、加密算法等
sha3_22422428未来标准的 SHA-3 家族成员,适用于数字签名等
sha3_25625632未来标准的 SHA-3 家族成员,适用于数字签名等
sha3_38438448未来标准的 SHA-3 家族成员,适用于数字签名等
sha3_51251264未来标准的 SHA-3 家族成员,适用于数字签名等
shake_128可变可变SHAKE 系列是 SHA-3 家族的可变长度版本,适用于各种应用
shake_256可变可变SHAKE 系列是 SHA-3 家族的可变长度版本,适用于各种应用

说明:

  • 摘要长度(位): 表示哈希算法输出的摘要长度,以位为单位。
  • 输出长度(字节): 表示哈希算法输出的摘要长度,以字节为单位。
  • 安全性: 表示哈希算法的安全性级别,包括 "不安全"、"低"、"中等"、"高"。这是一个一般性的分类,具体的安全性还要考虑算法的用途和具体的攻击场景。


总结

hashlib模块提供了强大的哈希加密功能:

  • 数据完整性验证:检查文件或数据是否被修改

  • 密码安全存储:安全地存储用户密码

  • 数据去重:通过哈希值识别重复数据

  • 数字指纹:为数据创建唯一标识

重要提醒:

  • MD5和SHA-1已经不安全,不建议用于安全敏感场景

  • 对于密码存储,使用加盐和多次哈希

  • 选择SHA-256或SHA-3等安全算法

  • 大文件要分块处理,避免内存问题

更多哈希加密的高级用法可以在fly63网站的Python安全编程教程中找到。在实际应用中,要根据具体需求选择合适的算法和安全措施。

本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!

链接: https://fly63.com/course/36_2130

目录选择