generate a password of 8 characters that contains at least one uppercase letter, one lowercase letter, and one number in go

Here's a simple code snippet to generate a random password of 8 characters with at least one uppercase letter, one lowercase letter, and one number:

main.go
package main

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

func generatePassword() (string, error) {
	var (
		password    string
		hasLower    bool
		hasUpper    bool
		hasNumber   bool
		charSet     = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
		charSetSize = big.NewInt(int64(len(charSet)))
	)

	for i := 0; i < 8; i++ {
		char, err := rand.Int(rand.Reader, charSetSize)
		if err != nil {
			return "", errors.New("failed to generate password")
		}
		password += string(charSet[char.Int64()])
		switch {
		case 'a' <= password[i] && password[i] <= 'z':
			hasLower = true
		case 'A' <= password[i] && password[i] <= 'Z':
			hasUpper = true
		case '0' <= password[i] && password[i] <= '9':
			hasNumber = true
		}
	}

	if !hasLower || !hasUpper || !hasNumber {
		return generatePassword()
	}

	return password, nil
}

func main() {
	password, err := generatePassword()
	if err != nil {
		panic(err)
	}
	println(password)
}
950 chars
49 lines

The code generates a random password by selecting characters from a set of lowercase and uppercase letters and numbers. It uses the crypto/rand package to generate random numbers, which is a more secure way of generating random data than using the standard math/rand package.

After generating the password, the code checks to make sure it contains at least one uppercase letter, one lowercase letter, and one number. If it doesn't, it generates a new password until it meets the criteria.

Note that this is just a simple example of password generation and should not be used as-is for real-world applications. In practice, you should use a dedicated password hashing library that includes features like salting, key stretching, and other cryptographic best practices to ensure the security of your users' passwords.

gistlibby LogSnag