本文介绍了Angular JS密码学. pbkdf2和迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用sha512和迭代计数将我的字符串转换为PBKDF2.我通过使用"pbkdf2"模块在nodejs中进行了操作.我该如何在有角度的JS中实现相同的目标.
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.
推荐答案
您可以使用内置的在所有现代浏览器中均具有本机支持的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);
这篇关于Angular JS密码学. pbkdf2和迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!