Project 11: Password generator
Complete video course: Udemy
Introduction
A password generator is a program that generates a strong random password (containing uppercase and lowercase characters, and numbers).
In our case, the generated password will be 8 characters long. The result will be displayed to the user upon generation.
Practical
Boilerplate code:
package main
import (
)
func main() {
}
We start by importing packages that we need for our program:
import (
"fmt"
"math/rand"
"time"
)
The fmt package is for the output operation (displaying the password to the user), and the math/rand and time packages are for the pseudo-random selection that we shall do to generate a random password.
Next, we shall create a constant (an identifier whose value cannot be changed once set) which contains the pool of characters from which we shall generate our password. We are using a constant instead of a variable since we will not update this data at any point in the program. It is also a good practice to have constants outside any functions, so we define it before the main function:
const pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Note that we use the const keyword with constants and not var which is for variables.
In our main function now, we start by defining a variable containing the desired password length (8), and declaring another one where we will store the generated password:
password_length := 8
var password string
Now it’s time to generate the password. First, we set the seed to the current time in nanoseconds to make this even more random:
rand.Seed(time.Now().UnixNano())
Next, we use a for loop to perform a random selection from our pool of characters n times, where n is the desired password length:
for i := 0; i < password_length; i++ {
character := pool[rand.Intn(len(pool))]
password += string(character)
}
To access the nth element in a collection, we use indices that define the position (and start from 0). In our case, we therefore pass as the index value a random number in the range 0 - 7 (rand.Intn(len(pool)). Once we have the character at that position, we append it to the password variable using the add and assign operator (+=).
Note that we use string(character). This is because, in the previous line, we get back a rune that is a special data type in Go. We cannot add a rune to a string hence the string conversion first.
Once the loop is complete, we can display the generated password to the user:
fmt.Println("Generated password is: ", password)
Complete code:
package main
import (
"fmt"
"math/rand"
"time"
)
const pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
func main() {
password_length := 8
var password string
rand.Seed(time.Now().UnixNano())
for i := 0; i < password_length; i++ {
character := pool[rand.Intn(len(pool))]
password += string(character)
}
fmt.Println("Generated password is: ", password)
}
Next: Project 12: JSON parser