create a password with uppercase letters and lowercase letters in go

Here's a simple example in Go to generate a random password with uppercase and lowercase letters using the math/rand and crypto/rand packages:

main.go
package main

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

func main() {
	// Set seed for math/rand, to ensure different random sequence each time
	rand.Seed(time.Now().UnixNano())

	// Length of the password you want to generate
	passwordLength := 12

	// Characters to use in the password
	charset := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

	password := make([]byte, passwordLength)
	for i := 0; i < passwordLength; i++ {
		// Generate a random index into the charset
		randomIndex, _ := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
		// Add the character corresponding to the random index to the password
		password[i] = charset[randomIndex.Int64()]
	}

	// Convert byte array to string and print password
	fmt.Println(string(password))
}
783 chars
31 lines

This code generates a random password of length 12, using both uppercase and lowercase letters from the charset string. We first set the seed for the rand package using the current time in nanoseconds, to ensure we get a different sequence of random numbers each time we run the program. We then use a for loop to iterate over each character in the password and randomly select a character from the charset string using math/rand. Finally, we convert the byte array to a string and print the generated password.

gistlibby LogSnag