Javascript 如何使用加密创建随机盐哈希

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11520126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:09:19  来源:igfitidea点击:

How to create random-salt-hash with crypto

javascriptnode.jscryptographynode-crypto

提问by dev.pus

I want to create a salt-hash using node.js crypto lib without having to parse any hardcoded data.

我想使用 node.js 加密库创建一个 salt-hash,而不必解析任何硬编码数据。

What do I mean with hardcoded?

硬编码是什么意思?

var salt, hardcodedString = "8397dhdjhjh";
crypto.createHmac('sha512', hardcodedString).update(salt).digest("base64");

Isn't there any other way how I can create a random string without using raw javascript, random functions or hardcoding something?

没有其他方法可以在不使用原始 javascript、随机函数或硬编码的情况下创建随机字符串吗?

Regards

问候

UPDATE

更新

var Crypto = require('crypto')
    , mongoose = require('mongoose');

module.exports = mongoose.model('User', new mongoose.Schema({
    username: {
        type: String
        , required: true
        , index: { unique: true, sparse: true }
        , set: toLower
    },
    email: {
        type: String
        , required: true
        , index: { unique: true, sparse: true }
        , set: toLower
    },
    salt: {
        type: String
        , set: generateSalt
    },
    password: {
        type: String
        , set: encodePassword
    }
}),'Users');

function toLower(string) {
    return string.toLowerCase();
}

function generateSalt() {
    //return Math.round((new Date().valueOf() * Math.random())) + '';
    Crypto.randomBytes('256', function(err, buf) {
        if (err) throw err;
        return buf;
    });
    // return Crypto.randomBytes('256'); // fails to
}

function encodePassword(password) {
    return password;
    // TODO: setter has no access to this.salt
    //return Crypto.createHmac('sha512', salt).update(password).digest("base64");
}

function authenticate(plainPassword) {
    return encodePassword(plainPassword) === this.password;
}

回答by CodesInChaos

A quick look at the documentation turns up the crypto.randomBytesfunction.

快速浏览一下文档就会发现这个crypto.randomBytes功能。

var buf = crypto.randomBytes(16);

This returns a buffer containing raw bytes. If you want a string, you can use toString('base64')or toString('hex').

这将返回一个包含原始字节的缓冲区。如果你想要一个字符串,你可以使用toString('base64')toString('hex')