英文:
NodeJS: How do I generate a random hex key for password reset?
问题
我正在开发一个express js端点,我需要发送一些随机的十六进制代码。
我正在尝试在nodejs中为重置密码过程生成一个随机的十六进制密钥。有人可以帮助吗?
是否有任何库?还是我应该使用一些标准代码?
我还应该像使用jwt一样对代码进行签名吗?
英文:
I am developing a express js end point and I need to send some random hex-decimal code
I am trying to generate a random hex key for a reset password process in nodejs. Can anyone help?
Is there any library? Or shell I use some standard code
Shell I also sign the code like with jwt?
答案1
得分: 1
第一种方法是使用纯JavaScript,不需要任何库:
const randomizer = (length) => {
const pullOfChars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890";
const generatedArrayOfChars = Array.from(
{ length: length },
(v, k) => pullOfChars[Math.floor(Math.random() * pullOfChars.length)].toString(16)
);
const randomizedString = generatedArrayOfChars.join("");
return randomizedString;
}
console.log(randomizer(10));
或者你可以使用Node.js的crypto库:
const crypto = require('crypto');
const randomString1 = crypto.randomBytes(10).toString('hex');
console.log(randomString1);
希望这有所帮助。
英文:
So let see if I can help
The first way is the js without any library
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const randomizer = (length) =>{
const pullOfChars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890";
const generatedArrayOfChars = Array.from(
{ length: length },
(v, k) => pullOfChars[Math.floor(Math.random() * pullOfChars.length)].toString(16)
);
const randomizedString = generatedArrayOfChars.join("");
return randomizedString
}
console.log(randomizer(10))
<!-- end snippet -->
Or you can use the of node js crypto
const crypto = require('crypto');
const randomString1 = crypto.randomBytes(10).toString('hex');
console.log(randomString1);
hope it helps
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论