File: bytes.go

package info (click to toggle)
golang-github-go-crypt-crypt 0.4.7-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 516 kB
  • sloc: makefile: 4
file content (32 lines) | stat: -rw-r--r-- 632 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
31
32
package random

import (
	"crypto/rand"
	"io"
)

// Bytes returns random arbitrary bytes with a length of n.
func Bytes(n int) (bytes []byte, err error) {
	bytes = make([]byte, n)

	if _, err = io.ReadFull(rand.Reader, bytes); err != nil {
		return nil, err
	}

	return bytes, nil
}

// CharSetBytes returns random bytes with a length of n from the characters in the charset.
func CharSetBytes(n int, charset string) (bytes []byte, err error) {
	bytes = make([]byte, n)

	if _, err = rand.Read(bytes); err != nil {
		return nil, err
	}

	for i, b := range bytes {
		bytes[i] = charset[b%byte(len(charset))]
	}

	return bytes, nil
}