Skip to content

Commit

Permalink
stupidgcm: Open: if "dst" is big enough, use it as the output buffer
Browse files Browse the repository at this point in the history
This means we won't need any allocation for the plaintext.
  • Loading branch information
rfjakob committed Jun 30, 2017
1 parent b2a23e9 commit e4b5005
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
16 changes: 15 additions & 1 deletion internal/stupidgcm/stupidgcm.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,18 @@ func (g stupidGCM) Open(dst, iv, in, authData []byte) ([]byte, error) {
if len(in) <= tagLen {
log.Panic("Input data too short")
}
buf := make([]byte, len(in)-tagLen)

// If the "dst" slice is large enough we can use it as our output buffer
outLen := len(in) - tagLen
var buf []byte
inplace := false
if cap(dst)-len(dst) >= outLen {
inplace = true
buf = dst[len(dst) : len(dst)+outLen]
} else {
buf = make([]byte, len(in)-tagLen)
}

ciphertext := in[:len(in)-tagLen]
tag := in[len(in)-tagLen:]

Expand Down Expand Up @@ -207,5 +218,8 @@ func (g stupidGCM) Open(dst, iv, in, authData []byte) ([]byte, error) {
return nil, ErrAuth
}

if inplace {
return dst[:len(dst)+outLen], nil
}
return append(dst, buf...), nil
}
7 changes: 7 additions & 0 deletions internal/stupidgcm/stupidgcm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,13 @@ func TestInplaceSeal(t *testing.T) {
}
}

// Open re-uses the "dst" buffer it is large enough.
// Check that this works correctly by testing different "dst" capacities from
// 5000 to 16 and "in" lengths from 1 to 5000.
func TestInplaceOpen(t *testing.T) {
t.Skipf("TODO: IMPLEMENT TEST")
}

// TestCorruption verifies that changes in the ciphertext result in a decryption
// error
func TestCorruption(t *testing.T) {
Expand Down

0 comments on commit e4b5005

Please sign in to comment.