← 中文资源

简体中文版本

Blake2b 带密钥哈希认证字节

blake2b 的 key 参数把普通摘要升级为带密钥的 MAC:内容动一个字节摘要就整体改变,digest_size 还能截短到适配头部字段。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

tag: 1532fcec7680a811af392faa29b21720
untouched matches: True
tampered differs : True

实现说明

逻辑集中在函数 tag里。

使用要点

  • 跑完文件,输出里会留下标记——tag:、untouched matches:、tampered differs :。
  • 值得导入的表面是 tag;周围的辅助代码对片段是私有的。

常见问题

这段代码会引入外部包吗?

不涉及外部包,每个调用都落在内建 API 上。 文件在加载时定义 tag。

主要签名是 def tag(payload: bytes) -> str

核心语句

def tag(payload: bytes) -> str:
    # blake2b 的 key 参数把普通摘要变成带密钥的 MAC,digest_size 可截短
    return hashlib.blake2b(payload, key=key, digest_size=16).hexdigest()

代码示例

import hashlib

key = b"release-signing-key"


def tag(payload: bytes) -> str:
    # blake2b 的 key 参数把普通摘要变成带密钥的 MAC,digest_size 可截短
    return hashlib.blake2b(payload, key=key, digest_size=16).hexdigest()


manifest = b"artifact=app.tar.gz+count=42"
seal = tag(manifest)
print("tag:", seal)

# 同一密钥重算一致:内容没变
print("untouched matches:", tag(manifest) == seal)

# 内容哪怕动一个字节,摘要整体改变
print("tampered differs :", tag(b"artifact=app.tar.gz+count=43") != seal)