create a sha256 hash from a string in typescript

To create a SHA256 hash from a string in TypeScript, you can use the crypto module that comes with Node.js.

Here's an example function that takes a string and returns its SHA256 hash:

index.ts
import * as crypto from 'crypto';

function sha256(input: string): string {
  const hash = crypto.createHash('sha256');
  hash.update(input);
  return hash.digest('hex');
}
173 chars
8 lines

You can then use this function like this:

index.ts
const myString = 'Hello, world!';
const myHash = sha256(myString);
console.log(myHash); // Output: '2ef7bde608ce5404e97d5f042f95f89f1c232871dfcc1e1a5f765b9cfc71acd8'
166 chars
4 lines

Note that this code will only work in a Node.js environment, not in a browser. If you need to use it in a browser, you can either use a library like CryptoJS or a Web API like SubtleCrypto.

gistlibby LogSnag