NodeJS:如何生成用于密码重置的随机十六进制密钥?

huangapple go评论88阅读模式
英文:

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) =&gt;{
  const pullOfChars = &quot;AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890&quot;;
  const generatedArrayOfChars = Array.from(
    { length: length },
    (v, k) =&gt; pullOfChars[Math.floor(Math.random() * pullOfChars.length)].toString(16)
  );

  const randomizedString = generatedArrayOfChars.join(&quot;&quot;);
  return randomizedString
  
}

console.log(randomizer(10))

<!-- end snippet -->

Or you can use the of node js crypto

const crypto = require(&#39;crypto&#39;);

const randomString1 = crypto.randomBytes(10).toString(&#39;hex&#39;);
console.log(randomString1);

hope it helps

huangapple
  • 本文由 发表于 2023年5月28日 01:02:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76348043.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定