我正在寻找一种独立于平台的方法来为 Twitter 随机数生成随机字母数字字符串。目前我正在使用它,但它取决于 /dev/random
,这显然是 UNIX 特定的:
private auto _getNonce() {
ubyte[32] buffer;
File devRandom = File("/dev/random", "rb");
auto randomData = devRandom.rawRead(buffer);
auto randomBase = Base64.encode(randomData);
auto nonWords = regex(r"[\W_]", "g");
return replaceAll(randomBase, nonWords, "");
}
下面是the recommendation in the Twitter development documentation要获取 32 字节的随机数据,请对它们进行 Base-64 编码并去除所有非字母数字字符。
随机数不必是加密安全的,它只是用于防止重复提交。对于在 Windows 和 UNIX 上都有效的更好方法有什么建议吗?
最佳答案
注意:这么多年过去了,我应该指出 randomCover
不会重复。这意味着该解决方案将只提供一次小写字符和一次大写字符。我考虑使用cycle()
来解决这个问题,但是randomCover
不支持无限范围。
如果您只需要 32 个字母数字字符:
import std.algorithm : fill;
import std.ascii : letters, digits;
import std.conv : to;
import std.random : randomCover, rndGen;
import std.range : chain;
import std.stdio : writeln;
void main() {
// dchar[] are random access, strings (char[]) are not
auto asciiLetters = to!(dchar[])(letters);
auto asciiDigits = to!(dchar[])(digits);
dchar[32] key;
fill(key[], randomCover(chain(asciiLetters, asciiDigits), rndGen));
writeln(key);
}
static assert(!isNarrowString!R); // narrow strings cannot be indexed as ranges
窄字符串是 char[] 和 wchar[]。虽然它们是数组,但无法在 O(1) 中找到“字符”2,531,从而阻止这些类型被视为随机访问,而这是 randomCover 所要求的。
关于twitter - 在 D 中生成随机字母数字字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20161811/