Sha256 Hashes in JavaScript

Here’s the translation of the SHA256 Hashes example from Go to JavaScript, formatted in Markdown suitable for Hugo:

JavaScript provides built-in cryptographic functionality through the crypto module. Here’s how to compute SHA256 hashes in JavaScript.

const crypto = require('crypto');

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

    // Create a new SHA256 hash object
    const hash = crypto.createHash('sha256');

    // Update the hash object with the input string
    hash.update(s);

    // Generate the finalized hash
    const bs = hash.digest('hex');

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

main();

In this example, we use the crypto module to create a SHA256 hash. The createHash function initializes a new hash object. We then use the update method to add data to the hash object, and finally call digest to generate the finalized hash.

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

$ node sha256-hashes.js
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 would use crypto.createHash('sha512').

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

In Node.js environments, the crypto module is built-in. However, for browser environments, you might need to use the Web Crypto API or a third-party library, as direct access to cryptographic functions can be limited due to security considerations.