how to compare hexadecimal hash, generated by 'createhash' in string in typescript

To compare hexadecimal hash generated by createHash in TypeScript, you first need to hash the string you want to compare and then compare the generated hash with the expected hash. Here's a simple example using Node.js crypto library:

index.ts
import { createHash } from 'crypto';

const originalString = 'Hello World';
const hashAlgorithm = 'sha256'; // Specify the hash algorithm
const expectedHash = '3651b529abf3c0aa45c5144b0b6201c8a3b60f7e5541c46d63fd7b4d40b0d19d';

const hash = createHash(hashAlgorithm).update(originalString).digest('hex');

if (hash === expectedHash) {
    console.log('Hashes match!');
} else {
    console.log('Hashes do not match.');
}
421 chars
14 lines

In this code snippet, you can set the originalString, hashAlgorithm, and expectedHash. The createHash function from the crypto module is used to generate the hash of the originalString using the specified hashing algorithm. Finally, the generated hash is compared with the expectedHash, and a message is logged to the console based on the comparison result.

related categories

gistlibby LogSnag