Skip to content

Commit

Permalink
add MustGenerateRandomKey function
Browse files Browse the repository at this point in the history
  • Loading branch information
chmike committed Feb 22, 2020
1 parent a766fd2 commit 5e935c8
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 2 deletions.
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ It is strongly recommended to generate the random key with the following functio
Save the key in a file using `hex.EncodeToString()` and restrict access to that file.

``` Go
var key []byte = securecookie.GenerateRandomKey()
var key []byte = securecookie.MustGenerateRandomKey()
```

To mitigate the risk of an attacker getting the saved key, you might store a second
Expand All @@ -67,7 +67,8 @@ difficult.

### Instantiating a cookie object

To return an error if an argument is invalid, use `securecookie.New()`.
A secure cookie is instantiated with the `New` function. It returns an error if an
argument is invalid.

``` Go
obj, err := securecookie.New("session", key, securecookie.Params{
Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
module github.com/chmike/securecookie

require github.com/gorilla/securecookie v1.1.1

go 1.13
10 changes: 10 additions & 0 deletions securecookie.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,16 @@ func GenerateRandomKey() ([]byte, error) {
return key, nil
}

// MustGenerateRandomKey returns a random key of KeyLen bytes.
// It calls GenerateRandomKey and panics if it returns an error.
func MustGenerateRandomKey() []byte {
key, err := GenerateRandomKey()
if err != nil {
panic("securecookie: generate random key: " + err.Error())
}
return key
}

// Params holds the optional cookie parameters.
type Params struct {
Path string // Optional : URL path to which the cookie will be returned
Expand Down
15 changes: 15 additions & 0 deletions securecookie_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,21 @@ func TestGenerateKeyErrors(t *testing.T) {
}
}

func TestMustGenerateRandomKey(t *testing.T) {
key := MustGenerateRandomKey()
if len(key) != KeyLen {
t.Errorf("len of key is %d, expected %d", len(key), KeyLen)
}
forceError = 1
defer func() { forceError = 0 }()
defer func() {
if r := recover(); r == nil {
t.Errorf("expected panic")
}
}()
MustGenerateRandomKey()
}

func TestCheckName(t *testing.T) {
if err := checkName("toto"); err != nil {
t.Errorf("unexpected error: %s", err)
Expand Down

0 comments on commit 5e935c8

Please sign in to comment.