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.
2 min readFeb 1, 2023
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');
}
- Import
crypto
library. - Encode the
ASCII
string as a byte object usingBuffer.from()
method. - Create a new
SHA-256
hash object, by usingcrypto.createHash(‘sha256’)
method. - Update the hash object with the byte string that we created earlier.
- Return the hexadecimal representation of the hash by calling
.digest('hex')
method onhashObject
.
(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 } =…