Developer Tools for Random Data Generation // v2.5.1
root@generate-random:~/passwords/go$ _

Generate Random Passwords in Go

Complete code tutorial with examples and best practices

[ Code Example - Quick Summary ]

Language: Go

What: Generate secure random passwords in Go using <code>crypto/rand</code> for cryptographically secure random generation. Perfect for microservices and backend systems.

Try it: Use our interactive Passwords generator or integrate this code into your Go application.

Generate secure random passwords in Go using crypto/rand for cryptographically secure random generation. Perfect for microservices and backend systems. Looking for other languages? Check our code examples in PHP , JavaScript , Python , Java , C# , C++ and Ruby or use our interactive web generator.

Go Code Example

package main

import (
    "crypto/rand"
    "fmt"
    "math/big"
)

const (
    lowercase = "abcdefghijklmnopqrstuvwxyz"
    uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    numbers   = "0123456789"
    special   = "!@#$%^&*()-_=+[]{}|;:,.<>?"
)

func generatePassword(length int, includeSpecial bool) (string, error) {
    chars := lowercase + uppercase + numbers
    if includeSpecial {
        chars += special
    }

    password := make([]byte, length)
    charsLen := big.NewInt(int64(len(chars)))

    for i := 0; i < length; i++ {
        num, err := rand.Int(rand.Reader, charsLen)
        if err != nil {
            return "", err
        }
        password[i] = chars[num.Int64()]
    }

    return string(password), nil
}

func main() {
    // Generate a 16-character password with special characters
    password, _ := generatePassword(16, true)
    fmt.Println(password)  // Example: aB3$xY7!mN2@pQ9&

    // Generate a 12-character password without special characters
    simplePassword, _ := generatePassword(12, false)
    fmt.Println(simplePassword)  // Example: aB3xY7mN2pQ9
}

[EXPLANATION]

crypto/rand.Int() provides cryptographically secure random integers. This implementation properly handles errors and uses big.Int for secure index generation within the character set range.

Expected Output

aB3$xY7!mN2@pQ9&
aB3xY7mN2pQ9

Common Use Cases

  • Microservices authentication systems
  • RESTful API security token generation
  • Kubernetes and Docker container secrets
  • gRPC service authentication
  • CLI tools and utilities
  • Cloud-native application security

Important Notes

  • Always use crypto/rand for password generation
  • Handle errors properly in production code
  • rand.Reader provides cryptographically secure random bytes
  • Consider using third-party password strength validators

Try Our Interactive Generator

Don't want to write code? Use our free web-based Passwords generator with instant results.

TRY PASSWORDS GENERATOR →