strand

package module
v1.3.2 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2025 License: MIT Imports: 6 Imported by: 0

README

strand

A lightweight, powerful Golang library for generating random strings with both cryptographically secure and seeded options.

PkgGoDev Go Report Card test golangci-lint

Features

  • Generate cryptographically secure random strings using crypto/rand
  • Create deterministic random strings with custom seeds using math/rand/v2
  • Context-aware functions for cancellation support
  • Predefined character sets for common use cases
  • Simple, clean API with both error-returning and panic-on-error versions

Installation

go get -u github.com/everlastingbeta/strand

Quick Start

package main

import (
    "fmt"
    "github.com/everlastingbeta/strand"
)

func main() {
    // Generate a secure random string with uppercase letters
    token, err := strand.String(16, strand.UppercaseAlphabet)
    if err != nil {
        panic(err)
    }
    fmt.Println("Secure token:", token)

    // Generate a predictable string with a custom charset and seed
    password := strand.SeededString(12, strand.ALL, 42)
    fmt.Println("Deterministic password:", password)
}

Usage Examples

Cryptographically Secure Random Generation

Use these functions for security-sensitive applications like tokens, passwords, and API keys.

// Generate a secure random byte slice with alphanumeric characters
bytes, err := strand.Bytes(12, strand.AlphaNumeric)
if err != nil {
    // Handle error
}
fmt.Printf("Random bytes: %v\n", bytes)

// Generate a secure random string with custom character set
apiKey, err := strand.String(32, strand.AlphaNumeric + "-_")
if err != nil {
    // Handle error
}
fmt.Println("API key:", apiKey)

// Non-error-returning versions (will panic on error)
token := strand.MustString(16, strand.ALL)
fmt.Println("Secure token:", token)
Deterministic Random Generation

Use these functions when you need reproducible results with a specific seed.

// Generate a random byte slice with a timestamp-based seed
bytes := strand.SeededBytes(8, strand.Numbers)
fmt.Printf("Seeded bytes: %v\n", bytes)

// Generate a random string with a custom seed and charset
id := strand.SeededString(10, "ACDEFGHJKLMNPQRSTUVWXYZ23456789", 12345)
fmt.Println("Deterministic ID:", id)
Context-Aware Functions

For operations that might need to be canceled or have timeouts.

import (
    "context"
    "time"
)

// Create a context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

// Generate random strings with context support
result, err := strand.StringWithContext(ctx, 20, strand.ALL)
if err != nil {
    // Handle context cancellation or other errors
}

// Also available for seeded versions
seededResult, err := strand.SeededStringWithContext(ctx, 20, strand.AlphaNumeric, 42)
if err != nil {
    // Handle errors
}

Available Character Sets

Strand provides several predefined character sets for convenience:

Constant Description
UppercaseAlphabet Uppercase letters (A-Z)
LowercaseAlphabet Lowercase letters (a-z)
Alphabet All letters (a-z, A-Z)
Numbers Digits (0-9)
AlphaNumeric All letters and digits
Symbols Common special characters
ALL All alphanumeric characters and symbols

You can also define your own custom character sets as strings.

Security Considerations

  • The Bytes() and String() functions use crypto/rand and are suitable for security-sensitive applications.
  • The SeededBytes() and SeededString() functions use math/rand/v2 and are NOT cryptographically secure. Use them only when predictable output is required.

License

MIT

Documentation

Index

Constants

View Source
const (
	// UppercaseAlphabet contains all uppercase letters in the English alphabet (A-Z).
	UppercaseAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

	// LowercaseAlphabet contains all lowercase letters in the English alphabet (a-z).
	LowercaseAlphabet = "abcdefghijklmnopqrstuvwxyz"

	// Alphabet combines both lowercase and uppercase letters in the English alphabet.
	// It is equivalent to LowercaseAlphabet + UppercaseAlphabet.
	Alphabet = LowercaseAlphabet + UppercaseAlphabet

	// Numbers contains all digits (0-9) used to create numeric values.
	Numbers = "0123456789"

	// AlphaNumeric combines all letters and numbers.
	// It is equivalent to Alphabet + Numbers.
	AlphaNumeric = Alphabet + Numbers

	// Symbols contains a selection of common special characters for use in
	// password and token generation.
	Symbols = "<>,\\./|?;:[]{}+=_-()*&^%$#@!~"

	// ALL combines all alphanumeric characters and symbols.
	// It is equivalent to AlphaNumeric + Symbols.
	ALL = AlphaNumeric + Symbols
)

Variables

View Source
var (
	ErrInvalidSize   = errors.New("invalid size: must be greater than 0")
	ErrEmptyCharset  = errors.New("invalid charset: cannot be empty")
	ErrRandomFailure = errors.New("failed to generate random bytes")
)

Common error types for the strand package.

Functions

func Bytes

func Bytes(size int, charset string) ([]byte, error)

Bytes generates a cryptographically secure random byte slice using characters from the provided charset.

Parameters:

  • size: the length of the byte slice to be returned. Must be greater than 0.
  • charset: the string of characters from which bytes will be selected. Cannot be empty.

Returns:

  • []byte: a randomly generated byte slice of the specified size.
  • error: an error if random generation fails or if invalid parameters are provided.

This function uses crypto/rand and is suitable for security-sensitive applications like generating tokens, passwords, and cryptographic keys.

func BytesWithContext added in v1.3.0

