add RandomHexString for unguessable identifiers and tokens
RandomHexString returns the requested number of bytes from crypto/rand as lowercase hexadecimal, so callers reaching for a token do not end up using the predictable math/rand instead. Comes with a doc comment and table-driven tests. (closes #13) Model: opus-5
This commit is contained in:
28
random.go
Normal file
28
random.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// RandomHexString returns byteLength random bytes from the operating system's
|
||||
// random source, written as lowercase hexadecimal, so the returned string is
|
||||
// twice as long as byteLength. The bytes come from crypto/rand, which means the
|
||||
// result is fit for session tokens, temporary filenames and anything else a
|
||||
// stranger should not be able to guess.
|
||||
//
|
||||
// An error comes back only for a negative length or if the random source
|
||||
// itself fails, which does not happen on a working system.
|
||||
func RandomHexString(byteLength int) (string, error) {
|
||||
if byteLength < 0 {
|
||||
return "", errors.New("byte length cannot be negative")
|
||||
}
|
||||
|
||||
buffer := make([]byte, byteLength)
|
||||
if _, err := rand.Read(buffer); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return hex.EncodeToString(buffer), nil
|
||||
}
|
||||
Reference in New Issue
Block a user