]> git.proxmox.com Git - mirror_edk2.git/blob - CryptoPkg/Library/BaseCryptLib/Rand/CryptRandTsc.c
bb8783d3546b51a398bbc2b984d39a6fcd6bb637
[mirror_edk2.git] / CryptoPkg / Library / BaseCryptLib / Rand / CryptRandTsc.c
1 /** @file
2 Pseudorandom Number Generator Wrapper Implementation over OpenSSL.
3
4 Copyright (c) 2012, Intel Corporation. All rights reserved.<BR>
5 This program and the accompanying materials
6 are licensed and made available under the terms and conditions of the BSD License
7 which accompanies this distribution. The full text of the license may be found at
8 http://opensource.org/licenses/bsd-license.php
9
10 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
12
13 **/
14
15 #include "InternalCryptLib.h"
16 #include <openssl/rand.h>
17 #include <Library/PrintLib.h>
18
19 /**
20 Sets up the seed value for the pseudorandom number generator.
21
22 This function sets up the seed value for the pseudorandom number generator.
23 If Seed is not NULL, then the seed passed in is used.
24 If Seed is NULL, then default seed is used.
25
26 @param[in] Seed Pointer to seed value.
27 If NULL, default seed is used.
28 @param[in] SeedSize Size of seed value.
29 If Seed is NULL, this parameter is ignored.
30
31 @retval TRUE Pseudorandom number generator has enough entropy for random generation.
32 @retval FALSE Pseudorandom number generator does not have enough entropy for random generation.
33
34 **/
35 BOOLEAN
36 EFIAPI
37 RandomSeed (
38 IN CONST UINT8 *Seed OPTIONAL,
39 IN UINTN SeedSize
40 )
41 {
42 CHAR8 DefaultSeed[128];
43
44 //
45 // Seed the pseudorandom number generator with user-supplied value.
46 // NOTE: A cryptographic PRNG must be seeded with unpredictable data.
47 //
48 if (Seed != NULL) {
49 RAND_seed (Seed, (UINT32) SeedSize);
50 } else {
51 //
52 // Retrieve current time.
53 //
54 AsciiSPrint (
55 DefaultSeed,
56 sizeof (DefaultSeed),
57 "UEFI Crypto Library default seed (%ld)",
58 AsmReadTsc ()
59 );
60
61 RAND_seed (DefaultSeed, sizeof (DefaultSeed));
62 }
63
64 return TRUE;
65 }
66
67 /**
68 Generates a pseudorandom byte stream of the specified size.
69
70 If Output is NULL, then return FALSE.
71
72 @param[out] Output Pointer to buffer to receive random value.
73 @param[in] Size Size of randome bytes to generate.
74
75 @retval TRUE Pseudorandom byte stream generated successfully.
76 @retval FALSE Pseudorandom number generator fails to generate due to lack of entropy.
77
78 **/
79 BOOLEAN
80 EFIAPI
81 RandomBytes (
82 OUT UINT8 *Output,
83 IN UINTN Size
84 )
85 {
86 //
87 // Check input parameters.
88 //
89 if (Output == NULL) {
90 return FALSE;
91 }
92
93 //
94 // Generate random data.
95 //
96 if (RAND_bytes (Output, (UINT32) Size) != 1) {
97 return FALSE;
98 }
99
100 return TRUE;
101 }