Sha256 Hashes in TypeScript

Here’s the translation of the SHA256 Hashes example from Go to TypeScript, formatted in Markdown 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 TypeScript.

import * as crypto from 'crypto';

function main() {
    const s = "sha256 this string";

    // Here we start with a new hash.
    const hash = crypto.createHash('sha256');

    // update expects a string or Buffer. If you have a string s,
    // you can use it directly.
    hash.update(s);

    // This gets the finalized hash result as a hexadecimal string.
    const bs = hash.digest('hex');

    console.log(s);
    console.log(bs);
}

main();

TypeScript doesn’t have built-in cryptographic functions, so we use the Node.js crypto module, which is available in most TypeScript environments.

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

$ ts-node sha256-hashes.ts
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...

You can compute other hashes using a similar pattern to the one shown above. For example, to compute SHA512 hashes, you can use crypto.createHash('sha512').

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

In TypeScript, we use the crypto module from Node.js, which provides a wide range of cryptographic functionality. The createHash function allows us to specify which hash algorithm we want to use.

Unlike in some other languages, we don’t need to explicitly convert our string to bytes - the update method of the hash object can accept strings directly.

The digest method finalizes the hash and returns the result. We specify ‘hex’ to get a hexadecimal string representation of the hash.

Remember to install the necessary types for Node.js if you’re using TypeScript in a Node.js environment:

npm install --save-dev @types/node

This will allow TypeScript to recognize the crypto module and provide proper type checking and autocompletion.