1

Uses the SubtleCrypto interface of the Web Cryptography API to hash a password u...

 1 year ago
source link: https://gist.github.com/chrisveness/770ee96945ec12ac84f134bf538d89fb
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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.

Author

chrisveness commented Feb 17, 2017

Cryptography is indeed subtle. If I have made any errors, let me know and I will attempt to correct.

Thx to Tim Taubert @ Mozilla.

new Uint8Array(saltStr.match(/./g).map(ch => ch.charCodeAt(0))) does not work as expected

"äõ".match(/./g).map(ch` => ch.charCodeAt(0))
// [228, 245]
new TextEncoder().encode("äo")
// [195, 164, 111]

Author

chrisveness commented Oct 15, 2018

@lauriro I think Uint8Array() is correct for saltUint8, as it needs to be byte-for-byte version of the salt, not a UTF-8-encoded version – I've updated my note about why TextEncoder().encode() wouldn't work.

Zemnmez commented Feb 20, 2019

edited

@chrisveness this implementation is dangerously broken under some conditions, because the number of iterations used to verify the digest is specified in the digest itself without possible verification. An attacker can send a digest with only one or zero iterations of HMAC.

-- additionally this implementation uses a non-fixed time string comparison, which allows an attacker to glean the digest (fwiw) if they are local to the system (e.g. in the same datacentre)

@chrisveness Best to normalize your text input before hashing.

const pwNrm = String(password).normalize('NFKC');
const pwUtf8 = new TextEncoder().encode(pwNrm);

Aside I'd probably use a fixed setting for the iteration count, or leave out the "version" at the beginning, and layer both the version and hard-code the iteration count in a parent wrapper method.


@Zemnmez what do you mean by "additionally this implementation uses a non-fixed time string comparison"?

@tracker1 this script uses regular equality to compare a 'good' input. regular equality is shortcut, meaning the more correct it is, the more time it will take to verify (as the comparison will bail as soon as a byte fails to compare). The security impact of this is subtle and depends a lot on where this is deployed, but in cases where an attacker can cause this to be called many times and measure response time, they can probably guess the correct PBKDF2 digest.

brandonros commented Dec 12, 2020

edited

This took me way longer than it should have so, anybody else who might benefit from it, here you go. I think it's secure...

<script type="text/javascript">
const deriveKeyAndIv = async (password, salt) => {
  const passwordKey = await crypto.subtle.importKey(
    'raw',
    password,
    'PBKDF2',
    false,
    ['deriveBits']
  )
  const keyLength = 32
  const ivLength = 16
  const numBits = (keyLength + ivLength) * 8
  const derviedBytes = await crypto.subtle.deriveBits({
    name: 'PBKDF2',
    hash: 'SHA-512',
    salt,
    iterations: 10000
  }, passwordKey, numBits)
  const key = await crypto.subtle.importKey(
    'raw',
    derviedBytes.slice(0, keyLength),
    'AES-GCM',
    false,
    ['encrypt', 'decrypt']
  )
  const iv = derviedBytes.slice(keyLength, keyLength + ivLength)
  return {
    key,
    iv
  }
}

const encrypt = async (password, salt, plainText) => {
  const { key, iv } = await deriveKeyAndIv(password, salt)
  return crypto.subtle.encrypt({
    name: 'AES-GCM',
    iv
  }, key, plainText)
}

const decrypt = async (password, salt, cipher) => {
  const { key, iv } = await deriveKeyAndIv(password, salt)
  return crypto.subtle.decrypt({
    name: 'AES-GCM',
    iv
  }, key, cipher)
}

const utf8ToUint8Array = (input) => new TextEncoder().encode(input)

const arrayBufferToUtf8 = (input) => new TextDecoder().decode(new Uint8Array(input))

const arrayBufferToHex = (input) => {
  input = new Uint8Array(input)
  const output = []
  for (let i = 0; i < input.length; ++i) {
    output.push(input[i].toString(16).padStart(2, '0'))
  }
  return output.join('')
}

const run = async () => {
  const password = utf8ToUint8Array('fdcf72d4-7c59-4240-a527-6630fc92fcbb')
  const salt = utf8ToUint8Array('233f9fad-7681-4ebd-ad5e-164480bbc3f5')
  const data = utf8ToUint8Array('Hello, world!')
  const cipher = await encrypt(password, salt, data)
  const plainText = await decrypt(password, salt, cipher)
  console.log(arrayBufferToHex(cipher))
  console.log(arrayBufferToUtf8(plainText))
}

run()
</script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK