Akhil Gopan Akhil Gopan - 1 year ago 186
Node.js Question

Angular JS Cryptography. pbkdf2 and iteration

I want to convert my string to PBKDF2 with sha512 and iteration count. I did in nodejs by using "pbkdf2" module. how can i achieve the same in angular JS.

Answer Source

You can use built-in WebCryptographyApi with native support in all modern browsers (http://caniuse.com/#feat=cryptography)

This in an example extracted (and modified) from here and here

function deriveAKey(password, salt, iterations, hash) {

    // First, create a PBKDF2 "key" containing the password
        {"name": "PBKDF2"},
        // Derive a key from the password
        return window.crypto.subtle.deriveKey(
                "name": "PBKDF2",
                "salt": stringToArrayBuffer(salt),
                "iterations": iterations,
                "hash": hash
            {"name": "AES-CBC", "length": 128}, // Key we want.Can be any AES algorithm ("AES-CTR", "AES-CBC", "AES-CMAC", "AES-GCM", "AES-CFB", "AES-KW", "ECDH", "DH", or "HMAC")
            true,                               // Extractable
            ["encrypt", "decrypt"]              // For new key
    }).then(function(aesKey) {
        // Export it so we can display it
        return window.crypto.subtle.exportKey("raw", aesKey);
    }).then(function(keyBytes) {
        // Display key in Base64 format
        var keyS = arrayBufferToString(keyBytes);
        var keyB64 = btoa (keyS);
    }).catch(function(err) {
        alert("Key derivation failed: " + err.message);

//Utility functions

function stringToArrayBuffer(byteString){
    var byteArray = new Uint8Array(byteString.length);
    for(var i=0; i < byteString.length; i++) {
        byteArray[i] = byteString.codePointAt(i);
    return byteArray;

function  arrayBufferToString(buffer){
    var byteArray = new Uint8Array(buffer);
    var byteString = '';
    for(var i=0; i < byteArray.byteLength; i++) {
        byteString += String.fromCodePoint(byteArray[i]);
    return byteString;


var salt = "Pick anything you want. This isn't secret.";
var iterations = 1000;
var hash = "SHA-512";
var password = "password";

deriveAKey(password, salt, iterations, hash);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download