How to Convert ASCII String to Its Hexadecimal SHA-256 Hash in JavaScript

Quick demonstration of how to create a function that converts a given ASCII string to its hexadecimal SHA-256 hash in JavaScript.

Ken Nersisyan
2 min readFeb 1, 2023
Photo by Almas Salakhov on Unsplash

Traditional Version

Here’s how the traditional version of the snippet would look like:

const crypto = require('crypto');

function asciiToSha256(asciiString) {
const byteString = Buffer.from(asciiString, 'ascii');
const hashObject = crypto.createHash('sha256');

hashObject.update(byteString);

return hashObject.digest('hex');
}
  1. Import crypto library.
  2. Encode the ASCII string as a byte object using Buffer.from() method.
  3. Create a new SHA-256 hash object, by using crypto.createHash(‘sha256’) method.
  4. Update the hash object with the byte string that we created earlier.
  5. Return the hexadecimal representation of the hash by calling .digest('hex') method on hashObject.

(See result below)

One-liner Version

This is how I prefer to do it, because it looks concise and it’s easier to read.

const { createHash } =…

--

--

Ken Nersisyan

JS Enthusiast | Front-End Engineer | Tech Writer | Gamer | Photographer