Context to compute cryptographic hashes over multiple iterations.
The HashingContext class provides an interface for computing cryptographic hashes over multiple iterations. This is useful for example when 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 [enum HashType] enum shows the supported hashing algorithms.
[codeblocks]
[gdscript]
const CHUNK_SIZE = 102
func hash_file(path):
# Check that file exists.
if not FileAccess.file_exists(path):
return
# Start a SHA-256 context.
var ctx = HashingContext.new()
ctx.start(HashingContext.HASH_SHA256)
# Open the file to hash.
var file = FileAccess.open(path, FileAccess.READ)
# Update the context after reading each chunk.
while not file.eof_reached():
ctx.update(file.get_buffer(CHUNK_SIZE))
# Get the computed hash.
var res = ctx.finish()
# Print the result as hex string and array.
printt(res.hex_encode(), Array(res))
[/gdscript]
[csharp]
public const int ChunkSize = 1024;
public void HashFile(string path)
{
var ctx = new HashingContext();
var file = new File();
// Start a SHA-256 context.
ctx.Start(HashingContext.HashType.Sha256);
// Check that file exists.
if (!file.FileExists(path))
{
return;
}
// Open the file to hash.
file.Open(path, File.ModeFlags.Read);
// Update the context after reading each chunk.
while (!file.EofReached())
{
ctx.Update(file.GetBuffer(ChunkSize));
}
// Get the computed hash.
byte[] res = ctx.Finish();
// Print the result as hex string and array.
GD.PrintT(res.HexEncode(), res);
}
[/csharp]
[/codeblocks]
Closes the current context, and return the computed hash.
Starts a new hash computation of the given [param type] (e.g. [constant HASH_SHA256] to start computation of a SHA-256).
Updates the computation with the given [param chunk] of data.
Hashing algorithm: MD5.
Hashing algorithm: SHA-1.
Hashing algorithm: SHA-256.