mirror of https://github.com/tailscale/tailscale/
util/rands: add package with HexString func
We use it a number of places in different repos. Might as well make one. Another use is coming. Updates #cleanup Change-Id: Ib7ce38de0db35af998171edee81ca875102349a4 Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>pull/9183/head
parent
f824274093
commit
7175f06e62
@ -0,0 +1,25 @@
|
||||
// Copyright (c) Tailscale Inc & AUTHORS
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
|
||||
// Package rands contains utility functions for randomness.
|
||||
package rands
|
||||
|
||||
import (
|
||||
crand "crypto/rand"
|
||||
"encoding/hex"
|
||||
)
|
||||
|
||||
// HexString returns a string of n cryptographically random lowercase
|
||||
// hex characters.
|
||||
//
|
||||
// That is, HexString(3) returns something like "0fc", containing 12
|
||||
// bits of randomness.
|
||||
func HexString(n int) string {
|
||||
nb := n / 2
|
||||
if n%2 == 1 {
|
||||
nb++
|
||||
}
|
||||
b := make([]byte, nb)
|
||||
crand.Read(b)
|
||||
return hex.EncodeToString(b)[:n]
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
// Copyright (c) Tailscale Inc & AUTHORS
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
|
||||
package rands
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestHexString(t *testing.T) {
|
||||
for i := 0; i <= 8; i++ {
|
||||
s := HexString(i)
|
||||
if len(s) != i {
|
||||
t.Errorf("HexString(%v) = %q; want len %v, not %v", i, s, i, len(s))
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue