Go: Generate a random string (password, booking reference)

Random Unicode string

rand.Seed(time.Now().UnixNano())
chars := []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZÅÄÖ" +
	"abcdefghijklmnopqrstuvwxyzåäö" +
	"0123456789")
length := 8
buf := make([]rune, length)
for i := range buf {
	buf[i] = chars[rand.Intn(len(chars))]
}
str := string(buf)

Random ASCII string with at least 1 digit and 1 special character

If all characters can be represented by a single byte, e.g. ASCII characters, you can use []byte instead of []rune.

rand.Seed(time.Now().UnixNano())
digits := "0123456789"
specials := "~=+%^*/()[]{}/!@#$?|"
all := "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
	"abcdefghijklmnopqrstuvwxyz" +
	digits + specials
length := 8
buf := make([]byte, length)
buf[0] = digits[rand.Intn(len(digits))]
buf[1] = specials[rand.Intn(len(specials))]
for i := 2; i < length; i++ {
	buf[i] = all[rand.Intn(len(all))]
}
for i := len(buf) - 1; i > 0; i-- {
	j := rand.Intn(i + 1)
	buf[i], buf[j] = buf[j], buf[i]
}
str := string(buf)
Warning: If you're building a password generator, consider using a string generation algorithm from a high-quality cryptographic library. If you're running your own, and you probably shouldn't, package crypto/rand offers a cryptographically secure pseudorandom number generator.

Comments