Web Crypto API PBKDF2 Generate Password

by Anish

Posted on Monday september 17, 2018

This sample chapter extracted from the book, Cryptography for JavaScript Developers.

Here's an example showing how to use deriveKey() to create a Secure Remote Password (also known as Proof of Secret) from a user's password using pbkdf2 algorithm

The PBKDF2 Demo

PBKDF2 Derived Key (Hex):
Random Salt (Hex) :
Note: Using Fixed salt will generate the same derive key

The Web crypto api Javascript example PBKDF

function generateKey(password,iterations) {
    // salt should be Uint8Array or ArrayBuffer

    var saltBuffer = crypto.getRandomValues(new Uint8Array(8));
    var encoder = new TextEncoder('utf-8');
    var passphraseKey = encoder.encode("password");

    // You should firstly import your passphrase Uint8array into a CryptoKey
  {name: 'PBKDF2'}, 
  ['deriveBits', 'deriveKey']
).then(function(key) {

  return window.crypto.subtle.deriveKey(
    { "name": 'PBKDF2',
      "salt": saltBuffer,
      // don't get too ambitious, or at least remember
      // that low-power phones will access your app
      "iterations": iterations,
      "hash": 'SHA-256'

    // Note: for this demo we don't actually need a cipher suite,
    // but the api requires that it must be specified.
    // For AES the length required to be 128 or 256 bits (not bytes)
    { "name": 'AES-CBC', "length": 256 },

    // Whether or not the key is extractable (less secure) or not (more secure)
    // when false, the key can only be passed as a web crypto object, not inspected

    // this web crypto object will only be allowed for these functions
    [ "encrypt", "decrypt" ]
}).then(function (webKey) {

  return crypto.subtle.exportKey("raw", webKey);

}).then(function (buffer) {

     document.getElementById("key").value= bytesToHexString(buffer);
     document.getElementById("salt").value= bytesToHexString(saltBuffer);


Download the sample code here
Next Reading Perform AES Encryption Using importKey Method

Thanku for reading !!! Give a Share for Support

Asking for donation sound bad to me, so i'm raising fund from The Modern Cryptography CookBook for Just $9. Leanpub books Discount coupon first 100 reader. No hurry read the sample chapters here then decide.

Alternatively you can buy My all four Cryptography book Just $10.99

  • The Modern Cryptography Book.
  • Python Cryptography
  • Cryptography for JavaScript Developer
  • Go lang Cryptography for developers

python Cryptography Topics
For Coffee/ Beer/ Amazon Bill and further development of the project Support by Purchasing, The Modern Cryptography CookBook for Just $9 Coupon Price

Cryptography for Python Developers

Cryptography for JavaScript Developers

Go lang ryptography for Developers