]> git.proxmox.com Git - mirror_edk2.git/blob - CryptoPkg/Library/BaseCryptLib/Rand/CryptRand.c
CryptoPkg: Replace BSD License with BSD+Patent License
[mirror_edk2.git] / CryptoPkg / Library / BaseCryptLib / Rand / CryptRand.c
1 /** @file
2 Pseudorandom Number Generator Wrapper Implementation over OpenSSL.
3
4 Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.<BR>
5 SPDX-License-Identifier: BSD-2-Clause-Patent
6
7 **/
8
9 #include "InternalCryptLib.h"
10 #include <openssl/rand.h>
11 #include <openssl/evp.h>
12
13 //
14 // Default seed for UEFI Crypto Library
15 //
16 CONST UINT8 DefaultSeed[] = "UEFI Crypto Library default seed";
17
18 /**
19 Sets up the seed value for the pseudorandom number generator.
20
21 This function sets up the seed value for the pseudorandom number generator.
22 If Seed is not NULL, then the seed passed in is used.
23 If Seed is NULL, then default seed is used.
24
25 @param[in] Seed Pointer to seed value.
26 If NULL, default seed is used.
27 @param[in] SeedSize Size of seed value.
28 If Seed is NULL, this parameter is ignored.
29
30 @retval TRUE Pseudorandom number generator has enough entropy for random generation.
31 @retval FALSE Pseudorandom number generator does not have enough entropy for random generation.
32
33 **/
34 BOOLEAN
35 EFIAPI
36 RandomSeed (
37 IN CONST UINT8 *Seed OPTIONAL,
38 IN UINTN SeedSize
39 )
40 {
41 if (SeedSize > INT_MAX) {
42 return FALSE;
43 }
44
45 //
46 // The software PRNG implementation built in OpenSSL depends on message digest algorithm.
47 // Make sure SHA-1 digest algorithm is available here.
48 //
49 if (EVP_add_digest (EVP_sha1 ()) == 0) {
50 return FALSE;
51 }
52
53 //
54 // Seed the pseudorandom number generator with user-supplied value.
55 // NOTE: A cryptographic PRNG must be seeded with unpredictable data.
56 //
57 if (Seed != NULL) {
58 RAND_seed (Seed, (UINT32) SeedSize);
59 } else {
60 RAND_seed (DefaultSeed, sizeof (DefaultSeed));
61 }
62
63 if (RAND_status () == 1) {
64 return TRUE;
65 }
66
67 return FALSE;
68 }
69
70 /**
71 Generates a pseudorandom byte stream of the specified size.
72
73 If Output is NULL, then return FALSE.
74
75 @param[out] Output Pointer to buffer to receive random value.
76 @param[in] Size Size of random bytes to generate.
77
78 @retval TRUE Pseudorandom byte stream generated successfully.
79 @retval FALSE Pseudorandom number generator fails to generate due to lack of entropy.
80
81 **/
82 BOOLEAN
83 EFIAPI
84 RandomBytes (
85 OUT UINT8 *Output,
86 IN UINTN Size
87 )
88 {
89 //
90 // Check input parameters.
91 //
92 if (Output == NULL || Size > INT_MAX) {
93 return FALSE;
94 }
95
96 //
97 // Generate random data.
98 //
99 if (RAND_bytes (Output, (UINT32) Size) != 1) {
100 return FALSE;
101 }
102
103 return TRUE;
104 }