Review random string/password generation
- factor password generation into lib/random.Password - call from appropriate places - choose appropriate use of random.String vs random.Password
This commit is contained in:
parent
beb8d5c134
commit
193c30d570
5 changed files with 83 additions and 25 deletions
|
@ -1,9 +1,16 @@
|
|||
// Package random holds a few functions for working with random numbers
|
||||
package random
|
||||
|
||||
import "math/rand"
|
||||
import (
|
||||
"encoding/base64"
|
||||
"math/rand"
|
||||
|
||||
// String create a random string for test purposes
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// String create a random string for test purposes.
|
||||
//
|
||||
// Do not use these for passwords.
|
||||
func String(n int) string {
|
||||
const (
|
||||
vowel = "aeiou"
|
||||
|
@ -20,3 +27,27 @@ func String(n int) string {
|
|||
}
|
||||
return string(out)
|
||||
}
|
||||
|
||||
// Password creates a crypto strong password which is just about
|
||||
// memorable. The password is composed of printable ASCII characters
|
||||
// from the base64 alphabet.
|
||||
//
|
||||
// Requres password strength in bits.
|
||||
// 64 is just about memorable
|
||||
// 128 is secure
|
||||
func Password(bits int) (password string, err error) {
|
||||
bytes := bits / 8
|
||||
if bits%8 != 0 {
|
||||
bytes++
|
||||
}
|
||||
var pw = make([]byte, bytes)
|
||||
n, err := rand.Read(pw)
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, "password read failed")
|
||||
}
|
||||
if n != bytes {
|
||||
return "", errors.Errorf("password short read: %d", n)
|
||||
}
|
||||
password = base64.RawURLEncoding.EncodeToString(pw)
|
||||
return password, nil
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue