Angular JS Cryptography。 pbkdf2和迭代

时间:2016-11-07 06:26:32

标签: angularjs node.js cryptography pbkdf2 webcryptoapi

我想用sha512和迭代计数将我的字符串转换为PBKDF2。我在nodejs中使用“pbkdf2”模块。我怎么能在角度JS中实现同样的目标。

1 个答案:

答案 0 :(得分:3)

您可以在所有现代浏览器中使用内置WebCryptographyApi本机支持(http://caniuse.com/#feat=cryptography

这是在herehere

中提取(和修改)的示例中
function deriveAKey(password, salt, iterations, hash) {

    // First, create a PBKDF2 "key" containing the password
    window.crypto.subtle.importKey(
        "raw",
        stringToArrayBuffer(password),
        {"name": "PBKDF2"},
        false,
        ["deriveKey"]).
    then(function(baseKey){
        // Derive a key from the password
        return window.crypto.subtle.deriveKey(
            {
                "name": "PBKDF2",
                "salt": stringToArrayBuffer(salt),
                "iterations": iterations,
                "hash": hash
            },
            baseKey,
            {"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);
        console.log(keyB64);
    }).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);