diff --git a/common.go b/common.go index ad2195d..d8208cd 100644 --- a/common.go +++ b/common.go @@ -5,6 +5,7 @@ import ( "crypto/aes" "crypto/cipher" "crypto/hmac" + "crypto/rand" "crypto/sha512" "crypto/subtle" "encoding/base64" @@ -178,6 +179,14 @@ func doHKDF(key, salt, info []byte) io.Reader { return hkdf.New(sha512.New384, key, salt, info) } +func readRand(size int) []byte { + b := make([]byte, size) + if _, err := io.ReadFull(rand.Reader, b); err != nil { + panic(err) + } + return b +} + func b64Decode(dst, src []byte) (n int, err error) { return base64.RawURLEncoding.Decode(dst, src) } diff --git a/v1loc.go b/v1loc.go index ab86196..5a07ab9 100644 --- a/v1loc.go +++ b/v1loc.go @@ -2,7 +2,6 @@ package paseto import ( "crypto/hmac" - "crypto/rand" "errors" "fmt" "io" @@ -43,10 +42,7 @@ func V1Encrypt(key []byte, payload, footer any, randBytes []byte) (string, error // step 3. b := randBytes if b == nil { - b = make([]byte, v1locNonce) - if _, err := io.ReadFull(rand.Reader, b); err != nil { - return "", fmt.Errorf("read from crypto/rand.Reader: %w", err) - } + b = readRand(v1locNonce) } // step 4. diff --git a/v2loc.go b/v2loc.go index feba814..a3e7a83 100644 --- a/v2loc.go +++ b/v2loc.go @@ -1,10 +1,8 @@ package paseto import ( - "crypto/rand" "errors" "fmt" - "io" "golang.org/x/crypto/chacha20poly1305" ) @@ -42,10 +40,7 @@ func V2Encrypt(key []byte, payload, footer any, randBytes []byte) (string, error // step 3. b := randBytes if b == nil { - b = make([]byte, v2locNonce) - if _, err := io.ReadFull(rand.Reader, b); err != nil { - return "", fmt.Errorf("read from crypto/rand.Reader: %w", err) - } + b = readRand(v2locNonce) } // step 4. diff --git a/v3loc.go b/v3loc.go index 08d53ef..5d0a863 100644 --- a/v3loc.go +++ b/v3loc.go @@ -2,7 +2,6 @@ package paseto import ( "crypto/hmac" - "crypto/rand" "errors" "fmt" "io" @@ -45,10 +44,7 @@ func V3Encrypt(key []byte, payload, footer any, implicit string, randBytes []byt // step 3. n := randBytes if n == nil { - n = make([]byte, v3locNonce) - if _, err := io.ReadFull(rand.Reader, n); err != nil { - return "", fmt.Errorf("read from crypto/rand.Reader: %w", err) - } + n = readRand(v3locNonce) } // step 4. diff --git a/v4loc.go b/v4loc.go index 0699d0c..de875e6 100644 --- a/v4loc.go +++ b/v4loc.go @@ -2,10 +2,8 @@ package paseto import ( "crypto/hmac" - "crypto/rand" "errors" "fmt" - "io" "strings" ) @@ -45,10 +43,7 @@ func V4Encrypt(key []byte, payload, footer any, implicit string, randBytes []byt // step 3. n := randBytes if n == nil { - n = make([]byte, v4locNonce) - if _, err := io.ReadFull(rand.Reader, n); err != nil { - return "", fmt.Errorf("read from crypto/rand.Reader: %w", err) - } + n = readRand(v4locNonce) } // step 4.