Python:hmac 库高级用法举例和应用详解

Python:hmac库高级用法举例和应用详解

模块介绍

hmac 模块是 Python 标准库中的一个重要组成部分,专用于生成和验证基于哈希函数的消息认证码(HMAC:Hash-based Message Authentication Code)。HMAC 能够确保信息在传递过程中不被篡改,并能证明数据的来源真实性。该模块适配 Python3,用户无需额外安装即可使用。

应用场景

HMAC 主要用于以下几个方面:

  • 确保数据完整性:通过生成消息认证码,可以确认数据在传输过程中没有被篡改。
  • 验证数据源:HMAC 可以验证数据是否确实来自特定的发送者。
  • API 安全保护:在 API 请求中使用 HMAC 验证,确保每个请求都是来自可信的客户端。
  • 保护敏感信息:用于验证重要数据传输的安全性,例如金融交易信息。

安装说明

由于 hmac 模块是 Python 标准库的一部分,默认情况下已经包含在 Python 解释器中。无需进行单独安装,您只需确保 Python 环境已经正确搭建完毕。

用法举例

下面通过三个详细的使用场景来展示 hmac 模块的各种功能。

示例 1:生成和验证 HMAC 码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import hmac
import hashlib

# 场景说明:生成HMAC码以确保传输数据的完整性和来源
secret_key = b'supersecretkey' # 定义密钥
message = b'This is a secret message' # 要验证的消息

# 使用密钥和消息生成HMAC码
hmac_code = hmac.new(secret_key, message, hashlib.sha256).hexdigest()
print(f"The HMAC code is: {hmac_code}") # 打印生成的HMAC码

# 验证消息的HMAC码
message_to_verify = b'This is a secret message'
received_hmac_code = hmac_code
expected_hmac_code = hmac.new(secret_key, message_to_verify, hashlib.sha256).hexdigest()

# 如果收到的HMAC码与期望的HMAC码匹配,则消息未被篡改
if received_hmac_code == expected_hmac_code:
print("The message is authentic and has not been tampered with.")
else:
print("The message has been tampered with or the HMAC code is incorrect.")

示例 2:在 API 请求中使用 HMAC 进行身份验证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import hmac
import hashlib
import requests

# 场景说明:在API请求中使用HMAC进行身份验证
secret_key = b'apisecretkey' # API密钥
data = b'{"username": "user1", "action": "login"}' # 请求数据
api_endpoint = 'https://api.example.com/login' # API端点

# 生成请求数据的HMAC码
signature = hmac.new(secret_key, data, hashlib.sha256).hexdigest()

# 发送请求时将HMAC码作为头部信息包含在内
headers = {
'Content-Type': 'application/json',
'Authorization': f'HMAC {signature}'
}
response = requests.post(api_endpoint, data=data, headers=headers)

# 检查响应状态码,确保请求成功
if response.status_code == 200:
print("Request was authenticated and processed successfully.")
else:
print("Failed to authenticate or process the request.")

示例 3:在通信中确保文件传输的完整性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import hmac
import hashlib

# 场景说明:在文件传输通信中确保文件的完整性
secret_key = b'filetransfersecret' # 定义密钥
file_path = 'example_file.txt' # 要传输的文件路径

# 读取文件内容
with open(file_path, 'rb') as f:
file_data = f.read()

# 计算文件的HMAC码
file_hmac_code = hmac.new(secret_key, file_data, hashlib.sha256).hexdigest()
print(f"File HMAC code: {file_hmac_code}") # 打印文件的HMAC码

# 假设我们在传输后收到了文件和对应的HMAC码
received_file_data = file_data # 在实际的接收场景中,这会是接收的数据
received_hmac_code = file_hmac_code # 在实际的接收场景中,这会是接收的HMAC码

# 验证接收的文件是否完整
expected_hmac_code = hmac.new(secret_key, received_file_data, hashlib.sha256).hexdigest()
if received_hmac_code == expected_hmac_code:
print("The received file is authentic and has not been tampered with.")
else:
print("The received file has been tampered with or the HMAC code is incorrect.")

关注「全糖冲击博客」

关注全糖冲击博客的理由实在太多了!作为一名热爱编程的开发者,我致力于为大家提供详细且易懂的 Python 标准库教程。关注我的博客,你将获得:

  • 全面覆盖:每一个 Python 标准库都包含在内,方便查询和学习。
  • 最新内容:持续更新最新的库和最佳实践,确保你掌握前沿技术。
  • 实用示例:通过丰富的实战案例和小技巧,提升你的代码能力和开发效率。
  • 互动交流:有问题可以随时留言,我会尽快回复你,帮助你解决疑惑。

快来订阅「全糖冲击博客」,一起在 Python 的世界里探索无限可能吧!

软件版本可能变动

如果本文档不再适用或有误,请留言或联系我进行更新。让我们一起营造良好的学习氛围。感谢您的支持! - Travis Tang