randstr

package
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2019 License: MIT Imports: 3 Imported by: 0

README

randstr

randstr provides a Make function for secure token generation which can be given an arbitrary charset (MakeCharset) and length.

In Linux, Darwin, and FreeBSD reading from crypto/rand will not produce an error and so in the interest of API simplicity, randstr panics when random data cannot be generated instead of returning an error.

See https://github.com/golang/go/wiki/CodeReviewComments#crypto-rand

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

func Key() string {
    buf := make([]byte, 16)
    _, err := rand.Read(buf)
    if err != nil {
        panic(err)  // out of randomness, should never happen
    }
    return fmt.Sprintf("%x", buf)
    // or hex.EncodeToString(buf)
    // or base64.StdEncoding.EncodeToString(buf)
}

Example

Generate a secure, random token of length 10:

fmt.Printf("Token: %v", randstr.Make(20))

Documentation

Index

Constants

View Source
const (
	Default = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
	Alpha   = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
	Upper   = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	Lower   = "abcdefghijklmnopqrstuvwxyz"
	Numeric = "0123456789"
	Hex     = "0123456789abcdef"
	// Human creates strings which are easily distinguishable from others
	// created with the same charset. It contains most lowercase alphanumeric characters without
	// 0,o,i,1,l.
	Human = "23456789abcdefghjkmnpqrstuvwxyz"
)

The provided charsets.

Variables

This section is empty.

Functions

func Make

func Make(size int) string

Make returns a random string using Default.

func MakeCharset

func MakeCharset(charsetStr string, size int) string

MakeCharset generates a random string using the provided charset and size.

Types

This section is empty.

Jump to

Keyboard shortcuts

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