create a password with symbols in go

To create a password with symbols in Go, you can use the crypto/rand package to generate a random set of symbols and add them to your password. Here's an example function to generate a random password with symbols:

main.go
package main

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

func generatePassword(length int) string {
	const symbols = "!@#$%^&*()_+-=[]{}|;:,./<>?"
	const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	var password strings.Builder

	for i := 0; i < length; i++ {
		var char string
		if i%3 == 0 {
			char = string(symbols[generateRandomIndex(len(symbols))])
		} else {
			char = string(letters[generateRandomIndex(len(letters))])
		}
		password.WriteString(char)
	}

	return password.String()
}

func generateRandomIndex(max int) int {
	num, _ := rand.Int(rand.Reader, big.NewInt(int64(max)))
	return int(num.Int64())
}

func main() {
	password := generatePassword(12)
	fmt.Println(password)
}
718 chars
35 lines

The generatePassword function takes a length parameter and uses a strings.Builder to construct the password. The function generates a random number between 0 and the length of either the symbols or letters strings, depending on whether the index is divisible by 3. The function returns the generated password as a string.

Note: This function should be used for generating random passwords for testing or development purposes only. For security-sensitive environments, use a library or service specifically designed for securely generating passwords.

gistlibby LogSnag