Skip to content

Instantly share code, notes, and snippets.

@SafeEval
Last active February 6, 2025 06:02
Show Gist options
  • Save SafeEval/7ff60e4b4dd965852167cf191a8fbef5 to your computer and use it in GitHub Desktop.
Save SafeEval/7ff60e4b4dd965852167cf191a8fbef5 to your computer and use it in GitHub Desktop.
TypeScript demo of argon2 for string hashing and verification
import { hash, verify, Options, Algorithm } from '@node-rs/argon2';
/**
* Hashes a string using the Argon2id algorithm.
* Argon2 is a memory-hard function that requires a large amount of memory to compute.
* The 'id' variant mixes resistance against both GPU cracking and side-channel attacks.
* A generated salt value adds resistance against pre-computed rainbow table attacks.
* The configuration options are included in argon2 hashes to simplify verification.
*
* @param value - The value to hash.
* @returns A promise that resolves to the hashed value.
*/
export async function argon2Hash(value: string): Promise<string> {
try {
const argon2HashOptions: Options = {
algorithm: Algorithm.Argon2id,
timeCost: 3, // Rounds/iterations to stretch required time
memoryCost: 65536, // 64MB memory allocated, filled, and used per hash to stretch required space
parallelism: 4, // 4 memory "lanes" using 16MB each (64MB/4)
};
return await hash(value, argon2HashOptions);
} catch (err) {
throw new Error(`Password hashing failed: ${err.message}`);
}
}
/**
* Verifies a string against an argon2 hash.
*
* @param hash - The hashed value to compare against.
* @param value - The plaintext value to recalculate and verify.
* @returns A promise that resolves to true if the value is verified, false otherwise.
*/
export async function argon2Verify(hash: string, value: string): Promise<boolean> {
try {
return await verify(hash, value);
} catch (err) {
throw new Error(`Password verification failed: ${err.message}`);
}
}
async function main() {
if (process.argv.length < 3) {
console.error('Usage: node argon2-demo.ts <text-value>');
process.exit(1);
}
const textValue = process.argv[2];
console.log('Value:', textValue);
const hash = await argon2Hash(textValue);
console.log('Hash:', hash);
const verified = await argon2Verify(hash, textValue);
console.log('Verified:', verified);
}
main();
{
"dependencies": {
"@node-rs/argon2": "^2.0.2",
},
"devDependencies": {
"@types/node": "^22.13.1",
"tsx": "^4.19.2",
"typescript": "^5.7.3"
}
}
$ npx tsx argon2-demo.ts foobar
Value: foobar
Hash: $argon2id$v=19$m=65536,t=3,p=4$U1GdvIp3dFgsTcGvcC78Jg$AkaqkY8zCZpT4T/h+DT1hEYK4zsVw5h5o0nLg+F4h3c
Verified: true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment