summaryrefslogtreecommitdiffstats
path: root/lib/rand.go
diff options
context:
space:
mode:
authorrsiddharth <s@ricketyspace.net>2021-02-24 18:09:52 -0500
committerrsiddharth <s@ricketyspace.net>2021-02-24 18:09:52 -0500
commit7db89aa66b95d67a82963996b26dccbc7384a926 (patch)
treeb3eca8abf1f482e85a61bca201a4395aec466f70 /lib/rand.go
parent1347de40f45ec0402ac61fcd86e8f87adf3473ad (diff)
lib: put rand functions in rand.go
Diffstat (limited to 'lib/rand.go')
-rw-r--r--lib/rand.go47
1 files changed, 47 insertions, 0 deletions
diff --git a/lib/rand.go b/lib/rand.go
new file mode 100644
index 0000000..03fd651
--- /dev/null
+++ b/lib/rand.go
@@ -0,0 +1,47 @@
+// Copyright © 2020 rsiddharth <s@ricketyspace.net>
+// SPDX-License-Identifier: ISC
+
+package lib
+
+import (
+ "crypto/rand"
+ "math/big"
+)
+
+// Return a random number from range [min, max]
+func RandomInt(min, max int64) int64 {
+ if min >= max {
+ panic("RandomInt: min cannot be >= max!")
+ }
+
+ var rn *big.Int
+ var err error
+ for {
+ rn, err = rand.Int(rand.Reader, big.NewInt(max+1))
+ if err != nil {
+ panic(err)
+ }
+ if rn.Int64() >= min {
+ return rn.Int64()
+ }
+ }
+}
+
+func RandomKey(size int) ([]byte, error) {
+ k := make([]byte, size)
+ _, err := rand.Read(k)
+ if err != nil {
+ return []byte{}, err
+ }
+ return k, nil
+}
+
+// Randomly generates `min` to `max` bytes.
+func randomBytes(min, max int64) []byte {
+ bs := make([]byte, RandomInt(min, max))
+ _, err := rand.Read(bs)
+ if err != nil {
+ panic(err)
+ }
+ return bs
+}