create a password with a custom length and uppercase letters in go

One way to create a random password with a custom length and uppercase letters in go is to use a combination of the math/rand and time packages. The math/rand package provides functions to generate random numbers while the time package can be used to seed the random number generator.

main.go
package main

import (
    "fmt"
    "math/rand"
    "time"
)

func generatePassword(length int) string {
    const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    var password string
    rand.Seed(time.Now().UnixNano())
    for i := 0; i < length; i++ {
        index := rand.Intn(len(letters))
        password += string(letters[index])
    }
    return password
}

func main() {
    password := generatePassword(12)
    fmt.Println(password)
}
478 chars
24 lines

In this code, we first define a constant letters which contains all the possible characters that can be in the password. Then we create a function generatePassword which takes an int parameter length and returns a string. Inside this function, we seed the random number generator using the time.Now().UnixNano() function, which returns the current Unix timestamp in nanoseconds. Then, we loop length number of times and select a random character from the letters string using the rand.Intn() function. Finally, we append the selected character to the password string and return it.

To include uppercase letters only, we can modify the letters constant to include only uppercase letters.

main.go
const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
45 chars
2 lines

To include both lowercase and uppercase letters, we can leave the letters constant as is. Finally, to improve the security of this password generation code, we can add additional complexity rules such as including special characters or enforcing a minimum length.

gistlibby LogSnag