我有一个想要哈希的字符串。在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. ');

其他回答

我使用的是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);
}

crypto模块使这非常容易。

设置:

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

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

用法:

sha256('Hello, world. ');

我不得不把我的2美分扔在希望这能帮助某人。

对于那些使用CommonJS的人

const crypto = require('crypto');
const secret = 'I love writing code, fixing things and building helpful tools';
const hash = crypto.createHmac('sha256', secret).digest('hex');

console.log('Hash successfully generated: ', hash);

适用于使用ES模块的用户

const { createHmac } = await import('crypto');
const secret = 'I love writing code, fixing things and building helpful tools';
const hash = createHmac('sha256', secret).digest('hex');

console.log('Hash successfully generated: ', hash);

超级简单! 快乐编码:)

简单的一句话:

如果你想要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

你可以使用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();