summaryrefslogtreecommitdiffhomepage
path: root/util/rands/rands.go
blob: 94c6e6f4a1c2904761fd6eca9a60c0bbaa33348f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Copyright (c) Tailscale Inc & contributors
// 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]
}