Sha256 Hashes in GDScript

Here’s the translation of the SHA256 hashes example to GDScript, formatted in Markdown suitable for Hugo:

SHA256 hashes are frequently used to compute short identities for binary or text blobs. For example, TLS/SSL certificates use SHA256 to compute a certificate’s signature. Here’s how to compute SHA256 hashes in GDScript.

extends Node

func _ready():
    var s = "sha256 this string"

    # Here we start with a new hash.
    var h = HashingContext.new()
    h.start(HashingContext.HASH_SHA256)

    # We need to convert the string to bytes.
    h.update(s.to_utf8())

    # This gets the finalized hash result as a PoolByteArray.
    var bs = h.finish()

    print(s)
    print(bs.hex_encode())

GDScript implements several hash functions in the HashingContext class.

The start() method initializes the hashing context with the desired algorithm. In this case, we’re using SHA256.

The update() method expects bytes. If you have a string s, use s.to_utf8() to convert it to bytes.

The finish() method returns the finalized hash result as a PoolByteArray.

Running the program computes the hash and prints it in a human-readable hex format.

sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...

You can compute other hashes using a similar pattern to the one shown above. For example, to compute SHA512 hashes, use HashingContext.HASH_SHA512 when starting the hashing context.

Note that if you need cryptographically secure hashes, you should carefully research hash strength!