create a password with a custom length in go

To create a password with a custom length in Go, we can use the crypto/rand and string packages. First, we need to specify the length of the password we want to generate. For simplicity purposes, let's say we want to generate a password of length 8. Here's an example code snippet that generates a random password with length 8:

main.go
package main

import (
    "crypto/rand"
    "encoding/base64"
    "fmt"
)

func main() {
    length := 8
    
    // Set up a byte array to hold the random bytes
    bytes := make([]byte, length)

    // Use crypto/rand to fill the byte array with random bytes
    _, err := rand.Read(bytes)
    if err != nil {
        panic(err)
    }

    // Encode the byte array into a base64 string
    password := base64.URLEncoding.EncodeToString(bytes)

    // Truncate the password to the specified length
    password = password[:length]

    fmt.Println(password)
}
562 chars
29 lines

In this code, we first specify the password length we want (8 in this case). We then initialize a byte array with the same length as our desired password. We use crypto/rand to fill this byte array with random bytes.

Next, we use base64.URLEncoding.EncodeToString() to convert the byte array into a base64 string. This step isn't strictly necessary, but it does give us a wider choice of characters to use in our password.

Finally, we truncate the password string to the specified length and print it out. In this case, we get a random 8-character password that could look something like this: res9se7D.

gistlibby LogSnag