如何生成一个指定长度、仅由十六进制字符(0123456789abcdef)组成的随机字符串?
使用展开运算符和.map()
的简短替代方法
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));
size
),用于返回字符串的长度。result
)和一个在[0-9]
和 [a-f]
范围内的字符串数组(hexRef
)。for
循环迭代中,生成一个0到15的随机数,并将其用作步骤2(hexRef
)中字符串数组的值的索引,然后使用push()
将该值添加到步骤2(result
)中的空数组中。result
)作为 join('')
的字符串返回。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));
您可以使用 randomBytes 函数,它位于crypto
模块内,用于生成给定大小的具有加密强度的伪随机数据。同时,您可以轻松将其转换为十六进制。
import crypto from "crypto";
const randomString = crypto.randomBytes(8).toString("hex");
console.log(randomString) // ee48d32e6c724c4d
以上代码片段生成一个随机的8字节十六进制数,您可以根据需要更改其长度。
有几种方法。其中一种方法是只从预定义字符串中提取:
```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;
}
function genHexString(len) {
let output = '';
for (let i = 0; i < len; ++i) {
output += (Math.floor(Math.random() * 16)).toString(16);
}
return output;
}
getHexaNumb() {
return Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")
}
这将安全地生成一个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
。 - user3064538crypto.getRandomValues
直到 Node 19 才存在,因此如果您需要在浏览器和 Node 中运行代码,则这种方式真的很麻烦。 - user3064538数组的长度是随机字符串的长度。
const randomHex = Array.from({ length: 32 }, () => "0123456789ABCDEF".charAt(Math.floor(Math.random() * 16))).join('');
console.log(randomHex);
let randomString = _.times(16, () => (Math.random()*0xF<<0).toString(16)).join('');
let result = "";
let hexChar = "0123456789abcdef";
for (var i = 0; i < 6; i++) {
result += hexChar.charAt(Math.floor(Math.random() * hexChar.length));
}
console.log(`#${result}`);
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
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
aAbBfF
是有效的吗?另外,是“普通”的随机还是加密强度的随机? - georg