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