2013-05-25 63 views

回答

37

我在https://jswebcrypto.azurewebsites.net/

去年做題爲Developer's Guide to JavaScript and Web Cryptography的介紹,並有演示網站在線這包括簡單的哈希,HMAC,PBKDF2和AES例子OpenSSL的命令行(作爲基準)SJCLCryptoJSNode.js Crypto,甚至W3C Web Cryptography API

這裏是SJCL例子:

哈希

var out = sjcl.hash.sha1.hash("The quick brown fox jumps over the lazy dog"); 
var hash = sjcl.codec.hex.fromBits(out) 
// "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12" 

HMAC

var key = sjcl.codec.utf8String.toBits("key"); 
var out = (new sjcl.misc.hmac(key, sjcl.hash.sha256)).mac("The quick brown fox jumps over the lazy dog"); 
var hmac = sjcl.codec.hex.fromBits(out) 
// "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8" 

PBKDF2

var hmacSHA1 = function (key) { 
    var hasher = new sjcl.misc.hmac(key, sjcl.hash.sha1); 
    this.encrypt = function() { 
     return hasher.encrypt.apply(hasher, arguments); 
    }; 
}; 

var passwordSalt = sjcl.codec.hex.toBits("cf7488cd1e48e84990f51b3f121e161318ba2098aa6c993ded1012c955d5a3e8"); 
var derivedKey = sjcl.misc.pbkdf2("password", passwordSalt, 100, 256, hmacSHA1); 
var hexKey = sjcl.codec.hex.fromBits(derivedKey); 
// c12b2e03a08f3f0d23f3c4429c248c275a728814053a093835e803bc8e695b4e 

注意:這需要你在包括sha1.js除了sjcl.js.

+0

該網站的例子是非常有用的,謝謝! 另外,如果您省略了hmacSHA1函數並且不將其作爲參數傳遞,它將默認使用hmac SHA256。 – janka102

+1

@ kevin-hakanson在閱讀你的答案的時候,我注意到,在'PBKDF2'示例函數中'hmacSHA1'什麼都不做 - 同一個鍵在使用和不使用時都返回 - http://jsfiddle.net/2802m8n5/。你能告訴我們爲什麼會發生這種情況? – Shtirlits

+0

更新小提琴(http://jsfiddle.net/2802m8n5/1/)以包含sha1(不屬於sjcl.js)https://github.com/bitwiseshiftleft/sjcl/blob/master/core/sha1.js –

13

這可能有點晚,但我最近也在研究如何做客戶端加密散列,並且answer by Kevin Hakanson非常有幫助,演示網站也非常有用!它演示瞭如何在PBKDF2(HMAC和SHA1)中使用自定義的僞隨機函數,但是我發現如果沒有通過,SJCL有默認設置,我只是想說明如何做到這一點,同時生成隨機鹽。

我也發現sjcl docs相當有幫助。

生成隨機鹽和密碼爲「password」使用PBKDF2,你能做到這一點,它最終被僅有3行:如果你想存儲鹽

// Each random "word" is 4 bytes, so 8 would be 32 bytes 
var saltBits = sjcl.random.randomWords(8); 
// eg. [588300265, -1755622410, -533744668, 1408647727, -876578935, 12500664, 179736681, 1321878387] 

// I left out the 5th argument, which defaults to HMAC which in turn defaults to use SHA256 
var derivedKey = sjcl.misc.pbkdf2("password", saltBits, 1000, 256); 
// eg. [-605875851, 757263041, -993332615, 465335420, 1306210159, -1270931768, -1185781663, -477369628] 

// Storing the key is probably easier encoded and not as a bitArray 
// I choose base64 just because the output is shorter, but you could use sjcl.codec.hex.fromBits 
var key = sjcl.codec.base64.fromBits(derivedKey); 
// eg. "2+MRdS0i6sHEyvJ5G7x0fE3bL2+0Px7IuVJoYeOL6uQ=" 

,你可能想編碼它

var salt = sjcl.codec.base64.fromBits(saltBits); 
// eg. "IxC/6ZdbU/bgL7PkU/ZCL8vAd4kAvr64CraQaU7KQ3M=" 
// Again I just used base64 because it's shorter, but you could use hex 

// And to get the bitArray back, you would do the exact opposite 
var saltBits = sjcl.codec.base64.toBits(salt);