至于前端 hash 也不用自己捣鼓 js/wasm 这些,主流浏览器早已内置 PBKDF2 算法,较新的 CPU 都有相应的硬件加速,比自己实现可以快很多倍。
演示:
const username = new TextEncoder().encode('alice')
const password = new TextEncoder().encode('hello1234')
// 重复 1000 万次 SHA256
const pbkdfOpts = {
name: 'PBKDF2',
hash: 'SHA-256',
salt: username,
iterations: 1e7,
}
async function pbkdf2(pwd, opts, bits) {
const baseKey = await crypto.subtle.importKey('raw', pwd, 'PBKDF2', false, ['deriveBits'])
const buf = await crypto.subtle.deriveBits(opts, baseKey, bits)
return new Uint8Array(buf)
}
const dk = await pbkdf2(password, pbkdfOpts, 256)
// 注册/登录提交 dk 即可,无需提交 password
console.log(dk)