Developer Documentation
Go
Updated September 19, 2026

Generate Secure Passwords in Go

Generate cryptographically secure random passwords without modulo bias in Go.

A password generator should draw randomness from the operating system or platform CSPRNG. Do not use predictable pseudo-random functions intended for simulations or UI effects.

Quick Start#

The following example uses the standard Go API or a widely used package for this task.

Quick start#

Go
1package main23import (4    "crypto/rand"5    "fmt"6    "math/big"7)89func password(length int, alphabet string) (string, error) {10    out := make([]byte, length)11    max := big.NewInt(int64(len(alphabet)))12    for i := range out {13        n, err := rand.Int(rand.Reader, max)14        if err != nil { return "", err }15        out[i] = alphabet[n.Int64()]16    }17    return string(out), nil18}1920func main() {21    p, err := password(, "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%")22    if err != nil { panic(err) }23    fmt.Println(p)24}

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Random bytes for machine secrets#

Go
1buf := make([]byte, )2if _, err := rand.Read(buf); err != nil {3    return err4}5token := base64.RawURLEncoding.EncodeToString(buf)

Important Notes#

Use crypto/rand, not math/rand, for passwords, tokens, and recovery codes.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement Password in other languages: