To generate a secure password containing uppercase, lowercase letters, numbers and symbols in Go, we can use the math/rand
and time
packages to generate random characters and strconv
package to convert integer to string.
Here's an example function that generates a random password:
main.go389 chars16 lines
In this function, we first define a slice of runes that contains all the characters we want in our password. We then use the rand.Seed
function to seed the random number generator with the current time. We then create a slice of runes representing the password and loop through it randomly selecting a character from the letters slice and assigning it to the current index in the password slice.
The rand.Intn(len(letters))
expression gets a random integer between 0 and the length of the letters slice - 1, which is then used to select a random character.
Finally, we convert the slice of runes to a string and return it as the generated password.
To use this function, we just need to pass it the length of the password we want to generate:
main.go91 chars3 lines
gistlibby LogSnag