Skip to content

Instantly share code, notes, and snippets.

@junderw
Created May 6, 2018 07:07
Show Gist options
  • Save junderw/8006056dc95a41580d39c74025e01f11 to your computer and use it in GitHub Desktop.
Save junderw/8006056dc95a41580d39c74025e01f11 to your computer and use it in GitHub Desktop.
pbkdf2 for modern browsers' JavaScript
async function pbkdf2(message, salt, iterations, keyLen, algorithm) {
const msgBuffer = new TextEncoder('utf-8').encode(message)
const msgUint8Array = new Uint8Array(msgBuffer)
const saltBuffer = new TextEncoder('utf-8').encode(salt)
const saltUint8Array = new Uint8Array(saltBuffer)
const key = await crypto.subtle.importKey('raw', msgUint8Array, { name: 'PBKDF2' }, false, ['deriveBits'])
const buffer = await crypto.subtle.deriveBits({ "name": 'PBKDF2', "salt": saltUint8Array, "iterations": iterations, "hash": algorithm }, key, keyLen * 8)
const hashArray = Array.from(new Uint8Array(buffer))
const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('')
return hashHex
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment