Calculate the SHA-256 hash of a string in JavaScript without library

Ever wondered how to generate a SHA-256 hash in JavaScript without relying on external libraries? This post walks you through a pure JavaScript implementation of the SHA-256 algorithm, helping you understand each step and the underlying logic.

The SHA-256 (Secure Hash Algorithm 256) is a widely used cryptographic hash function that produces a fixed-size output for any given input. It is commonly used to verify the integrity of data. In this post, we will learn how to implement the SHA-256 hash function in JavaScript without using any external libraries.

function sha256(string) {
  // Initialize the SHA-256 hash
  var hash = new Uint32Array(8);
  hash[0] = 0x6a09e667;
  hash[1] = 0xbb67ae85;
  hash[2] = 0x3c6ef372;
  hash[3] = 0xa54ff53a;
  hash[4] = 0x510e527f;
  hash[5] = 0x9b05688c;
  hash[6] = 0x1f83d9ab;
  hash[7] = 0x5be0cd19;

  // Convert the string to a byte array
  var stringBytes = toUTF8Bytes(string);

  // Pad the byte array to a multiple of 64 bytes
  var paddedBytes = padToMultipleOf(stringBytes, 64);

  // Process the padded byte array in blocks of 64 bytes
  for (var i = 0; i < paddedBytes.length; i += 64) {
    processBlock(paddedBytes.slice(i, i + 64), hash);
  }

  // Return the final hash as a hexadecimal string
  return toHexString(hash);
}

The hexadecimal values 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, and 0x5be0cd19 are the initial values of the eight 32-bit words used in the SHA-256 algorithm. These values are defined in the SHA-2 standard and serve as the starting state of the hash calculation. They are commonly referred to as the “initial hash values” or the “initial digest.”

This function calculates the SHA-256 hash of a given string by first initializing the hash with the default initial values, then converting the string to a byte array, padding the byte array to a multiple of 64 bytes, and finally processing the padded byte array in blocks of 64 bytes.

The toUTF8Bytes, padToMultipleOf, processBlock, and toHexString functions are helper functions used to convert the string to a byte array, pad the byte array, process the blocks of bytes, and convert the final hash to a hexadecimal string, respectively.

📚 Continue Reading

Sign in with your Google or Facebook account to read the full article.
It takes just 2 seconds!

Already have an account? Log in here

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *