Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 7 additions & 9 deletions securecookie.go
Original file line number Diff line number Diff line change
Expand Up @@ -398,11 +398,10 @@ func encrypt(block cipher.Block, value []byte) ([]byte, error) {
if iv == nil {
return nil, errGeneratingIV
}
// Encrypt it.
dst := make([]byte, len(value))
stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(value, value)
// Return iv + ciphertext.
return append(iv, value...), nil
stream.XORKeyStream(dst, value)
return append(iv, dst...), nil
}

// decrypt decrypts a value using the given block in counter mode.
Expand All @@ -414,12 +413,11 @@ func decrypt(block cipher.Block, value []byte) ([]byte, error) {
if len(value) > size {
// Extract iv.
iv := value[:size]
// Extract ciphertext.
value = value[size:]
// Decrypt it.
ciphertext := value[size:]
dst := make([]byte, len(ciphertext))
stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(value, value)
return value, nil
stream.XORKeyStream(dst, ciphertext)
return dst, nil
}
return nil, errDecryptionFailed
}
Expand Down
15 changes: 15 additions & 0 deletions securecookie_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,21 @@ func TestAuthentication(t *testing.T) {
}
}

func TestEncryptDoesNotMutateInput(t *testing.T) {
block, err := aes.NewCipher([]byte("1234567890123456"))
if err != nil {
t.Fatalf("Block could not be created")
}
orig := []byte("hello world")
clone := append([]byte(nil), orig...)
if _, err := encrypt(block, orig); err != nil {
t.Fatal(err)
}
if string(orig) != string(clone) {
t.Fatalf("encrypt mutated input: got %q want %q", orig, clone)
}
}

func TestEncryption(t *testing.T) {
block, err := aes.NewCipher([]byte("1234567890123456"))
if err != nil {
Expand Down
Loading