DEV Community

Cover image for How to Generate Strong and Secure Passwords with Go: A Step-by-Step Guide πŸ”πŸ‘¨β€πŸ’»
Ekemini Samuel
Ekemini Samuel

Posted on • Edited on

How to Generate Strong and Secure Passwords with Go: A Step-by-Step Guide πŸ”πŸ‘¨β€πŸ’»

πŸš€Welcome back to my journey of learning back-end development with Go! In this follow-up tutorial, I will be sharing my experience building a password generator program in Go. This program is a great example of how you can use Go to build simple yet valuable applications.

Building a password generator is a great exercise for beginners and intermediate developers alike, as it provides a practical application of Go's core concepts, such as data types, functions, and control structures.

In this tutorial, I will provide a step-by-step guide to building the password generator program, including a sample code that you can use as a starting point. I will also discuss some of the ways in which you can customise the program to meet your specific needs.

Whether you are a beginner looking to gain hands-on experience with Go or an experienced developer looking to build and document, this tutorial provides a valuable resource. I hope it will be of help to you in your own learning journey.

In today's digital age, strong and secure passwords are essential to protect sensitive information such as personal data, financial and confidential business information. A password generator can be a useful tool for creating strong, random passwords.

Prerequisites

Before you start building your password generator program, make sure you have the Go installed on your computer:

Follow the instructions at https://golang.org/doc/install to install Go on your computer.

Building the Password Generator Program

Here are the steps to building a password generator program in Go:

  1. Create a new project: In your terminal, command prompt or code editor, navigate to your Go workspace and create a new directory for your project.

  2. Write the code: Open a new file named main.go in your project directory and write the following code into the file.



package main

import (
    "math/rand"
    "time"
    "fmt"
)

const (
    letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    specialBytes = "!@#$%^&*()_+-=[]{}\\|;':\",.<>/?`~"
    numBytes = "0123456789"
)

func init() {
    rand.Seed(time.Now().UnixNano())
}

func generatePassword(length int, useLetters bool, useSpecial bool, useNum bool) string {
    b := make([]byte, length)
    for i := range b {
        if useLetters {
            b[i] = letterBytes[rand.Intn(len(letterBytes))]
        } else if useSpecial {
            b[i] = specialBytes[rand.Intn(len(specialBytes))]
        } else if useNum {
            b[i] = numBytes[rand.Intn(len(numBytes))]
        }
    }
    return string(b)
}

func main() {
    password := generatePassword(12, true, true, true)
    fmt.Println("Random password:", password)
}

```
This code implements a password generator program in Go. The `generatePassword` function takes four parameters: `length`, `useLetters`, `useSpecial`, and `useNum`. The `length` parameter specifies the length of the password to be generated. The `useLetters`, `useSpecial`, and `useNum` parameters specify whether to include uppercase letters, special characters, and numbers, respectively.

3. Run the program: In your terminal/command prompt, navigate to your project directory and run the command `go run main.go`. You should see a randomly generated password printed in the console.

#Customizing the Program

We can then customize the password generator program to include more options for generating passwords or change the way passwords are generated. For example, we can add an option to specify the number of uppercase letters, special characters, and numbers to include in the password.
Additionally, the password generator program can easily be customized to meet specific needs. This could include changing the length of the password, the types of characters included, or adding additional options for users to choose from. By making these modifications, you can tailor the program to meet your own requirements, making it an even more valuable tool in your back-end development toolkit.

To generate passwords that include numbers and special characters, we can modify the `generatePassword` function as follows:

```go
func generatePassword(length int, includeNumber bool, includeSpecial bool) string {
    const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    var password []byte
    var charSource string

    if includeNumber {
        charSource += "0123456789"
    }
    if includeSpecial {
        charSource += "!@#$%^&*()_+=-"
    }
    charSource += charset

    for i := 0; i < length; i++ {
        randNum := rand.Intn(len(charSource))
        password = append(password, charSource[randNum])
    }
    return string(password)
}

```

In this modification, two new arguments, `includeNumber` and `includeSpecial`, are added to the `generatePassword` function. These arguments determine whether numbers and special characters should be included in the password or not.
If either of these arguments is set to true, the corresponding characters are added to the `charSource` string. The `charSource` string is then used as the source of characters to generate the password.

We can then update the code that calls the `generatePassword` function to specify whether numbers and special characters should be included or not:

```go
password := generatePassword(12, true, true)

```

This will then generate a password that is 12 characters long and includes both numbers and special characters.

#Conclusion

In this tutorial, we covered how to build a password generator program in Go. We explained the basic steps involved in building the program and provided a sample code that you can use as a starting point. With a few modifications, you can customize the program to meet your specific needs. Whether you are a developer looking to add password generation functionality to your application or a user looking for a quick and easy way to generate strong passwords, this tutorial provides a solid foundation for your next project.

I hope you found this tutorial helpful. If you have any questions or comments, feel free to reach out. 

Happy coding!πŸ‘¨β€πŸ’»

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
isaac_weingarten_ac4f9329 profile image
Isaac Weingarten

as of the go doc never use math/rand for Generate secured password only use crypto/rand

const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+"
const length = 16
func generateSecurePassword() (string, error) {

    password := make([]byte, length)
    charsetLength := big.NewInt(int64(len(charset)))
    for i := range password {
        index, err := rand.Int(rand.Reader, charsetLength)
        if err != nil {
            return "", fmt.Errorf("error generating random index: %v", err)
        }
        password[i] = charset[index.Int64()]
    }

    return string(password), nil
}

Enter fullscreen mode Exit fullscreen mode

go playground link