xref: /aosp_15_r20/external/tink/go/subtle/random/random.go (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1// Copyright 2018 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15////////////////////////////////////////////////////////////////////////////////
16
17// Package random provides functions that generate random numbers or bytes.
18package random
19
20import (
21	"crypto/rand"
22	"encoding/binary"
23)
24
25// GetRandomBytes randomly generates n bytes.
26func GetRandomBytes(n uint32) []byte {
27	buf := make([]byte, n)
28	_, err := rand.Read(buf)
29	if err != nil {
30		panic(err) // out of randomness, should never happen
31	}
32	return buf
33}
34
35// GetRandomUint32 randomly generates an unsigned 32-bit integer.
36func GetRandomUint32() uint32 {
37	b := GetRandomBytes(4)
38	return binary.BigEndian.Uint32(b)
39}
40