Buy Me A Coffee 😇

Generate Youtube like ID in Different Programming Languages

/ YouTube is one of the most popular video hosting and most popular social but I was curious about how to generate a youtube video ID. So let us look at how we can create a youtube ID using different languages.

Apr. 21, 2023. 6:10 AM

Currently, I have been given a task to create a media file system for managing files. And it came to my mind how do I create an identity for a file? I can use the default UUID generated by the database but I like to explore more like creating my own ID. After searching Google a lot of times I was able to find a piece of code and tried to convert them into different languages so here you go.

To be precise YouTube uses 64-bit numbers to generate the video ID which equals to 73,786,976,294,838,206,464 possible IDs. For more information about the math and number theory behind this, I can recommend the excellent YouTube video "Will YouTube Ever Run Out Of Video IDs?" from Tom Scott.


function generateHash(): string
    $bytes = random_bytes(8);
    $base64 = base64_encode($bytes);

    return rtrim(strtr($base64, '+/', '-_'), '=');


import base64
import secrets

def generate_hash() -> str:
    bytes = secrets.token_bytes(8)
    base64_str = base64.urlsafe_b64encode(bytes).rstrip(b"=")
    return base64_str.decode("utf-8").translate(str.maketrans("+/", "-_"))


import java.util.Base64;

public class HashGenerator {
    public static String generateHash() {
        SecureRandom random = new SecureRandom();
        byte[] bytes = new byte[8];
        String base64 = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
        return base64.replace('+', '-').replace('/', '_');


function generateHash() {
    const bytes = new Uint8Array(8);
    const base64 = btoa(String.fromCharCode.apply(null, bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
    return base64;


using System.Security.Cryptography;
using System.Text;

public class HashGenerator {
    public static string GenerateHash() {
        var bytes = new byte[8];
        using (var rng = new RNGCryptoServiceProvider()) {
        var base64 = Convert.ToBase64String(bytes).Replace('+', '-').Replace('/', '_').TrimEnd('=');
        return base64;


function generateHash(): string {
    const bytes = new Uint8Array(8);
    const base64 = btoa(String.fromCharCode.apply(null, bytes))
        .replace(/\+/g, "-")
        .replace(/\//g, "_")
        .replace(/=+$/, "");
    return base64;


With that said you can create your own function or follow the codes above. Also, I recommend you add date time generated integer and convert it to something so that everything cannot be replicated, especially if it's based on date and time.

If you enjoy this article and would like to show your support, you can easily do so by buying me a coffee. Your contribution is greatly appreciated!

Jenuel Ganawed Buy me Coffee