nodejs crypto module vs crypto-js

陌路散爱 提交于 2019-12-05 06:23:04

Apparently I can't add comments to freakish's answer, so I'll write it here instead:

reset() works fine. The significant difference is you're converting the hash output to a hex string within the iteration loop.

In the cryptojs example, finalize() returns raw binary data. In the crypto module example, digest() is returning a hex string. That difference in output means a difference in input when you iteratively re-hash.

Use PKDF2 instead!

Why are you not using the built-in PBKDF2 from node-crypto:

var hashedpw = crypto.pbkdf2Sync(password, salt, iterations, keysize);

and crypto-js:

var hashedpw = CryptoJS.PBKDF2(
    password, 
    salt, 
    { keySize: keysize/32, iterations: iterations }
);

Not only is it more secure than what you're trying to do by being much more expensive to compute than repeated hashing, it's also a lot easier to implement.

I've done some tests and apparently this reset function ( in crypto-js ) messes up. I'm not sure what it does and I don't have enough patience to look for an issue. :) However, here's the working solution:

function SHA256Encrypt(password, salt, iteration) {
    var saltedpassword = salt + password;
    for(var i = 0; i < iteration-1; i++) {
        alert("saltedpassword = " + saltedpassword);
        saltedpassword = CryptoJS.SHA256( saltedpassword ).toString( CryptoJS.enc.Hex );
    }
    saltedpassword = CryptoJS.SHA256( saltedpassword );
    return saltedpassword.toString(CryptoJS.enc.Base64);
}

which makes both codes even more similar, which is good.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!