21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

spc_rand( ) by reading from /dev/urandom. Finally, we will implement spc_keygen( )<br />

by reading as much data as possible from /dev/random in a nonblocking fashion, then<br />

falling back to /dev/urandom when /dev/random is dry.<br />

Note that we need to open /dev/random on two file descriptors, one blocking and<br />

one not, so that we may avoid race conditions where spc_keygen( ) expects a function<br />

to be nonblocking but spc_entropy( ) has set the descriptor to blocking in<br />

another thread.<br />

In addition, we assume that the system has sufficient entropy to seed /dev/urandom<br />

properly and /dev/random’s entropy is not reused by /dev/urandom. If you are worried<br />

about either of these assumptions, see the recipes suggested earlier for remedies.<br />

Note that you can expect that /dev/random output is properly postprocessed (whitened)<br />

to remove any patterns that might facilitate analysis in the case that the data<br />

contains less entropy than expected.<br />

This code depends on the spc_make_fd_nonblocking( ) function presented earlier.<br />

#include <br />

#include <br />

#include <br />

#include <br />

#include <br />

static int spc_devrand_fd = -1,<br />

spc_devrand_fd_noblock = -1,<br />

spc_devurand_fd = -1;<br />

void spc_rand_init(void) {<br />

spc_devrand_fd = open("/dev/random", O_RDONLY);<br />

spc_devrand_fd_noblock = open("/dev/random", O_RDONLY);<br />

spc_devurand_fd = open("/dev/urandom", O_RDONLY);<br />

if (spc_devrand_fd = = -1 || spc_devrand_fd_noblock = = -1) {<br />

perror("spc_rand_init failed to open /dev/random");<br />

exit(-1);<br />

}<br />

if (spc_devurand_fd = = -1) {<br />

perror("spc_rand_init failed to open /dev/urandom");<br />

exit(-1);<br />

}<br />

spc_make_fd_nonblocking(spc_devrand_fd_noblock);<br />

}<br />

unsigned char *spc_rand(unsigned char *buf, size_t nbytes) {<br />

ssize_t r;<br />

unsigned char *where = buf;<br />

if (spc_devrand_fd = = -1 && spc_devrand_fd_noblock = = -1 && spc_devurand_fd = = -1)<br />

spc_rand_init( );<br />

while (nbytes) {<br />

if ((r = read(spc_devurand_fd, where, nbytes)) = = -1) {<br />

578 | Chapter 11: Random Numbers<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!