HashingContext

Inherits: RefCounted < Object

Provides functionality for computing cryptographic hashes chunk by chunk.

Description

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 a 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 not file.eof_reached():
  13. ctx.update(file.get_buffer(CHUNK_SIZE))
  14. # Get the computed hash.
  15. var res = ctx.finish()
  16. # Print the result as hex string and array.
  17. 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 a 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.EofReached())
  16. {
  17. ctx.Update(file.GetBuffer(ChunkSize));
  18. }
  19. // Get the computed hash.
  20. byte[] res = ctx.Finish();
  21. // Print the result as hex string and array.
  22. GD.PrintT(res.HexEncode(), (Variant)res);
  23. }

Methods

PackedByteArray

finish ( )

Error

start ( HashType type )

Error

update ( PackedByteArray chunk )


Enumerations

enum HashType:

HashType HASH_MD5 = 0

Hashing algorithm: MD5.

HashType HASH_SHA1 = 1

Hashing algorithm: SHA-1.

HashType HASH_SHA256 = 2

Hashing algorithm: SHA-256.


Method Descriptions

PackedByteArray finish ( )

Closes the current context, and return the computed hash.


Error start ( HashType type )

Starts a new hash computation of the given type (e.g. HASH_SHA256 to start computation of a SHA-256).


Error update ( PackedByteArray chunk )

Updates the computation with the given chunk of data.

Previous Next


© Copyright 2014-present Juan Linietsky, Ariel Manzur and the Godot community (CC BY 3.0). Revision 53e837c6.

Built with Sphinx using a theme provided by Read the Docs.