mirror of
https://github.com/hanzoai/pki.git
synced 2026-11-03 18:08:14 +00:00
54 lines
1.2 KiB
Go
54 lines
1.2 KiB
Go
package certutil
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"fmt"
|
|
"io"
|
|
)
|
|
|
|
type randSource interface {
|
|
Read(p []byte) (n int, err error)
|
|
}
|
|
|
|
// RandReader is used so that it can be replaced in tests that require
|
|
// deterministic output
|
|
var RandReader randSource = rand.Reader
|
|
|
|
// Random returns a randomly generated bytes of the requested length.
|
|
func Random(byteLength int) []byte {
|
|
b := make([]byte, byteLength)
|
|
_, err := io.ReadFull(RandReader, b)
|
|
if err != nil {
|
|
panic(fmt.Sprintf("error reading random bytes: %s", err))
|
|
}
|
|
return b
|
|
}
|
|
|
|
// L uniformly random [A-Za-z0-9] characters
|
|
const alpha62 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
|
|
|
|
// RandomString returns a random string of the given length over [0-9A-Za-z].
|
|
// It panics if the random source fails.
|
|
func RandomString(length int) string {
|
|
if length <= 0 {
|
|
return ""
|
|
}
|
|
out := make([]byte, 0, length)
|
|
tmp := make([]byte, 64)
|
|
for len(out) < length {
|
|
_, err := io.ReadFull(RandReader, tmp)
|
|
if err != nil {
|
|
panic(fmt.Sprintf("error reading random bytes: %s", err))
|
|
}
|
|
for _, v := range tmp {
|
|
if v < 248 { // 248 = floor(256/62)*62
|
|
out = append(out, alpha62[int(v%62)])
|
|
if len(out) == length {
|
|
break
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return string(out)
|
|
}
|