randstring

package module
v0.0.0-...-ea45414 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 22, 2026 License: BSD-2-Clause Imports: 3 Imported by: 0

README

randstring

randstring is a Go package for generating random strings:

import (
	"fmt"

	"codeberg.org/slimhazard/randstring"
)

func main() {
	gen := randstring.NewGenerator()
	
	// Print a random string with 20 alphanumeric characters.
	fmt.Println(gen.RandAlphaNum(20))
}

See the package documentation for details about the API.

Secure randomness

The no-arg factory function NewGenerator() shown in the example above creates an instance of Generator whose internal source of randomness is the default from the stdlib package math/rand/v2. That's sufficient for many purposes, but the randomness source is not cryptographic, and should not be used for applications whose security depends on the unpredictability of the random strings.

To generate random strings that cannot be guessed by an attacker, use the factory function NewGeneratorFromSource(), with a cryptographically secure instance of its Source argument. This example illustrates using ChaCha8 as the Source:

	// Assume that seed() returns an unpredictable seed appropriate for
	// creation of the ChaCha8 instance.
	seed := seed()
	chacha := rand.NewChaCha8(seed)

	// Create a Generator instance with ChaCha8 as its source.
	gen := randstring.NewGeneratorFromSource(chacha)
	fmt.Println(gen.RandAlphaNum(20))

See the package examples of the package documentation for more examples of secure random sources.

Building and testing

Code builds, unit tests, and other development tasks are driven by the project Makefile:

# Compile code
$ make build

# Run unit tests
# These two targets are equivalent
$ make test
$ make check

# Run benchmarks
# These two targets are equivalent
$ make benchmark
$ make bench

# Generate code coverage reports
# Reports are created in the ./reports/ directory
$ make coverage

# Clean up prior builds, and delete other artifacts such as coverage
# reports if necessary.
$ make clean

Documentation

Overview

Package randstring provides functions that generate random strings. The strings are formed from common classes of characters, such as the ASCII characters classified by C's ctype functions (including alphabetical characters, alphanumerics, decimal digits, and so on), or by named character classes of POSIX regular expressions (cf. regexp/syntax).

Random strings are created by calling methods on an instance of Generator. The no-arg factory function NewGenerator returns an instance whose internal source of randomness is not cryptographic. That is sufficient for many purposes, but it should not be used in contexts where the security of an application depends on an attacker being unable to guess the contents of the random strings.

For secure randomness, use the factory function NewGeneratorFromSource, and provide an instance of math/rand/v2.Source that is cryptographically secure, as illustrated in the examples.

Example (ChaCha8)

Example_chaCha8 demonstrates creating a generator with an instance of math/rand/v2.ChaCha8 as its source.

package main

import (
	csrng "crypto/rand"
	"fmt"
	"math/rand/v2"

	"codeberg.org/slimhazard/randstring"
)

func seed() [32]byte {
	// The Read function from crypto/rand is used here to get seed
	// values for the ChaCha8 Source.
	seed := make([]byte, 32)
	csrng.Read(seed)
	return [32]byte(seed)
}

// Example_chaCha8 demonstrates creating a generator with an instance
// of [math/rand/v2.ChaCha8] as its source.
func main() {
	seed := seed()
	chacha := rand.NewChaCha8(seed)
	gen := randstring.NewGeneratorFromSource(chacha)
	fmt.Println(gen.RandAlphaNum(10))
}
Example (Crypto_rand)

Example_crypto_rand demonstrates creating a generator with the cryptographically secure RNG from crypto/rand as its source.

package main

import (
	csrng "crypto/rand"
	"encoding/binary"
	"fmt"

	"codeberg.org/slimhazard/randstring"
)

type secureSource struct{}

// Uint64 is required to satisfy the interface [math/rand/v2.Source].
func (secureSource) Uint64() uint64 {
	b := make([]byte, 8)
	csrng.Read(b)
	return binary.NativeEndian.Uint64(b)
}

// Example_crypto_rand demonstrates creating a generator with the
// cryptographically secure RNG from [crypto/rand] as its source.
func main() {
	src := secureSource{}
	gen := randstring.NewGeneratorFromSource(src)
	fmt.Println(gen.RandAlphaNum(10))
}
Example (PCG)

Example_pCG demonstrates creating a generator with an instance of math/rand/v2.PCG as its source.

package main

import (
	csrng "crypto/rand"
	"fmt"
	"math/rand/v2"

	"codeberg.org/slimhazard/randstring"
)

