我有一个想要哈希的字符串。在node.js中生成哈希最简单的方法是什么?

散列用于版本控制,而不是安全性。


当前回答

crypto模块使这非常容易。

设置:

// import crypto from 'crypto';
const crypto = require('crypto');

const sha256 = x => crypto.createHash('sha256').update(x, 'utf8').digest('hex');

用法:

sha256('Hello, world. ');

其他回答

即使哈希不是为了安全性,您也可以使用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。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);
});

简单的一句话:

如果你想要UTF8文本哈希:

const hash = require('crypto').createHash('sha256').update('Hash me', 'utf8').digest('hex');

如果你想用Python, PHP, Perl, Github得到相同的散列:

const hash = require('crypto').createHash('sha256').update('Hash me', 'binary').digest('hex');

你也可以用sha1, md5, sha256, sha512替换sha256

如果你只是想md5哈希一个简单的字符串,我发现这对我有用。

var crypto = require('crypto');
var name = 'braitsch';
var hash = crypto.createHash('md5').update(name).digest('hex');
console.log(hash); // 9b74c9897bac770ffc029102a200c5de
sha256("string or binary");

我在其他答案上遇到了问题。我建议你将编码参数设置为二进制以使用字节字符串,并防止Javascript (NodeJS)和其他语言/服务之间的不同哈希,如Python, PHP, Github…

如果你不使用这段代码,你可以在NodeJS和Python之间得到不同的散列…

如何获得相同的散列,Python, PHP, Perl, Github(并防止一个问题):

NodeJS正在哈希字符串的UTF-8表示。其他语言(如Python、PHP或PERL…)是对字节字符串进行哈希。

我们可以添加二进制参数来使用字节字符串。

代码:

const crypto = require("crypto");

function sha256(data) {
    return crypto.createHash("sha256").update(data, "binary").digest("base64");
    //                                               ------  binary: hash the byte string
}

sha256("string or binary");

文档:

加密。createHash(algorithm[, options]):该算法依赖于平台上OpenSSL版本支持的可用算法。 hash.digest([encoding]):编码可以是'hex', 'latin1'或'base64'。(64进制更短)。

你可以把问题:sha256(“\ xac”),“\ xd1”、“\ xb9”,“\ xe2”、“\ xbb”,“\ x93”等……

其他语言(如PHP, Python, Perl…)和我用.update(data, "binary")的解决方案: sha1(“\ xac”)/ / 39527 c59247a39d18ad48b9947ea738396a3bc47 默认情况下(不含二进制文件): sha1 / / f50eb35d94f1d75480496e54f4b4a472a9148752(“\ xac”)