我有一个想要哈希的字符串。在node.js中生成哈希最简单的方法是什么?
散列用于版本控制,而不是安全性。
我有一个想要哈希的字符串。在node.js中生成哈希最简单的方法是什么?
散列用于版本控制,而不是安全性。
当前回答
看看crypto。createhash (algorithm)
var filename = process.argv[2];
var crypto = require('crypto');
var fs = require('fs');
var md5sum = crypto.createHash('md5');
var s = fs.ReadStream(filename);
s.on('data', function(d) {
md5sum.update(d);
});
s.on('end', function() {
var d = md5sum.digest('hex');
console.log(d + ' ' + filename);
});
其他回答
我使用的是blueimp-md5,它“兼容服务器端环境,如Node.js,模块加载器,如RequireJS, Browserify或webpack和所有网络浏览器。”
像这样使用它:
var md5 = require("blueimp-md5");
var myHashedString = createHash('GreensterRox');
createHash(myString){
return md5(myString);
}
如果在公开场合传递散列值,对它们加盐总是一个好主意,这样人们就更难重新创建它们:
createHash(myString){
var salt = 'HnasBzbxH9';
return md5(myString+salt);
}
即使哈希不是为了安全性,您也可以使用sha而不是md5。在我看来,人们现在应该忘记md5,它是过去的事了!
不建议使用普通的nodejs sha256。所以,现在你有两个选择:
var shajs = require('sha.js') - https://www.npmjs.com/package/sha.js (used by Browserify)
var hash = require('hash.js') - https://github.com/indutny/hash.js
我更喜欢使用shajs而不是哈希,因为我认为sha是目前最好的哈希函数,你现在不需要一个不同的哈希函数。所以要在十六进制中获得一些哈希,你应该像下面这样做:
sha256.update('hello').digest('hex')
crypto模块使这非常容易。
设置:
// import crypto from 'crypto';
const crypto = require('crypto');
const sha256 = x => crypto.createHash('sha256').update(x, 'utf8').digest('hex');
用法:
sha256('Hello, world. ');
你可以使用crypto-js javaScript库的加密标准,有最简单的方法生成sha256或sha512
const SHA256 = require("crypto-js/sha256");
const SHA512 = require("crypto-js/sha512");
let password = "hello"
let hash_256 = SHA256 (password).toString();
let hash_512 = SHA512 (password).toString();
考虑到来自 http://www.thoughtcrime.org/blog/the-cryptographic-doom-principle/ (简而言之:首先加密,然后验证。之后先验证,然后解密) 我在node.js中实现了以下解决方案:
function encrypt(text,password){
var cipher = crypto.createCipher(algorithm,password)
var crypted = cipher.update(text,'utf8','hex')
crypted += cipher.final('hex');
return crypted;
}
function decrypt(text,password){
var decipher = crypto.createDecipher(algorithm,password)
var dec = decipher.update(text,'hex','utf8')
dec += decipher.final('utf8');
return dec;
}
function hashText(text){
var hash = crypto.createHash('md5').update(text).digest("hex");
//console.log(hash);
return hash;
}
function encryptThenAuthenticate(plainText,pw)
{
var encryptedText = encrypt(plainText,pw);
var hash = hashText(encryptedText);
return encryptedText+"$"+hash;
}
function VerifyThenDecrypt(encryptedAndAuthenticatedText,pw)
{
var encryptedAndHashArray = encryptedAndAuthenticatedText.split("$");
var encrypted = encryptedAndHashArray[0];
var hash = encryptedAndHashArray[1];
var hash2Compare = hashText(encrypted);
if (hash === hash2Compare)
{
return decrypt(encrypted,pw);
}
}
它可以用以下方法进行测试:
var doom = encryptThenAuthenticate("The encrypted text",user.cryptoPassword);
console.log(VerifyThenDecrypt(doom,user.cryptoPassword));
希望这对你有所帮助:-)