Add qemu 2.4.0
[kvmfornfv.git] / qemu / roms / ipxe / src / crypto / random_nz.c
1 /*
2  * Copyright (C) 2012 Michael Brown <mbrown@fensystems.co.uk>.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License as
6  * published by the Free Software Foundation; either version 2 of the
7  * License, or any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17  * 02110-1301, USA.
18  */
19
20 FILE_LICENCE ( GPL2_OR_LATER );
21
22 /** @file
23  *
24  * Random non-zero bytes
25  *
26  * The RSA algorithm requires the generation of random non-zero bytes,
27  * i.e. bytes in the range [0x01,0xff].
28  *
29  * This algorithm is designed to comply with ANS X9.82 Part 1-2006
30  * Section 9.2.1.  This standard is not freely available, but most of
31  * the text appears to be shared with NIST SP 800-90, which can be
32  * downloaded from
33  *
34  *     http://csrc.nist.gov/publications/nistpubs/800-90/SP800-90revised_March2007.pdf
35  *
36  * Where possible, references are given to both documents.  In the
37  * case of any disagreement, ANS X9.82 takes priority over NIST SP
38  * 800-90.  (In particular, note that some algorithms that are
39  * Approved by NIST SP 800-90 are not Approved by ANS X9.82.)
40  */
41
42 #include <stddef.h>
43 #include <stdint.h>
44 #include <ipxe/rbg.h>
45 #include <ipxe/random_nz.h>
46
47 /**
48  * Get random non-zero bytes
49  *
50  * @v data              Output buffer
51  * @v len               Length of output buffer
52  * @ret rc              Return status code
53  *
54  * This algorithm is designed to be isomorphic to the Simple Discard
55  * Method described in ANS X9.82 Part 1-2006 Section 9.2.1 (NIST SP
56  * 800-90 Section B.5.1.1).
57  */
58 int get_random_nz ( void *data, size_t len ) {
59         uint8_t *bytes = data;
60         int rc;
61
62         while ( len ) {
63
64                 /* Generate random byte */
65                 if ( ( rc = rbg_generate ( NULL, 0, 0, bytes, 1 ) ) != 0 )
66                         return rc;
67
68                 /* Move to next byte if this byte is acceptable */
69                 if ( *bytes != 0 ) {
70                         bytes++;
71                         len--;
72                 }
73         }
74
75         return 0;
76 }