Skip to content

Instantly share code, notes, and snippets.

@orip
Created June 9, 2022 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orip/5066e3dc8da203ec38818f481a256c97 to your computer and use it in GitHub Desktop.
Save orip/5066e3dc8da203ec38818f481a256c97 to your computer and use it in GitHub Desktop.
Generate secure passwords in Go
package main
import (
"crypto/rand"
"flag"
"fmt"
"math/big"
)
func GenerateSecurePassword(n int, alphabet string) (string, error) {
alphabetLength := big.NewInt(int64(len(alphabet)))
ret := make([]byte, n)
for i := 0; i < n; i++ {
charIndex, err := rand.Int(rand.Reader, alphabetLength)
if err != nil {
return "", err
}
ret[i] = alphabet[charIndex.Int64()]
}
return string(ret), nil
}
func GenerateAlphaNumericPassword(n int) (string, error) {
const alphaNumericAlphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return GenerateSecurePassword(n, alphaNumericAlphabet)
}
func main() {
n := flag.Int("n", 12, "password length")
flag.Parse()
password, err := GenerateAlphaNumericPassword(*n)
if err != nil {
panic(err)
}
fmt.Println("Password:", password)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment