summaryrefslogtreecommitdiffstats
path: root/SecurityPkg/RandomNumberGenerator/RngDxe/ArmTrng.c
blob: ffe557b6925a18a642b678617e24bb13583e2aa0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/** @file
  RNG Driver to produce the UEFI Random Number Generator protocol.

  The driver implements the EFI_RNG_ALGORITHM_RAW using the FW-TRNG
  interface to provide entropy.

  Copyright (c) 2021 - 2022, Arm Limited. All rights reserved.<BR>

  SPDX-License-Identifier: BSD-2-Clause-Patent

**/

#include <Library/BaseLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/DebugLib.h>
#include <Library/ArmTrngLib.h>
#include <Protocol/Rng.h>

#include "RngDxeInternals.h"

/**
  Generate high-quality entropy source using a TRNG or through RDRAND.

  @param[in]   Length        Size of the buffer, in bytes, to fill with.
  @param[out]  Entropy       Pointer to the buffer to store the entropy data.

  @retval  RETURN_SUCCESS            The function completed successfully.
  @retval  RETURN_INVALID_PARAMETER  Invalid parameter.
  @retval  RETURN_UNSUPPORTED        Function not implemented.
  @retval  RETURN_BAD_BUFFER_SIZE    Buffer size is too small.
  @retval  RETURN_NOT_READY          No Entropy available.
**/
EFI_STATUS
EFIAPI
GenerateEntropy (
  IN  UINTN  Length,
  OUT UINT8  *Entropy
  )
{
  EFI_STATUS  Status;
  UINTN       CollectedEntropyBits;
  UINTN       RequiredEntropyBits;
  UINTN       EntropyBits;
  UINTN       Index;
  UINTN       MaxBits;

  ZeroMem (Entropy, Length);

  RequiredEntropyBits  = (Length << 3);
  Index                = 0;
  CollectedEntropyBits = 0;
  MaxBits              = GetArmTrngMaxSupportedEntropyBits ();
  while (CollectedEntropyBits < RequiredEntropyBits) {
    EntropyBits = MIN ((RequiredEntropyBits - CollectedEntropyBits), MaxBits);
    Status      = GetArmTrngEntropy (
                    EntropyBits,
                    (Length - Index),
                    &Entropy[Index]
                    );
    if (EFI_ERROR (Status)) {
      // Discard the collected bits.
      ZeroMem (Entropy, Length);
      return Status;
    }

    CollectedEntropyBits += EntropyBits;
    Index                += (EntropyBits >> 3);
  } // while

  return Status;
}