Help us understand the problem. What is going on with this article?

ランダムな(重複しない)ID的文字列を生成する

概要

IDとかに使う重複しない文字列を生成するメモ。
node.jsのcryptoを使う

生成方法

cryptoのrandomBytesを利用して、ランダムなBufferを生成し、それをエンコードして整形する。

  • 重複しないためにはある程度長さが必要なので20文字以上を生成するようにする(今回は20文字)。
  • エンコードはbase64。ただし+とか/が入るのでreplaceで削除
const crypto = require("crypto");
const Length = 20;

const ids = [];
console.log("生成開始");
for (let i = 0; i < 10; i++) {

    const _id = crypto.randomBytes(Length + 2).toString("base64");
    const id = _id.replace(/\W/g, '').substring(0, Length);
    ids.push(id);

}
console.log(ids);
console.log("生成終了");

実行するとこんな感じで取得できる。

生成開始
[
  '5ijpeWvWucz0TQiK0M5u',
  'gatv1ox3SkoTeq8dEOce',
  'wis9LuhRwp2E5Iq8f4Jt',
  'ZuD1MSCdAUkstja4OCVO',
  '9lWprxeENzriFYuRDk8k',
  'oyzZeimnb83fswto3qpC',
  '2mG32SOm9KaYkVlQtbOQ',
  '6XQUoKUlNWieRWBEmXq7',
  'Xyg4BBNM9gxPYzhE06cM',
  'wDdQqIguxUwhV7aHEHKT'
]
生成終了

重複チェック

一応重複チェックしてみる。

console.log("重複チェック開始");
ids.forEach((id, index) => {
    ids.forEach((id2, index2) => {
        if (id == id2 && index !== index2) {
            console.log("重複:" + id);
        }
    });
});
console.log("重複チェック終了");

10件くらいだと何やっても大体重複しませんが、1万件生成してやってみても重複しなかったので大丈夫そうでした。

以下は1,000件生成時の結果(一応)。

生成開始
[
  'KhU8XXnyNeA6NcLInDOs', '31IXFQJVJLFhheSkMSv7', 'ZkkkcmqSdMVfyA7z5jWk',
  'e29d1PifNUHuolBig0yY', '31cSIoNDqVMZO9e5qMSr', 'A2mAWgfM8NC8IeTMHC2J',
  'tx2IGh5bpUlNRzWmQgY4', 'epfcwUkdcjb1bJ2qMCP8', 'kITqkUqO6ZhnjHXE6Qo0',
  '0euYTpcRqyQ7fhIiSGej', '9eVrmlwH3goaEFgFARdT', 'LIM5sgYHCSFdMqCXX4r8',
  '7UBeOVcozIHk2ThhV50G', '8JEUiish4Ly81SNpuYkc', 'Mb3s6Xaycd2FZSlIKaQ6',
  'Q3NZNYiiAsNycXXKYyA3', 'oalTcnrH8YoTRcGkRiYS', 'XOcqrCHYRXyzaoJUJSqD',
  'lkm7XJfh8V64Ge16VrWY', 'jQtjEQhHCNbzuJqT5H5y', 'GdZY46ByCBfFjTtyInf7',
  'z0YGMmk8Bvsmb1DbSr0o', '8jDU6UULnyoOBCMDOker', 'hPoCtjTy5lY08HmUE6pG',
  'j28qcMYqmDiZXBDFVKPf', 'bPQb6lsagGvejFwLU1Tx', 'rXGXCZLJjXQvfhMiehed',
  'TJoaswumdySH3kRlyENu', 'QFECTerBcL7yqwW54vBd', 'xBb9VYDmbeZOMm8sPINU',
  'e69npMEyfvB368BHyhSa', 'd4ehXcuLs4J07Lfew6Uv', 'Bbun5vXWcVP9s5izIktf',
  'YroygL5r4DZz4b5OT0j8', '0sFbrsscezT6xAphfnmQ', 'TIMcxfa9dNJLEV0u7nf0',
  '6nooqflKNwNAeSMUr49r', 'ryuEkmwEiSyhFhUEDJqe', 'RuuU5kmyuTWhEj3385yp',
  'D5SVemMddF5iveCzNDN4', 'IFggTyHagkYB1tegJprZ', 'SAHe5u3jgKseZVNNAkJA',
  'PoNiSRshvjYMuLVwOpYH', 'iM9uZNLnLcAccbWP5CyF', 'ObEQIo9jtQHz6aiVdj4g',
  'RpcHmsTr9WYRulgfC9bd', 'S2UEsLFQ0iEqHc2QERDe', 'ec2MFmF0qcu3lOhfw676',
  '204YtC6TlJYA52lTGhTp', 'CQmAL3QcbwvSF1MJZzg5', 'LPhRcCJ2P4VteyKgsN63',
  'TyMe5iB81KinWHGdXSxb', 'UlfFcgIsbel3wyJhFUTH', 'KpSTwMtqBuRMSIo1aM0V',
  'alBf8wWFCW09qqIkgLTT', 'LDNuBcSKLH2TukqQlX0B', '2De2aOP9WJc8koImVNlC',
  'tPK0oeEavqMjgBC0siyh', 'NKNv7EDQEXSeOkvy3V8P', 'DMsXhNgCgXmCP0hbkOgR',
  'OqdmW3iqg13WLQ1nT8YH', '3rTUwtTTguR6v6Dxq7aZ', '5npiptejaxR8LPxopATd',
  'dEqXyAP7KVSJSdG7mdLb', 'mJfjEA5DbIdnkTzKTLkp', 'ORiVGtw5gnpFn9r7k4MW',
  'Li3xBB5Trlcn13Tsk0Qk', 'QIF74WIRUGrOHJvDAgBX', 'ylT05Bl4ZKKQ62rzjTQm',
  '0RYaQenLVXxcA5RM9OMp', 'm914UgXvXq3UO7swGeTR', 'q7DlJqCUql44JTMOqgj4',
  'scnAzdDH756t8muo35Hs', 'hukcWg9hIg8aIM0v5hOz', 'zz27UhFgPPkOz5h13mOD',
  'ob2z1Lj0GHpE39b4izEj', 'aYbEBJL52uZUB1Mbsnq9', 'PArJkEjz5x5J4UYD8ifR',
  'LnhLBzFIjjNoVhe7bgcA', 'kdpgNl8M2WhX68rNG7vI', 'Ke9YizGC17hslrivhNei',
  'OvxKN5KbWkfYFeXNK8aB', 'CSLngsPPKUlk6p3ayaLn', 'Ci9J3DJalgHae2g04r0y',
  '5FBlrZf9iEfGcoZjflKj', 'flWvyK1iCGygADkj5H5V', 'GWchhgbYvAj4PegEoirP',
  'bVHC7ahGiYVG9MKxecxj', 'XSc3McPRaa2ADT7KsFKJ', 'uHq38Ay6ICgaZKdUAW4U',
  'iI8teio406X0V6iGXBUQ', '4sbEbJ1ZjroTLPdAPI7J', 'ODJhSFHQHaXnaex6kwoP',
  'dR6XHHmRNJNy3hxtaI7s', 'xnMECDItfkmZUCDcKMtn', 'YePfE0tSUMB6ROHsejgU',
  'mEnFclJAezNIe9CjaFey', 'zBAjohTNQJ0ss6S8Nk6F', '0kTgqjeYkTGQ79P04mqM',
  'vNZJNgccPGbTcKvWWRsM',
  ... 900 more items
]
生成終了
重複チェック開始
重複チェック終了
reika_i
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした