rand.Read() or io.ReadFull(rand.Reader)?

1,612 views
Skip to first unread message

Dmitry Chestnykh

unread,
Apr 5, 2011, 4:21:14 PM4/5/11
to golan...@googlegroups.com
There's a convenience function in crypto/rand called Read, which calls rand.Reader.Read.
rand.Reader.Read in rand_unix.go is implemented via bufio, and bufio's documentation states:

"Read reads data into p. It returns the number of bytes read into p. It calls Read at most once on the underlying Reader, hence n may be less than len(p). At EOF, the count will be zero and err will be os.EOF."

Does this mean that doing this on Unix:

b := make([]byte, 10)
if _, err := rand.Read(b); err != nil {
   // report error
}

doesn't guarantee that it reads 10 bytes into b, unless you check for returned length or use io.ReadFull?

I see that ecdsa packages doesn't check the returned length:
(actually, it's a bug, since it uses whatever random Reader you pass to the function, I'll file it later).

while dsa package uses io.ReadFull:

(As for how /dev/random may not return the bytes requested, I found this: https://groups.google.com/d/msg/obstcp/zxfXPqb7AtA/SuhgLIkDZQQJ)

-Dmitry

Russ Cox

unread,
Apr 5, 2011, 4:24:32 PM4/5/11
to golan...@googlegroups.com, Dmitry Chestnykh
Code should probably call io.ReadFull.

There's no security problem with the current code's behavior,
because the rand.Reader is a bufio.Reader, and it
behaves like io.ReadFull on ordinary reads.
But that is a detail of one implementation,
not something to rely on.

Russ

Reply all
Reply to author
Forward
0 new messages