public inbox for devel@edk2.groups.io
 help / color / mirror / Atom feed
* [edk2-devel] [PATCH] Add SHA3/SM3 functions with openssl for Mbedtls
@ 2024-04-22  1:33 Wenxing Hou
  2024-04-22  7:43 ` Li, Yi
  0 siblings, 1 reply; 3+ messages in thread
From: Wenxing Hou @ 2024-04-22  1:33 UTC (permalink / raw)
  To: devel; +Cc: Jiewen Yao, Yi Li

REF: https://bugzilla.tianocore.org/show_bug.cgi?id=4177

Because the Mbedlts 3.3.0 doesn't have SHA3 and Sm3, the SHA3 and Sm3
implementaion based on Openssl.

Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Yi Li <yi1.li@intel.com>
Signed-off-by: Wenxing Hou <wenxing.hou@intel.com>
---
 CryptoPkg/CryptoPkg.ci.yaml                   |   1 +
 .../BaseCryptLibMbedTls/Hash/CryptCShake256.c | 282 +++++++++
 .../Hash/CryptDispatchApDxe.c                 |  49 ++
 .../Hash/CryptDispatchApMm.c                  |  35 ++
 .../Hash/CryptDispatchApPei.c                 |  54 ++
 .../Hash/CryptParallelHash.c                  | 254 ++++++++
 .../Hash/CryptParallelHash.h                  | 231 +++++++
 .../BaseCryptLibMbedTls/Hash/CryptSha3.c      | 166 +++++
 .../BaseCryptLibMbedTls/Hash/CryptSm3.c       | 235 +++++++
 .../BaseCryptLibMbedTls/Hash/CryptXkcp.c      | 107 ++++
 .../SysCall/DummyOpensslSupport.c             | 595 ++++++++++++++++++
 CryptoPkg/Library/MbedTlsLib/MbedTlsLib.inf   |   6 +
 .../Library/MbedTlsLib/MbedTlsLibFull.inf     |   6 +
 13 files changed, 2021 insertions(+)
 create mode 100644 CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptCShake256.c
 create mode 100644 CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptDispatchApDxe.c
 create mode 100644 CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptDispatchApMm.c
 create mode 100644 CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptDispatchApPei.c
 create mode 100644 CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptParallelHash.c
 create mode 100644 CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptParallelHash.h
 create mode 100644 CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptSha3.c
 create mode 100644 CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptSm3.c
 create mode 100644 CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptXkcp.c
 create mode 100644 CryptoPkg/Library/BaseCryptLibMbedTls/SysCall/DummyOpensslSupport.c

diff --git a/CryptoPkg/CryptoPkg.ci.yaml b/CryptoPkg/CryptoPkg.ci.yaml
index b601bcf85c..046cc05163 100644
--- a/CryptoPkg/CryptoPkg.ci.yaml
+++ b/CryptoPkg/CryptoPkg.ci.yaml
@@ -40,6 +40,7 @@
             "Library/Include/CrtLibSupport.h",
             # This has OpenSSL interfaces that aren't UEFI spec compliant
             "Library/BaseCryptLib/Hash/CryptParallelHash.h",
+            "Library/BaseCryptLibMbedTls/Hash/CryptParallelHash.h",
             "Library/Include/fcntl.h",
             # This has Mbedtls interfaces that aren't UEFI spec compliant
             "Library/Include/stdint.h",
diff --git a/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptCShake256.c b/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptCShake256.c
new file mode 100644
index 0000000000..64d8fa97c5
--- /dev/null
+++ b/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptCShake256.c
@@ -0,0 +1,282 @@
+/** @file
+  cSHAKE-256 Digest Wrapper Implementations.
+
+Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "CryptParallelHash.h"
+
+#define  CSHAKE256_SECURITY_STRENGTH  256
+#define  CSHAKE256_RATE_IN_BYTES      136
+
+CONST CHAR8  mZeroPadding[CSHAKE256_RATE_IN_BYTES] = { 0 };
+
+/**
+  CShake256 initial function.
+
+  Initializes user-supplied memory pointed by CShake256Context as cSHAKE-256 hash context for
+  subsequent use.
+
+  @param[out] CShake256Context  Pointer to cSHAKE-256 context being initialized.
+  @param[in]  OutputLen         The desired number of output length in bytes.
+  @param[in]  Name              Pointer to the function name string.
+  @param[in]  NameLen           The length of the function name in bytes.
+  @param[in]  Customization     Pointer to the customization string.
+  @param[in]  CustomizationLen  The length of the customization string in bytes.
+
+  @retval TRUE   cSHAKE-256 context initialization succeeded.
+  @retval FALSE  cSHAKE-256 context initialization failed.
+  @retval FALSE  This interface is not supported.
+**/
+BOOLEAN
+EFIAPI
+CShake256Init (
+  OUT  VOID        *CShake256Context,
+  IN   UINTN       OutputLen,
+  IN   CONST VOID  *Name,
+  IN   UINTN       NameLen,
+  IN   CONST VOID  *Customization,
+  IN   UINTN       CustomizationLen
+  )
+{
+  BOOLEAN  Status;
+  UINT8    EncBuf[sizeof (UINTN) + 1];
+  UINTN    EncLen;
+  UINTN    AbsorbLen;
+  UINTN    PadLen;
+
+  //
+  // Check input parameters.
+  //
+  if ((CShake256Context == NULL) || (OutputLen == 0) || ((NameLen != 0) && (Name == NULL)) || ((CustomizationLen != 0) && (Customization == NULL))) {
+    return FALSE;
+  }
+
+  //
+  // Initialize KECCAK context with pad value and block size.
+  //
+  if ((NameLen == 0) && (CustomizationLen == 0)) {
+    //
+    // When N and S are both empty strings, cSHAKE(X, L, N, S) is equivalent to
+    // SHAKE as defined in FIPS 202.
+    //
+    Status = (BOOLEAN)KeccakInit (
+                        (Keccak1600_Ctx *)CShake256Context,
+                        '\x1f',
+                        (KECCAK1600_WIDTH - CSHAKE256_SECURITY_STRENGTH * 2) / 8,
+                        OutputLen
+                        );
+
+    return Status;
+  } else {
+    Status = (BOOLEAN)KeccakInit (
+                        (Keccak1600_Ctx *)CShake256Context,
+                        '\x04',
+                        (KECCAK1600_WIDTH - CSHAKE256_SECURITY_STRENGTH * 2) / 8,
+                        OutputLen
+                        );
+    if (!Status) {
+      return FALSE;
+    }
+
+    AbsorbLen = 0;
+    //
+    // Absorb Absorb bytepad(.., rate).
+    //
+    EncLen = LeftEncode (EncBuf, CSHAKE256_RATE_IN_BYTES);
+    Status = (BOOLEAN)Sha3Update ((Keccak1600_Ctx *)CShake256Context, EncBuf, EncLen);
+    if (!Status) {
+      return FALSE;
+    }
+
+    AbsorbLen += EncLen;
+
+    //
+    // Absorb encode_string(N).
+    //
+    EncLen = LeftEncode (EncBuf, NameLen * 8);
+    Status = (BOOLEAN)Sha3Update ((Keccak1600_Ctx *)CShake256Context, EncBuf, EncLen);
+    if (!Status) {
+      return FALSE;
+    }
+
+    AbsorbLen += EncLen;
+    Status     = (BOOLEAN)Sha3Update ((Keccak1600_Ctx *)CShake256Context, Name, NameLen);
+    if (!Status) {
+      return FALSE;
+    }
+
+    AbsorbLen += NameLen;
+
+    //
+    // Absorb encode_string(S).
+    //
+    EncLen = LeftEncode (EncBuf, CustomizationLen * 8);
+    Status = (BOOLEAN)Sha3Update ((Keccak1600_Ctx *)CShake256Context, EncBuf, EncLen);
+    if (!Status) {
+      return FALSE;
+    }
+
+    AbsorbLen += EncLen;
+    Status     = (BOOLEAN)Sha3Update ((Keccak1600_Ctx *)CShake256Context, Customization, CustomizationLen);
+    if (!Status) {
+      return FALSE;
+    }
+
+    AbsorbLen += CustomizationLen;
+
+    //
+    // Absorb zero padding up to rate.
+    //
+    PadLen = CSHAKE256_RATE_IN_BYTES - AbsorbLen % CSHAKE256_RATE_IN_BYTES;
+    Status = (BOOLEAN)Sha3Update ((Keccak1600_Ctx *)CShake256Context, mZeroPadding, PadLen);
+    if (!Status) {
+      return FALSE;
+    }
+
+    return TRUE;
+  }
+}
+
+/**
+  Digests the input data and updates cSHAKE-256 context.
+
+  This function performs cSHAKE-256 digest on a data buffer of the specified size.
+  It can be called multiple times to compute the digest of long or discontinuous data streams.
+  cSHAKE-256 context should be already correctly initialized by CShake256Init(), and should not be finalized
+  by CShake256Final(). Behavior with invalid context is undefined.
+
+  @param[in, out]  CShake256Context   Pointer to the cSHAKE-256 context.
+  @param[in]       Data               Pointer to the buffer containing the data to be hashed.
+  @param[in]       DataSize           Size of Data buffer in bytes.
+
+  @retval TRUE   cSHAKE-256 data digest succeeded.
+  @retval FALSE  cSHAKE-256 data digest failed.
+  @retval FALSE  This interface is not supported.
+
+**/
+BOOLEAN
+EFIAPI
+CShake256Update (
+  IN OUT  VOID        *CShake256Context,
+  IN      CONST VOID  *Data,
+  IN      UINTN       DataSize
+  )
+{
+  //
+  // Check input parameters.
+  //
+  if (CShake256Context == NULL) {
+    return FALSE;
+  }
+
+  //
+  // Check invalid parameters, in case that only DataLength was checked in OpenSSL.
+  //
+  if ((Data == NULL) && (DataSize != 0)) {
+    return FALSE;
+  }
+
+  return (BOOLEAN)(Sha3Update ((Keccak1600_Ctx *)CShake256Context, Data, DataSize));
+}
+
+/**
+  Completes computation of the cSHAKE-256 digest value.
+
+  This function completes cSHAKE-256 hash computation and retrieves the digest value into
+  the specified memory. After this function has been called, the cSHAKE-256 context cannot
+  be used again.
+  cSHAKE-256 context should be already correctly initialized by CShake256Init(), and should not be
+  finalized by CShake256Final(). Behavior with invalid cSHAKE-256 context is undefined.
+
+  @param[in, out]  CShake256Context  Pointer to the cSHAKE-256 context.
+  @param[out]      HashValue         Pointer to a buffer that receives the cSHAKE-256 digest
+                                     value.
+
+  @retval TRUE   cSHAKE-256 digest computation succeeded.
+  @retval FALSE  cSHAKE-256 digest computation failed.
+  @retval FALSE  This interface is not supported.
+
+**/
+BOOLEAN
+EFIAPI
+CShake256Final (
+  IN OUT  VOID   *CShake256Context,
+  OUT     UINT8  *HashValue
+  )
+{
+  //
+  // Check input parameters.
+  //
+  if ((CShake256Context == NULL) || (HashValue == NULL)) {
+    return FALSE;
+  }
+
+  //
+  // cSHAKE-256 Hash Finalization.
+  //
+  return (BOOLEAN)(Sha3Final ((Keccak1600_Ctx *)CShake256Context, HashValue));
+}
+
+/**
+  Computes the CSHAKE-256 message digest of a input data buffer.
+
+  This function performs the CSHAKE-256 message digest of a given data buffer, and places
+  the digest value into the specified memory.
+
+  @param[in]   Data               Pointer to the buffer containing the data to be hashed.
+  @param[in]   DataSize           Size of Data buffer in bytes.
+  @param[in]   OutputLen          Size of output in bytes.
+  @param[in]   Name               Pointer to the function name string.
+  @param[in]   NameLen            Size of the function name in bytes.
+  @param[in]   Customization      Pointer to the customization string.
+  @param[in]   CustomizationLen   Size of the customization string in bytes.
+  @param[out]  HashValue          Pointer to a buffer that receives the CSHAKE-256 digest
+                                  value.
+
+  @retval TRUE   CSHAKE-256 digest computation succeeded.
+  @retval FALSE  CSHAKE-256 digest computation failed.
+  @retval FALSE  This interface is not supported.
+
+**/
+BOOLEAN
+EFIAPI
+CShake256HashAll (
+  IN   CONST VOID  *Data,
+  IN   UINTN       DataSize,
+  IN   UINTN       OutputLen,
+  IN   CONST VOID  *Name,
+  IN   UINTN       NameLen,
+  IN   CONST VOID  *Customization,
+  IN   UINTN       CustomizationLen,
+  OUT  UINT8       *HashValue
+  )
+{
+  BOOLEAN         Status;
+  Keccak1600_Ctx  Ctx;
+
+  //
+  // Check input parameters.
+  //
+  if (HashValue == NULL) {
+    return FALSE;
+  }
+
+  if ((Data == NULL) && (DataSize != 0)) {
+    return FALSE;
+  }
+
+  Status = CShake256Init (&Ctx, OutputLen, Name, NameLen, Customization, CustomizationLen);
+  if (!Status) {
+    return FALSE;
+  }
+
+  Status = CShake256Update (&Ctx, Data, DataSize);
+  if (!Status) {
+    return FALSE;
+  }
+
+  return CShake256Final (&Ctx, HashValue);
+}
diff --git a/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptDispatchApDxe.c b/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptDispatchApDxe.c
new file mode 100644
index 0000000000..34424a16f7
--- /dev/null
+++ b/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptDispatchApDxe.c
@@ -0,0 +1,49 @@
+/** @file
+  Dispatch Block to Aps in Dxe phase for parallelhash algorithm.
+
+Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "CryptParallelHash.h"
+#include <Library/UefiBootServicesTableLib.h>
+#include <Protocol/MpService.h>
+
+/**
+  Dispatch the block task to each AP in PEI phase.
+
+**/
+VOID
+EFIAPI
+DispatchBlockToAp (
+  VOID
+  )
+{
+  EFI_STATUS                Status;
+  EFI_MP_SERVICES_PROTOCOL  *MpServices;
+
+  Status = gBS->LocateProtocol (
+                  &gEfiMpServiceProtocolGuid,
+                  NULL,
+                  (VOID **)&MpServices
+                  );
+  if (EFI_ERROR (Status)) {
+    //
+    // Failed to locate MpServices Protocol, do parallel hash by one core.
+    //
+    DEBUG ((DEBUG_ERROR, "[DispatchBlockToApDxe] Failed to locate MpServices Protocol. Status = %r\n", Status));
+    return;
+  }
+
+  Status = MpServices->StartupAllAPs (
+                         MpServices,
+                         ParallelHashApExecute,
+                         FALSE,
+                         NULL,
+                         0,
+                         NULL,
+                         NULL
+                         );
+  return;
+}
diff --git a/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptDispatchApMm.c b/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptDispatchApMm.c
new file mode 100644
index 0000000000..bbd1024d71
--- /dev/null
+++ b/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptDispatchApMm.c
@@ -0,0 +1,35 @@
+/** @file
+  Dispatch the block task to each AP in Smm mode for parallelhash algorithm.
+
+Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "CryptParallelHash.h"
+#include <Library/MmServicesTableLib.h>
+
+/**
+  Dispatch the block task to each AP in SMM mode.
+
+**/
+VOID
+EFIAPI
+DispatchBlockToAp (
+  VOID
+  )
+{
+  UINTN  Index;
+
+  if (gMmst == NULL) {
+    return;
+  }
+
+  for (Index = 0; Index < gMmst->NumberOfCpus; Index++) {
+    if (Index != gMmst->CurrentlyExecutingCpu) {
+      gMmst->MmStartupThisAp (ParallelHashApExecute, Index, NULL);
+    }
+  }
+
+  return;
+}
diff --git a/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptDispatchApPei.c b/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptDispatchApPei.c
new file mode 100644
index 0000000000..8d7f953285
--- /dev/null
+++ b/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptDispatchApPei.c
@@ -0,0 +1,54 @@
+/** @file
+  Dispatch Block to Aps in Pei phase for parallelhash algorithm.
+
+Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "CryptParallelHash.h"
+#include <Library/PeiServicesTablePointerLib.h>
+#include <PiPei.h>
+#include <Ppi/MpServices.h>
+#include <Library/PeiServicesLib.h>
+
+/**
+  Dispatch the block task to each AP in PEI phase.
+
+**/
+VOID
+EFIAPI
+DispatchBlockToAp (
+  VOID
+  )
+{
+  EFI_STATUS               Status;
+  CONST EFI_PEI_SERVICES   **PeiServices;
+  EFI_PEI_MP_SERVICES_PPI  *MpServicesPpi;
+
+  PeiServices = GetPeiServicesTablePointer ();
+  Status      = (*PeiServices)->LocatePpi (
+                                  PeiServices,
+                                  &gEfiPeiMpServicesPpiGuid,
+                                  0,
+                                  NULL,
+                                  (VOID **)&MpServicesPpi
+                                  );
+  if (EFI_ERROR (Status)) {
+    //
+    // Failed to locate MpServices Ppi, do parallel hash by one core.
+    //
+    DEBUG ((DEBUG_ERROR, "[DispatchBlockToApPei] Failed to locate MpServices Ppi. Status = %r\n", Status));
+    return;
+  }
+
+  Status = MpServicesPpi->StartupAllAPs (
+                            (CONST EFI_PEI_SERVICES **)PeiServices,
+                            MpServicesPpi,
+                            ParallelHashApExecute,
+                            FALSE,
+                            0,
+                            NULL
+                            );
+  return;
+}
diff --git a/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptParallelHash.c b/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptParallelHash.c
new file mode 100644
index 0000000000..2c04d3e29e
--- /dev/null
+++ b/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptParallelHash.c
@@ -0,0 +1,254 @@
+/** @file
+  ParallelHash Implementation.
+
+Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "CryptParallelHash.h"
+#include <Library/SynchronizationLib.h>
+
+#define PARALLELHASH_CUSTOMIZATION  "ParallelHash"
+
+UINTN      mBlockNum;
+UINTN      mBlockSize;
+UINTN      mLastBlockSize;
+UINT8      *mInput;
+UINTN      mBlockResultSize;
+UINT8      *mBlockHashResult;
+BOOLEAN    *mBlockIsCompleted;
+SPIN_LOCK  *mSpinLockList;
+
+/**
+  Complete computation of digest of each block.
+
+  Each AP perform the function called by BSP.
+
+  @param[in] ProcedureArgument Argument of the procedure.
+**/
+VOID
+EFIAPI
+ParallelHashApExecute (
+  IN VOID  *ProcedureArgument
+  )
+{
+  UINTN    Index;
+  BOOLEAN  Status;
+
+  for (Index = 0; Index < mBlockNum; Index++) {
+    if (AcquireSpinLockOrFail (&mSpinLockList[Index])) {
+      //
+      // Completed, try next one.
+      //
+      if (mBlockIsCompleted[Index]) {
+        ReleaseSpinLock (&mSpinLockList[Index]);
+        continue;
+      }
+
+      //
+      // Calculate CShake256 for this block.
+      //
+      Status = CShake256HashAll (
+                 mInput + Index * mBlockSize,
+                 (Index == (mBlockNum - 1)) ? mLastBlockSize : mBlockSize,
+                 mBlockResultSize,
+                 NULL,
+                 0,
+                 NULL,
+                 0,
+                 mBlockHashResult + Index * mBlockResultSize
+                 );
+      if (!EFI_ERROR (Status)) {
+        mBlockIsCompleted[Index] = TRUE;
+      }
+
+      ReleaseSpinLock (&mSpinLockList[Index]);
+    }
+  }
+}
+
+/**
+  Parallel hash function ParallelHash256, as defined in NIST's Special Publication 800-185,
+  published December 2016.
+
+  @param[in]   Input            Pointer to the input message (X).
+  @param[in]   InputByteLen     The number(>0) of input bytes provided for the input data.
+  @param[in]   BlockSize        The size of each block (B).
+  @param[out]  Output           Pointer to the output buffer.
+  @param[in]   OutputByteLen    The desired number of output bytes (L).
+  @param[in]   Customization    Pointer to the customization string (S).
+  @param[in]   CustomByteLen    The length of the customization string in bytes.
+
+  @retval TRUE   ParallelHash256 digest computation succeeded.
+  @retval FALSE  ParallelHash256 digest computation failed.
+  @retval FALSE  This interface is not supported.
+
+**/
+BOOLEAN
+EFIAPI
+ParallelHash256HashAll (
+  IN CONST VOID   *Input,
+  IN       UINTN  InputByteLen,
+  IN       UINTN  BlockSize,
+  OUT      VOID   *Output,
+  IN       UINTN  OutputByteLen,
+  IN CONST VOID   *Customization,
+  IN       UINTN  CustomByteLen
+  )
+{
+  UINT8    EncBufB[sizeof (UINTN)+1];
+  UINTN    EncSizeB;
+  UINT8    EncBufN[sizeof (UINTN)+1];
+  UINTN    EncSizeN;
+  UINT8    EncBufL[sizeof (UINTN)+1];
+  UINTN    EncSizeL;
+  UINTN    Index;
+  UINT8    *CombinedInput;
+  UINTN    CombinedInputSize;
+  BOOLEAN  AllCompleted;
+  UINTN    Offset;
+  BOOLEAN  ReturnValue;
+
+  if ((InputByteLen == 0) || (OutputByteLen == 0) || (BlockSize == 0)) {
+    return FALSE;
+  }
+
+  if ((Input == NULL) || (Output == NULL)) {
+    return FALSE;
+  }
+
+  if ((CustomByteLen != 0) && (Customization == NULL)) {
+    return FALSE;
+  }
+
+  mBlockSize = BlockSize;
+
+  //
+  // Calculate block number n.
+  //
+  mBlockNum = InputByteLen % mBlockSize == 0 ? InputByteLen / mBlockSize : InputByteLen / mBlockSize + 1;
+
+  //
+  // Set hash result size of each block in bytes.
+  //
+  mBlockResultSize = OutputByteLen;
+
+  //
+  // Encode B, n, L to string and record size.
+  //
+  EncSizeB = LeftEncode (EncBufB, mBlockSize);
+  EncSizeN = RightEncode (EncBufN, mBlockNum);
+  EncSizeL = RightEncode (EncBufL, OutputByteLen * CHAR_BIT);
+
+  //
+  // Allocate buffer for combined input (newX), Block completed flag and SpinLock.
+  //
+  CombinedInputSize = EncSizeB + EncSizeN + EncSizeL + mBlockNum * mBlockResultSize;
+  CombinedInput     = AllocateZeroPool (CombinedInputSize);
+  mBlockIsCompleted = AllocateZeroPool (mBlockNum * sizeof (BOOLEAN));
+  mSpinLockList     = AllocatePool (mBlockNum * sizeof (SPIN_LOCK));
+  if ((CombinedInput == NULL) || (mBlockIsCompleted == NULL) || (mSpinLockList == NULL)) {
+    ReturnValue = FALSE;
+    goto Exit;
+  }
+
+  //
+  // Fill LeftEncode(B).
+  //
+  CopyMem (CombinedInput, EncBufB, EncSizeB);
+
+  //
+  // Prepare for parallel hash.
+  //
+  mBlockHashResult = CombinedInput + EncSizeB;
+  mInput           = (UINT8 *)Input;
+  mLastBlockSize   = InputByteLen % mBlockSize == 0 ? mBlockSize : InputByteLen % mBlockSize;
+
+  //
+  // Initialize SpinLock for each result block.
+  //
+  for (Index = 0; Index < mBlockNum; Index++) {
+    InitializeSpinLock (&mSpinLockList[Index]);
+  }
+
+  //
+  // Dispatch blocklist to each AP.
+  //
+  DispatchBlockToAp ();
+
+  //
+  // Wait until all block hash completed.
+  //
+  do {
+    AllCompleted = TRUE;
+    for (Index = 0; Index < mBlockNum; Index++) {
+      if (AcquireSpinLockOrFail (&mSpinLockList[Index])) {
+        if (!mBlockIsCompleted[Index]) {
+          AllCompleted = FALSE;
+          ReturnValue  = CShake256HashAll (
+                           mInput + Index * mBlockSize,
+                           (Index == (mBlockNum - 1)) ? mLastBlockSize : mBlockSize,
+                           mBlockResultSize,
+                           NULL,
+                           0,
+                           NULL,
+                           0,
+                           mBlockHashResult + Index * mBlockResultSize
+                           );
+          if (ReturnValue) {
+            mBlockIsCompleted[Index] = TRUE;
+          }
+
+          ReleaseSpinLock (&mSpinLockList[Index]);
+          break;
+        }
+
+        ReleaseSpinLock (&mSpinLockList[Index]);
+      } else {
+        AllCompleted = FALSE;
+        break;
+      }
+    }
+  } while (!AllCompleted);
+
+  //
+  // Fill LeftEncode(n).
+  //
+  Offset = EncSizeB + mBlockNum * mBlockResultSize;
+  CopyMem (CombinedInput + Offset, EncBufN, EncSizeN);
+
+  //
+  // Fill LeftEncode(L).
+  //
+  Offset += EncSizeN;
+  CopyMem (CombinedInput + Offset, EncBufL, EncSizeL);
+
+  ReturnValue = CShake256HashAll (
+                  CombinedInput,
+                  CombinedInputSize,
+                  OutputByteLen,
+                  PARALLELHASH_CUSTOMIZATION,
+                  AsciiStrLen (PARALLELHASH_CUSTOMIZATION),
+                  Customization,
+                  CustomByteLen,
+                  Output
+                  );
+
+Exit:
+  ZeroMem (CombinedInput, CombinedInputSize);
+
+  if (CombinedInput != NULL) {
+    FreePool (CombinedInput);
+  }
+
+  if (mSpinLockList != NULL) {
+    FreePool ((VOID *)mSpinLockList);
+  }
+
+  if (mBlockIsCompleted != NULL) {
+    FreePool (mBlockIsCompleted);
+  }
+
+  return ReturnValue;
+}
diff --git a/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptParallelHash.h b/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptParallelHash.h
new file mode 100644
index 0000000000..64af09c484
--- /dev/null
+++ b/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptParallelHash.h
@@ -0,0 +1,231 @@
+/** @file
+  ParallelHash related function and type declaration.
+
+Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+Copyright 2024 The OpenSSL Project Authors. All Rights Reserved.
+Licensed under the OpenSSL license (the "License").  You may not use
+this file except in compliance with the License.  You can obtain a copy
+in the file LICENSE in the source distribution or at
+https://www.openssl.org/source/license.html
+
+Copyright 2024 The eXtended Keccak Code Package (XKCP)
+https://github.com/XKCP/XKCP
+Keccak, designed by Guido Bertoni, Joan Daemen, Michael Peeters and Gilles Van Assche.
+Implementation by the designers, hereby denoted as "the implementer".
+For more information, feedback or questions, please refer to the Keccak Team website:
+https://keccak.team/
+To the extent possible under law, the implementer has waived all copyright
+and related or neighboring rights to the source code in this file.
+http://creativecommons.org/publicdomain/zero/1.0/
+**/
+
+#ifndef CRYPT_PARALLE_HASH_H_
+#define CRYPT_PARALLE_HASH_H_
+
+#include "InternalCryptLib.h"
+
+#define KECCAK1600_WIDTH  1600
+
+typedef UINT64 uint64_t;
+
+//
+// This struct referring to m_sha3.c from opessl and modified its type name.
+//
+typedef struct {
+  uint64_t         A[5][5];
+  size_t           block_size;  /* cached ctx->digest->block_size */
+  size_t           md_size;     /* output length, variable in XOF */
+  size_t           num;         /* used bytes in below buffer */
+  unsigned char    buf[KECCAK1600_WIDTH / 8 - 32];
+  unsigned char    pad;
+} Keccak1600_Ctx;
+
+/**
+  SHA3_absorb can be called multiple times, but at each invocation
+  largest multiple of |r| out of |len| bytes are processed. Then
+  remaining amount of bytes is returned. This is done to spare caller
+  trouble of calculating the largest multiple of |r|. |r| can be viewed
+  as blocksize. It is commonly (1600 - 256*n)/8, e.g. 168, 136, 104,
+  72, but can also be (1600 - 448)/8 = 144. All this means that message
+  padding and intermediate sub-block buffering, byte- or bitwise, is
+  caller's responsibility.
+**/
+size_t
+SHA3_absorb (
+  uint64_t             A[5][5],
+  const unsigned char  *inp,
+  size_t               len,
+  size_t               r
+  );
+
+/**
+  SHA3_squeeze is called once at the end to generate |out| hash value
+  of |len| bytes.
+**/
+VOID
+SHA3_squeeze (
+  uint64_t       A[5][5],
+  unsigned char  *out,
+  size_t         len,
+  size_t         r
+  );
+
+/**
+  Encode function from XKCP.
+
+  Encodes the input as a byte string in a way that can be unambiguously parsed
+  from the beginning of the string by inserting the length of the byte string
+  before the byte string representation of input.
+
+  @param[out] EncBuf  Result of left encode.
+  @param[in]  Value   Input of left encode.
+
+  @retval EncLen  Size of encode result in bytes.
+**/
+UINTN
+EFIAPI
+LeftEncode (
+  OUT UINT8  *EncBuf,
+  IN  UINTN  Value
+  );
+
+/**
+  Encode function from XKCP.
+
+  Encodes the input as a byte string in a way that can be unambiguously parsed
+  from the end of the string by inserting the length of the byte string after
+  the byte string representation of input.
+
+  @param[out] EncBuf  Result of right encode.
+  @param[in]  Value   Input of right encode.
+
+  @retval EncLen  Size of encode result in bytes.
+**/
+UINTN
+EFIAPI
+RightEncode (
+  OUT UINT8  *EncBuf,
+  IN  UINTN  Value
+  );
+
+/**
+  Keccak initial fuction.
+
+  Set up state with specified capacity.
+
+  @param[out] Context           Pointer to the context being initialized.
+  @param[in]  Pad               Delimited Suffix.
+  @param[in]  BlockSize         Size of context block.
+  @param[in]  MessageDigestLen  Size of message digest in bytes.
+
+  @retval 1  Initialize successfully.
+  @retval 0  Fail to initialize.
+**/
+UINT8
+EFIAPI
+KeccakInit (
+  OUT Keccak1600_Ctx  *Context,
+  IN  UINT8           Pad,
+  IN  UINTN           BlockSize,
+  IN  UINTN           MessageDigstLen
+  );
+
+/**
+  Sha3 update fuction.
+
+  This function performs Sha3 digest on a data buffer of the specified size.
+  It can be called multiple times to compute the digest of long or discontinuous data streams.
+
+  @param[in,out] Context   Pointer to the Keccak context.
+  @param[in]     Data      Pointer to the buffer containing the data to be hashed.
+  @param[in]     DataSize  Size of Data buffer in bytes.
+
+  @retval 1  Update successfully.
+**/
+UINT8
+EFIAPI
+Sha3Update (
+  IN OUT Keccak1600_Ctx  *Context,
+  IN const VOID          *Data,
+  IN UINTN               DataSize
+  );
+
+/**
+  Completes computation of Sha3 message digest.
+
+  This function completes sha3 hash computation and retrieves the digest value into
+  the specified memory. After this function has been called, the keccak context cannot
+  be used again.
+
+  @param[in, out]  Context        Pointer to the keccak context.
+  @param[out]      MessageDigest  Pointer to a buffer that receives the message digest.
+
+  @retval 1   Meaasge digest computation succeeded.
+**/
+UINT8
+EFIAPI
+Sha3Final (
+  IN OUT Keccak1600_Ctx  *Context,
+  OUT    UINT8           *MessageDigest
+  );
+
+/**
+  Computes the CSHAKE-256 message digest of a input data buffer.
+
+  This function performs the CSHAKE-256 message digest of a given data buffer, and places
+  the digest value into the specified memory.
+
+  @param[in]   Data               Pointer to the buffer containing the data to be hashed.
+  @param[in]   DataSize           Size of Data buffer in bytes.
+  @param[in]   OutputLen          Size of output in bytes.
+  @param[in]   Name               Pointer to the function name string.
+  @param[in]   NameLen            Size of the function name in bytes.
+  @param[in]   Customization      Pointer to the customization string.
+  @param[in]   CustomizationLen   Size of the customization string in bytes.
+  @param[out]  HashValue          Pointer to a buffer that receives the CSHAKE-256 digest
+                                  value.
+
+  @retval TRUE   CSHAKE-256 digest computation succeeded.
+  @retval FALSE  CSHAKE-256 digest computation failed.
+  @retval FALSE  This interface is not supported.
+
+**/
+BOOLEAN
+EFIAPI
+CShake256HashAll (
+  IN   CONST VOID  *Data,
+  IN   UINTN       DataSize,
+  IN   UINTN       OutputLen,
+  IN   CONST VOID  *Name,
+  IN   UINTN       NameLen,
+  IN   CONST VOID  *Customization,
+  IN   UINTN       CustomizationLen,
+  OUT  UINT8       *HashValue
+  );
+
+/**
+  Complete computation of digest of each block.
+
+  Each AP perform the function called by BSP.
+
+  @param[in] ProcedureArgument Argument of the procedure.
+**/
+VOID
+EFIAPI
+ParallelHashApExecute (
+  IN VOID  *ProcedureArgument
+  );
+
+/**
+  Dispatch the block task to each AP.
+
+**/
+VOID
+EFIAPI
+DispatchBlockToAp (
+  VOID
+  );
+
+#endif
diff --git a/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptSha3.c b/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptSha3.c
new file mode 100644
index 0000000000..f85946d2b1
--- /dev/null
+++ b/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptSha3.c
@@ -0,0 +1,166 @@
+/** @file
+  SHA3 realted functions from OpenSSL.
+
+Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+Copyright 2024 The OpenSSL Project Authors. All Rights Reserved.
+Licensed under the OpenSSL license (the "License").  You may not use
+this file except in compliance with the License.  You can obtain a copy
+in the file LICENSE in the source distribution or at
+https://www.openssl.org/source/license.html
+**/
+
+#include "CryptParallelHash.h"
+
+/**
+  Keccak initial fuction.
+
+  Set up state with specified capacity.
+
+  @param[out] Context           Pointer to the context being initialized.
+  @param[in]  Pad               Delimited Suffix.
+  @param[in]  BlockSize         Size of context block.
+  @param[in]  MessageDigestLen  Size of message digest in bytes.
+
+  @retval 1  Initialize successfully.
+  @retval 0  Fail to initialize.
+**/
+UINT8
+EFIAPI
+KeccakInit (
+  OUT Keccak1600_Ctx  *Context,
+  IN  UINT8           Pad,
+  IN  UINTN           BlockSize,
+  IN  UINTN           MessageDigestLen
+  )
+{
+  if (BlockSize <= sizeof (Context->buf)) {
+    memset (Context->A, 0, sizeof (Context->A));
+
+    Context->num        = 0;
+    Context->block_size = BlockSize;
+    Context->md_size    = MessageDigestLen;
+    Context->pad        = Pad;
+
+    return 1;
+  }
+
+  return 0;
+}
+
+/**
+  Sha3 update fuction.
+
+  This function performs Sha3 digest on a data buffer of the specified size.
+  It can be called multiple times to compute the digest of long or discontinuous data streams.
+
+  @param[in,out] Context   Pointer to the Keccak context.
+  @param[in]     Data      Pointer to the buffer containing the data to be hashed.
+  @param[in]     DataSize  Size of Data buffer in bytes.
+
+  @retval 1  Update successfully.
+**/
+UINT8
+EFIAPI
+Sha3Update (
+  IN OUT Keccak1600_Ctx  *Context,
+  IN const VOID          *Data,
+  IN UINTN               DataSize
+  )
+{
+  const UINT8  *DataCopy;
+  UINTN        BlockSize;
+  UINTN        Num;
+  UINTN        Rem;
+
+  DataCopy  = Data;
+  BlockSize = (UINT8)(Context->block_size);
+
+  if (DataSize == 0) {
+    return 1;
+  }
+
+  if ((Num = Context->num) != 0) {
+    //
+    // process intermediate buffer
+    //
+    Rem = BlockSize - Num;
+
+    if (DataSize < Rem) {
+      memcpy (Context->buf + Num, DataCopy, DataSize);
+      Context->num += DataSize;
+      return 1;
+    }
+
+    //
+    // We have enough data to fill or overflow the intermediate
+    // buffer. So we append |Rem| bytes and process the block,
+    // leaving the rest for later processing.
+    //
+    memcpy (Context->buf + Num, DataCopy, Rem);
+    DataCopy += Rem;
+    DataSize -= Rem;
+    (void)SHA3_absorb (Context->A, Context->buf, BlockSize, BlockSize);
+    Context->num = 0;
+    // Context->buf is processed, Context->num is guaranteed to be zero.
+  }
+
+  if (DataSize >= BlockSize) {
+    Rem = SHA3_absorb (Context->A, DataCopy, DataSize, BlockSize);
+  } else {
+    Rem = DataSize;
+  }
+
+  if (Rem > 0) {
+    memcpy (Context->buf, DataCopy + DataSize - Rem, Rem);
+    Context->num = Rem;
+  }
+
+  return 1;
+}
+
+/**
+  Completes computation of Sha3 message digest.
+
+  This function completes sha3 hash computation and retrieves the digest value into
+  the specified memory. After this function has been called, the keccak context cannot
+  be used again.
+
+  @param[in, out]  Context        Pointer to the keccak context.
+  @param[out]      MessageDigest  Pointer to a buffer that receives the message digest.
+
+  @retval 1   Meaasge digest computation succeeded.
+**/
+UINT8
+EFIAPI
+Sha3Final (
+  IN OUT Keccak1600_Ctx  *Context,
+  OUT    UINT8           *MessageDigest
+  )
+{
+  UINTN  BlockSize;
+  UINTN  Num;
+
+  BlockSize = Context->block_size;
+  Num       = Context->num;
+
+  if (Context->md_size == 0) {
+    return 1;
+  }
+
+  //
+  // Pad the data with 10*1. Note that |Num| can be |BlockSize - 1|
+  // in which case both byte operations below are performed on
+  // same byte.
+  //
+  memset (Context->buf + Num, 0, BlockSize - Num);
+  Context->buf[Num]            = Context->pad;
+  Context->buf[BlockSize - 1] |= 0x80;
+
+  (void)SHA3_absorb (Context->A, Context->buf, BlockSize, BlockSize);
+
+  SHA3_squeeze (Context->A, MessageDigest, Context->md_size, BlockSize);
+
+  return 1;
+}
diff --git a/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptSm3.c b/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptSm3.c
new file mode 100644
index 0000000000..1a442d714e
--- /dev/null
+++ b/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptSm3.c
@@ -0,0 +1,235 @@
+/** @file
+  SM3 Digest Wrapper Implementations over openssl.
+
+Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include "InternalCryptLib.h"
+#include "internal/sm3.h"
+
+/**
+  Retrieves the size, in bytes, of the context buffer required for SM3 hash operations.
+
+  @return  The size, in bytes, of the context buffer required for SM3 hash operations.
+
+**/
+UINTN
+EFIAPI
+Sm3GetContextSize (
+  VOID
+  )
+{
+  //
+  // Retrieves Openssl SM3 Context Size
+  //
+  return (UINTN)(sizeof (SM3_CTX));
+}
+
+/**
+  Initializes user-supplied memory pointed by Sm3Context as SM3 hash context for
+  subsequent use.
+
+  If Sm3Context is NULL, then return FALSE.
+
+  @param[out]  Sm3Context  Pointer to SM3 context being initialized.
+
+  @retval TRUE   SM3 context initialization succeeded.
+  @retval FALSE  SM3 context initialization failed.
+
+**/
+BOOLEAN
+EFIAPI
+Sm3Init (
+  OUT  VOID  *Sm3Context
+  )
+{
+  //
+  // Check input parameters.
+  //
+  if (Sm3Context == NULL) {
+    return FALSE;
+  }
+
+  //
+  // Openssl SM3 Context Initialization
+  //
+  ossl_sm3_init ((SM3_CTX *)Sm3Context);
+  return TRUE;
+}
+
+/**
+  Makes a copy of an existing SM3 context.
+
+  If Sm3Context is NULL, then return FALSE.
+  If NewSm3Context is NULL, then return FALSE.
+  If this interface is not supported, then return FALSE.
+
+  @param[in]  Sm3Context     Pointer to SM3 context being copied.
+  @param[out] NewSm3Context  Pointer to new SM3 context.
+
+  @retval TRUE   SM3 context copy succeeded.
+  @retval FALSE  SM3 context copy failed.
+  @retval FALSE  This interface is not supported.
+
+**/
+BOOLEAN
+EFIAPI
+Sm3Duplicate (
+  IN   CONST VOID  *Sm3Context,
+  OUT  VOID        *NewSm3Context
+  )
+{
+  //
+  // Check input parameters.
+  //
+  if ((Sm3Context == NULL) || (NewSm3Context == NULL)) {
+    return FALSE;
+  }
+
+  CopyMem (NewSm3Context, Sm3Context, sizeof (SM3_CTX));
+
+  return TRUE;
+}
+
+/**
+  Digests the input data and updates SM3 context.
+
+  This function performs SM3 digest on a data buffer of the specified size.
+  It can be called multiple times to compute the digest of long or discontinuous data streams.
+  SM3 context should be already correctly initialized by Sm3Init(), and should not be finalized
+  by Sm3Final(). Behavior with invalid context is undefined.
+
+  If Sm3Context is NULL, then return FALSE.
+
+  @param[in, out]  Sm3Context     Pointer to the SM3 context.
+  @param[in]       Data           Pointer to the buffer containing the data to be hashed.
+  @param[in]       DataSize       Size of Data buffer in bytes.
+
+  @retval TRUE   SM3 data digest succeeded.
+  @retval FALSE  SM3 data digest failed.
+
+**/
+BOOLEAN
+EFIAPI
+Sm3Update (
+  IN OUT  VOID        *Sm3Context,
+  IN      CONST VOID  *Data,
+  IN      UINTN       DataSize
+  )
+{
+  //
+  // Check input parameters.
+  //
+  if (Sm3Context == NULL) {
+    return FALSE;
+  }
+
+  //
+  // Check invalid parameters, in case that only DataLength was checked in Openssl
+  //
+  if ((Data == NULL) && (DataSize != 0)) {
+    return FALSE;
+  }
+
+  //
+  // Openssl SM3 Hash Update
+  //
+  ossl_sm3_update ((SM3_CTX *)Sm3Context, Data, DataSize);
+
+  return TRUE;
+}
+
+/**
+  Completes computation of the SM3 digest value.
+
+  This function completes SM3 hash computation and retrieves the digest value into
+  the specified memory. After this function has been called, the SM3 context cannot
+  be used again.
+  SM3 context should be already correctly initialized by Sm3Init(), and should not be
+  finalized by Sm3Final(). Behavior with invalid SM3 context is undefined.
+
+  If Sm3Context is NULL, then return FALSE.
+  If HashValue is NULL, then return FALSE.
+
+  @param[in, out]  Sm3Context     Pointer to the SM3 context.
+  @param[out]      HashValue      Pointer to a buffer that receives the SM3 digest
+                                  value (32 bytes).
+
+  @retval TRUE   SM3 digest computation succeeded.
+  @retval FALSE  SM3 digest computation failed.
+
+**/
+BOOLEAN
+EFIAPI
+Sm3Final (
+  IN OUT  VOID   *Sm3Context,
+  OUT     UINT8  *HashValue
+  )
+{
+  //
+  // Check input parameters.
+  //
+  if ((Sm3Context == NULL) || (HashValue == NULL)) {
+    return FALSE;
+  }
+
+  //
+  // Openssl SM3 Hash Finalization
+  //
+  ossl_sm3_final (HashValue, (SM3_CTX *)Sm3Context);
+
+  return TRUE;
+}
+
+/**
+  Computes the SM3 message digest of a input data buffer.
+
+  This function performs the SM3 message digest of a given data buffer, and places
+  the digest value into the specified memory.
+
+  If this interface is not supported, then return FALSE.
+
+  @param[in]   Data        Pointer to the buffer containing the data to be hashed.
+  @param[in]   DataSize    Size of Data buffer in bytes.
+  @param[out]  HashValue   Pointer to a buffer that receives the SM3 digest
+                           value (32 bytes).
+
+  @retval TRUE   SM3 digest computation succeeded.
+  @retval FALSE  SM3 digest computation failed.
+  @retval FALSE  This interface is not supported.
+
+**/
+BOOLEAN
+EFIAPI
+Sm3HashAll (
+  IN   CONST VOID  *Data,
+  IN   UINTN       DataSize,
+  OUT  UINT8       *HashValue
+  )
+{
+  SM3_CTX  Ctx;
+
+  //
+  // Check input parameters.
+  //
+  if (HashValue == NULL) {
+    return FALSE;
+  }
+
+  if ((Data == NULL) && (DataSize != 0)) {
+    return FALSE;
+  }
+
+  //
+  // SM3 Hash Computation.
+  //
+  ossl_sm3_init (&Ctx);
+
+  ossl_sm3_update (&Ctx, Data, DataSize);
+
+  ossl_sm3_final (HashValue, &Ctx);
+
+  return TRUE;
+}
diff --git a/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptXkcp.c b/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptXkcp.c
new file mode 100644
index 0000000000..420ed11280
--- /dev/null
+++ b/CryptoPkg/Library/BaseCryptLibMbedTls/Hash/CryptXkcp.c
@@ -0,0 +1,107 @@
+/** @file
+  Encode realted functions from Xkcp.
+
+Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+
+Copyright 2024 The eXtended Keccak Code Package (XKCP)
+https://github.com/XKCP/XKCP
+Keccak, designed by Guido Bertoni, Joan Daemen, Michael Peeters and Gilles Van Assche.
+Implementation by the designers, hereby denoted as "the implementer".
+For more information, feedback or questions, please refer to the Keccak Team website:
+https://keccak.team/
+To the extent possible under law, the implementer has waived all copyright
+and related or neighboring rights to the source code in this file.
+http://creativecommons.org/publicdomain/zero/1.0/
+
+**/
+
+#include "CryptParallelHash.h"
+
+/**
+  Encode function from XKCP.
+
+  Encodes the input as a byte string in a way that can be unambiguously parsed
+  from the beginning of the string by inserting the length of the byte string
+  before the byte string representation of input.
+
+  @param[out] EncBuf  Result of left encode.
+  @param[in]  Value   Input of left encode.
+
+  @retval EncLen  Size of encode result in bytes.
+**/
+UINTN
+EFIAPI
+LeftEncode (
+  OUT UINT8  *EncBuf,
+  IN  UINTN  Value
+  )
+{
+  UINT32  BlockNum;
+  UINT32  EncLen;
+  UINT32  Index;
+  UINTN   ValueCopy;
+
+  for ( ValueCopy = Value, BlockNum = 0; ValueCopy && (BlockNum < sizeof (UINTN)); ++BlockNum, ValueCopy >>= 8 ) {
+    //
+    // Empty
+    //
+  }
+
+  if (BlockNum == 0) {
+    BlockNum = 1;
+  }
+
+  for (Index = 1; Index <= BlockNum; ++Index) {
+    EncBuf[Index] = (UINT8)(Value >> (8 * (BlockNum - Index)));
+  }
+
+  EncBuf[0] = (UINT8)BlockNum;
+  EncLen    = BlockNum + 1;
+
+  return EncLen;
+}
+
+/**
+  Encode function from XKCP.
+
+  Encodes the input as a byte string in a way that can be unambiguously parsed
+  from the end of the string by inserting the length of the byte string after
+  the byte string representation of input.
+
+  @param[out] EncBuf  Result of right encode.
+  @param[in]  Value   Input of right encode.
+
+  @retval EncLen  Size of encode result in bytes.
+**/
+UINTN
+EFIAPI
+RightEncode (
+  OUT UINT8  *EncBuf,
+  IN  UINTN  Value
+  )
+{
+  UINT32  BlockNum;
+  UINT32  EncLen;
+  UINT32  Index;
+  UINTN   ValueCopy;
+
+  for (ValueCopy = Value, BlockNum = 0; ValueCopy && (BlockNum < sizeof (UINTN)); ++BlockNum, ValueCopy >>= 8) {
+    //
+    // Empty
+    //
+  }
+
+  if (BlockNum == 0) {
+    BlockNum = 1;
+  }
+
+  for (Index = 1; Index <= BlockNum; ++Index) {
+    EncBuf[Index-1] = (UINT8)(Value >> (8 * (BlockNum-Index)));
+  }
+
+  EncBuf[BlockNum] = (UINT8)BlockNum;
+  EncLen           = BlockNum + 1;
+
+  return EncLen;
+}
diff --git a/CryptoPkg/Library/BaseCryptLibMbedTls/SysCall/DummyOpensslSupport.c b/CryptoPkg/Library/BaseCryptLibMbedTls/SysCall/DummyOpensslSupport.c
new file mode 100644
index 0000000000..c50001959c
--- /dev/null
+++ b/CryptoPkg/Library/BaseCryptLibMbedTls/SysCall/DummyOpensslSupport.c
@@ -0,0 +1,595 @@
+/**
+Copyright (c) 2024, Intel Corporation. All rights reserved.<BR>
+SPDX-License-Identifier: BSD-2-Clause-Patent
+**/
+
+#include <CrtLibSupport.h>
+
+int  errno = 0;
+
+FILE  *stderr = NULL;
+FILE  *stdin  = NULL;
+FILE  *stdout = NULL;
+
+typedef
+  int
+(*SORT_COMPARE)(
+  IN  VOID  *Buffer1,
+  IN  VOID  *Buffer2
+  );
+
+//
+// Duplicated from EDKII BaseSortLib for qsort() wrapper
+//
+STATIC
+VOID
+QuickSortWorker (
+  IN OUT    VOID          *BufferToSort,
+  IN CONST  UINTN         Count,
+  IN CONST  UINTN         ElementSize,
+  IN        SORT_COMPARE  CompareFunction,
+  IN        VOID          *Buffer
+  )
+{
+  VOID   *Pivot;
+  UINTN  LoopCount;
+  UINTN  NextSwapLocation;
+
+  ASSERT (BufferToSort    != NULL);
+  ASSERT (CompareFunction != NULL);
+  ASSERT (Buffer          != NULL);
+
+  if ((Count < 2) || (ElementSize  < 1)) {
+    return;
+  }
+
+  NextSwapLocation = 0;
+
+  //
+  // Pick a pivot (we choose last element)
+  //
+  Pivot = ((UINT8 *)BufferToSort + ((Count - 1) * ElementSize));
+
+  //
+  // Now get the pivot such that all on "left" are below it
+  // and everything "right" are above it
+  //
+  for (LoopCount = 0; LoopCount < Count - 1; LoopCount++) {
+    //
+    // If the element is less than the pivot
+    //
+    if (CompareFunction ((VOID *)((UINT8 *)BufferToSort + ((LoopCount) * ElementSize)), Pivot) <= 0) {
+      //
+      // Swap
+      //
+      CopyMem (Buffer, (UINT8 *)BufferToSort + (NextSwapLocation * ElementSize), ElementSize);
+      CopyMem ((UINT8 *)BufferToSort + (NextSwapLocation * ElementSize), (UINT8 *)BufferToSort + ((LoopCount) * ElementSize), ElementSize);
+      CopyMem ((UINT8 *)BufferToSort + ((LoopCount) * ElementSize), Buffer, ElementSize);
+
+      //
+      // Increment NextSwapLocation
+      //
+      NextSwapLocation++;
+    }
+  }
+
+  //
+  // Swap pivot to its final position (NextSwapLocation)
+  //
+  CopyMem (Buffer, Pivot, ElementSize);
+  CopyMem (Pivot, (UINT8 *)BufferToSort + (NextSwapLocation * ElementSize), ElementSize);
+  CopyMem ((UINT8 *)BufferToSort + (NextSwapLocation * ElementSize), Buffer, ElementSize);
+
+  //
+  // Now recurse on 2 partial lists.  Neither of these will have the 'pivot' element.
+  // IE list is sorted left half, pivot element, sorted right half...
+  //
+  QuickSortWorker (
+    BufferToSort,
+    NextSwapLocation,
+    ElementSize,
+    CompareFunction,
+    Buffer
+    );
+
+  QuickSortWorker (
+    (UINT8 *)BufferToSort + (NextSwapLocation + 1) * ElementSize,
+    Count - NextSwapLocation - 1,
+    ElementSize,
+    CompareFunction,
+    Buffer
+    );
+
+  return;
+}
+
+// ---------------------------------------------------------
+// Standard C Run-time Library Interface Wrapper
+// ---------------------------------------------------------
+
+//
+// -- String Manipulation Routines --
+//
+
+/* Scan a string for the last occurrence of a character */
+char *
+strrchr (
+  const char  *str,
+  int         c
+  )
+{
+  char  *save;
+
+  for (save = NULL; ; ++str) {
+    if (*str == c) {
+      save = (char *)str;
+    }
+
+    if (*str == 0) {
+      return (save);
+    }
+  }
+}
+
+/* Compare first n bytes of string s1 with string s2, ignoring case */
+int
+strncasecmp (
+  const char  *s1,
+  const char  *s2,
+  size_t      n
+  )
+{
+  int  Val;
+
+  ASSERT (s1 != NULL);
+  ASSERT (s2 != NULL);
+
+  if (n != 0) {
+    do {
+      Val = tolower (*s1) - tolower (*s2);
+      if (Val != 0) {
+        return Val;
+      }
+
+      ++s1;
+      ++s2;
+      if (*s1 == '\0') {
+        break;
+      }
+    } while (--n != 0);
+  }
+
+  return 0;
+}
+
+/* Read formatted data from a string */
+int
+sscanf (
+  const char  *buffer,
+  const char  *format,
+  ...
+  )
+{
+  //
+  // Null sscanf() function implementation to satisfy the linker, since
+  // no direct functionality logic dependency in present UEFI cases.
+  //
+  return 0;
+}
+
+/* Maps errnum to an error-message string */
+char *
+strerror (
+  int  errnum
+  )
+{
+  return NULL;
+}
+
+/* Computes the length of the maximum initial segment of the string pointed to by s1
+   which consists entirely of characters from the string pointed to by s2. */
+size_t
+strspn (
+  const char  *s1,
+  const char  *s2
+  )
+{
+  UINT8   Map[32];
+  UINT32  Index;
+  size_t  Count;
+
+  for (Index = 0; Index < 32; Index++) {
+    Map[Index] = 0;
+  }
+
+  while (*s2) {
+    Map[*s2 >> 3] |= (1 << (*s2 & 7));
+    s2++;
+  }
+
+  if (*s1) {
+    Count = 0;
+    while (Map[*s1 >> 3] & (1 << (*s1 & 7))) {
+      Count++;
+      s1++;
+    }
+
+    return Count;
+  }
+
+  return 0;
+}
+
+/* Computes the length of the maximum initial segment of the string pointed to by s1
+   which consists entirely of characters not from the string pointed to by s2. */
+size_t
+strcspn (
+  const char  *s1,
+  const char  *s2
+  )
+{
+  UINT8   Map[32];
+  UINT32  Index;
+  size_t  Count;
+
+  for (Index = 0; Index < 32; Index++) {
+    Map[Index] = 0;
+  }
+
+  while (*s2) {
+    Map[*s2 >> 3] |= (1 << (*s2 & 7));
+    s2++;
+  }
+
+  Map[0] |= 1;
+
+  Count = 0;
+  while (!(Map[*s1 >> 3] & (1 << (*s1 & 7)))) {
+    Count++;
+    s1++;
+  }
+
+  return Count;
+}
+
+char *
+strcpy (
+  char        *strDest,
+  const char  *strSource
+  )
+{
+  // AsciiStrCpyS (strDest, MAX_STRING_SIZE, strSource);
+  // return strDest;
+  return NULL;
+}
+
+//
+// -- Character Classification Routines --
+//
+
+/* Determines if a particular character is a decimal-digit character */
+int
+isdigit (
+  int  c
+  )
+{
+  //
+  // <digit> ::= [0-9]
+  //
+  return (('0' <= (c)) && ((c) <= '9'));
+}
+
+/* Determine if an integer represents character that is a hex digit */
+int
+isxdigit (
+  int  c
+  )
+{
+  //
+  // <hexdigit> ::= [0-9] | [a-f] | [A-F]
+  //
+  return ((('0' <= (c)) && ((c) <= '9')) ||
+          (('a' <= (c)) && ((c) <= 'f')) ||
+          (('A' <= (c)) && ((c) <= 'F')));
+}
+
+/* Determines if a particular character represents a space character */
+int
+isspace (
+  int  c
+  )
+{
+  //
+  // <space> ::= [ ]
+  //
+  return ((c) == ' ');
+}
+
+/* Determine if a particular character is an alphanumeric character */
+int
+isalnum (
+  int  c
+  )
+{
+  //
+  // <alnum> ::= [0-9] | [a-z] | [A-Z]
+  //
+  return ((('0' <= (c)) && ((c) <= '9')) ||
+          (('a' <= (c)) && ((c) <= 'z')) ||
+          (('A' <= (c)) && ((c) <= 'Z')));
+}
+
+/* Determines if a particular character is in upper case */
+int
+isupper (
+  int  c
+  )
+{
+  //
+  // <uppercase letter> := [A-Z]
+  //
+  return (('A' <= (c)) && ((c) <= 'Z'));
+}
+
+//
+// -- Data Conversion Routines --
+//
+
+/* Convert strings to a long-integer value */
+long
+strtol (
+  const char  *nptr,
+  char        **endptr,
+  int         base
+  )
+{
+  //
+  // Null strtol() function implementation to satisfy the linker, since there is
+  // no direct functionality logic dependency in present UEFI cases.
+  //
+  return 0;
+}
+
+/* Convert strings to an unsigned long-integer value */
+unsigned long
+strtoul (
+  const char  *nptr,
+  char        **endptr,
+  int         base
+  )
+{
+  //
+  // Null strtoul() function implementation to satisfy the linker, since there is
+  // no direct functionality logic dependency in present UEFI cases.
+  //
+  return 0;
+}
+
+/* Convert character to lowercase */
+int
+tolower (
+  int  c
+  )
+{
+  if (('A' <= (c)) && ((c) <= 'Z')) {
+    return (c - ('A' - 'a'));
+  }
+
+  return (c);
+}
+
+//
+// -- Searching and Sorting Routines --
+//
+
+/* Performs a quick sort */
+void
+qsort (
+  void *base,
+  size_t num,
+  size_t width,
+  int ( *compare )(const void *, const void *)
+  )
+{
+  VOID  *Buffer;
+
+  ASSERT (base    != NULL);
+  ASSERT (compare != NULL);
+
+  //
+  // Use CRT-style malloc to cover BS and RT memory allocation.
+  //
+  Buffer = malloc (width);
+  ASSERT (Buffer != NULL);
+
+  //
+  // Re-use PerformQuickSort() function Implementation in EDKII BaseSortLib.
+  //
+  QuickSortWorker (base, (UINTN)num, (UINTN)width, (SORT_COMPARE)compare, Buffer);
+
+  free (Buffer);
+  return;
+}
+
+//
+// -- Process and Environment Control Routines --
+//
+
+/* Get a value from the current environment */
+char *
+getenv (
+  const char  *varname
+  )
+{
+  //
+  // Null getenv() function implementation to satisfy the linker, since there is
+  // no direct functionality logic dependency in present UEFI cases.
+  //
+  return NULL;
+}
+
+/* Get a value from the current environment */
+char *
+secure_getenv (
+  const char  *varname
+  )
+{
+  //
+  // Null secure_getenv() function implementation to satisfy the linker, since
+  // there is no direct functionality logic dependency in present UEFI cases.
+  //
+  // From the secure_getenv() manual: 'just like getenv() except that it
+  // returns NULL in cases where "secure execution" is required'.
+  //
+  return NULL;
+}
+
+//
+// -- Stream I/O Routines --
+//
+
+/* Write data to a stream */
+size_t
+fwrite (
+  const void  *buffer,
+  size_t      size,
+  size_t      count,
+  FILE        *stream
+  )
+{
+  return 0;
+}
+
+#ifdef __GNUC__
+
+typedef
+  VOID
+(EFIAPI *NoReturnFuncPtr)(
+  VOID
+  ) __attribute__ ((__noreturn__));
+
+STATIC
+VOID
+EFIAPI
+NopFunction (
+  VOID
+  )
+{
+}
+
+void
+abort (
+  void
+  )
+{
+  NoReturnFuncPtr  NoReturnFunc;
+
+  NoReturnFunc = (NoReturnFuncPtr)NopFunction;
+
+  NoReturnFunc ();
+}
+
+#else
+
+void
+abort (
+  void
+  )
+{
+  // Do nothing
+}
+
+#endif
+
+int
+fclose (
+  FILE  *f
+  )
+{
+  return 0;
+}
+
+FILE *
+fopen (
+  const char  *c,
+  const char  *m
+  )
+{
+  return NULL;
+}
+
+size_t
+fread (
+  void    *b,
+  size_t  c,
+  size_t  i,
+  FILE    *f
+  )
+{
+  return 0;
+}
+
+uid_t
+getuid (
+  void
+  )
+{
+  return 0;
+}
+
+uid_t
+geteuid (
+  void
+  )
+{
+  return 0;
+}
+
+gid_t
+getgid (
+  void
+  )
+{
+  return 0;
+}
+
+gid_t
+getegid (
+  void
+  )
+{
+  return 0;
+}
+
+int
+printf (
+  char const  *fmt,
+  ...
+  )
+{
+  return 0;
+}
+
+void *
+malloc     (
+  size_t  a
+  )
+{
+  return NULL;
+}
+
+void *
+realloc    (
+  void    *a,
+  size_t  b
+  )
+{
+  return NULL;
+}
+
+void
+free        (
+  void  *b
+  )
+{
+}
diff --git a/CryptoPkg/Library/MbedTlsLib/MbedTlsLib.inf b/CryptoPkg/Library/MbedTlsLib/MbedTlsLib.inf
index adcf770902..93f8e69383 100644
--- a/CryptoPkg/Library/MbedTlsLib/MbedTlsLib.inf
+++ b/CryptoPkg/Library/MbedTlsLib/MbedTlsLib.inf
@@ -13,6 +13,7 @@
   MODULE_TYPE                    = BASE
   VERSION_STRING                 = 1.0
   LIBRARY_CLASS                  = MbedTlsLib
+  DEFINE OPENSSL_PATH            = ../OpensslLib/openssl
 
 #
 # The following information is for reference only and not required by the build tools.
@@ -21,6 +22,11 @@
 #
 
 [Sources]
+# Openssl files list starts here
+  $(OPENSSL_PATH)/crypto/mem_clr.c
+  $(OPENSSL_PATH)/crypto/sha/keccak1600.c
+  $(OPENSSL_PATH)/crypto/sm3/sm3.c
+# Openssl files list ends here
   Include/mbedtls/mbedtls_config.h
   mbedtls/library/aes.c
   mbedtls/library/asn1parse.c
diff --git a/CryptoPkg/Library/MbedTlsLib/MbedTlsLibFull.inf b/CryptoPkg/Library/MbedTlsLib/MbedTlsLibFull.inf
index 7715392a9d..98695312cf 100644
--- a/CryptoPkg/Library/MbedTlsLib/MbedTlsLibFull.inf
+++ b/CryptoPkg/Library/MbedTlsLib/MbedTlsLibFull.inf
@@ -13,6 +13,7 @@
   MODULE_TYPE                    = BASE
   VERSION_STRING                 = 1.0
   LIBRARY_CLASS                  = MbedTlsLib
+  DEFINE OPENSSL_PATH            = ../OpensslLib/openssl
 
 #
 # The following information is for reference only and not required by the build tools.
@@ -21,6 +22,11 @@
 #
 
 [Sources]
+# Openssl files list starts here
+  $(OPENSSL_PATH)/crypto/mem_clr.c
+  $(OPENSSL_PATH)/crypto/sha/keccak1600.c
+  $(OPENSSL_PATH)/crypto/sm3/sm3.c
+# Openssl files list ends here
   Include/mbedtls/mbedtls_config.h
   mbedtls/library/aes.c
   mbedtls/library/asn1parse.c
-- 
2.26.2.windows.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#118058): https://edk2.groups.io/g/devel/message/118058
Mute This Topic: https://groups.io/mt/105662372/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 3+ messages in thread

end of thread, other threads:[~2024-04-24  8:27 UTC | newest]

Thread overview: 3+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2024-04-22  1:33 [edk2-devel] [PATCH] Add SHA3/SM3 functions with openssl for Mbedtls Wenxing Hou
2024-04-22  7:43 ` Li, Yi
2024-04-24  8:27   ` Wenxing Hou

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox