I don't really understand your issue. You call
encrypted := secretbox.Seal(nonce[:], []byte(s), &nonce, &secretKey)
That means you pass `nonce[:]` as the `out` argument, `s` as the `message`
argument, and the nonce and key and assign the result to `encrypted`.
According to the docs of `secretbox`, `Seal` will `append` the encrypted
message to `nonce[:]` and that encrypted message will be 16 bytes longer
than the message, which is 11 bytes long. Appending 37 (16+11) bytes to a
24 byte nonce gives you 51 bytes, which is what you observe as the length
of `encrypted`.
The length of `nonce` doesn't change (it's an array, after all) - but
passing `append` to a slice does not change the length of the slice, it
just returns a new slice, so that seems expected.

So, from what I can tell, the code does exactly what the docs say it should
do.

> In their example code the out parameter is nil.  So what does it do?

Appending to `nil` allocates a new slice. The point of still accepting an
`out` parameter is that you can potentially prevent an allocation by
passing in a slice with 0 length and extra capacity (which can then be
allocated on the stack, or which is from a `sync.Pool`). If you don't need
that, passing in `nil` seems fine.

> The second argument is encrypted[len(nonce):] which includes the Overhead
at the start of the []byte. Apparently that Overhead is important.

Yes, the Overhead is important. It is used to authenticate the message. You
can imagine the process of `Seal` as "encrypt the message and attach a
hash". The hash is the Overhead. The process also needs a random `nonce`,
that both the sender and the receiver need to know. That's why the example
code sends it along with the message (it doesn't have to be secret). So
that `Seal` call does, effectively (again, for illustrative purposes):
encrypted := append(append(nonce, <encryptedMessage>), <hash>)
As `nonce` is an array, this allocates a new backing array for the returned
slice, which ends up filled with
<nonce><encryptedMessage><hash>

The `Open` call then retrieves the `nonce` from the first 24 bytes (by
copying it into `decryptNonce`) and passes the `<encryptedMessage><hash>`
slice as the `box` argument. Which decrypts the message, authenticates the
hash and appends the decrypted message to `out` (which is `nil` in the
example code).

So, the docs are correct. And it seems to me, the code works as expected.
I'm not sure where the misunderstanding is.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAEkBMfEy_%3Dd5PpOwn7xSUWnZU3mqva8_%2Bf%3D%2BAcMMisegaLqdxA%40mail.gmail.com.

Reply via email to