I'm seeing strange behaviour where I should get an error back from a function, but I get nil instead.
The following code block contains 2 encrypt functions using cypher/aes. The only difference is the first 1/2 lines of each function. In encrypt2
, I've combined the assignment of the first line of encrypt1
into the conditional.
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
func main() {
invalidKey := []byte("TCbKgXZsT")
plaintext := []byte("dummycontenttoenctrypt")
fmt.Println(encrypt1(plaintext, invalidKey))
fmt.Println(encrypt2(plaintext, invalidKey))
}
func encrypt1(plaintext []byte, key []byte) (encrypted []byte, err error) {
c, err := aes.NewCipher(key)
if err == nil {
if gcm, err := cipher.NewGCM(c); err == nil {
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err == nil {
return gcm.Seal(nonce, nonce, plaintext, nil), nil
}
}
}
return nil, err
}
func encrypt2(plaintext []byte, key []byte) (encrypted []byte, err error) {
if c, err := aes.NewCipher(key); err == nil {
if gcm, err := cipher.NewGCM(c); err == nil {
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err == nil {
return gcm.Seal(nonce, nonce, plaintext, nil), nil
}
}
}
return nil, err
}
I expected the same behaviour from these functions, as the logic is the same. However, calling encrypt1
returns an error (correct), while encrypt2
does not return the error (returns just nil).
I have used named arguments, so err
is declared at the start of the function and should be populated by the first error in both functions.
Anything I'm doing wrong here?