Auth: Add RandomBytes() to generate secure random bytes #98 #782

Signed-off-by: Michael Mayer <michael@photoprism.app>
This commit is contained in:
Michael Mayer
2022-09-28 13:38:08 +02:00
parent 5c03535381
commit b32a970aab
2 changed files with 30 additions and 0 deletions

13
pkg/rnd/bytes.go Normal file
View File

@@ -0,0 +1,13 @@
package rnd
import "crypto/rand"
// RandomBytes returns cryptographically secure random bytes.
func RandomBytes(n int) ([]byte, error) {
b := make([]byte, n)
_, err := rand.Read(b)
if err != nil {
return nil, err
}
return b, nil
}

17
pkg/rnd/bytes_test.go Normal file
View File

@@ -0,0 +1,17 @@
package rnd
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestRandomBytes(t *testing.T) {
for n := 0; n <= 64; n++ {
if result, err := RandomBytes(n); err != nil {
t.Fatal(err)
} else {
assert.Len(t, result, n)
}
}
}