Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
HashingContext
继承: RefCounted < Object
提供分段计算加密哈希的功能。
描述
HashingContext 类提供了一个接口,用于在多次迭代中计算加密哈希值。常用于计算大文件(不必全部加载到内存中)、网络流和一般数据流(不必持有缓冲区)的哈希值。
HashType 枚举显示了支持的哈希算法。
const CHUNK_SIZE = 1024
func hash_file(path):
# 检查文件是否存在。
if not FileAccess.file_exists(path):
return
# 启动一个 SHA-256 上下文。
var ctx = HashingContext.new()
ctx.start(HashingContext.HASH_SHA256)
# 打开文件进行哈希处理。
var file = FileAccess.open(path, FileAccess.READ)
# 读取每个块后更新上下文。
while file.get_position() < file.get_length():
var remaining = file.get_length() - file.get_position()
ctx.update(file.get_buffer(min(remaining, CHUNK_SIZE)))
# 获取计算的哈希值。
var res = ctx.finish()
# 将结果打印为十六进制字符串和数组。
printt(res.hex_encode(), Array(res))
public const int ChunkSize = 1024;
public void HashFile(string path)
{
// 检查文件是否存在。
if (!FileAccess.FileExists(path))
{
return;
}
// 启动一个 SHA-256 上下文。
var ctx = new HashingContext();
ctx.Start(HashingContext.HashType.Sha256);
// 打开文件进行哈希处理。
using var file = FileAccess.Open(path, FileAccess.ModeFlags.Read);
// 读取每个块后更新上下文。
while (file.GetPosition() < file.GetLength())
{
int remaining = (int)(file.GetLength() - file.GetPosition());
ctx.Update(file.GetBuffer(Mathf.Min(remaining, ChunkSize)));
}
// 获取计算的哈希值。
byte[] res = ctx.Finish();
// 将结果打印为十六进制字符串和数组。
GD.PrintT(res.HexEncode(), (Variant)res);
}
方法
finish() |
|
update(chunk: PackedByteArray) |
枚举
enum HashType: 🔗
HashType HASH_MD5 = 0
哈希算法:MD5。
HashType HASH_SHA1 = 1
哈希算法:SHA-1。
HashType HASH_SHA256 = 2
哈希算法:SHA-256。
方法说明
PackedByteArray finish() 🔗
关闭当前上下文,并返回计算出的哈希值。
开始对给定类型 type
的哈希计算(例如 HASH_SHA256 会开始计算 SHA-256)。
Error update(chunk: PackedByteArray) 🔗
使用给定的数据块 chunk
更新计算。