Go: generating random strings

Go: generating random strings

In this article, we'll explore how to generate random strings in Go, taking advantage of the language's features and some auxiliary libraries.

Generating random strings is a common operation in many programming scenarios, ranging from generating secure passwords to generating test data. In this article, well explore how to generate random strings in Go, taking advantage of the languages features and some auxiliary libraries.

Method 1: Using Gos "math/rand" package

Go offers a standard package called "math/rand" that provides random number generation functionality. We can use this package to generate a random string. The following is a code example that generates a random string of specified length:


package main

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

func generateRandomString(length int) string {
	rand.Seed(time.Now().UnixNano())

	charset := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	result := make([]byte, length)
	for i := range result {
		result[i] = charset[rand.Intn(len(charset))]
	}

	return string(result)
}

func main() {
	randomString := generateRandomString(10)
	fmt.Println(randomString)
}

Lets explain the code step by step:

  1. In the math/rand package, we use the Seed() function to initialize the random number generator with a different seed each time it runs, based on the current time.
  2. We define a set of allowed characters in the charset variable. You can customize this set according to your needs.
  3. We create a byte array of specified length and fill it with random characters selected from the set charset .
  4. We convert the byte array into a string and return it as a result of the generateRandomString() function.
  5. In the main example ( main() ), we call the generateRandomString() function specifying the desired length and print the generated random string to the console.

This method is simple, fast and effective for generating random strings in Go.

Method 2: Using Gos "crypto/rand" package

If you want to generate cryptographically secure random strings, Go also provides the "crypto/rand" package which offers secure random number generation capabilities. This package uses a more reliable source of entropy than the "math/rand" package. Here is a code example using the "crypto/rand" package:


package main

import (
	"crypto/rand"
	"encoding/base64"
	"fmt"
)

func generateRandomString(length int) (string, error) {
	randomBytes := make([]byte, length)

	_, err := rand.Read(randomBytes)
	if err != nil {
		return "", err
	}

	return base64.URLEncoding.EncodeToString(randomBytes)[:length], nil
}

func main() {
	randomString, err := generateRandomString(10)
	if err != nil {
		fmt.Println("Errore nella generazione della stringa casuale:", err)
		return
	}

	fmt.Println(randomString)
}

Lets explain the code step by step:

  1. In the crypto/rand package, we use the Read() function to generate safe random bytes, which we store in the randomBytes variable.
  2. The Read() function also returns an error if there is a problem generating the random bytes.
  3. We convert the random bytes into a string using base64 encoding. Calling [:length] in the result ensures that the generated string has the desired length.
  4. In the main example ( main() ), we call the generateRandomString() function specifying the desired length and handle any errors while generating the random string.

Conclusions

Generating random strings is a common operation in many programming contexts. In Go, we explored two methods of generating random strings: using the "math/rand" package and the "crypto/rand" package. The first method is simple and fast, but its not suitable for cryptographic purposes. The second method, based on "crypto/rand", is more secure and recommended when cryptographically secure random generation is desired.