create a password with at least one number in go

One way to create a password with at least one number in Go is by using the crypto/rand package to generate a random password string and then appending a random number at a random index in the string.

Here's an example code snippet that generates a password with at least one number:

main.go
package main

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

func main() {
    const passwordLength = 10 // Length of password
    const numChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    pw := make([]byte, passwordLength)

    // Generate a random password string
    for i := range pw {
        idx, _ := rand.Int(rand.Reader, big.NewInt(int64(len(numChars))))
        pw[i] = numChars[idx.Int64()]
    }

    // Insert a random number
    idx, _ := rand.Int(rand.Reader, big.NewInt(int64(passwordLength)))
    pw[idx.Int64()] = byte('0' + rand.Intn(10))

    fmt.Printf("Password: %s\n", pw)
}
634 chars
26 lines

This code first generates a random string of specified length using a set of valid characters. It then inserts a random number at a random index in the string by converting it to an integer and then adding '0'. The password string is finally printed.

gistlibby LogSnag