Skip to content

Commit

Permalink
remove unnecessarily defer
Browse files Browse the repository at this point in the history
godoc says hash.Hash.Write never returns an error: https://pkg.go.dev/hash#Hash

> Write (via the embedded io.Writer interface) adds more data to the running hash.
> It never returns an error.

So, we don't need to check errors of Write and panics in Hmac.ComputeAuthTag.
  • Loading branch information
shogo82148 committed Jun 20, 2023
1 parent 2fa2a3b commit 61708f1
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 36 deletions.
21 changes: 12 additions & 9 deletions jwe/internal/aescbc/aescbc.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,17 +140,20 @@ func (c Hmac) Overhead() int {
}

func (c Hmac) ComputeAuthTag(aad, nonce, ciphertext []byte) ([]byte, error) {
buf := make([]byte, len(aad)+len(nonce)+len(ciphertext)+8)
n := 0
n += copy(buf, aad)
n += copy(buf[n:], nonce)
n += copy(buf[n:], ciphertext)
binary.BigEndian.PutUint64(buf[n:], uint64(len(aad)*8))
var buf [8]byte
binary.BigEndian.PutUint64(buf[:], uint64(len(aad)*8))

h := hmac.New(c.hash, c.integrityKey)
if _, err := h.Write(buf); err != nil {
return nil, fmt.Errorf(`failed to write ComputeAuthTag using Hmac: %w`, err)
}

// compute the tag
// no need to check errors because Write never returns an error: https://pkg.go.dev/hash#Hash
//
// > Write (via the embedded io.Writer interface) adds more data to the running hash.
// > It never returns an error.
h.Write(aad)
h.Write(nonce)
h.Write(ciphertext)
h.Write(buf[:])
s := h.Sum(nil)
return s[:c.tagsize], nil
}
Expand Down
27 changes: 0 additions & 27 deletions jwe/internal/cipher/cipher.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,19 +89,6 @@ func (c AesContentCipher) Encrypt(cek, plaintext, aad []byte) (iv, ciphertxt, ta
return nil, nil, nil, fmt.Errorf(`failed to fetch AEAD: %w`, err)
}

// Seal may panic (argh!), so protect ourselves from that
defer func() {
if e := recover(); e != nil {
switch e := e.(type) {
case error:
err = e
default:
err = fmt.Errorf("%s", e)
}
err = fmt.Errorf(`failed to encrypt: %w`, err)
}
}()

var bs keygen.ByteSource
if c.NonceGenerator == nil {
bs, err = keygen.NewRandom(aead.NonceSize()).Generate()
Expand Down Expand Up @@ -133,20 +120,6 @@ func (c AesContentCipher) Decrypt(cek, iv, ciphertxt, tag, aad []byte) (plaintex
return nil, fmt.Errorf(`failed to fetch AEAD data: %w`, err)
}

// Open may panic (argh!), so protect ourselves from that
defer func() {
if e := recover(); e != nil {
switch e := e.(type) {
case error:
err = e
default:
err = fmt.Errorf(`%s`, e)
}
err = fmt.Errorf(`failed to decrypt: %w`, err)
return
}
}()

combined := make([]byte, len(ciphertxt)+len(tag))
copy(combined, ciphertxt)
copy(combined[len(ciphertxt):], tag)
Expand Down

0 comments on commit 61708f1

Please sign in to comment.