Last active
September 11, 2023 13:53
-
-
Save felixbuenemann/9a30be873ce7dc11dbdd to your computer and use it in GitHub Desktop.
Generate random 10 byte base58 identifiers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var min = 7427658739644928; // min int value that is 10 bytes long in base58 | |
var max = 9007199254740992; // max safe integer (exclusive), also 10 bytes | |
var alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'; // base58 | |
var base = alphabet.length; | |
function encode(num) { | |
var mod, str = ''; | |
while (num >= base) { | |
mod = num % base; | |
str = alphabet[mod] + str; | |
num = (num - mod) / base; | |
} | |
return alphabet[num] + str; | |
}; | |
// returns random int between min (inclusive) and max (exclusive) | |
function randomInt(min, max) { | |
return Math.floor(Math.random() * (max - min)) + min; | |
} | |
// generate 10 byte random base58 id with ~50 bits of entropy | |
function generateShortUid() { | |
return encode(randomInt(min, max)); | |
} | |
module.exports = { | |
generateShortUid: generateShortUid | |
} |
Base58uid
This code generates a random id using the javascript integer range that is guaranteed to encode to a 10 byte base 58 string (~50 Bits of entropy). This can for example be used for client generated database identifiers.
Example usage in node.js:
var base58uid = require('base58uid');
base58uid.generateShortUid(); // '2aSQkrU5hp'
base58uid.generateShortUid(); // '23QryQGzWU'
I've converted this code to Kotlin, in case anyone ever needs it:
object Base58 {
private const val min = 7427658739644928 // min int value that is 10 bytes long in base58
private const val max = 9007199254740992 // max safe integer (exclusive), also 10 bytes
private const val alphabet = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" // base58
private const val base = alphabet.length
private fun encode(input: Long) : String{
var num = input
var str = ""
while (num >= base) {
val mod = (num % base).toInt()
str = alphabet[mod] + str
num = (num - mod) / base
}
return alphabet[num.toInt()] + str
}
// returns random int between min (inclusive) and max (exclusive)
private fun randomInt(min: Long, max: Long): Long {
return (floor(Math.random() * (max - min)) + min).roundToLong()
}
// generate 10 byte random base58 id with ~50 bits of entropy
fun generateShortUid(): String {
return encode(randomInt(min, max))
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Angular Module: