rands

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Dec 17, 2021 License: MIT Imports: 7 Imported by: 0

README

rands

Go package providing a suite of functions that use crypto/rand to generate cryptographically secure random strings in various formats, as well as ints and bytes.

Go Reference GitHub tag (latest SemVer) Actions Status Coverage GitHub issues GitHub pull requests License Status

rands package

rands is intended for use in production code where random data generation is required. All functions have a error return value which should be checked.

For tests there is the randsmust package, which has all the same functions but with single return values, and they panic in the event of an error.

Import

import "github.com/jimeh/rands"

Usage

s, err := rands.Base64(16)       // => CYxqEdUB1Rzno3SyZu2g/g==
s, err := rands.Base64URL(16)    // => zlqw9aFqcFggbk2asn3_aQ
s, err := rands.Hex(16)          // => 956e2ec9e7f19ddd58bb935826926531
s, err := rands.Alphanumeric(16) // => Fvk1PkrmG5crgOjT
s, err := rands.Alphabetic(16)   // => XEJIzcZufHkuUmRM
s, err := rands.Upper(16)        // => UMAGAFPPNDRGLUPZ
s, err := rands.UpperNumeric(16) // => DF0CQS0TK9CPUO3E
s, err := rands.Lower(16)        // => ocsmggykzrxzfwgt
s, err := rands.LowerNumeric(16) // => rwlv7a1p7klqffs5
s, err := rands.Numeric(16)      // => 9403373143598295

s, err := rands.String(16, "abcdefABCDEF")                               // => adCDCaDEdeffeDeb
s, err := rands.UnicodeString(16, []rune("九七二人入八力十下三千上口土夕大")) // => 下下口九力下土夕下土八上二夕大三

s, err := rands.DNSLabel(16) // => z0ij9o8qkbs0ru-h
s, err := rands.UUID()       // => a62b8712-f238-43ba-a47e-333f5fffe785

n, err := rands.Int(2147483647)                   // => 1334400235
n, err := rands.Int64(int64(9223372036854775807)) // => 8256935979116161233

b, err := rands.Bytes(8) // => [0 220 137 243 135 204 34 63]

randsmust package

randsmust is specifically intended as an alternative to rands for use in tests. All functions return a single value, and panic in the event of an error. This makes them easy to use when building structs in test cases that need random data.

For production code, make sure to use the rands package and check returned errors.

Import

import "github.com/jimeh/rands/randsmust"

Usage

s := randsmust.Base64(16)       // => d1wm/wS6AQGduO3uaey1Cg==
s := randsmust.Base64URL(16)    // => 4pHWVcddXsL_45vhOfCdng
s := randsmust.Hex(16)          // => b5552558bc009264d129c422a666fe56
s := randsmust.Alphanumeric(16) // => j5WkpNKmW8K701XF
s := randsmust.Alphabetic(16)   // => OXxsqfFjNLvmZqDb
s := randsmust.Upper(16)        // => AOTLYQRCVNMEPRCX
s := randsmust.UpperNumeric(16) // => 1NTY6KATDVAXBTY2
s := randsmust.Lower(16)        // => xmftrwvurrritqfu
s := randsmust.LowerNumeric(16) // => yszg56fzeql7pjpl
s := randsmust.Numeric(16)      // => 0761782105447226

s := randsmust.String(16, "abcdefABCDEF")                               // => dfAbBfaDDdDFDaEa
s := randsmust.UnicodeString(16, []rune("九七二人入八力十下三千上口土夕大")) // => 十十千口三十十下九上千口七夕土口

s := randsmust.DNSLabel(16) // => pu31o0gqyk76x35f
s := randsmust.UUID()       // => d616c873-f3dd-4690-bcd6-ed307eec1105

n := randsmust.Int(2147483647)                   // => 1293388115
n := randsmust.Int64(int64(9223372036854775807)) // => 6168113630900161239

b := randsmust.Bytes(8) // => [205 128 54 95 0 95 53 51]

Documentation

Please see the Go Reference for documentation and examples:

Benchmarks

Benchmark reports and graphs are available here: https://jimeh.me/rands/dev/bench/

License

MIT

Documentation

Overview

Package rands provides a suite of functions that use crypto/rand to generate cryptographically secure random strings in various formats, as well as ints and bytes.

All functions which produce strings from a alphabet of characters uses rand.Int() to ensure a uniform distribution of all possible values.

rands is intended for use in production code where random data generation is required. All functions have a error return value, which should be checked.

For tests there is the randsmust package, which has all the same functions but with single return values, and they panic in the event of an error.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrNonASCIIAlphabet = fmt.Errorf(
		"%w: alphabet contains non-ASCII characters", Err,
	)

	ErrDNSLabelLength = fmt.Errorf(
		"%w: DNS labels must be between 1 and 63 characters in length", Err,
	)
)
View Source
var Err = errors.New("rands")
View Source
var ErrInvalidMaxInt = fmt.Errorf("%w: max cannot be less than 1", Err)

Functions

func Alphabetic

func Alphabetic(n int) (string, error)

Alphabetic generates a random alphabetic string of n length.

The returned string may contain A-Z, and a-z.

Example
package main

import (
	"fmt"
	"log"

	"github.com/jimeh/rands"
)

func main() {
	s, err := rands.Alphabetic(16)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(s) // => VzcovEqvMRBWUtQC
}
Output:

func Alphanumeric

func Alphanumeric(n int) (string, error)

Alphanumeric generates a random alphanumeric string of n length.

The returned string may contain A-Z, a-z, and 0-9.

Example
package main

import (
	"fmt"
	"log"

	"github.com/jimeh/rands"
)

func main() {
	s, err := rands.Alphanumeric(16)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(s) // => EgPieCBO7MuWhHtj
}
Output:

func Base64

func Base64(n int) (string, error)

Base64 generates a random base64 encoded string of n number of bytes.

Length of the returned string is about one third greater than the value of n, and it may contain characters A-Z, a-z, 0-9, "+", "/", and "=".

Example
package main

import (
	"fmt"
	"log"

	"github.com/jimeh/rands"
)

func main() {
	s, err := rands.Base64(16)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(s) // => nYQLhIYTqh8oH/W4hZuXMQ==
}
Output:

func Base64URL

func Base64URL(n int) (string, error)

Base64URL generates a URL-safe un-padded random base64 encoded string of n number of bytes.

Length of the returned string is about one third greater than the value of n, and it may contain characters A-Z, a-z, 0-9, "-", and "_".

Example
package main

import (
	"fmt"
	"log"

	"github.com/jimeh/rands"
)

func main() {
	s, err := rands.Base64URL(16)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(s) // => zI_zrc1l0uPT4MxncR6e5w
}
Output:

func Bytes

func Bytes(n int) ([]byte, error)

Bytes generates a byte slice of n number of random bytes.

Example
package main

import (
	"fmt"
	"log"

	"github.com/jimeh/rands"
)

func main() {
	b, err := rands.Bytes(8)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%+v\n", b) // => [181 153 143 235 241 20 208 173]
}
Output:

func DNSLabel

func DNSLabel(n int) (string, error)

DNSLabel returns a random string of n length in a DNS label compliant format as defined in RFC 1035, section 2.3.1.

It also adheres to RFC 5891, section 4.2.3.1.

In summary, the generated random string will:

  • be between 1 and 63 characters in length, other n values returns a error
  • first character will be one of a-z
  • last character will be one of a-z or 0-9
  • in-between first and last characters consist of a-z, 0-9, or "-"
  • potentially contain two or more consecutive "-", except the 3rd and 4th characters, as that would violate RFC 5891, section 4.2.3.1.
Example
package main

import (
	"fmt"
	"log"

	"github.com/jimeh/rands"
)

func main() {
	s, err := rands.DNSLabel(16)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(s) // => ab-sbh5q0gfb6sqo
}
Output:

func Hex

func Hex(n int) (string, error)

Hex generates a random hexadecimal encoded string of n number of bytes.

Length of the returned string is twice the value of n, and it may contain characters 0-9 and a-f.

Example
package main

import (
	"fmt"
	"log"

	"github.com/jimeh/rands"
)

func main() {
	s, err := rands.Hex(16)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(s) // => b59e8977a13f3c030bd2ea1002ec8081
}
Output:

func Int

func Int(max int) (int, error)

Int generates a random int ranging between 0 and max.

Example
package main

import (
	"fmt"
	"log"

	"github.com/jimeh/rands"
)

func main() {
	n, err := rands.Int(2147483647)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%d\n", n) // => 1908357440
}
Output:

func Int64

func Int64(max int64) (int64, error)

Int64 generates a random int64 ranging between 0 and max.

Example
package main

import (
	"fmt"
	"log"

	"github.com/jimeh/rands"
)

func main() {
	n, err := rands.Int64(int64(9223372036854775807))
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%d\n", n) // => 6530460062499341591
}
Output:

func Lower

func Lower(n int) (string, error)

Lower generates a random lowercase alphabetic string of n length.

The returned string may contain a-z.

Example
package main

import (
	"fmt"
	"log"

	"github.com/jimeh/rands"
)

func main() {
	s, err := rands.Lower(16)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(s) // => dhoqhrqljadsztaa
}
Output:

func LowerNumeric

func LowerNumeric(n int) (string, error)

LowerNumeric generates a random lowercase alphanumeric string of n length.

The returned string may contain A-Z and 0-9.

Example
package main

import (
	"fmt"
	"log"

	"github.com/jimeh/rands"
)

func main() {
	s, err := rands.LowerNumeric(16)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(s) // => th1z1b1d24l5h8pu
}
Output:

func Numeric

func Numeric(n int) (string, error)

Numeric generates a random numeric string of n length.

The returned string may contain 0-9.

Example
package main

import (
	"fmt"
	"log"

	"github.com/jimeh/rands"
)

func main() {
	s, err := rands.Numeric(16)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(s) // => 3378802228987741
}
Output:

func String

func String(n int, alphabet string) (string, error)

String generates a random string of n length using the given ASCII alphabet.

The specified alphabet determines what characters are used in the returned random string. The alphabet can only contain ASCII characters, use UnicodeString() if you need a alphabet with Unicode characters.

Example
package main

import (
	"fmt"
	"log"

	"github.com/jimeh/rands"
)

func main() {
	s, err := rands.String(16, "abcdefABCDEF")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(s) // => BAFffADaadeeacfa
}
Output:

func UUID added in v0.2.0

func UUID() (string, error)

UUID returns a random UUID v4 in string format as defined by RFC 4122, section 4.4.

Example
package main

import (
	"fmt"
	"log"

	"github.com/jimeh/rands"
)

func main() {
	s, err := rands.UUID()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(s) // => 6a1c4f65-d5d6-4a28-aa51-eaa94fa7ad4a
}
Output:

func UnicodeString

func UnicodeString(n int, alphabet []rune) (string, error)

UnicodeString generates a random string of n length using the given Unicode alphabet.

The specified alphabet determines what characters are used in the returned random string. The length of the returned string will be n or greater depending on the byte-length of characters which were randomly selected from the alphabet.

Example
package main

import (
	"fmt"
	"log"

	"github.com/jimeh/rands"
)

func main() {
	s, err := rands.UnicodeString(16, []rune("九七二人入八力十下三千上口土夕大"))
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(s) // => 八三口上土土七入力夕人力下三上力
}
Output:

func Upper

func Upper(n int) (string, error)

Upper generates a random uppercase alphabetic string of n length.

The returned string may contain A-Z.

Example
package main

import (
	"fmt"
	"log"

	"github.com/jimeh/rands"
)

func main() {
	s, err := rands.Upper(16)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(s) // => MCZEGPWGYKNUEDCK
}
Output:

func UpperNumeric

func UpperNumeric(n int) (string, error)

UpperNumeric generates a random uppercase alphanumeric string of n length.

The returned string may contain A-Z and 0-9.

Example
package main

import (
	"fmt"
	"log"

	"github.com/jimeh/rands"
)

func main() {
	s, err := rands.UpperNumeric(16)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(s) // => 6LLPBBUW77B26X2X
}
Output:

Types

This section is empty.

Directories

Path Synopsis
Package randsmust provides a suite of functions that use crypto/rand to generate cryptographically secure random strings in various formats, as well as ints and bytes.
Package randsmust provides a suite of functions that use crypto/rand to generate cryptographically secure random strings in various formats, as well as ints and bytes.

Jump to

Keyboard shortcuts

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