From 7b1adcdea5cbb8dec4fe117d164e790218ffcb12 Mon Sep 17 00:00:00 2001 From: Peter Sanchez Date: Thu, 29 Dec 2022 19:09:11 -0600 Subject: [PATCH] Using a proper seed for key generation --- cookies/cookies.go | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/cookies/cookies.go b/cookies/cookies.go index 47a75ce..c14f654 100644 --- a/cookies/cookies.go +++ b/cookies/cookies.go @@ -7,6 +7,7 @@ import ( "crypto/rand" "crypto/sha256" "encoding/base64" + "encoding/binary" "errors" "fmt" "io" @@ -44,11 +45,20 @@ type KeyWallet struct { Reset bool } -// GenerateSecretKey will generate a random 32byte key used for cookie -// signing and/or encryption +// GenerateSecretKey will generate a random key of `keylen` length to be +// used for cookie signing and/or encryption. If `alpha` is true then the key +// will consist of only alphanumeric characters (plus common symbols) func GenerateSecretKey(keylen int, alpha bool) []byte { key := make([]byte, keylen) if alpha { + var seed [8]byte + _, err := rand.Read(seed[:]) + if err != nil { + // XXX Panic? + panic("cannot seed cryptographically secure random number generator") + } + mrand.Seed(int64(binary.LittleEndian.Uint64(seed[:]))) + chars := `abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ0123456789!@#$%^&*()-_=+[]{}\\|'";:/?.>,<` for i := 0; i < keylen; i++ { key[i] = chars[mrand.Intn(len(chars))] -- 2.45.2