How To Generate Passwords in Go

March 04, 2024
Written by
Temitope Taiwo Oyedele
Contributor
Opinions expressed by Twilio contributors are their own
Reviewed by

How to Generate Passwords in Go

Security is paramount in today's digital world. Creating strong, unique passwords is one of the most common ways to secure your digital assets. However, crafting these passwords manually can be daunting due to their complexity and length. This is where password generators come in handy.

This tutorial will guide you through how to build a password generator in Go.

Prerequisites

To proceed with this tutorial, you'll need the following:

How the app works

The password generator will leverage a combination of lowercase letters, uppercase letters, numbers, and special characters to create secure and random passwords. It's important to note that while this method enhances password strength, no password is entirely immune to potential threats.

Set up your project

Create a new project directory, navigate into it, and initialize a new Go module by running the following commands:

mkdir go_password_generator
cd go_password_generator
go mod init generator

Feel free to replace 'generator' with an identifier of your choice. This command generates a go.mod file in the project's top-level directory, which manages your project's dependencies.

Install the required dependencies

We'll incorporate the Fyne library to build a Graphical User Interface (GUI) for our password generator. To install it, execute the following commands:

go get fyne.io/fyne/v2@latest
go install fyne.io/fyne/v2/cmd/fyne@latest
go mod tidy

The go mod tidy command helps optimize and clean up the go.mod file.

Importing Go packages

Before we dive into creating our functions, let's first import all the Go packages we’ll use for this tutorial. First, create a file called main.go and add the following code to the file to import the necessary packages

import (
    "math/rand"
    "strconv"
    "time"

    "fyne.io/fyne/v2"
    "fyne.io/fyne/v2/app"
    "fyne.io/fyne/v2/canvas"
    "fyne.io/fyne/v2/container"
    "fyne.io/fyne/v2/theme"
    "fyne.io/fyne/v2/widget"
)
func PasswordGenerator(passwordLength int) string {
    // Character sets for generating passwords
    lowerCase := "abcdefghijklmnopqrstuvwxyz"     // lowercase
    upperCase := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"     // uppercase
    numbers := "0123456789"                       // numbers
    specialChar := "!@#$%^&*()_-+={}[/?]"         // special characters

    // Variable for storing password
    password := ""

    // Initialize the random number generator
    source := rand.NewSource(time.Now().UnixNano())
    rng := rand.New(source)

    // Generate password character by character
    for n := 0; n < passwordLength; n++ {
        // Generate a random number to choose a character set
        randNum := rng.Intn(4)

        switch randNum {
        case 0:
            randCharNum := rng.Intn(len(lowerCase))
            password += string(lowerCase[randCharNum])
        case 1:
            randCharNum := rng.Intn(len(upperCase))
            password += string(upperCase[randCharNum])
        case 2:
            randCharNum := rng.Intn(len(numbers))
            password += string(numbers[randCharNum])
        case 3:
            randCharNum := rng.Intn(len(specialChar))
            password += string(specialChar[randCharNum])
        }
    }

    return password
}

Now, let's break down what this function does:

  • First, we define the possible character sets for the password: lowercase letters, uppercase letters, numerical digits, and special characters
  • Next, we initialize an empty string password to store the generated password
  • Seed the random number generator with the current UNIX timestamp using time.Now().UnixNano() to ensure different random numbers each time the program runs
  • We then enter a loop that runs for the number of times equal to the desired password length
  • Inside the loop, we generate a random number between case 0 and 3 and use it to select a random character from one of our character sets
  • We append this random character to our password string
  • Finally, we return the generated password

Now, let's move on to creating the main() function which will be our user interface.

Create the main function

Create a function called main() right at the top of the main.go file before the PasswordGenerator() function. We'll be calling the PasswordGenerator() function from this function. Inside the main() function, add the following code:

func main() {
    // Create a new Fyne app and window
    a := app.New()
    myWindow := a.NewWindow("Password generator")

    // Resize the window to dimensions 400x400 pixels
    myWindow.Resize(fyne.NewSize(400, 400))

    // Create UI elements: title, input box, text label, and generate button
    title := canvas.NewText("Password generator", theme.ForegroundColor())

    // Input box for password length
    input := widget.NewEntry()
    input.SetPlaceHolder("Enter password length")

    // Text label to display the generated password
    text := canvas.NewText("", theme.ForegroundColor())

    // Button to trigger password generation
    generateButton := widget.NewButton("Generate", func() {
        // Convert input to integer
        passwordLength, err := strconv.Atoi(input.Text)
        if err != nil {
            text.Text = "Please enter a valid number"
            text.Refresh()
            return
        }

        // Generate password of the specified length
        text.Text = PasswordGenerator(passwordLength)
        text.Refresh()
    })

    // Set up the window content
    myWindow.SetContent(
        container.NewVBox(
            title,
            input,
            text,
            generateButton,
        ),
    )

    // Display and run the window
    myWindow.ShowAndRun()
}

This function does the following:

  • Initializes a new Fyne app and creates a new window titled Password generator
  • Sets the window size to 400 x 400 pixels
  • Creates a text element for the title, an entry widget for the user to input the desired password length, a text element to display the generated password, and a button to trigger the password generation process
  • Sets the content of the window to a vertical box containing the title, input box, text label, and the Generate button
  • Shows and runs the window, which starts the event loop and allows the user to interact with the GUI

Now, let's test it out by running this command:

go run main.go

Then, set the length of the password to generate, and click Generate.

Image display of a password generator created with Go programming language, showcasing a user interface with input fields, buttons, and text elements.

Congratulations! You've successfully built a GUI password generator using Go. Here's the link to the code on GitHub for your reference.

That's how to create a password generator in Go

In this tutorial, we explored the step-by-step process of building a simplistic password generator with a graphical user interface using the Go programming language and the Fyne library.

This project is a great example of the practical application of Go's core concepts, such as data types, functions, control structures, and more. It also highlights Go's ability to create powerful command-line tools and cross-platform desktop applications. Happy coding!

Temitope Taiwo Oyedele is a software engineer and technical writer. He likes to write about things he’s learned and experienced.