Skip to content

Instantly share code, notes, and snippets.

View chrisveness's full-sized avatar

Chris Veness chrisveness

View GitHub Profile
@chrisveness
chrisveness / crypto-pbkdf2.js
Last active December 21, 2023 19:20
Uses the SubtleCrypto interface of the Web Cryptography API to hash a password using PBKDF2, and validate a stored password hash against a subsequently supplied password. Note that both bcrypt and scrypt offer better defence against ASIC/GPU attacks, but are not available within WebCrypto.
/**
* Returns PBKDF2 derived key from supplied password.
*
* Stored key can subsequently be used to verify that a password matches the original password used
* to derive the key, using pbkdf2Verify().
*
* @param {String} password - Password to be hashed using key derivation function.
* @param {Number} [iterations=1e6] - Number of iterations of HMAC function to apply.
* @returns {String} Derived key as base64 string.
*
@chrisveness
chrisveness / crypto-aes-gcm.js
Last active March 17, 2024 15:36
Uses the SubtleCrypto interface of the Web Cryptography API to encrypt and decrypt text using AES-GCM (AES Galois counter mode).
/**
* Encrypts plaintext using AES-GCM with supplied password, for decryption with aesGcmDecrypt().
* (c) Chris Veness MIT Licence
*
* @param {String} plaintext - Plaintext to be encrypted.
* @param {String} password - Password to use to encrypt plaintext.
* @returns {String} Encrypted ciphertext.
*
* @example
* const ciphertext = await aesGcmEncrypt('my secret text', 'pw');