Skip to content

UUID Generator — Kotlin source

Generate RFC 4122 v4 UUIDs with crypto-grade randomness. Bulk generate, copy all, toggle format (uppercase / no hyphens).

This is the Kotlin implementation — the same logic the interactive tool runs, in a shareable, citable form.

// RFC 4122 v4 UUID generator (cryptographically secure).
//
// Language: Kotlin (JVM)
// CosmoDev polyglot showcase port of the `uuid` tool.
// Ported from src/lib/uuid.ts — display source, part of CosmoDev's
// polyglot tool pages.
//
// Produces a random (v4) UUID: 36 characters, lowercase, hyphenated as
// 8-4-4-4-12 hex digits, with the RFC version (4) and variant (10xx)
// bits set. SecureRandom is the JVM's bridge to the host CSPRNG, so
// output is unpredictable and collision-safe.

import java.security.SecureRandom

private val csprng = SecureRandom()

/** Return a freshly generated RFC 4122 version-4 UUID string. */
fun uuidV4(): String {
    val b = ByteArray(16)
    csprng.nextBytes(b)

    b[6] = ((b[6].toInt() and 0x0f) or 0x40).toByte() // version 4
    b[8] = ((b[8].toInt() and 0x3f) or 0x80).toByte() // variant 10xx

    // Lowercase hex, hyphens at the 8-4-4-4-12 boundaries.
    return buildString(36) {
        b.forEachIndexed { i, byte ->
            if (i == 4 || i == 6 || i == 8 || i == 10) append('-')
            append("%02x".format(byte))
        }
    }
}

fun main() = println(uuidV4())

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →