如何在节点 js 中使用加密生成唯一的 8 位数字?

问题描述 投票:0回答:3

我想每次都生成一个唯一的数字。我为此使用了加密模块。

const alphanu = crypto.randomBytes(16).toString('hex')

这将生成长度为 32 的字母数字字符串。我想生成一个长度为 8 的数字。

我也试过 randomInt

const num = crypto.randomInt(10000000,99999999)

它总是会生成一个唯一的数字吗?

如何实现我想要的?

javascript node.js random cryptojs
3个回答
0
投票

要制作一个随机且唯一的数字,您必须将

.random()
和时间戳混合在一起。

这是我使用了一段时间的简单 UID 生成器,我修改了

.substring()
以便它返回 8 个字符。

const alphanu = Date.now().toString(36) + Math.random().toString(36).substring(13);

console.log(alphanu); 

0
投票

你的“独特”要求会比你想象的更难实现。如果您的意思是“不确定性”,那么就像您在问题中所做的那样使用

crypto.randomInt()

crypto.randomInt(10**7, 10**8-1) // 8 digit, no leading zeroes
crypto.randomInt(0, 10**8-1).toString().padStart(8, "0") // 8 digits, allows leading zeroes

从技术上讲,这是伪随机,不是随机的。但是,对于大多数用例,您将无法区分。

现在,如果您需要独特性,那么您可以使用两种相当简单的方法:

  1. 将您已经使用过的每个号码存储在数据库中,或者
  2. 从 0 开始,每次递增 1,并在必要时添加前导零(如果您不想要前导零,则从 10^7 开始)。有了这个,您需要做的就是存储最后使用的号码。但是,使用这种方法,结果是确定性的,这可能是一个安全缺陷,具体取决于您的用例。

-1
投票

它有多独特取决于可能性。如果您将它限制为非常小且只有十进制数的固定大小/长度,那么一个数字出现多次的可能性很高。 随机化不是唯一的好方法。 但这取决于用例的重要性。

我会使用 padStart 将长度固定为 8 位数字。

const randomNumber = crypto.randomInt(0, 99999999).toString();
const randomNumberFixedTo8Digits = randomNumber.padStart(8, "0");

更独特的是这种方法(但不固定为 8 位数字):

const crypto = require("crypto");

const id = crypto.randomBytes(16).toString("hex");

console.log(id); // => f9b327e70bbcf42494ccb28b2d98e00e

或者您可以使用 uuid,当需要唯一时(但不限于 8 位数字)更安全:

const { randomUUID } = require('crypto'); // Added in: node v14.17.0

console.log(randomUUID());

// '89rct5ac2-8493-49b0-95d8-de843d90e6ca'
© www.soinside.com 2019 - 2024. All rights reserved.