create a blake2s hash from a string in javascript

To create a Blake2s hash from a string in JavaScript, you can use the blake2s module. You can install it using npm:

index.tsx
npm install blake2s
20 chars
2 lines

Then, you can use the following code to create a Blake2s hash from a string:

index.tsx
const blake2s = require('blake2s');

// Define the input string
const inputString = 'Hello, world!';

// Convert the input string to a Buffer
const inputBuffer = Buffer.from(inputString, 'utf8');

// Create a Blake2s hash
const hash = blake2s(inputBuffer);

// Convert the hash to a hexadecimal string
const hashHex = hash.toString('hex');

console.log(hashHex); // Output: fdbd8b8cebfc2d5194680d331e408f20c865e8807cfd355be01f32f79b4e8e62
439 chars
16 lines

In this example, we first define the input string "Hello, world!". We then convert it to a Buffer using the Buffer.from() method. We pass the 'utf8' encoding to indicate that the input string is encoded in UTF-8.

We then create a Blake2s hash from the input Buffer using the blake2s() function from the blake2s module. The resulting hash is also a Buffer.

Finally, we convert the hash to a hexadecimal string using the toString('hex') method, and log it to the console.

Note that the Blake2s hash function is not suitable for cryptographic purposes on its own, as it is susceptible to length extension attacks. If you need a secure hashing function for cryptographic purposes, you should use a function such as SHA-256 instead.

gistlibby LogSnag