我想使用 sha512 和迭代计数将我的字符串转换为 PBKDF2。我在nodejs中使用“pbkdf2”模块。我怎样才能在 Angular JS 中实现同样的效果。
问问题
1939 次
1 回答
5
您可以在所有现代浏览器中使用具有本机支持的内置WebCryptographyApi ( http://caniuse.com/#feat=cryptography )
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);
于 2016-11-07T14:59:13.957 回答