如何在JavaScript中生成随机十六进制字符串

45
如何生成一个指定长度、仅由十六进制字符(0123456789abcdef)组成的随机字符串?

1
'十六进制字符'到底是什么,例如aAbBfF是有效的吗?另外,是“普通”的随机还是加密强度的随机? - georg
2
更新问题。普通随机就可以了... - Alessandro Dionisi
17个回答

69

使用展开运算符和.map()的简短替代方法


Demo 1

const genRanHex = size => [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join('');

console.log(genRanHex(6));
console.log(genRanHex(12));
console.log(genRanHex(3));

  1. 传入一个数字(size),用于返回字符串的长度。
  2. 定义一个空数组(result)和一个在[0-9][a-f]范围内的字符串数组(hexRef)。
  3. 在每次for循环迭代中,生成一个0到15的随机数,并将其用作步骤2(hexRef)中字符串数组的值的索引,然后使用push()将该值添加到步骤2(result)中的空数组中。
  4. 将数组(result)作为 join('') 的字符串返回。

Demo 2

const getRanHex = size => {
  let result = [];
  let hexRef = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];

  for (let n = 0; n < size; n++) {
    result.push(hexRef[Math.floor(Math.random() * 16)]);
  }
  return result.join('');
}

console.log(getRanHex(6));
console.log(getRanHex(12));
console.log(getRanHex(3));


1
parseInt返回字符串中编码为指定基数的数字的整数,而不是相反。 - Lukáš Řádek
你说得完全正确,我不知道当时在想什么,感谢你发现了这个问题,@LukášŘádek 请查看更新。 - zer00ne
1
你知道吗,你也曾经让我上当了一秒钟。乍一看似乎还算合理。请从-1到+1进行投票。 - Lukáš Řádek
1
当两个客户端生成时,它不能是唯一的机会是多少? - Naga
@Naga 不够安全。我最终创建了一个微服务来跟踪客户端之间的16位十六进制字符串。 - Angel S. Moreno

44

NodeJS 用户

您可以使用 randomBytes 函数,它位于crypto 模块内,用于生成给定大小的具有加密强度的伪随机数据。同时,您可以轻松将其转换为十六进制。

import crypto from "crypto";

const randomString = crypto.randomBytes(8).toString("hex");

console.log(randomString)  // ee48d32e6c724c4d

以上代码片段生成一个随机的8字节十六进制数,您可以根据需要更改其长度。


9
有几种方法。其中一种方法是只从预定义字符串中提取:
```html

有几种方法。其中一种方法是只从预定义字符串中提取:

```
function genHexString(len) {
    const hex = '0123456789ABCDEF';
    let output = '';
    for (let i = 0; i < len; ++i) {
        output += hex.charAt(Math.floor(Math.random() * hex.length));
    }
    return output;
}

另一种方法是附加一个随机数,该随机数在0到15之间,并将其转换为十六进制字符串,使用toString:
function genHexString(len) {
    let output = '';
    for (let i = 0; i < len; ++i) {
        output += (Math.floor(Math.random() * 16)).toString(16);
    }
    return output;
}

6
您可以使用十六进制数字0xfffff来生成一个十六进制字符串。
getHexaNumb() {
    return Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")
}


4

这将安全地生成一个32字节的随机字符串,并将其编码为十六进制格式(64个字符)。

Array.from(crypto.getRandomValues(new Uint8Array(32)))
    .map(b => b.toString(16).padStart(2, '0')).join('');

长版:

function generateRandomHexString(numBytes) {
    const bytes = crypto.getRandomValues(new Uint8Array(numBytes));
    const array = Array.from(bytes);
    const hexPairs = array.map(b => b.toString(16).padStart(2, '0'));
    return hexPairs.join('')
}

返回的字符串长度将为 numBytes * 2 - user3064538
crypto.getRandomValues 直到 Node 19 才存在,因此如果您需要在浏览器和 Node 中运行代码,则这种方式真的很麻烦。 - user3064538

2

数组的长度是随机字符串的长度。

const randomHex = Array.from({ length: 32 }, () => "0123456789ABCDEF".charAt(Math.floor(Math.random() * 16))).join('');
console.log(randomHex);

1
如果您可以使用lodash库,这里是生成16个字符的代码片段:

let randomString = _.times(16, () => (Math.random()*0xF<<0).toString(16)).join('');

如果您只想要四位数字,我认为您可以将前面的16改为4。 - Ron

0
使用 for 循环、charAt 和 Math.random。
let result = "";
let hexChar = "0123456789abcdef";
for (var i = 0; i < 6; i++) {
  result += hexChar.charAt(Math.floor(Math.random() * hexChar.length));
}
console.log(`#${result}`);

1
你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community

0
let generateMacAdd = (function () {
    let hexas = '0123456789ABCDEF'
    let storeMac = []
    let i = 0
    do {
        let random1st = hexas.charAt(Math.floor(Math.random() * hexas.length))
        let random2nd = hexas.charAt(Math.floor(Math.random() * hexas.length))
        storeMac.push(random1st + random2nd)
        i++
    } while (i <= 6)
    return storeMac.join(':')
})()
console.log(generateMacAdd);       //will generate a formatted mac address

我在这里使用自调用函数,这样你就可以不需要任何参数直接调用变量。 我还使用了 do while 循环,只是为了方便自己,你可以根据自己的习惯使用任何类型的循环。

0
在现代浏览器上还有Web Crypto API。它也允许生成(具有密码学强度的)随机值,类似于node:crypto的功能。
const randomHex = (bytes = 8) => {
  // fill typed array with random numbers
  // from 0..255 per entry
  const array = new Uint8Array(bytes)
  window.crypto.getRandomValues(array)

  // wrap to array and convert numbers to hex
  // then join to single string
  return [...array]
    .map(n => n.toString(16))
    .join('')
}

使用示例

console.debug(randomHex(2)) // 47be
console.debug(randomHex(4)) // 414c34a2
console.debug(randomHex(8)) // 53f5d393e13bd86

资源

https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接