Crypto Rand Text Token

Mint tokens with crypto/rand Text, check the base32 alphabet and length, and collect a thousand identifiers to confirm uniqueness.

GoSecurity Boundaries

Code

snippet
package main

import (
	"crypto/rand"
	"fmt"
	"strings"
)

func main() {
	// rand.Text returns a random base32 string suitable for tokens
	token := rand.Text()
	fmt.Println("length:", len(token))
	fmt.Println("base32 alphabet:", strings.Trim(token, "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567") == "")

	second := rand.Text()
	fmt.Println("two tokens differ:", token != second)

	seen := make(map[string]bool)
	duplicates := 0
	for i := 0; i < 1000; i++ {
		id := rand.Text()
		if seen[id] {
			duplicates++
		}
		seen[id] = true
	}
	fmt.Println("unique ids:", len(seen))
	fmt.Println("duplicates:", duplicates)

	// raw bytes are still needed when an exact length is required
	buf := make([]byte, 16)
	if _, err := rand.Read(buf); err != nil {
		fmt.Println("read failed:", err)
		return
	}
	fmt.Println("raw bytes:", len(buf))
}

How it works

Crypto Rand Text Token is built around the function main.

Iteration happens inside for i := 0; i < 1000; i++ — everything outside it runs once. Error handling is inline: 1 place test err != nil and branch immediately.

What to watch for

  • It is dependency-free in the strict sense — the import list, if any, is empty of packages.

Putting it to use

Look for the length:, base32 alphabet:, two tokens differ: prefixes when the file runs; they tie each line to its step.

The core lines of the flow

seen := make(map[string]bool)
buf := make([]byte, 16)

Interactive Tools for This Topic

FAQ

What does Crypto Rand Text Token print when run?
Run it as a complete program — the output lines carry labels such as `length:`, `base32 alphabet:`, `two tokens differ:`.