How To Hash In Javascript

Hashing is a process of converting data into a fixed-size string of bytes, usually for security purposes or comparing data. In this blog post, we’ll learn how to hash data in JavaScript using the SubtleCrypto API, which provides a set of cryptographic primitives.

What You Need to Know

  • JavaScript does not have a built-in hashing function, but you can use the SubtleCrypto API to hash data.
  • The SubtleCrypto API is available in modern browsers, including Chrome, Firefox, Safari, and Edge.
  • We’ll use the async/await syntax for better readability, which is supported in modern JavaScript environments.

Hashing Data with SubtleCrypto

The SubtleCrypto API provides a digest() method for hashing data. Let’s see how to use this method to hash a string:

    async function hashData(data) {
        const encoder = new TextEncoder();
        const dataBuffer = encoder.encode(data);
        const hashBuffer = await crypto.subtle.digest('SHA-256', dataBuffer);
        const hashArray = Array.from(new Uint8Array(hashBuffer));
        const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
        return hashHex;
    }

    (async () => {
        const data = "Hello, world!";
        const hash = await hashData(data);
        console.log("Hash:", hash);
    })();
    

Let’s break down the code:

  1. We create a function called hashData that takes a string as input.
  2. We use the TextEncoder class to convert the input string into a Uint8Array (a byte array).
  3. We call the crypto.subtle.digest() method with the hashing algorithm (‘SHA-256’) and the byte array. This method returns a Promise that resolves with the hashed data.
  4. We convert the hashed data (an ArrayBuffer) into a Uint8Array and then into an array of numbers.
  5. We convert each number in the array into a hexadecimal string and join them to get the final hash.

Conclusion

In this blog post, we’ve learned how to hash data in JavaScript using the SubtleCrypto API. Although JavaScript doesn’t have built-in hashing functions, the SubtleCrypto API provides a convenient and secure way to hash data in modern browsers. Remember to always use the latest cryptographic standards and practices to ensure the security of your data.