HashingContext

继承: RefCounted < Object

提供分段计算加密哈希的功能。

描述

The HashingContext class provides an interface for computing cryptographic hashes over multiple iterations. Useful for computing hashes of big files (so you don’t have to load them all in memory), network streams, and data streams in general (so you don’t have to hold buffers).

The HashType enum shows the supported hashing algorithms.

GDScriptC#

  1. const CHUNK_SIZE = 1024
  2. func hash_file(path):
  3. # Check that file exists.
  4. if not FileAccess.file_exists(path):
  5. return
  6. # Start an SHA-256 context.
  7. var ctx = HashingContext.new()
  8. ctx.start(HashingContext.HASH_SHA256)
  9. # Open the file to hash.
  10. var file = FileAccess.open(path, FileAccess.READ)
  11. # Update the context after reading each chunk.
  12. while file.get_position() < file.get_length():
  13. var remaining = file.get_length() - file.get_position()
  14. ctx.update(file.get_buffer(min(remaining, CHUNK_SIZE)))
  15. # Get the computed hash.
  16. var res = ctx.finish()
  17. # Print the result as hex string and array.
  18. printt(res.hex_encode(), Array(res))
  1. public const int ChunkSize = 1024;
  2. public void HashFile(string path)
  3. {
  4. // Check that file exists.
  5. if (!FileAccess.FileExists(path))
  6. {
  7. return;
  8. }
  9. // Start an SHA-256 context.
  10. var ctx = new HashingContext();
  11. ctx.Start(HashingContext.HashType.Sha256);
  12. // Open the file to hash.
  13. using var file = FileAccess.Open(path, FileAccess.ModeFlags.Read);
  14. // Update the context after reading each chunk.
  15. while (file.GetPosition() < file.GetLength())
  16. {
  17. int remaining = (int)(file.GetLength() - file.GetPosition());
  18. ctx.Update(file.GetBuffer(Mathf.Min(remaining, ChunkSize)));
  19. }
  20. // Get the computed hash.
  21. byte[] res = ctx.Finish();
  22. // Print the result as hex string and array.
  23. GD.PrintT(res.HexEncode(), (Variant)res);
  24. }

方法

PackedByteArray

finish()

Error

start(type: HashType)

Error

update(chunk: PackedByteArray)


枚举

enum HashType: 🔗

HashType HASH_MD5 = 0

哈希算法:MD5。

HashType HASH_SHA1 = 1

哈希算法:SHA-1。

HashType HASH_SHA256 = 2

哈希算法:SHA-256。


方法说明

PackedByteArray finish() 🔗

关闭当前上下文,并返回计算出的哈希值。


Error start(type: HashType) 🔗

开始对给定类型 type 的哈希计算(例如 HASH_SHA256 会开始计算 SHA-256)。


Error update(chunk: PackedByteArray) 🔗

使用给定的数据块 chunk 更新计算。