How to Create a Password Generator in Golang


In today’s digital age, password security is more important than ever before. Hackers can easily guess weak passwords, leading to identity theft and other cybersecurity breaches. To ensure our online safety, we need to use strong and secure passwords that are difficult to guess. A good password generator can help us create random and strong passwords. In this blog post, we’ll discuss how to create a password generator in Golang.


To create a password generator in Golang, we’ll need the following:

  • Golang installed on our system
  • A text editor or IDE

Generating a Random Password in Golang

To generate a random password in Golang, we’ll use the “crypto/rand” package.This package provides a cryptographically secure random number generator. The following code generates a random password of length 12:

package main

import (

func main() {
	const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	const length = 12
	b := make([]byte, length)
	for i := range b {
		n, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
		if err != nil {
		b[i] = charset[n.Int64()]
	password := string(b)

In this code, we define a constant “charset” that contains all the possible characters that can be used in the password. We also define a constant “length” that specifies the length of the password we want to generate.

We then create a byte slice “b” of length “length”. We use a for loop to fill the byte slice with random characters from the “charset”. To generate a random index for the “charset”, we use the “crypto/rand” package to generate a random number between 0 and the length of the “charset”. We convert this number to an ASCII character and add it to the byte slice.

Finally, we convert the byte slice to a string and print it to the console.