func BytesWithContext(ctx context.Context, size int, charset string) ([]byte, error)

BytesWithContext generates a cryptographically secure random byte slice using characters from the provided charset, with support for context cancellation.

Parameters:

  • ctx: context for cancellation support.
  • size: the length of the byte slice to be returned. Must be greater than 0.
  • charset: the string of characters from which bytes will be selected. Cannot be empty.

Returns:

  • []byte: a randomly generated byte slice of the specified size.
  • error: an error if random generation fails, if invalid parameters are provided, or if the context is canceled.

This function uses crypto/rand and is suitable for security-sensitive applications.

func MustBytes added in v1.3.0

func MustBytes(size int, charset string) []byte

MustBytes works like Bytes but panics on error instead of returning it.

This function is useful when you know the inputs are valid and want a simpler API without error checking, such as in initialization code or when using constant values.

Parameters:

  • size: the length of the byte slice to be returned. Must be greater than 0.
  • charset: the string of characters from which bytes will be selected. Cannot be empty.

Returns a randomly generated byte slice of the specified size.

Panics if an error occurs during generation or if invalid parameters are provided.

func MustString added in v1.3.0

func MustString(size int, charset string) string

MustString works like String but panics on error instead of returning it.

This function is useful when you know the inputs are valid and want a simpler API without error checking, such as in initialization code or when using constant values.

Parameters:

  • size: the length of the string to be returned. Must be greater than 0.
  • charset: the string of characters from which the result will be generated. Cannot be empty.

Returns a randomly generated string of the specified size.

Panics if an error occurs during generation or if invalid parameters are provided.

func SeededBytes

func SeededBytes(size int, charset string, seed ...int64) []byte

SeededBytes returns a deterministic byte slice based on the provided seed. The function generates a sequence of bytes where each byte is selected from the provided charset.

Parameters:

  • size: the length of the byte slice to be returned.
  • charset: the string of characters from which the bytes will be selected.
  • seed: optional int64 value to initialize the random source. If omitted, time.Now().UnixNano() will be used as the default seed.

Returns a byte slice of the specified size with characters from the charset.

Security Notice: This function uses math/rand/v2 which is NOT cryptographically secure. For security-sensitive applications, use Bytes() instead.

func SeededBytesWithContext added in v1.3.0

func SeededBytesWithContext(ctx context.Context, size int, charset string, seed ...int64) ([]byte, error)

SeededBytesWithContext returns a deterministic byte slice like SeededBytes, but accepts a context for cancellation support.

Parameters:

  • ctx: context for cancellation support.
  • size: the length of the byte slice to be returned.
  • charset: the string of characters from which the bytes will be selected.
  • seed: optional int64 value to initialize the random source. If omitted, time.Now().UnixNano() will be used as the default seed.

Returns a byte slice of the specified size or an error if the context is canceled.

Security Notice: This function uses math/rand/v2 which is NOT cryptographically secure. For security-sensitive applications, use BytesWithContext() instead.

func SeededString

func SeededString(size int, charset string, seed ...int64) string

SeededString returns a deterministic string based on the provided seed. This is a convenience wrapper around SeededBytes that converts the result to a string.

Parameters:

  • size: the length of the string to be returned.
  • charset: the string of characters from which the string will be generated.
  • seed: optional int64 value to initialize the random source. If omitted, time.Now().UnixNano() will be used as the default seed.

Returns a string of the specified size with characters from the charset.

Security Notice: This function uses math/rand/v2 which is NOT cryptographically secure. For security-sensitive applications, use String() instead.

func SeededStringWithContext added in v1.3.0

func SeededStringWithContext(ctx context.Context, size int, charset string, seed ...int64) (string, error)

SeededStringWithContext returns a deterministic string like SeededString, but accepts a context for cancellation support.

Parameters:

  • ctx: context for cancellation support.
  • size: the length of the string to be returned.
  • charset: the string of characters from which the string will be generated.
  • seed: optional int64 value to initialize the random source. If omitted, time.Now().UnixNano() will be used as the default seed.

Returns a string of the specified size or an error if the context is canceled.

Security Notice: This function uses math/rand/v2 which is NOT cryptographically secure. For security-sensitive applications, use StringWithContext() instead.

func String

func String(size int, charset string) (string, error)

String generates a cryptographically secure random string using characters from the provided charset.

Parameters:

  • size: the length of the string to be returned. Must be greater than 0.
  • charset: the string of characters from which the result will be generated. Cannot be empty.

Returns:

  • string: a randomly generated string of the specified size.
  • error: an error if random generation fails or if invalid parameters are provided.

This function uses crypto/rand and is suitable for security-sensitive applications like generating passwords, session tokens, and API keys.

func StringWithContext added in v1.3.0

func StringWithContext(ctx context.Context, size int, charset string) (string, error)

StringWithContext generates a cryptographically secure random string using characters from the provided charset, with support for context cancellation.

Parameters:

  • ctx: context for cancellation support.
  • size: the length of the string to be returned. Must be greater than 0.
  • charset: the string of characters from which the result will be generated. Cannot be empty.

Returns:

  • string: a randomly generated string of the specified size.
  • error: an error if random generation fails, if invalid parameters are provided, or if the context is canceled.

This function uses crypto/rand and is suitable for security-sensitive applications.

Types

This section is empty.

Jump to

Keyboard shortcuts

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