Home » Programming » Javascript » Javascript Hash String

Generate a Hash from String in Javascript, with Examples

This tutorial will show you a practical way to generate a hash for a string in JavaScript, and provide working code examples you can use in your own project.

What is a Hash?

A Hash or Checksum is a calculated value with a specific length. By passing a hashing algorithm a string – which can be any length – a calculated hash of a consistent length is returned. Whenever the same string is passed to the hashing algorithm, the same calculated hash should be returned.

As the result of the hashing algorithm should be the same every time, provided the input is the same, the returned value can be used to determine whether the original value has been modified or not.

One example use of this is with file downloads. A file is downloaded, and the downloaded file, regardless of size, can be hashed. This hash can then be compared with the hash of the original file to verify that the download was successful and no corruption occurred.

As hashes are of a fixed size which is smaller than the downloaded file, the file doesn’t have to be re-downloaded to be verified – only the much shorter hash needs to be known.

Uses in JavaScript

This is useful in JavaScript for just that purpose – verifying transferred data. If the hash is known for a large chunk of data, it can be verified.

Secure Hash Algorithms

Hashing is often used in security and cryptography, especially hashes that are difficult to reverse. Hashes used for cryptography can also be used for other purposes, such as the download verification example outlined above.

Generating a Hash in JavaScript

SubtleCrypto is a recent addition to JavaScript which can be used to generate secure hashes.

They can be used to generate hashes for any purpose – not just security – which is handy as it means we can use them instead of writing additional code ourselves.

The below function uses SubtleCrypto to generate the secure hash for a given string:

// Function to generate a hash from a string
// The algorithm used can be specified, or will default to SHA-512
function generateHash(str, algorithm = "SHA-512") {

    // Create an array buffer for the supplied string - this buffer contains an integer representation of the string which can be used to generate the hash
    let strBuffer = new TextEncoder().encode(str);

    // use SubtleCrypto to generate the hash using the specified algorithm
    return crypto.subtle.digest(algorithm, strBuffer)
        .then(hash => {

            // The resulting hash is an arrayBuffer, and should be converted to its hexadecimal representation

            // Initialize the result as an empty string - the hexadecimal characters for the values in the array buffer will be appended to it
            let result = '';

            // The DataView view provides an interface for reading number types from the ArrayBuffer
            const view = new DataView(hash);

            // Iterate over each value in the arrayBuffer and append the converted hexadecimal value to the result
            for (let i = 0; i < hash.byteLength; i += 4) {
                result += ('00000000' + view.getUint32(i).toString(16)).slice(-8);
            }

            return result;
        });

}

This function returns a Promise, it is used like so:

generateHash('London Bridge is falling down')
    .then(hash => {
        console.log(hash);
    });

The promise resolves with the hash for the supplied string – a SHA-512 hash containing hexadecimal values.

Rolling your Own Authentication?

If you are using your own hash functions to build your own authentication system – be it hashing passwords for storage, generating verification codes, or anything security related… Don’t.

Use a community maintained, established, and properly vetted library or service to handle your authentication. It’s not worth it to maintain your own system – even a simple mistake could compromise your application, your systems, or your users’ private information.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment