diff --git a/securecookie.go b/securecookie.go index 4d5ea86..08412a6 100644 --- a/securecookie.go +++ b/securecookie.go @@ -513,6 +513,9 @@ func decode(value []byte) ([]byte, error) { // Callers should explicitly check for the possibility of a nil return, treat // it as a failure of the system random number generator, and not continue. func GenerateRandomKey(length int) []byte { + if length <= 0 { + return nil + } k := make([]byte, length) if _, err := io.ReadFull(rand.Reader, k); err != nil { return nil diff --git a/securecookie_test.go b/securecookie_test.go index 72905ae..e278afb 100644 --- a/securecookie_test.go +++ b/securecookie_test.go @@ -342,3 +342,15 @@ func FuzzEncodeDecode(f *testing.F) { } }) } + +func TestGenerateRandomKeyNonPositive(t *testing.T) { + if got := GenerateRandomKey(0); got != nil { + t.Fatalf("GenerateRandomKey(0)=%v, want nil", got) + } + if got := GenerateRandomKey(-1); got != nil { + t.Fatalf("GenerateRandomKey(-1)=%v, want nil", got) + } + if got := GenerateRandomKey(16); got == nil || len(got) != 16 { + t.Fatalf("GenerateRandomKey(16)=%v, want 16-byte key", got) + } +}