Package crypto/nacl/box has a strange (non idiomatic Go) API

428 views
Skip to first unread message

Gerard

unread,
Dec 7, 2014, 3:17:11 AM12/7/14
to golan...@googlegroups.com
After playing a bit with "golang.org/x/crypto/nacl/box" (and some crashes) I discovered the API is kinda weird. This playground example (run in terminal) explains.

See line 40 + 45 and 47 + 52. The documentation of the box package says that function Seal and Open appends the encrypted/decrypted message to out. However due to []byte in the function the append doesn't work as expected (you need *[]byte for that). You first need to set the len of the output buffer to zero and after the (Seal/Open) function you need to set the len of the output buffer to the size of the encrypted/decrypted message. Weird. These functions also returns the encrypted output, which doesn't make sense (overkill).

Btw, the "nonce *[24]byte, peersPublicKey, privateKey *[32]byte" function arguments are brilliant.

Why isn't the encrypted/decrypted message not simply copied to output? In that case these functions could also return an error when the output buffer != inputbuffer + or - box.Overhead.

The functions could look like this:

func Open(out, box []byte, nonce *[24]byte, peersPublicKey, privateKey *[32]byte) error

with description:

"Open authenticates and decrypts a box produced by Seal and copies the message to out, which must not overlap box. The output needs to be Overhead bytes smaller than box."

And

func Seal(out, message []byte, nonce *[24]byte, peersPublicKey, privateKey *[32]byte) error

with a similar description.

The previous example would look like this.

Tamás Gulácsi

unread,
Dec 7, 2014, 3:29:35 AM12/7/14
to golan...@googlegroups.com
It is idiomatic: see append, hash.Sum, and a lot more place. If a []byte is appended into, the function usually returns the resulting slice, so we don't need double pointers, and you can allocate early if speed is a concern, or just use nil, if convenience is the requirement.

Gerard

unread,
Dec 7, 2014, 3:43:38 AM12/7/14
to golan...@googlegroups.com
Ok, it works that way too. TIL ;-)

The playground example looks like this in that case.
Reply all
Reply to author
Forward
0 new messages