func chacha8() *rand.ChaCha8 {
	seed := make([]byte, 32)
	csrng.Read(seed)
	return rand.NewChaCha8([32]byte(seed))
}

// Example_pCG demonstrates creating a generator with an instance of
// [math/rand/v2.PCG] as its source.
func main() {
	// An instance of ChaCha8 is used here to generate the seed
	// values for PCG.
	chacha := chacha8()
	pcg := rand.NewPCG(chacha.Uint64(), chacha.Uint64())
	gen := randstring.NewGeneratorFromSource(pcg)
	fmt.Println(gen.RandAlphaNum(10))
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Generator

type Generator struct {
	// contains filtered or unexported fields
}

A Generator has the capability to generate random strings.

func NewGenerator

func NewGenerator() *Generator

NewGenerator is a factory function to create a new Generator. Its internal generator of randomness is the default rand.Source provided by package math/rand/v2.

Note that the Source is not a cryptographic RNG. It is suitable for many purposes, but outputs may be predictable to an attacker, and hence it is not appropriate for security-senstive tasks.

func NewGeneratorFromSource

func NewGeneratorFromSource(src rand.Source) *Generator

NewGeneratorFromSource is a factory function to create a Generator, whose internal generator of randomness is a rand.Source from package math/rand/v2 provided in the argument.

See the package examples for demonstrations of providing a rand.Source that is cryptographically secure.

func (*Generator) RandAlpha

func (gen *Generator) RandAlpha(length int) string

RandAlpha returns a random string of the given length consisting of ASCII alphabetic characters. These are the characters in the class `[A-Za-z]`.

The alphabetic characters match the regexp class `[[:alpha:]]`.

func (*Generator) RandAlphaNum

func (gen *Generator) RandAlphaNum(length int) string

RandAlphaNum returns a random string of the given length consisting of ASCII alphanumeric characters. These are the characters in the class `[A-Za-z0-9]`.

The alphabetic characters match the regexp class `[[:alnum:]]`. They are identical to the word characters, except that the underscore `_` is not included.

func (*Generator) RandDecimal

func (gen *Generator) RandDecimal(length int) string

RandDecimal returns a random string of the given length consisting of ASCII decimal characters. These are the characters in the range '0' to '9' (byte values 0x30 to 0x39, inclusive).

Decimal characters match the regexp classes `[[:digit:]]` and `\d`.

func (*Generator) RandGraphical

func (gen *Generator) RandGraphical(length int) string

RandGraphical returns a random string of the given length consisting of ASCII graphical characters. These are the characters in the range '!' to '~' (byte values 0x21 to 0x7e, inclusive).

Graphical characters match the regexp class `[[:graph:]]`. They are identical to the printable characters, except that they do not include the space character.

func (*Generator) RandHexLower

func (gen *Generator) RandHexLower(length int) string

RandHexLower returns a random string of the given length consisting of ASCII hexadecimal lower case characters. These are the characters in the class `[0-9a-f]`.

func (*Generator) RandHexUpper

func (gen *Generator) RandHexUpper(length int) string

RandHexUpper returns a random string of the given length consisting of ASCII hexadecimal upper case characters. These are the characters in the class `[0-9A-F]`.

func (*Generator) RandLower

func (gen *Generator) RandLower(length int) string

RandLower returns a random string of the given length consisting of ASCII lower case alphabetic characters. These are the characters in the range 'a' to 'z' (byte values 0x61 to 0x7a, inclusive).

The lower case characters match the regexp class `[[:lower:]]`.

func (*Generator) RandPrintable

func (gen *Generator) RandPrintable(length int) string

RandPrintable returns a random string of the given length consisting of ASCII printable characters. These are the characters in the range ' ' (space) to '~' (byte values 0x20 to 0x7e, inclusive).

Printable characters match the regexp class `[[:print:]]`. They are identical to the graphical characters, except for the inclusion of the space character.

func (*Generator) RandUpper

func (gen *Generator) RandUpper(length int) string

RandUpper returns a random string of the given length consisting of ASCII upper case alphabetic characters. These are the characters in the range 'A' to 'Z' (byte values 0x41 to 0x5a, inclusive).

The upper case characters match the regexp class `[[:upper:]]`.

func (*Generator) RandWord

func (gen *Generator) RandWord(length int) string

RandWord returns a random string of the given length consisting of ASCII word characters. These are the characters in the class `[A-Za-z0-9_]`.

The word characters match the regexp classes `[[:word:]]` and `\w`. They are identical to the alphanumeric characters, except for the inclusion of the underscore `_`.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL