2026-09-04
token.cpp
#include <algorithm>
#include <print>
#include <string>
const std::string alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
std::string token(const std::string& bytes) {
std::string s;
for (unsigned char b : bytes)
s += alphabet[b % alphabet.size()];
return s;
}
int main() {
std::string all;
for (int b = 0; b < 256; ++b)
all += static_cast<char>(b);
std::string t = token(all);
std::println("{} {}", std::ranges::count(t, 'A'), std::ranges::count(t, 'z'));
}
token は、乱数のバイト列から、英数字62文字のどれもが同じ確率で出るトークンを作るつもりの関数です。main は 0〜255 のバイトを1つずつすべて渡し、できた文字列に 'A' と 'z' が何回ずつ現れるかを出力します。本来は 4 4 を出力するはずですが、いまは 5 4 を出力します。
Answer
Wrong
for (unsigned char b : bytes)
s += alphabet[b % alphabet.size()];
バイトは256通りあり、256 = 62 × 4 + 8 です。b % 62 はバイト 0〜247 で 0〜61 を4周し、残りの 248〜255 で 0〜7 をもう一度たどります。alphabet の先頭8文字 A〜H には5つのバイトが、残りの54文字には4つずつが対応するので、'A' は5回、'z' は4回現れます。
本物の乱数を渡しても同じで、A〜H は他の文字の 5/4 倍出やすくなります。推測されにくいことが求められるトークンに、文字の出方の偏りが残ります。
Right
for (unsigned char b : bytes)
if (b < 256 - 256 % alphabet.size())
s += alphabet[b % alphabet.size()];
256 - 256 % 62 は 248 で、62 の倍数です。248 以上のバイトを捨てれば、残る 0〜247 は62文字のそれぞれにちょうど4つずつ対応します。捨てた分だけトークンは渡したバイト数より短くなるので、実際に使うときは、必要な長さになるまでバイトを読み足します。