Skip to content

Instantly share code, notes, and snippets.

@felixbuenemann
Last active September 11, 2023 13:53
Show Gist options
  • Save felixbuenemann/9a30be873ce7dc11dbdd to your computer and use it in GitHub Desktop.
Save felixbuenemann/9a30be873ce7dc11dbdd to your computer and use it in GitHub Desktop.
Generate random 10 byte base58 identifiers
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
}
@bodiam
Copy link

bodiam commented Mar 20, 2023

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