github.com/xhghs/rclone@v1.51.1-0.20200430155106-e186a28cced8/lib/random/random.go (about)

     1  // Package random holds a few functions for working with random numbers
     2  package random
     3  
     4  import (
     5  	"encoding/base64"
     6  	"math/rand"
     7  
     8  	"github.com/pkg/errors"
     9  )
    10  
    11  // String create a random string for test purposes.
    12  //
    13  // Do not use these for passwords.
    14  func String(n int) string {
    15  	const (
    16  		vowel     = "aeiou"
    17  		consonant = "bcdfghjklmnpqrstvwxyz"
    18  		digit     = "0123456789"
    19  	)
    20  	pattern := []string{consonant, vowel, consonant, vowel, consonant, vowel, consonant, digit}
    21  	out := make([]byte, n)
    22  	p := 0
    23  	for i := range out {
    24  		source := pattern[p]
    25  		p = (p + 1) % len(pattern)
    26  		out[i] = source[rand.Intn(len(source))]
    27  	}
    28  	return string(out)
    29  }
    30  
    31  // Password creates a crypto strong password which is just about
    32  // memorable.  The password is composed of printable ASCII characters
    33  // from the base64 alphabet.
    34  //
    35  // Requres password strength in bits.
    36  // 64 is just about memorable
    37  // 128 is secure
    38  func Password(bits int) (password string, err error) {
    39  	bytes := bits / 8
    40  	if bits%8 != 0 {
    41  		bytes++
    42  	}
    43  	var pw = make([]byte, bytes)
    44  	n, err := rand.Read(pw)
    45  	if err != nil {
    46  		return "", errors.Wrap(err, "password read failed")
    47  	}
    48  	if n != bytes {
    49  		return "", errors.Errorf("password short read: %d", n)
    50  	}
    51  	password = base64.RawURLEncoding.EncodeToString(pw)
    52  	return password, nil
    53  }