File: crypto.go

package info (click to toggle)
golang-github-pion-randutil 0.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bookworm-backports, experimental, forky, sid, trixie
  • size: 144 kB
  • sloc: makefile: 2
file content (30 lines) | stat: -rw-r--r-- 685 bytes parent folder | download
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
26
27
28
29
30
package randutil

import (
	crand "crypto/rand"
	"encoding/binary"
	"math/big"
)

// GenerateCryptoRandomString generates a random string for cryptographic usage.
func GenerateCryptoRandomString(n int, runes string) (string, error) {
	letters := []rune(runes)
	b := make([]rune, n)
	for i := range b {
		v, err := crand.Int(crand.Reader, big.NewInt(int64(len(letters))))
		if err != nil {
			return "", err
		}
		b[i] = letters[v.Int64()]
	}
	return string(b), nil
}

// CryptoUint64 returns cryptographic random uint64.
func CryptoUint64() (uint64, error) {
	var v uint64
	if err := binary.Read(crand.Reader, binary.LittleEndian, &v); err != nil {
		return 0, err
	}
	return v, nil
}