MCUXpresso SDK Documentation

middleware/wireless/framework/services/SecLib_RNG/SecLib.c

middleware/wireless/framework/services/SecLib_RNG/SecLib.c#

   1/*
   2 * Copyright (c) 2015 Freescale Semiconductor, Inc.
   3 * Copyright 2016-2018, 2020-2026 NXP
   4 * SPDX-License-Identifier: BSD-3-Clause
   5 */
   6/*! *********************************************************************************
   7 * \file
   8 *
   9 * This is the source file for the security module.
  10 *
  11 ********************************************************************************** */
  12
  13/*! *********************************************************************************
  14*************************************************************************************
  15* Include
  16*************************************************************************************
  17********************************************************************************** */
  18#include "FunctionLib.h"
  19#include "SecLib.h"
  20#include "fsl_device_registers.h"
  21#include "fsl_os_abstraction.h"
  22#include "fsl_component_mem_manager.h"
  23#include "CryptoLibSW.h"
  24
  25/* header file to be included after fsl_device_registers.h as it potentially overwrites some feature MACROs
  26    (FSL_FEATURE_SOC_LTC_COUNT) */
  27#include "fwk_config.h"
  28
  29#if (defined(FSL_FEATURE_SOC_MMCAU_COUNT) && (FSL_FEATURE_SOC_MMCAU_COUNT > 0))
  30
  31#ifndef FREESCALE_MMCAU
  32#define FREESCALE_MMCAU 1
  33#endif
  34
  35#ifndef FREESCALE_MMCAU_SHA
  36#define FREESCALE_MMCAU_SHA 1
  37#endif
  38
  39#include "cau_api.h"
  40#endif /* FSL_FEATURE_SOC_MMCAU_COUNT */
  41
  42#if (defined(FSL_FEATURE_SOC_LTC_COUNT) && (FSL_FEATURE_SOC_LTC_COUNT > 0))
  43#include "fsl_ltc.h"
  44#endif
  45
  46/*! *********************************************************************************
  47*************************************************************************************
  48* Private macros
  49*************************************************************************************
  50********************************************************************************** */
  51
  52/* AES constants */
  53#define AES128        128U
  54#define AES128_ROUNDS 10U
  55
  56#define AES192        192U
  57#define AES192_ROUNDS 12U
  58
  59#define AES256        256U
  60#define AES256_ROUNDS 14U
  61
  62/* Limit the size of the hashed stream so that the number of bits does not exceed 32 bit in size.
  63 * (UINT32_MAX / 8uL) enforces that the number of bits fits in a 32-bit unsigned integer.
  64 * This limitation is arbitrary but 2^29 is more than enough.
  65 */
  66#define MAX_SHA256_TOTAL_BYTES (UINT32_MAX / 8uL)
  67
  68#if ((defined(USE_RTOS) && (USE_RTOS > 0)) &&                                       \
  69     ((defined FSL_FEATURE_SOC_LTC_COUNT && (FSL_FEATURE_SOC_LTC_COUNT > 0)) ||     \
  70      (defined FSL_FEATURE_SOC_MMCAU_COUNT && (FSL_FEATURE_SOC_MMCAU_COUNT > 0)) || \
  71      (defined FSL_FEATURE_SOC_AES_HW && (FSL_FEATURE_SOC_AES_HW > 0))))
  72#define gSecLibUseMutex_c TRUE
  73#else
  74#define gSecLibUseMutex_c FALSE
  75#endif
  76
  77secResultType_t SecLibMutexCreate(void);
  78
  79#if (defined(gSecLibUseMutex_c) && (gSecLibUseMutex_c > 0))
  80
  81#define SECLIB_MUTEX_LOCK()   (void)SecLibMutexLock()
  82#define SECLIB_MUTEX_UNLOCK() (void)SecLibMutexUnlock()
  83#else
  84#define SECLIB_MUTEX_LOCK()
  85#define SECLIB_MUTEX_UNLOCK()
  86#endif
  87/*
  88 * __DSP_PRESENT is defined in the device specific file, however avoid use of __DSP_PRESENT to avoid
  89 * a dependency with SDK.
  90 * It is likely to be present on all Core M33, Core M7 and Core M4 devices.
  91 * Nonetheless RW61x was designed without ARM DSP extension, in which case avoid defining
  92 * gSecLibUseDspExtension_d.
  93 * gSecLibUseDspExtension_d follows __DSP_PRESENT definition unless overridden to 0
  94 */
  95
  96#ifndef gSecLibUseDspExtension_d
  97#define gSecLibUseDspExtension_d 0
  98#endif
  99
 100#ifndef RAISE_ERROR
 101#define RAISE_ERROR(x, code) \
 102    {                        \
 103        (x) = (code);        \
 104        break;               \
 105    }
 106#endif
 107
 108#define AES_BLOCK_ALIGN_MASK (0x0000000fUL)
 109/* Compute number of whole AES block bytes */
 110#define AES_WHOLE_BLOCK_BYTES(_LEN_) (((uint32_t)(_LEN_)) & ~AES_BLOCK_ALIGN_MASK)
 111/* Compute number of residual bytes constituting a partial AES block */
 112#define AES_PARTIAL_BLOCK_BYTES(_LEN_) (((uint32_t)(_LEN_)) & AES_BLOCK_ALIGN_MASK)
 113
 114#define AES_TOTAL_BLOCK_NB(_LEN_) ((((uint32_t)(_LEN_)) + ((AES_BLOCK_SIZE)-1U)) / AES_BLOCK_SIZE)
 115
 116/*! *********************************************************************************
 117*************************************************************************************
 118* Private prototypes
 119*************************************************************************************
 120********************************************************************************** */
 121
 122/*! *********************************************************************************
 123*************************************************************************************
 124* Private type definitions
 125*************************************************************************************
 126********************************************************************************** */
 127typedef union _uuint128_tag
 128{
 129    uint8_t  u8[16];
 130    uint64_t u64[2];
 131} uuint128_t;
 132
 133#if (defined(USE_TASK_FOR_HW_AES) && (USE_TASK_FOR_HW_AES == 1))
 134uint8_t AES128ECB_Enc_Id;
 135uint8_t AES128ECB_Dec_Id;
 136uint8_t AES128ECBB_Enc_Id;
 137uint8_t AES128ECBB_Dec_Id;
 138
 139uint8_t AES128CTR_Enc_Id;
 140uint8_t AES128CTR_Dec_Id;
 141
 142uint8_t AES128CMAC_Id;
 143#endif
 144
 145#if (defined(FSL_FEATURE_SOC_MMCAU_COUNT) && (FSL_FEATURE_SOC_MMCAU_COUNT > 0))
 146typedef struct mmcauAesContext_tag
 147{
 148    uint8_t keyExpansion[44 * 4];
 149    uint8_t alignedIn[AES_BLOCK_SIZE];
 150    uint8_t alignedOut[AES_BLOCK_SIZE];
 151} mmcauAesContext_t;
 152
 153/*! MMCAU AES Context Buffer for both AES Encrypt and Decrypt operations.*/
 154mmcauAesContext_t mmcauAesCtx;
 155#endif /* FSL_FEATURE_SOC_MMCAU_COUNT */
 156
 157#if gSecLibUseMutex_c
 158/*! Mutex used to protect the AES Context when an RTOS is used. */
 159static OSA_MUTEX_HANDLE_DEFINE(mSecLibMutexId);
 160#endif /* USE_RTOS */
 161
 162typedef struct sha256Context_tag
 163{
 164    uint32_t hash[SHA256_HASH_SIZE / sizeof(uint32_t)];
 165    uint8_t  buffer[SHA256_BLOCK_SIZE];
 166    uint32_t totalBytes;
 167    uint8_t  bytes;
 168} sha256Context_t;
 169
 170typedef struct HMAC_SHA256_context_tag
 171{
 172    sha256Context_t shaCtx;
 173    uint8_t         pad[SHA256_BLOCK_SIZE];
 174} HMAC_SHA256_context_t;
 175
 176/************************************************************************************
 177*************************************************************************************
 178* Private memory declarations
 179*************************************************************************************
 180************************************************************************************/
 181/*! Callback used to offload Security steps onto application message queue. When it is not set the
 182 * multiplication is done using SecLib means */
 183extern secLibCallback_t pfSecLibMultCallback;
 184
 185#if (gSecLibUseBleDebugKeys_d == 1)
 186/*! Bluetooth LE debug keys as specified in section 2.3.5.6.1 vol. 3, part H of the Bluetooth Core specification version 5.4 */
 187static const ecp256KeyPair_t mBleDebugKeyPair = {
 188    .public_key.components_8bit.x = {0x20, 0xb0, 0x03, 0xd2, 0xf2, 0x97, 0xbe, 0x2c, 0x5e, 0x2c, 0x83,
 189                                     0xa7, 0xe9, 0xf9, 0xa5, 0xb9, 0xef, 0xf4, 0x91, 0x11, 0xac, 0xf4,
 190                                     0xfd, 0xdb, 0xcc, 0x03, 0x01, 0x48, 0x0e, 0x35, 0x9d, 0xe6},
 191    .public_key.components_8bit.y = {0xdc, 0x80, 0x9c, 0x49, 0x65, 0x2a, 0xeb, 0x6d, 0x63, 0x32, 0x9a,
 192                                     0xbf, 0x5a, 0x52, 0x15, 0x5c, 0x76, 0x63, 0x45, 0xc2, 0x8f, 0xed,
 193                                     0x30, 0x24, 0x74, 0x1c, 0x8e, 0xd0, 0x15, 0x89, 0xd2, 0x8b},
 194    .private_key.raw_8bit         = {0x3f, 0x49, 0xf6, 0xd4, 0xa3, 0xc5, 0x5f, 0x38, 0x74, 0xc9, 0xb3,
 195                                     0xe3, 0xd2, 0x10, 0x3f, 0x50, 0x4a, 0xff, 0x60, 0x7b, 0xeb, 0x40,
 196                                     0xb7, 0x99, 0x58, 0x99, 0xb8, 0xa6, 0xcd, 0x3c, 0x1a, 0xbd}};
 197#endif /* gSecLibUseBleDebugKeys_d */
 198
 199/*! *********************************************************************************
 200*************************************************************************************
 201* Public prototypes
 202*************************************************************************************
 203********************************************************************************** */
 204
 205/*! *********************************************************************************
 206*************************************************************************************
 207* Private prototypes
 208*************************************************************************************
 209********************************************************************************** */
 210static void SHA256_hash_n(const uint8_t *pData, uint32_t nBlk, uint32_t *pHash);
 211static void AES_128_CMAC_Generate_Subkey(const uint8_t *key, uint8_t *K1, uint8_t *K2);
 212static void SecLib_LeftShiftOneBit(uint8_t *input, uint8_t *output);
 213static void SecLib_Xor128(const uint8_t *a, const uint8_t *b, uint8_t *out);
 214
 215static uint8_t SecLib_Padding(const uint8_t *lastb, uint8_t pad_block[AES_BLOCK_SIZE], uint8_t length);
 216static uint8_t SecLib_DePadding(const uint8_t pad_block[AES_BLOCK_SIZE]);
 217
 218#if (defined(FSL_FEATURE_SOC_LTC_COUNT) && (FSL_FEATURE_SOC_LTC_COUNT == 1U))
 219#else
 220static void AES_128_IncrementCounter(uint8_t *ctr);
 221#endif
 222
 223#ifdef FSL_FEATURE_SOC_AES_HW
 224static void AES_128_ECB_Enc_HW(AES_param_t *ECB_p);
 225static void AES_128_ECB_Dec_HW(AES_param_t *ECB_p);
 226static void AES_128_ECB_Block_Enc_HW(AES_param_t *ECBB_p);
 227static void AES_128_ECB_Block_Dec_HW(AES_param_t *ECBB_p);
 228
 229static void AES_128_CTR_Enc_HW(AES_param_t *CTR_p);
 230static void AES_128_CTR_Dec_HW(AES_param_t *CTR_p);
 231
 232static void AES_128_CMAC_HW(AES_param_t *CMAC_p);
 233#endif
 234
 235/*! *********************************************************************************
 236*************************************************************************************
 237* Private functions
 238*************************************************************************************
 239********************************************************************************** */
 240
 241#if gSecLibUseDspExtension_d
 242static bool ECP256_LePointValid(const ecp256Point_t *P)
 243{
 244    ecp256Point_t tmp;
 245    ECP256_PointCopy_and_change_endianness(tmp.raw, P->raw);
 246    return ECP256_PointValid(&tmp);
 247}
 248#else
 249
 250extern bool_t EcP256_IsPointOnCurve(const uint32_t *X, const uint32_t *Y);
 251
 252static bool ECP256_LePointValid(const ecp256Point_t *P)
 253{
 254    return EcP256_IsPointOnCurve((const uint32_t *)&P->components_32bit.x[0],
 255                                 (const uint32_t *)&P->components_32bit.y[0]);
 256}
 257#endif
 258
 259/*! *********************************************************************************
 260*************************************************************************************
 261* Public functions
 262*************************************************************************************
 263********************************************************************************** */
 264
 265secResultType_t SecLibMutexCreate(void)
 266{
 267    secResultType_t st = gSecSuccess_c;
 268#if gSecLibUseMutex_c
 269    static bool seclib_mutex_created = false;
 270    if (!seclib_mutex_created)
 271    {
 272        /*! Initialize the SecLib Mutex here. If not already done by RNG module */
 273        osa_status_t ret = OSA_MutexCreate((osa_mutex_handle_t)mSecLibMutexId);
 274
 275        if (KOSA_StatusSuccess != ret)
 276        {
 277            st = gSecAllocError_c;
 278            assert(false);
 279        }
 280        else
 281        {
 282            seclib_mutex_created = true;
 283        }
 284    }
 285#endif
 286    return st;
 287}
 288
 289secResultType_t SecLibMutexLock(void)
 290{
 291#if gSecLibUseMutex_c
 292    osa_status_t ret = OSA_MutexLock((osa_mutex_handle_t)mSecLibMutexId, osaWaitForever_c);
 293    return (ret == KOSA_StatusSuccess) ? gSecSuccess_c : gSecError_c;
 294#else
 295    return gSecSuccess_c;
 296#endif
 297}
 298
 299secResultType_t SecLibMutexUnlock(void)
 300{
 301#if gSecLibUseMutex_c
 302    osa_status_t ret = OSA_MutexUnlock((osa_mutex_handle_t)mSecLibMutexId);
 303    return (ret == KOSA_StatusSuccess) ? gSecSuccess_c : gSecError_c;
 304#else
 305    return gSecSuccess_c;
 306#endif
 307}
 308
 309/*! *********************************************************************************
 310 * \brief  This function performs initialization of the cryptographic HW acceleration.
 311 *
 312 ********************************************************************************** */
 313void SecLib_Init(void)
 314{
 315    static bool initialized = false;
 316    if (!initialized)
 317    {
 318        initialized = true;
 319#if (defined(FSL_FEATURE_SOC_LTC_COUNT) && (FSL_FEATURE_SOC_LTC_COUNT > 0))
 320        LTC_Init(LTC0);
 321#endif /* FSL_FEATURE_SOC_LTC_COUNT */
 322
 323#if gSecLibUseMutex_c
 324        /*! Initialize the MMCAU AES Context Buffer Mutex here. */
 325        (void)SecLibMutexCreate();
 326#endif
 327    }
 328}
 329
 330/*! *********************************************************************************
 331 * \brief  This function performs initialization of the cryptographic HW acceleration.
 332 *
 333 ********************************************************************************** */
 334void SecLib_ReInit(void)
 335{
 336    /* Nothing to do for Software implementation */
 337}
 338
 339/*! *********************************************************************************
 340 * \brief  This function will allow reinitizialize the cryptographic HW acceleration
 341 * next time we need it, typically after lowpower mode.
 342 *
 343 ********************************************************************************** */
 344void SecLib_DeInit(void)
 345{
 346    /* Nothing to do for Software implementation */
 347}
 348
 349#if !(defined(gSecLibUseDspExtension_d) && (gSecLibUseDspExtension_d > 0))
 350/* In case the SecLib is using dsp extension the API from the Ultrafast library will be used,
 351 * no need to offload elliptic curve multiplication.
 352 * Otherwise the operation takes too long and multiplication must be segmented in multiple steps.
 353 */
 354/*! *********************************************************************************
 355 * \brief  This function performs initialization of the callback used to offload
 356 * elliptic curve multiplication.
 357 *
 358 * \param[in]  pfCallback Pointer to the function used to handle multiplication.
 359 *
 360 ********************************************************************************** */
 361void SecLib_SetExternalMultiplicationCb(secLibCallback_t pfCallback)
 362{
 363    pfSecLibMultCallback = pfCallback;
 364}
 365
 366/*! *********************************************************************************
 367 * \brief  This function performs calls the multiplication Callback.
 368 *
 369 * \param[in]  pMsg Pointer to the data used in multiplication.
 370 *
 371 ********************************************************************************** */
 372bool_t SecLib_ExecMultiplicationCb(computeDhKeyParam_t *pMsg)
 373{
 374    bool_t result = FALSE;
 375
 376    if (pfSecLibMultCallback != NULL)
 377    {
 378        pfSecLibMultCallback(pMsg);
 379        result = TRUE;
 380    }
 381
 382    return result;
 383}
 384#endif
 385/*! *********************************************************************************
 386 * \brief  This function performs AES-128 encryption on a 16-byte block.
 387 *
 388 * \param[in]  pInput Pointer to the location of the 16-byte plain text block.
 389 *
 390 * \param[in]  pKey Pointer to the location of the 128-bit key.
 391 *
 392 * \param[out]  pOutput Pointer to the location to store the 16-byte ciphered output.
 393 *
 394 * \pre All Input/Output pointers must refer to a memory address aligned to 4 bytes!
 395 *
 396 ********************************************************************************** */
 397secResultType_t SecLib_AES_128_Encrypt(const uint8_t *pInput, const uint8_t *pKey, uint8_t *pOutput)
 398{
 399    secResultType_t result = gSecSuccess_c;
 400    do
 401    {
 402        if ((pInput == NULL) || (pKey == NULL) || (pOutput == NULL))
 403        {
 404            result = gSecBadArgument_c;
 405            break;
 406        }
 407
 408#if (defined(FSL_FEATURE_SOC_MMCAU_COUNT) && (FSL_FEATURE_SOC_MMCAU_COUNT > 0))
 409
 410        mmcauAesContext_t *pCtx = &mmcauAesCtx;
 411        uint8_t           *pIn;
 412        uint8_t           *pOut;
 413        SECLIB_MUTEX_LOCK();
 414
 415        /* Check if pKey is 4 bytes aligned */
 416        if ((uint32_t)pKey & 0x00000003u)
 417        {
 418            FLib_MemCpy(pCtx->alignedIn, (uint8_t *)pKey, AES_BLOCK_SIZE);
 419            pIn = pCtx->alignedIn;
 420        }
 421        else
 422        {
 423            pIn = (uint8_t *)pKey;
 424        }
 425
 426        /* Expand Key */
 427        mmcau_aes_set_key(pIn, AES128, pCtx->keyExpansion);
 428
 429        /* Check if pData is 4 bytes aligned */
 430        if ((uint32_t)pInput & 0x00000003u)
 431        {
 432            FLib_MemCpy(pCtx->alignedIn, (uint8_t *)pInput, AES_BLOCK_SIZE);
 433            pIn = pCtx->alignedIn;
 434        }
 435        else
 436        {
 437            pIn = (uint8_t *)pInput;
 438        }
 439        /* Check if pReturnData is 4 bytes aligned */
 440        if ((uint32_t)pOutput & 0x00000003u)
 441        {
 442            pOut = pCtx->alignedOut;
 443        }
 444        else
 445        {
 446            pOut = pOutput;
 447        }
 448
 449        /* Encrypt data */
 450        mmcau_aes_encrypt(pIn, pCtx->keyExpansion, AES128_ROUNDS, pOut);
 451
 452        if (pOut == pCtx->alignedOut)
 453        {
 454            FLib_MemCpy(pOutput, pCtx->alignedOut, AES_BLOCK_SIZE);
 455        }
 456        SECLIB_MUTEX_UNLOCK();
 457#endif /* MMCAU */
 458#if (defined(FSL_FEATURE_SOC_LTC_COUNT) && (FSL_FEATURE_SOC_LTC_COUNT > 0))
 459        SECLIB_MUTEX_LOCK();
 460        (void)LTC_AES_EncryptEcb(LTC0, pInput, pOutput, AES_BLOCK_SIZE, pKey, AES_BLOCK_SIZE);
 461        SECLIB_MUTEX_UNLOCK();
 462#endif
 463#if (defined FSL_FEATURE_SOC_AES_HW && (FSL_FEATURE_SOC_AES_HW > 0))
 464        SECLIB_MUTEX_LOCK();
 465        aes_enc_status_t hw_ase_status_flag;
 466
 467        do
 468        {
 469            while (*(uint8_t *)(0x04000168u + 76u) == true)
 470            {
 471                OSA_TaskYield();
 472            }
 473            __disable_irq();
 474            hw_ase_status_flag = AES_128_Encrypt_HW(pInput, pKey, pOutput);
 475            __enable_irq();
 476        } while (hw_ase_status_flag == HW_AES_Previous_Enc_on_going);
 477        SECLIB_MUTEX_UNLOCK();
 478#else
 479        sw_Aes128(pInput, pKey, 1, pOutput);
 480#endif
 481    } while (false);
 482    return result;
 483}
 484
 485/*! *********************************************************************************
 486 * \brief  This function performs AES-128 decryption on a 16-byte block.
 487 *
 488 * \param[in]  pInput Pointer to the location of the 16-byte ciphered text block.
 489 *
 490 * \param[in]  pKey Pointer to the location of the 128-bit key.
 491 *
 492 * \param[out]  pOutput Pointer to the location to store the 16-byte plain text output.
 493 *
 494 * \pre All Input/Output pointers must refer to a memory address aligned to 4 bytes!
 495 *
 496 ********************************************************************************** */
 497secResultType_t SecLib_AES_128_Decrypt(const uint8_t *pInput, const uint8_t *pKey, uint8_t *pOutput)
 498{
 499    secResultType_t result = gSecSuccess_c;
 500    do
 501    {
 502        if ((pInput == NULL) || (pKey == NULL) || (pOutput == NULL))
 503        {
 504            result = gSecBadArgument_c;
 505            break;
 506        }
 507#if (defined(FSL_FEATURE_SOC_MMCAU_COUNT) && (FSL_FEATURE_SOC_MMCAU_COUNT > 0))
 508        mmcauAesContext_t *pCtx = &mmcauAesCtx;
 509        uint8_t           *pIn;
 510        uint8_t           *pOut;
 511
 512        SECLIB_MUTEX_LOCK();
 513        /* Check if pKey is 4 bytes aligned */
 514        if ((uint32_t)pKey & 0x00000003u)
 515        {
 516            FLib_MemCpy(pCtx->alignedIn, (uint8_t *)pKey, AES_BLOCK_SIZE);
 517            pIn = pCtx->alignedIn;
 518        }
 519        else
 520        {
 521            pIn = (uint8_t *)pKey;
 522        }
 523
 524        /* Expand Key */
 525        mmcau_aes_set_key(pIn, AES128, pCtx->keyExpansion);
 526
 527        /* Check if pData is 4 bytes aligned */
 528        if ((uint32_t)pInput & 0x00000003u)
 529        {
 530            FLib_MemCpy(pCtx->alignedIn, (uint8_t *)pInput, AES_BLOCK_SIZE);
 531            pIn = pCtx->alignedIn;
 532        }
 533        else
 534        {
 535            pIn = (uint8_t *)pInput;
 536        }
 537
 538        /* Check if pReturnData is 4 bytes aligned */
 539        if ((uint32_t)pOutput & 0x00000003u)
 540        {
 541            pOut = pCtx->alignedOut;
 542        }
 543        else
 544        {
 545            pOut = pOutput;
 546        }
 547
 548        /* Decrypt data */
 549        mmcau_aes_decrypt(pIn, pCtx->keyExpansion, AES128_ROUNDS, pOut);
 550
 551        if (pOut == pCtx->alignedOut)
 552        {
 553            FLib_MemCpy(pOutput, pCtx->alignedOut, AES_BLOCK_SIZE);
 554        }
 555        SECLIB_MUTEX_UNLOCK();
 556#elif (defined(FSL_FEATURE_SOC_LTC_COUNT) && (FSL_FEATURE_SOC_LTC_COUNT > 0))
 557        SECLIB_MUTEX_LOCK();
 558        (void)LTC_AES_DecryptEcb(LTC0, pInput, pOutput, AES_BLOCK_SIZE, pKey, AES_BLOCK_SIZE, kLTC_EncryptKey);
 559        SECLIB_MUTEX_UNLOCK();
 560
 561#elif (defined FSL_FEATURE_SOC_AES_HW && (FSL_FEATURE_SOC_AES_HW > 0))
 562
 563        aes_enc_status_t hw_ase_status_flag;
 564        SECLIB_MUTEX_LOCK();
 565        do
 566        {
 567            while (*(uint8_t *)(0x04000168u + 76u) == true)
 568            {
 569                OSA_TaskYield();
 570            }
 571            __disable_irq();
 572            hw_ase_status_flag = AES_128_Decrypt_HW(pInput, pKey, pOutput);
 573            __enable_irq();
 574
 575        } while (hw_ase_status_flag == HW_AES_Previous_Enc_on_going);
 576
 577        SECLIB_MUTEX_UNLOCK();
 578#else
 579        sw_Aes128(pInput, pKey, 0, pOutput);
 580#endif
 581    } while (false);
 582    return result;
 583}
 584
 585/*! *********************************************************************************
 586 * \brief  This function performs AES-128-ECB encryption on a message block.
 587 *
 588 * \param[in]  pInput Pointer to the location of the input message.
 589 *
 590 * \param[in]  inputLen Input message length in bytes.
 591 *
 592 * \param[in]  pKey Pointer to the location of the 128-bit key.
 593 *
 594 * \param[out]  pOutput Pointer to the location to store the ciphered output.
 595 *
 596 * \pre All Input/Output pointers must refer to a memory address aligned to 4 bytes!
 597 *
 598 ********************************************************************************** */
 599secResultType_t SecLib_AES_128_ECB_Encrypt(const uint8_t *pInput,
 600                                           uint32_t       inputLen,
 601                                           const uint8_t *pKey,
 602                                           uint8_t       *pOutput)
 603{
 604    secResultType_t status = gSecError_c; /* CERT EXP33-C (CID 22660163): initialize to avoid uninitialized read */
 605    do
 606    {
 607        if (pInput == NULL || pKey == NULL || pOutput == NULL || inputLen == 0)
 608        {
 609            RAISE_ERROR(status, gSecBadArgument_c);
 610        }
 611        if ((inputLen % AES_128_BLOCK_SIZE) != 0U)
 612        {
 613            RAISE_ERROR(status, gSecBadArgument_c);
 614        }
 615
 616#ifdef FSL_FEATURE_SOC_AES_HW /* HW AES */
 617        AES_param_t pAES;
 618
 619        pAES.CTR_counter = NULL;
 620        pAES.Key         = pKey;
 621        pAES.Len         = inputLen;
 622        pAES.pCipher     = pOutput;
 623        pAES.pInitVector = NULL;
 624        pAES.pPlain      = pInput;
 625        pAES.Blocks      = 0;
 626#if (defined(USE_TASK_FOR_HW_AES) && (USE_TASK_FOR_HW_AES > 0))
 627        AESM_InitType(&AES128ECB_Enc_Id, gAESMGR_ECB_Enc_c);
 628        AESM_SetParam(AES128ECB_Enc_Id, pAES, AES_128_ECB_Enc_HW);
 629        AESM_Start(AES128ECB_Enc_Id);
 630#else
 631        SECLIB_MUTEX_LOCK();
 632        AES_128_ECB_Enc_HW(&pAES);
 633        SECLIB_MUTEX_UNLOCK();
 634#endif /* USE_TASK_FOR_HW_AES */
 635        status = gSecSuccess_c;
 636
 637#else /* SW AES */
 638        uint8_t tempBuffIn[AES_BLOCK_SIZE]  = {0};
 639        uint8_t tempBuffOut[AES_BLOCK_SIZE] = {0};
 640
 641        /* If remaining data bigger than one AES block size */
 642        while (inputLen > AES_BLOCK_SIZE)
 643        {
 644            AES_128_Encrypt(pInput, pKey, pOutput);
 645
 646            pInput += AES_BLOCK_SIZE;
 647            pOutput += AES_BLOCK_SIZE;
 648            /* CERT INT30-C (CID 24723444): inputLen > AES_BLOCK_SIZE is guaranteed by loop condition */
 649            inputLen -= AES_BLOCK_SIZE;
 650        }
 651        /* If remaining data is smaller then one AES block size */
 652        FLib_MemCpy(tempBuffIn, pInput, inputLen);
 653        AES_128_Encrypt(tempBuffIn, pKey, tempBuffOut);
 654        FLib_MemCpy(pOutput, tempBuffOut, inputLen);
 655#endif
 656        status = gSecSuccess_c;
 657
 658    } while (false);
 659
 660    return status;
 661}
 662
 663/*! *********************************************************************************
 664 * \brief  This function performs AES-128-ECB decryption on a message block.
 665 *
 666 * \param[in]  pInput Pointer to the location of the input message.
 667 *
 668 * \param[in]  inputLen Input message length in bytes.
 669 *
 670 * \param[in]  pKey Pointer to the location of the 128-bit key.
 671 *
 672 * \param[out]  pOutput Pointer to the location to store the ciphered output.
 673 *
 674 * \pre All Input/Output pointers must refer to a memory address aligned to 4 bytes!
 675 *
 676 ********************************************************************************** */
 677secResultType_t SecLib_AES_128_ECB_Decrypt(const uint8_t *pInput,
 678                                           uint32_t       inputLen,
 679                                           const uint8_t *pKey,
 680                                           uint8_t       *pOutput)
 681{
 682    secResultType_t status = gSecError_c; /* CERT EXP33-C (CID 51791927): initialize to avoid uninitialized read */
 683    do
 684    {
 685        if (pInput == NULL || pKey == NULL || pOutput == NULL || inputLen == 0)
 686        {
 687            RAISE_ERROR(status, gSecBadArgument_c);
 688        }
 689        if ((inputLen % AES_128_BLOCK_SIZE) != 0U)
 690        {
 691            RAISE_ERROR(status, gSecBadArgument_c);
 692        }
 693#ifdef FSL_FEATURE_SOC_AES_HW
 694
 695        AES_param_t pAES;
 696
 697        pAES.CTR_counter = NULL;
 698        pAES.Key         = pKey;
 699        pAES.Len         = inputLen;
 700        pAES.pCipher     = pInput;
 701        pAES.pInitVector = NULL;
 702        pAES.pPlain      = pOutput;
 703        pAES.Blocks      = 0;
 704#if (defined(USE_TASK_FOR_HW_AES) && (USE_TASK_FOR_HW_AES > 0))
 705        AESM_InitType(&AES128ECB_Dec_Id, gAESMGR_ECB_Dec_c);
 706        AESM_SetParam(AES128ECB_Dec_Id, pAES, AES_128_ECB_Dec_HW);
 707        AESM_Start(AES128ECB_Dec_Id);
 708#else
 709        SECLIB_MUTEX_LOCK();
 710        AES_128_ECB_Dec_HW(&pAES);
 711        SECLIB_MUTEX_UNLOCK();
 712#endif /* USE_TASK_FOR_HW_AES */
 713        status = gSecSuccess_c;
 714
 715#else  /* SW AES */
 716        uint8_t tempBuffIn[AES_BLOCK_SIZE]  = {0};
 717        uint8_t tempBuffOut[AES_BLOCK_SIZE] = {0};
 718
 719        /* If remaining data bigger than one AES block size */
 720        while (inputLen > AES_BLOCK_SIZE)
 721        {
 722            AES_128_Decrypt(pInput, pKey, pOutput);
 723
 724            pInput += AES_BLOCK_SIZE;
 725            pOutput += AES_BLOCK_SIZE;
 726            /* CERT INT30-C (CID 51791928): inputLen > AES_BLOCK_SIZE is guaranteed by loop condition */
 727            inputLen -= AES_BLOCK_SIZE;
 728        }
 729        /* If remaining data is smaller then one AES block size */
 730        FLib_MemCpy(tempBuffIn, pInput, inputLen);
 731        AES_128_Decrypt(tempBuffIn, pKey, tempBuffOut);
 732        FLib_MemCpy(pOutput, tempBuffOut, inputLen);
 733#endif /* FSL_FEATURE_SOC_AES_HW */
 734
 735        status = gSecSuccess_c;
 736
 737    } while (false);
 738    return status;
 739}
 740
 741/*! *********************************************************************************
 742 * \brief  This function performs AES-128-CBC encryption on a message block.
 743 *
 744 *
 745 * \param[in]  pInput Pointer to the location of the input message.
 746 *
 747 * \param[in]  inputLen Input message length in bytes - must be a multiple of AES_BLOCK_SIZE
 748 *
 749 * \param[in, out]  pInitVector Pointer to the location of the 128-bit initialization vector.
 750 *                 On exit the IV content is updated with ciphered output to be injected as next block IV.
 751 *                 Because IV is modifiable, it cannot be RO (const).
 752 *
 753 * \param[in]  pKey Pointer to the location of the 128-bit key.
 754 *
 755 * \param[out]  pOutput Pointer to the location to store the ciphered output.
 756 *
 757 * \return : gSecSuccess_c if no error,
 758 *           gSecBadArgument_c in case of bad arguments,
 759 *           gSecError_c in case of internal error.
 760 *
 761 ********************************************************************************** */
 762secResultType_t SecLib_AES_128_CBC_Encrypt(
 763    const uint8_t *pInput, uint32_t inputLen, uint8_t *pInitVector, const uint8_t *pKey, uint8_t *pOutput)
 764{
 765    secResultType_t ret;
 766
 767    do
 768    {
 769        if ((pInput == NULL) || (pInitVector == NULL) || (pKey == NULL) || (pOutput == NULL) ||
 770            /* If the input length is not a non zero multiple of AES 128 block size,  return */
 771            (inputLen < AES_BLOCK_SIZE) || (AES_PARTIAL_BLOCK_BYTES(inputLen) != 0U))
 772        {
 773            RAISE_ERROR(ret, gSecBadArgument_c);
 774        }
 775
 776        /* LTC is capable of performing CBC operation natively */
 777#if (defined(FSL_FEATURE_SOC_LTC_COUNT) && (FSL_FEATURE_SOC_LTC_COUNT > 0))
 778        status_t st;
 779        SECLIB_MUTEX_LOCK();
 780        st = LTC_AES_EncryptCbc(LTC0, pInput, pOutput, inputLen, pInitVector, pKey, AES_128_KEY_BYTE_LEN);
 781        SECLIB_MUTEX_UNLOCK();
 782        if (st != kStatus_Success)
 783        {
 784            RAISE_ERROR(ret, gSecError_c);
 785        }
 786        /* Update IV with last ciphered block to be injected at next call */
 787        /* Note that inputLen is greater than or equal to AES_BLOCK_SIZE, otherwise would have exited
 788           with gSecBadArgument_c, so difference cannot be negative */
 789        FLib_MemCpy(pInitVector, &pOutput[inputLen - AES_BLOCK_SIZE], AES_BLOCK_SIZE);
 790#else
 791        uint8_t tempBuffIn[AES_BLOCK_SIZE] = {0};
 792
 793        FLib_MemCpy(tempBuffIn, pInitVector, AES_BLOCK_SIZE);
 794        /* If remaining data is bigger than one AES block size */
 795        while (inputLen > 0u)
 796        {
 797            SecLib_XorN(tempBuffIn, pInput, AES_BLOCK_SIZE);
 798            AES_128_Encrypt(tempBuffIn, pKey, pOutput);
 799            FLib_MemCpy(tempBuffIn, pOutput, AES_BLOCK_SIZE);
 800            pInput += AES_BLOCK_SIZE;
 801            pOutput += AES_BLOCK_SIZE;
 802            /* CERT INT30-C (CID 51791930): inputLen is a multiple of AES_BLOCK_SIZE (validated at entry),
 803             * so subtraction cannot wrap */
 804            inputLen -= AES_BLOCK_SIZE;
 805        }
 806        FLib_MemCpy(pInitVector, tempBuffIn, AES_BLOCK_SIZE);
 807#endif
 808        ret = gSecSuccess_c;
 809    } while (false);
 810
 811    return ret;
 812}
 813
 814/*! *********************************************************************************
 815 * \brief  This function performs AES-128-CBC decryption on a message block.
 816 *
 817 * \param[in]  pInput Pointer to the location of the input ciphered message.
 818 *
 819 * \param[in]  inputLen Input message length in bytes - must be a multiple of AES_BLOCK_SIZE.
 820 *
 821 * \param[in, out]  pInitVector Pointer to the location of the 128-bit initialization vector.
 822 *                 On exit the IV content is updated with ciphered output to be injected as next block IV.
 823 *                 Because IV is modifiable, it cannot be RO (const).
 824 *
 825 * \param[in]  pKey Pointer to the location of the 128-bit key.
 826 *
 827 * \param[out]  pOutput Pointer to the location to store the plain text output.
 828 *
 829 * \return : gSecSuccess_c if no error,
 830 *           gSecBadArgument_c in case of bad arguments,
 831 *           gSecError_c in case of internal error.
 832 *
 833 ********************************************************************************** */
 834secResultType_t SecLib_AES_128_CBC_Decrypt(
 835    const uint8_t *pInput, uint32_t inputLen, uint8_t *pInitVector, const uint8_t *pKey, uint8_t *pOutput)
 836{
 837    secResultType_t ret;
 838
 839    do
 840    {
 841        if ((pInput == NULL) || (pInitVector == NULL) || (pKey == NULL) || (pOutput == NULL) ||
 842            /* If the input length is not a non zero multiple of AES 128 block size,  return */
 843            (inputLen < AES_BLOCK_SIZE) || (AES_PARTIAL_BLOCK_BYTES(inputLen) != 0U))
 844        {
 845            RAISE_ERROR(ret, gSecBadArgument_c);
 846        }
 847
 848#if (defined(FSL_FEATURE_SOC_LTC_COUNT) && (FSL_FEATURE_SOC_LTC_COUNT > 0)) && \
 849    (defined(LTC_KEY_REGISTER_READABLE) && (LTC_KEY_REGISTER_READABLE == 1))
 850        status_t st;
 851        SECLIB_MUTEX_LOCK();
 852        st = LTC_AES_DecryptCbc(LTC0, pInput, pOutput, inputLen, pInitVector, pKey, AES_128_KEY_BYTE_LEN,
 853                                kLTC_DecryptKey);
 854        SECLIB_MUTEX_UNLOCK();
 855        if (st != kStatus_Success)
 856        {
 857            RAISE_ERROR(ret, gSecError_c);
 858        }
 859        /* Update IV with last ciphered block to be injected at next call */
 860        /* Note that inputLen is greater than or equal to AES_BLOCK_SIZE, otherwise would have exited
 861           with gSecBadArgument_c, so difference cannot be negative */
 862        FLib_MemCpy(pInitVector, &pInput[inputLen - AES_BLOCK_SIZE], AES_BLOCK_SIZE);
 863#else
 864        uint8_t temp[AES_BLOCK_SIZE] = {0u};
 865
 866        while (inputLen > 0u)
 867        {
 868            FLib_MemCpy(temp, pInput, AES_BLOCK_SIZE);
 869            AES_128_Decrypt(pInput, pKey, pOutput);
 870            SecLib_XorN(pOutput, pInitVector, AES_BLOCK_SIZE);
 871
 872            FLib_MemCpy(pInitVector, temp, AES_BLOCK_SIZE);
 873
 874            pInput += AES_BLOCK_SIZE;
 875            pOutput += AES_BLOCK_SIZE;
 876            /* CERT INT30-C (CID 51791933): inputLen is a multiple of AES_BLOCK_SIZE (validated at entry),
 877             * so subtraction cannot wrap */
 878            inputLen -= AES_BLOCK_SIZE;
 879        }
 880#endif
 881        ret = gSecSuccess_c;
 882
 883    } while (false);
 884
 885    return ret;
 886}
 887
 888/*! *********************************************************************************
 889 * \brief  This function performs AES-128-CBC encryption on a message block after
 890 *         padding until AES block completion.
 891 *
 892 * Padding scheme is ISO/IEC 7816-4: one 80h byte (1 bit), followed by as many 00h as
 893 * required to fill a 128 bit block. Note that if the message length is a multiple of
 894 * AES block size already, another block is appended to the original message.
 895 *
 896 * \param[in]  pInput Pointer to the location of the input message.
 897 *
 898 * \param[in]  inputLen Input message length in bytes - no specific constraint.
 899 *
 900 *  IMPORTANT: User must make sure output buffer has at least inputLen + 16 bytes size.
 901 *  This constraint does not apply to input buffer (any longer).
 902 *
 903 * \param[in, out]  pInitVector Pointer to the location of the 128-bit initialization vector.
 904 *                 On exit the IV content is updated with ciphered output to be injected as next block IV.
 905 *                 Because it is modifiable it cannot be RO (const).
 906 *
 907 * \param[in]  pKey Pointer to the location of the 128-bit key.
 908 *
 909 * \param[out]  pOutput Pointer to the location to store the ciphered output.
 910 *
 911 * \return size of output message after padding is appended.
 912 *
 913 ********************************************************************************** */
 914uint32_t AES_128_CBC_Encrypt_And_Pad(
 915    uint8_t *pInput, uint32_t inputLen, uint8_t *pInitVector, const uint8_t *pKey, uint8_t *pOutput)
 916{
 917    uint32_t roundedLen = 0u;
 918
 919    do
 920    {
 921        uint32_t last_blk_msg_sz;
 922        /* Coverity UNINIT: SecLib_Padding() only writes last_block when its
 923         * length argument is < AES_BLOCK_SIZE; on the (unreachable here) else path it writes
 924         * nothing, so the analyzer cannot prove last_block is fully initialized before it is
 925         * consumed by SecLib_AES_128_CBC_Encrypt() below. Zero-initialize the buffer at
 926         * declaration to make the read well-defined. */
 927        uint8_t last_block[AES_BLOCK_SIZE] = {0}; /* Buffer used to generate last block containing padding */
 928        /* compute new length */
 929        roundedLen      = AES_WHOLE_BLOCK_BYTES(inputLen);
 930        last_blk_msg_sz = AES_PARTIAL_BLOCK_BYTES(inputLen);
 931        /* Perform AES-CBC operation on whole AES blocks */
 932        if (SecLib_AES_128_CBC_Encrypt(pInput, roundedLen, pInitVector, pKey, pOutput) != gSecSuccess_c)
 933        {
 934            roundedLen = 0u;
 935            break;
 936        }
 937        pInput += roundedLen;
 938        pOutput += roundedLen;
 939        /* There may be a remainder modulus 16 : copy it to last_block byte array (on stack).
 940         * then add padding so as to fill the last_block array. The amount of padding is 16 bytes if already
 941         * AES block aligned, or any size [0..15] to pad till AES block is full.
 942         */
 943        (void)SecLib_Padding(pInput, last_block, last_blk_msg_sz);
 944        if (SecLib_AES_128_CBC_Encrypt(last_block, AES_BLOCK_SIZE, pInitVector, pKey, pOutput) != gSecSuccess_c)
 945        {
 946            roundedLen = 0u;
 947            break;
 948        }
 949        roundedLen += AES_BLOCK_SIZE;
 950    } while (false);
 951
 952    return roundedLen;
 953}
 954
 955/*! *********************************************************************************
 956 * \brief  This function performs AES_128_CBC_Decrypt_And_Depad decryption on a message.
 957 *
 958 * \param[in]  pInput Pointer to the location of the input ciphered message.
 959 *
 960 * \param[in]  inputLen Input message length in bytes must be a multiple of AES block size
 961 *
 962 * \param[in]  pInitVector Pointer to the location of the 128-bit initialization vector.
 963 *
 964 * \param[in]  pKey Pointer to the location of the 128-bit key.
 965 *
 966 * \param[out] pOutput Pointer to the location to store the plain text output.
 967 *
 968 * \return size of output buffer (after depadding the 0x80 [0x00 .. ]. padding sequence)
 969 *
 970 ********************************************************************************** */
 971uint32_t AES_128_CBC_Decrypt_And_Depad(
 972    const uint8_t *pInput, uint32_t inputLen, uint8_t *pInitVector, const uint8_t *pKey, uint8_t *pOutput)
 973{
 974    uint32_t newLen = 0uL;
 975
 976    if (inputLen > 0u)
 977    {
 978        if (SecLib_AES_128_CBC_Decrypt(pInput, inputLen, pInitVector, pKey, pOutput) == gSecSuccess_c)
 979        {
 980            uint8_t padding_len;
 981            /* If we are here inputLen is a non 0 multiple of AES_BLOCK_SIZE, otherwise AES_128_CBC_Decrypt would have
 982            returned an error.
 983            Yet the test below is to prevent a false MISRA error detection.
 984            */
 985            if ((inputLen >= AES_BLOCK_SIZE) && (AES_PARTIAL_BLOCK_BYTES(inputLen) == 0u))
 986            {
 987                uint8_t *p_last_block = &pOutput[inputLen - AES_BLOCK_SIZE];
 988                padding_len           = SecLib_DePadding(p_last_block);
 989                if ((padding_len > 0u) && (padding_len <= AES_BLOCK_SIZE))
 990                {
 991                    /* Safe: inputLen is a multiple of AES_BLOCK_SIZE and >= AES_BLOCK_SIZE,
 992                    padding_len is in [1..AES_BLOCK_SIZE], so subtraction cannot underflow */
 993                    newLen = inputLen - (uint32_t)padding_len;
 994                }
 995            }
 996        }
 997    }
 998    /* coverity [return_overflow:FALSE] see above */
 999    return newLen;
1000}
1001
1002/*! *********************************************************************************
1003 * \brief  This function performs AES-128-CTR encryption on a message block.
1004 *
1005 * \param[in]  pInput Pointer to the location of the input message.
1006 *
1007 * \param[in]  inputLen Input message length in bytes.
1008 *
1009 * \param[in]  pCounter Pointer to the location of the 128-bit counter.
1010 *
1011 * \param[in]  pKey Pointer to the location of the 128-bit key.
1012 *
1013 * \param[out]  pOutput Pointer to the location to store the ciphered output.
1014 *
1015 ********************************************************************************** */
1016secResultType_t SecLib_AES_128_CTR(
1017    const uint8_t *pInput, uint32_t inputLen, uint8_t *pCounter, const uint8_t *pKey, uint8_t *pOutput)
1018{
1019    secResultType_t status = gSecError_c;
1020    do
1021    {
1022        if ((pInput == NULL) || (pOutput == NULL) || (pKey == NULL) || (pCounter == NULL) || (inputLen == 0UL))
1023        {
1024            RAISE_ERROR(status, gSecBadArgument_c);
1025        }
1026#ifdef FSL_FEATURE_SOC_AES_HW /* HW AES */
1027        AES_param_t pAES;
1028
1029        pAES.CTR_counter = pCounter;
1030        pAES.Key         = pKey;
1031        pAES.Len         = inputLen;
1032        pAES.pCipher     = pOutput;
1033        pAES.pInitVector = NULL;
1034        pAES.pPlain      = pInput;
1035        pAES.Blocks      = 0;
1036#if (defined(USE_TASK_FOR_HW_AES) && (USE_TASK_FOR_HW_AES > 0))
1037        AESM_InitType(&AES128CTR_Enc_Id, gAESMGR_CTR_Enc_c);
1038        AESM_SetParam(AES128CTR_Enc_Id, pAES, AES_128_CTR_Enc_HW);
1039        AESM_Start(AES128CTR_Enc_Id);
1040#else
1041        SECLIB_MUTEX_LOCK();
1042        AES_128_CTR_Enc_HW(&pAES);
1043        SECLIB_MUTEX_UNLOCK();
1044#endif /* USE_TASK_FOR_HW_AES */
1045        status = gSecSuccess_c;
1046#else  /*FSL_FEATURE_SOC_AES_HW */
1047
1048#if (defined(FSL_FEATURE_SOC_LTC_COUNT) && (FSL_FEATURE_SOC_LTC_COUNT > 0))
1049        status_t st;
1050        SECLIB_MUTEX_LOCK();
1051        st = LTC_AES_EncryptCtr(LTC0, pInput, pOutput, inputLen, pCounter, pKey, AES_BLOCK_SIZE, (void *)NULL,
1052                                (void *)NULL);
1053        SECLIB_MUTEX_UNLOCK();
1054        if (st != kStatus_Success)
1055        {
1056            RAISE_ERROR(ret, gSecError_c);
1057        }
1058#else
1059        uint8_t tempBuffIn[AES_BLOCK_SIZE] = {0};
1060        uint8_t encrCtr[AES_BLOCK_SIZE]    = {0};
1061
1062        /* If remaining data bigger than one AES block size */
1063        while (inputLen > AES_BLOCK_SIZE)
1064        {
1065            FLib_MemCpy(tempBuffIn, pInput, AES_BLOCK_SIZE);
1066            AES_128_Encrypt(pCounter, pKey, encrCtr);
1067            SecLib_XorN(tempBuffIn, encrCtr, AES_BLOCK_SIZE);
1068            FLib_MemCpy(pOutput, tempBuffIn, AES_BLOCK_SIZE);
1069            pInput += AES_BLOCK_SIZE;
1070            pOutput += AES_BLOCK_SIZE;
1071            inputLen -= AES_BLOCK_SIZE;
1072            AES_128_IncrementCounter(pCounter);
1073        }
1074        /* If remaining data is smaller then one AES block size  */
1075        FLib_MemCpy(tempBuffIn, pInput, inputLen);
1076        AES_128_Encrypt(pCounter, pKey, encrCtr);
1077        SecLib_XorN(tempBuffIn, encrCtr, AES_BLOCK_SIZE);
1078        FLib_MemCpy(pOutput, tempBuffIn, inputLen);
1079        AES_128_IncrementCounter(pCounter);
1080#endif /* FSL_FEATURE_SOC_LTC_COUNT */
1081#endif /* FSL_FEATURE_SOC_AES_HW */
1082        status = gSecSuccess_c;
1083    } while (false);
1084
1085    return status;
1086}
1087
1088/*! *********************************************************************************
1089 * \brief  This function performs AES-128-CTR decryption on a message block.
1090 *
1091 * \param[in]  pInput Pointer to the location of the input message.
1092 *
1093 * \param[in]  inputLen Input message length in bytes.
1094 *
1095 * \param[in]  pCounter Pointer to the location of the 128-bit counter.
1096 *
1097 * \param[in]  pKey Pointer to the location of the 128-bit key.
1098 *
1099 * \param[out]  pOutput Pointer to the location to store the ciphered output.
1100 *
1101 ********************************************************************************** */
1102#ifdef FSL_FEATURE_SOC_AES_HW
1103void AES_128_CTR_Decrypt(
1104    const uint8_t *pInput, uint32_t inputLen, uint8_t *pCounter, const uint8_t *pKey, uint8_t *pOutput)
1105{
1106    AES_param_t pAES;
1107
1108    pAES.CTR_counter = pCounter;
1109    pAES.Key         = pKey;
1110    pAES.Len         = inputLen;
1111    pAES.pCipher     = pInput;
1112    pAES.pInitVector = NULL;
1113    pAES.pPlain      = pOutput;
1114    pAES.Blocks      = 0;
1115#if (defined(USE_TASK_FOR_HW_AES) && (USE_TASK_FOR_HW_AES > 0))
1116    AESM_InitType(&AES128CTR_Dec_Id, gAESMGR_CTR_Dec_c);
1117    AESM_SetParam(AES128CTR_Dec_Id, pAES, AES_128_CTR_Dec_HW);
1118    AESM_Start(AES128CTR_Dec_Id);
1119#else
1120    SECLIB_MUTEX_LOCK();
1121    AES_128_CTR_Dec_HW(&pAES);
1122    SECLIB_MUTEX_UNLOCK();
1123#endif /* USE_TASK_FOR_HW_AES */
1124}
1125#endif /* FSL_FEATURE_SOC_AES_HW */
1126
1127/*! *********************************************************************************
1128 * \brief  This function performs AES-128-CMAC on a message block.
1129 *
1130 * \param[in]  pInput Pointer to the location of the input message.
1131 *
1132 * \param[in]  inputLen Length of the input message in bytes. The input data must be provided MSB first.
1133 *
1134 * \param[in]  pKey Pointer to the location of the 128-bit key. The key must be provided MSB first.
1135 *
1136 * \param[out]  pOutput Pointer to the location to store the 16-byte authentication code. The code will be generated
1137 *MSB
1138 *first.
1139 *
1140 * \remarks This is public open source code! Terms of use must be checked before use!
1141 *
1142 ********************************************************************************** */
1143secResultType_t SecLib_AES_128_CMAC(const uint8_t *pInput,
1144                                    const uint32_t inputLen,
1145                                    const uint8_t *pKey,
1146                                    uint8_t       *pOutput)
1147{
1148    secResultType_t status;
1149    do
1150    {
1151        if ((pInput == 0) || (pKey == NULL) || (pOutput == NULL))
1152        {
1153            RAISE_ERROR(status, gSecBadArgument_c);
1154        }
1155#ifdef FSL_FEATURE_SOC_AES_HW /* HW AES */
1156        AES_param_t pAES;
1157
1158        pAES.CTR_counter = NULL;
1159        pAES.Key         = pKey;
1160        pAES.Len         = inputLen;
1161        pAES.pCipher     = pOutput;
1162        pAES.pInitVector = NULL;
1163        pAES.pPlain      = pInput;
1164        pAES.Blocks      = 0;
1165#if (defined(USE_TASK_FOR_HW_AES) && (USE_TASK_FOR_HW_AES > 0))
1166        AESM_InitType(&AES128CMAC_Id, gAESMGR_CMAC_Enc_c);
1167        AESM_SetParam(AES128CMAC_Id, pAES, AES_128_CMAC_HW);
1168        AESM_Start(AES128CMAC_Id);
1169#else
1170        SECLIB_MUTEX_LOCK();
1171        AES_128_CMAC_HW(&pAES);
1172        SECLIB_MUTEX_UNLOCK();
1173#endif /* USE_TASK_FOR_HW_AES */
1174
1175#else  /* SW AES */
1176
1177        uint8_t X[16];
1178        uint8_t Y[16];
1179        uint8_t M_last[16] = {0};
1180        uint8_t padded[16] = {0};
1181
1182        uint8_t K1[16] = {0};
1183        uint8_t K2[16] = {0};
1184
1185        uint32_t n;
1186        uint32_t i;
1187        uint8_t  flag;
1188        uint32_t residual_len;
1189
1190        AES_128_CMAC_Generate_Subkey(pKey, K1, K2);
1191
1192        n            = AES_TOTAL_BLOCK_NB(inputLen); /* n is number of rounds */
1193        residual_len = AES_PARTIAL_BLOCK_BYTES(inputLen);
1194
1195        if (n == 0u)
1196        {
1197            n    = 1u;
1198            flag = 0u;
1199        }
1200        else
1201        {
1202            if (residual_len == 0u)
1203            { /* last block is a complete block */
1204                flag = 1u;
1205            }
1206            else
1207            { /* last block is not complete block */
1208                flag = 0u;
1209            }
1210        }
1211
1212        /* Process the last block  - the last part the MSB first input data */
1213        if (flag > 0u)
1214        { /* last block is complete block */
1215            SecLib_Xor128(&pInput[AES_BLOCK_SIZE * (n - 1u)], K1, M_last);
1216        }
1217        else
1218        {
1219            (void)SecLib_Padding(&pInput[AES_BLOCK_SIZE * (n - 1u)], padded, residual_len);
1220            SecLib_Xor128(padded, K2, M_last);
1221        }
1222
1223        for (i = 0u; i < 16u; i++)
1224        {
1225            X[i] = 0u;
1226        }
1227
1228        for (i = 0u; i < (n - 1u); i++)
1229        {
1230            SecLib_Xor128(X, &pInput[AES_BLOCK_SIZE * i], Y); /* Y := Mi (+) X  */
1231            AES_128_Encrypt(Y, pKey, X);                      /* X := AES-128(KEY, Y) */
1232        }
1233
1234        SecLib_Xor128(X, M_last, Y);
1235        AES_128_Encrypt(Y, pKey, X);
1236
1237        for (i = 0u; i < 16u; i++)
1238        {
1239            pOutput[i] = X[i];
1240        }
1241#endif /* FSL_FEATURE_SOC_AES_HW */
1242        status = gSecSuccess_c;
1243    } while (false);
1244
1245    return status;
1246}
1247
1248/*! *********************************************************************************
1249 * \brief  This function performs AES-128-CMAC on a message block accepting input data
1250 *         which is in LSB first format and computing the authentication code starting from the end of the data.
1251 *
1252 * \param[in]  pInput Pointer to the location of the input message.
1253 *
1254 * \param[in]  inputLen Length of the input message in bytes. The input data must be provided LSB first.
1255 *
1256 * \param[in]  pKey Pointer to the location of the 128-bit key. The key must be provided MSB first.
1257 *
1258 * \param[out]  pOutput Pointer to the location to store the 16-byte authentication code. The code will be generated
1259 *MSB
1260 *first.
1261 *
1262 ********************************************************************************** */
1263secResultType_t SecLib_AES_128_CMAC_LsbFirstInput(const uint8_t *pInput,
1264                                                  uint32_t       inputLen,
1265                                                  const uint8_t *pKey,
1266                                                  uint8_t       *pOutput)
1267{
1268    secResultType_t status;
1269
1270    do
1271    {
1272        if ((pInput == NULL) || (pKey == NULL) || (pOutput == NULL))
1273        {
1274            RAISE_ERROR(status, gSecBadArgument_c);
1275        }
1276        uint8_t X[16];
1277        uint8_t Y[16];
1278        uint8_t M_last[16]        = {0};
1279        uint8_t padded[16]        = {0};
1280        uint8_t reversedBlock[16] = {0};
1281
1282        uint8_t K1[16] = {0};
1283        uint8_t K2[16] = {0};
1284
1285        uint32_t n;
1286        uint32_t i;
1287        uint8_t  flag;
1288        uint32_t residual_len;
1289
1290        AES_128_CMAC_Generate_Subkey(pKey, K1, K2);
1291
1292        n = AES_TOTAL_BLOCK_NB(inputLen); /* n is number of rounds i.e. number of 16 byte chunks rounded up */
1293        residual_len = AES_PARTIAL_BLOCK_BYTES(inputLen);
1294
1295        if (n == 0u)
1296        {
1297            n    = 1u;
1298            flag = 0u;
1299        }
1300        else
1301        {
1302            if (residual_len == 0u) /* last block is a complete block */
1303            {
1304                flag = 1u;
1305            }
1306            else /* last block is not complete block */
1307            {
1308                flag = 0u;
1309            }
1310        }
1311
1312        /* Process the last block  - the first part the LSB first input data */
1313        if (flag > 0u) /* last block is complete block */
1314        {
1315            FLib_MemCpyReverseOrder(reversedBlock, &pInput[0], AES_BLOCK_SIZE);
1316            SecLib_Xor128(reversedBlock, K1, M_last);
1317        }
1318        else
1319        {
1320            FLib_MemCpyReverseOrder(reversedBlock, &pInput[0], residual_len);
1321            (void)SecLib_Padding(reversedBlock, padded, residual_len);
1322            SecLib_Xor128(padded, K2, M_last);
1323        }
1324
1325        for (i = 0u; i < 16u; i++)
1326        {
1327            X[i] = 0u;
1328        }
1329
1330        for (i = 0u; i < (n - 1u); i++)
1331        {
1332            FLib_MemCpyReverseOrder(reversedBlock, &pInput[inputLen - AES_BLOCK_SIZE * (i + 1u)], AES_BLOCK_SIZE);
1333            SecLib_Xor128(X, reversedBlock, Y); /* Y := Mi (+) X  */
1334            AES_128_Encrypt(Y, pKey, X);        /* X := AES-128(KEY, Y) */
1335        }
1336
1337        SecLib_Xor128(X, M_last, Y);
1338        AES_128_Encrypt(Y, pKey, X);
1339
1340        for (i = 0u; i < 16u; i++)
1341        {
1342            pOutput[i] = X[i];
1343        }
1344        status = gSecSuccess_c;
1345    } while (false);
1346    return status;
1347}
1348
1349/*! *********************************************************************************
1350 * \brief  This function performs AES 128 CMAC Pseudo-Random Function (AES-CMAC-PRF-128),
1351 *         according to rfc4615, on a message block.
1352 *
1353 * \details The AES-CMAC-PRF-128 algorithm behaves similar to teh AES CMAC 128 algorithm
1354 *          but removes 128 bit key size restriction.
1355 *
1356 * \param[in]  pInput Pointer to the location of the input message.
1357 *
1358 * \param[in]  inputLen Length of the input message in bytes.
1359 *
1360 * \param[in]  pVarKey Pointer to the location of the variable length key.
1361 *
1362 * \param[in]  varKeyLen Length of the input key in bytes
1363 *
1364 * \param[out]  pOutput Pointer to the location to store the 16-byte pseudo random variable.
1365 *
1366 ********************************************************************************** */
1367secResultType_t SecLib_AES_CMAC_PRF_128(
1368    const uint8_t *pInput, uint32_t inputLen, const uint8_t *pVarKey, uint32_t varKeyLen, uint8_t *pOutput)
1369{
1370    secResultType_t status;
1371    do
1372    {
1373        uint8_t        K[16];              /*!< Temporary key location to be used if the key length is not 16 bytes. */
1374        const uint8_t *pCmacKey = pVarKey; /*!<  Pointer to the key used by the CMAC operation which generates the
1375                                            *    output. */
1376        if ((pInput == NULL) || (pVarKey == NULL) || (pOutput == NULL))
1377        {
1378            RAISE_ERROR(status, gSecBadArgument_c);
1379        }
1380
1381        if (varKeyLen == 0u)
1382        {
1383            /* NIST SP 800‑38B and RFC 4493 allow empty message input.
1384             * RFC 4615 could mathematically accepts variable-length to be 0, nonetheless it is strongly discouraged
1385             * and ought to be rejected because of the lack of entropy. Using it could let the PRF be predictable
1386             * */
1387            RAISE_ERROR(status, gSecBadArgument_c);
1388        }
1389
1390        if (varKeyLen != 16u)
1391        {
1392            uint8_t K0[16] = {0x00u, 0x00,  0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u,
1393                              0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u};
1394            /*! Perform AES 128 CMAC on the variable key if it has a length which
1395             *  is different from 16 bytes using a 128 bit key with all zeroes and
1396             *  set the CMAC key to point to the result. */
1397
1398            status = SecLib_AES_128_CMAC(pVarKey, varKeyLen, K0, K);
1399            if (status != gSecSuccess_c)
1400            {
1401                break;
1402            }
1403            pCmacKey = K;
1404        }
1405
1406        /*! Perform the CMAC operation which generates the output using the local
1407         *  key pointer whcih will be set to the initial key or the generated one. */
1408        status = SecLib_AES_128_CMAC(pInput, inputLen, pCmacKey, pOutput);
1409    } while (false);
1410    return status;
1411}
1412
1413/*! *********************************************************************************
1414 * \brief  This function performs AES-128-CCM on a message block.
1415 *
1416 * \param[in]  pInput       Pointer to the location of the input message (plaintext or ciphertext).
1417 *
1418 * \param[in]  inputLen     Length of the input plaintext in bytes when encrypting.
1419 *                          Length of the input ciphertext without the MAC length when decrypting.
1420 *
1421 * \param[in]  pAuthData    Pointer to the additional authentication data.
1422 *
1423 * \param[in]  authDataLen  Length of additional authentication data.
1424 *
1425 * \param[in]  pNonce       Pointer to the Nonce.
1426 *
1427 * \param[in]  nonceSize    The size of the nonce (7-13).
1428 *
1429 * \param[in]  pKey         Pointer to the location of the 128-bit key.
1430 *
1431 * \param[out]  pOutput     Pointer to the location to store the plaintext data when decrypting.
1432 *                          Pointer to the location to store the ciphertext data when encrypting.
1433 *
1434 * \param[out]  pCbcMac     Pointer to the location to store the Message Authentication Code (MAC) when encrypting.
1435 *                          Pointer to the location where the received MAC can be found when decrypting.
1436 *
1437 * \param[out]  macSize     The size of the MAC.
1438 *
1439 * \param[out]  flags       Select encrypt/decrypt operations (gSecLib_CCM_Encrypt_c, gSecLib_CCM_Decrypt_c)
1440 *
1441 * \return 0 if encryption/decryption was successful; otherwise, error code for failed encryption/decryption
1442 *
1443 * \remarks At decryption, MIC fail is also signaled by returning a non-zero value.
1444 *
1445 ********************************************************************************** */
1446secResultType_t SecLib_AES_128_CCM(const uint8_t *pInput,
1447                                   uint16_t       inputLen,
1448                                   const uint8_t *pAuthData,
1449                                   uint16_t       authDataLen,
1450                                   const uint8_t *pNonce,
1451                                   uint8_t        nonceSize,
1452                                   const uint8_t *pKey,
1453                                   uint8_t       *pOutput,
1454                                   uint8_t       *pCbcMac,
1455                                   uint8_t        macSize,
1456                                   uint32_t       flags)
1457{
1458    secResultType_t st = gSecError_c;
1459    uint8_t         status;
1460
1461    if ((pInput == NULL) || (pAuthData == NULL) || (pNonce == NULL) || (pOutput == NULL) || (pKey == NULL) ||
1462        (pCbcMac == NULL))
1463    {
1464        return gSecBadArgument_c;
1465    }
1466
1467#if (defined(FSL_FEATURE_SOC_LTC_COUNT) && (FSL_FEATURE_SOC_LTC_COUNT == 1))
1468    SECLIB_MUTEX_LOCK();
1469    if ((flags & gSecLib_CCM_Decrypt_c) == gSecLib_CCM_Decrypt_c)
1470    {
1471        status = (uint8_t)(LTC_AES_DecryptTagCcm(LTC0, pInput, pOutput, (uint32_t)inputLen, pNonce, (uint32_t)nonceSize,
1472                                                 pAuthData, (uint32_t)authDataLen, pKey, AES_BLOCK_SIZE, pCbcMac,
1473                                                 (uint32_t)macSize));
1474    }
1475    else
1476    {
1477        status = (uint8_t)(LTC_AES_EncryptTagCcm(LTC0, pInput, pOutput, (uint32_t)inputLen, pNonce, (uint32_t)nonceSize,
1478                                                 pAuthData, (uint32_t)authDataLen, pKey, AES_BLOCK_SIZE, pCbcMac,
1479                                                 (uint32_t)macSize));
1480    }
1481    SECLIB_MUTEX_UNLOCK();
1482
1483#else
1484    status = sw_AES128_CCM(pInput, inputLen, pAuthData, authDataLen, pNonce, nonceSize, pKey, pOutput, pCbcMac, macSize,
1485                           flags);
1486#endif
1487    if (status == 0u)
1488    {
1489        st = gSecSuccess_c;
1490    }
1491
1492    return st;
1493}
1494
1495/*! *********************************************************************************
1496 * \brief  This function calculates XOR of individual byte pairs in two uint8_t arrays.
1497 *         pDst[i] := pDst[i] ^ pSrc[i] for i=0 to n-1
1498 *
1499 * \param[in, out]  pDst First byte array operand for XOR and destination byte array
1500 *
1501 * \param[in]  pSrc Second byte array operand for XOR
1502 *
1503 * \param[in]  n  Length of the byte arrays which will be XORed
1504 *
1505 ********************************************************************************** */
1506void SecLib_XorN(uint8_t *pDst, const uint8_t *pSrc, uint8_t n)
1507{
1508    while (n > 0u)
1509    {
1510        *pDst = *pDst ^ *pSrc;
1511        pDst  = pDst + 1u;
1512        pSrc  = pSrc + 1u;
1513        n--;
1514    }
1515}
1516
1517/*! *********************************************************************************
1518 * \brief  This function allocates a memory buffer for a SHA256 context structure
1519 *
1520 * \return    Address of the SHA256 context buffer
1521 *            Deallocate using SHA256_FreeCtx()
1522 *
1523 ********************************************************************************** */
1524void *SecLib_SHA256_AllocCtx(void)
1525{
1526    void *sha256Ctx = MEM_BufferAlloc(sizeof(sha256Context_t));
1527
1528    return sha256Ctx;
1529}
1530
1531/*! *********************************************************************************
1532* \brief  This function deallocates the memory buffer for the SHA256 context structure
1533*
1534
1535* \param [in]    pContext    Address of the SHA256 context buffer
1536*
1537********************************************************************************** */
1538void SecLib_SHA256_FreeCtx(void *pContext)
1539{
1540    (void)MEM_BufferFree(pContext);
1541}
1542
1543/*! *********************************************************************************
1544 * \brief  This function clones SHA256 context.
1545 *         Make sure the size of the allocated destination context buffer is appropriate.
1546 *
1547 * \param [in]    pDestCtx    Address of the destination SHA256 context
1548 * \param [in]    pSourceCtx  Address of the source SHA256 context
1549 *
1550 ********************************************************************************** */
1551void SecLib_SHA256_CloneCtx(void *pDestCtx, void *pSourceCtx)
1552{
1553    FLib_MemCpy(pDestCtx, pSourceCtx, sizeof(sha256Context_t));
1554}
1555
1556/*! *********************************************************************************
1557 * \brief  This function initializes the SHA256 context data
1558 *
1559 * \param [in]    pContext    Pointer to the SHA256 context data
1560 *                            Allocated using SHA256_AllocCtx()
1561 *
1562 ********************************************************************************** */
1563secResultType_t SecLib_SHA256_Init(void *pContext)
1564{
1565    secResultType_t  st      = gSecBadArgument_c;
1566    sha256Context_t *context = (sha256Context_t *)pContext;
1567
1568    if (context != NULL)
1569    {
1570        context->bytes      = 0u;
1571        context->totalBytes = 0u;
1572#if (defined(FSL_FEATURE_SOC_MMCAU_COUNT) && (FSL_FEATURE_SOC_MMCAU_COUNT > 0))
1573        SECLIB_MUTEX_LOCK();
1574        (void)mmcau_sha256_initialize_output((const unsigned int *)context->hash);
1575        SECLIB_MUTEX_UNLOCK();
1576
1577#else
1578        sw_sha256_initialize_output(context->hash);
1579#endif
1580        st = gSecSuccess_c;
1581    }
1582    return st;
1583}
1584
1585/*! *********************************************************************************
1586 * \brief  This function performs SHA256 on multiple bytes and updates the context data
1587 *
1588 * \param [in]    pContext    Pointer to the SHA256 context data
1589 *                            Allocated using SHA256_AllocCtx()
1590 * \param [in]    pData       Pointer to the input data
1591 * \param [in]    numBytes    Number of bytes to hash
1592 * \return        0  if operation successful
1593 *                -1 if context is NULL
1594 *                -2 if bytes in context greater than 64
1595 *                -3 if numBytes is about to let number of accumulated bytes of context exceeds 2^29.
1596 *
1597 ********************************************************************************** */
1598secResultType_t SecLib_SHA256_HashUpdate(void *pContext, const uint8_t *pData, uint32_t numBytes)
1599{
1600    uint32_t         blocks;
1601    sha256Context_t *context = (sha256Context_t *)pContext;
1602    secResultType_t  st;
1603    /* The Hash Finish operation needs space to convert in number of bits so must
1604     * be smaller than 2^29 */
1605    do
1606    {
1607        uint8_t  copyBytes;
1608        uint32_t whole_sha256_blk_sz;
1609        if ((context == NULL) || (pData == NULL))
1610        {
1611            RAISE_ERROR(st, gSecBadArgument_c);
1612        }
1613        assert(context->bytes < SHA256_BLOCK_SIZE);
1614        if (MAX_SHA256_TOTAL_BYTES - context->totalBytes < numBytes)
1615        {
1616            RAISE_ERROR(st, gSecError_c);
1617        }
1618        /* update total byte count */
1619        context->totalBytes += numBytes;
1620
1621        copyBytes = SHA256_BLOCK_SIZE - context->bytes;
1622
1623        if (numBytes < (uint32_t)copyBytes)
1624        {
1625            /* store bytes for later processing, a full block will not be accumulated yet */
1626            FLib_MemCpy(&context->buffer[context->bytes], pData, numBytes);
1627            context->bytes += (uint8_t)(numBytes & 0xffu);
1628        }
1629        else
1630        {
1631            /* Check for bytes leftover from previous update */
1632            if (context->bytes > 0u)
1633            {
1634                FLib_MemCpy(&context->buffer[context->bytes], pData, copyBytes);
1635                SHA256_hash_n(context->buffer, 1u, context->hash);
1636                pData += copyBytes;
1637                /* numBytes necessarily greater or equal to copyBytes in this branch */
1638                numBytes -= (uint32_t)copyBytes;
1639                context->bytes = 0u;
1640            }
1641            /* Hash 64 bytes blocks */
1642            /* blocks is the number of 64-byte whole blocks.
1643             * Since numBytes is enforced to be smaller than MAX_SHA256_TOTAL_BYTES (2^29),
1644             * blocks is smaller than 2^24 */
1645            blocks = (numBytes / SHA256_BLOCK_SIZE);
1646            /* CERT INT30-C whole_sha256_blk_sz calculation cannot overflow */
1647            whole_sha256_blk_sz = blocks * SHA256_BLOCK_SIZE;
1648
1649            SHA256_hash_n(pData, blocks, context->hash);
1650            /* CERT INT30-C numBytes calculation cannot wrap */
1651            numBytes -= whole_sha256_blk_sz;
1652            pData += whole_sha256_blk_sz; /* Check if we have at least 1 SHA256 block */
1653                                          /* Check for remaining bytes */
1654            if (numBytes > 0u)
1655            {
1656                context->bytes = (uint8_t)(numBytes & (uint32_t)(SHA256_BLOCK_SIZE - 1));
1657                FLib_MemCpy(context->buffer, pData, numBytes);
1658            }
1659        }
1660        st = gSecSuccess_c;
1661    } while (0);
1662
1663    return st;
1664}
1665
1666/*! *********************************************************************************
1667 * \brief  This function finalizes the SHA256 hash computation and clears the context data.
1668 *         The final hash value is stored at the provided output location.
1669 *
1670 * \param [in]       pContext    Pointer to the SHA256 context data
1671 *                               Allocated using SHA256_AllocCtx()
1672 * \param [out]      pOutput     Pointer to the output location
1673 *
1674 ********************************************************************************** */
1675secResultType_t SecLib_SHA256_HashFinish(void *pContext, uint8_t *pOutput)
1676{
1677    secResultType_t st;
1678
1679    sha256Context_t *context = (sha256Context_t *)pContext;
1680    /* The Hash Finish operation needs space to convert in number of bits so must
1681     * be smaller than 2^29 */
1682    do
1683    {
1684        uint32_t numBytes;
1685
1686        if ((context == NULL) || (pOutput == NULL))
1687        {
1688            RAISE_ERROR(st, gSecBadArgument_c);
1689        }
1690
1691        numBytes = context->bytes;
1692        if ((numBytes >= SHA256_BLOCK_SIZE) || (MAX_SHA256_TOTAL_BYTES - context->totalBytes < numBytes))
1693        {
1694            assert(false);
1695            RAISE_ERROR(st, gSecError_c);
1696        }
1697
1698        /* Add 1 bit (a 0x80 byte) after the message to begin padding */
1699        context->buffer[numBytes++] = 0x80u;
1700        /* Check for space to fit an 8 byte length field plus the 0x80 */
1701        if (numBytes >= (SHA256_BLOCK_SIZE - 7u))
1702        {
1703            /* Fill the rest of the chunk with zeros */
1704            FLib_MemSet(&context->buffer[numBytes], 0u, SHA256_BLOCK_SIZE - numBytes);
1705            SHA256_hash_n(context->buffer, 1u, context->hash);
1706            numBytes = 0u;
1707        }
1708        /* Fill the rest of the chunk with zeros */
1709        FLib_MemSet(&context->buffer[numBytes], 0, SHA256_BLOCK_SIZE - numBytes);
1710        /* Append the total length of the message (Big Endian), in bits (bytes << 3).
1711         * SHA-256 spec requires a 64-bit (8-byte) message length at the end of the
1712         * last block. The high 32 bits are already zeroed by FLib_MemSet above.
1713         * Conversion can be done safely on a 32-bit variable because we have
1714         * ascertained that totalBytes remain smaller than 2^29. */
1715        context->totalBytes <<= 3u;
1716        /* Write the low 32 bits of the 64-bit length field at bytes [60..63] */
1717        FLib_MemCpyReverseOrder(&context->buffer[SHA256_BLOCK_SIZE - sizeof(uint64_t) + sizeof(uint32_t)],
1718                                &context->totalBytes, sizeof(uint32_t));
1719        SHA256_hash_n(context->buffer, 1u, context->hash);
1720        /* Convert to Big Endian */
1721        for (uint32_t i = 0u; i < SHA256_HASH_SIZE / sizeof(uint32_t); i++)
1722        {
1723            uint32_t temp;
1724            temp = context->hash[i];
1725            FLib_MemCpyReverseOrder(&context->hash[i], &temp, sizeof(uint32_t));
1726        }
1727
1728        /* Copy the generated hash to the indicated output location */
1729        FLib_MemCpy(pOutput, (uint8_t *)(context->hash), SHA256_HASH_SIZE);
1730        st = gSecSuccess_c;
1731    } while (false);
1732
1733    return st;
1734}
1735
1736/*! *********************************************************************************
1737 * \brief  This function performs all SHA256 steps on multiple bytes: initialize,
1738 *         update and finish.
1739 *         The final hash value is stored at the provided output location.
1740 *
1741 * \param [in]       pData       Pointer to the input data
1742 * \param [in]       numBytes    Number of bytes to hash
1743 * \param [out]      pOutput     Pointer to the output location
1744 *
1745 ********************************************************************************** */
1746secResultType_t SecLib_SHA256_Hash(const uint8_t *pData, uint32_t numBytes, uint8_t *pOutput)
1747{
1748    secResultType_t st;
1749    sha256Context_t context;
1750    do
1751    {
1752        (void)SecLib_SHA256_Init(&context);
1753        st = SecLib_SHA256_HashUpdate(&context, pData, numBytes);
1754        if (st != gSecSuccess_c)
1755        {
1756            break;
1757        }
1758        st = SecLib_SHA256_HashFinish(&context, pOutput);
1759        if (st != gSecSuccess_c)
1760        {
1761            break;
1762        }
1763    } while (false);
1764    return st;
1765}
1766
1767/*! *********************************************************************************
1768 * \brief  This function allocates a memory buffer for a HMAC SHA256 context structure
1769 *
1770 * \return    Address of the HMAC SHA256 context buffer
1771 *            Deallocate using HMAC_SHA256_FreeCtx()
1772 *
1773 ********************************************************************************** */
1774void *SecLib_HMAC_SHA256_AllocCtx(void)
1775{
1776    void *hmacSha256Ctx = MEM_BufferAlloc(sizeof(HMAC_SHA256_context_t));
1777
1778    return hmacSha256Ctx;
1779}
1780
1781/*! *********************************************************************************
1782 * \brief  This function deallocates the memory buffer for the HMAC SHA256 context structure
1783 *
1784 * \param [in]    pContext    Address of the HMAC SHA256 context buffer
1785 *
1786 ********************************************************************************** */
1787void SecLib_HMAC_SHA256_FreeCtx(void *pContext)
1788{
1789    (void)MEM_BufferFree(pContext);
1790}
1791
1792/*! *********************************************************************************
1793 * \brief  This function performs the initialization of the HMAC SHA256 context data
1794 *
1795 * \param [in]    pContext    Pointer to the HMAC SHA256 context data
1796 *                            Allocated using HMAC_SHA256_AllocCtx()
1797 * \param [in]    pKey        Pointer to the HMAC key
1798 * \param [in]    keyLen      Length of the HMAC key in bytes
1799 *
1800 ********************************************************************************** */
1801secResultType_t SecLib_HMAC_SHA256_Init(void *pContext, const uint8_t *pKey, uint32_t keyLen)
1802{
1803    secResultType_t st;
1804
1805    do
1806    {
1807        uint8_t                i;
1808        HMAC_SHA256_context_t *context = (HMAC_SHA256_context_t *)pContext;
1809        sha256Context_t       *hash_ctx;
1810        uint8_t                sha256HashKeyBuffer[SHA256_HASH_SIZE] = {0};
1811
1812        if ((context == NULL) || (pKey == NULL))
1813        {
1814            RAISE_ERROR(st, gSecBadArgument_c);
1815        }
1816        hash_ctx = &context->shaCtx;
1817
1818        if (keyLen > SHA256_BLOCK_SIZE)
1819        {
1820            st = SecLib_SHA256_Hash(pKey, keyLen, sha256HashKeyBuffer);
1821            if (st != gSecSuccess_c)
1822            {
1823                break;
1824            }
1825            pKey   = sha256HashKeyBuffer;
1826            keyLen = SHA256_HASH_SIZE;
1827        }
1828        /* Create i_pad */
1829        for (i = 0u; i < keyLen; i++)
1830        {
1831            context->pad[i] = pKey[i] ^ gHmacIpad_c;
1832        }
1833
1834        for (i = (uint8_t)(keyLen & 0xffu); i < SHA256_BLOCK_SIZE; i++)
1835        {
1836            context->pad[i] = gHmacIpad_c;
1837        }
1838
1839        /* start hashing of the i_key_pad */
1840        st = SecLib_SHA256_Init(hash_ctx);
1841        if (st != gSecSuccess_c)
1842        {
1843            break;
1844        }
1845
1846        st = SecLib_SHA256_HashUpdate(hash_ctx, context->pad, SHA256_BLOCK_SIZE);
1847        if (st != gSecSuccess_c)
1848        {
1849            break;
1850        }
1851        /* create o_pad by xor-ing pad[i] with 0x36 ^ 0x5C: */
1852        for (i = 0u; i < SHA256_BLOCK_SIZE; i++)
1853        {
1854            context->pad[i] ^= (gHmacIpad_c ^ gHmacOpad_c);
1855        }
1856    } while (false);
1857    return st;
1858}
1859
1860/*! *********************************************************************************
1861 * \brief  This function performs HMAC update with the input data.
1862 *
1863 * \param [in]    pContext    Pointer to the HMAC SHA256 context data
1864 *                            Allocated using HMAC_SHA256_AllocCtx()
1865 * \param [in]    pData       Pointer to the input data
1866 * \param [in]    numBytes    Number of bytes to hash
1867 *
1868 ********************************************************************************** */
1869secResultType_t SecLib_HMAC_SHA256_Update(void *pContext, const uint8_t *pData, uint32_t numBytes)
1870{
1871    HMAC_SHA256_context_t *context = (HMAC_SHA256_context_t *)pContext;
1872    sha256Context_t       *sha_ctx = (context == NULL) ? NULL : &context->shaCtx;
1873    return SecLib_SHA256_HashUpdate(sha_ctx, pData, numBytes);
1874}
1875
1876/*! *********************************************************************************
1877 * \brief  This function finalizes the HMAC SHA256 computation and clears the context data.
1878 *         The final hash value is stored at the provided output location.
1879 *
1880 * \param [in]       pContext    Pointer to the HMAC SHA256 context data
1881 *                               Allocated using HMAC_SHA256_AllocCtx()
1882 * \param [in,out]   pOutput     Pointer to the output location
1883 *
1884 ********************************************************************************** */
1885secResultType_t SecLib_HMAC_SHA256_Finish(void *pContext, uint8_t *pOutput)
1886{
1887    secResultType_t st;
1888    do
1889    {
1890        HMAC_SHA256_context_t *context = (HMAC_SHA256_context_t *)pContext;
1891        sha256Context_t       *sha_ctx = (context == NULL) ? NULL : &context->shaCtx;
1892        uint8_t                hash1[SHA256_HASH_SIZE];
1893
1894        /* finalize the hash of the i_key_pad and message */
1895        st = SecLib_SHA256_HashFinish(sha_ctx, hash1);
1896        if (st != gSecSuccess_c)
1897        {
1898            break;
1899        }
1900        /* perform hash of the o_key_pad and hash1 */
1901        st = SecLib_SHA256_Init(sha_ctx);
1902        if (st != gSecSuccess_c)
1903        {
1904            break;
1905        }
1906        st = SecLib_SHA256_HashUpdate(sha_ctx, context->pad, SHA256_BLOCK_SIZE);
1907        if (st != gSecSuccess_c)
1908        {
1909            break;
1910        }
1911        st = SecLib_SHA256_HashUpdate(sha_ctx, hash1, SHA256_HASH_SIZE);
1912        if (st != gSecSuccess_c)
1913        {
1914            break;
1915        }
1916
1917        st = SecLib_SHA256_HashFinish(sha_ctx, pOutput);
1918
1919    } while (false);
1920    return st;
1921}
1922
1923/*! *********************************************************************************
1924 * \brief  This function performs all HMAC SHA256 steps on multiple bytes: initialize,
1925 *         update, finish, and update context data.
1926 *         The final HMAC value is stored at the provided output location.
1927 *
1928 * \param [in]       pKey        Pointer to the HMAC key
1929 * \param [in]       keyLen      Length of the HMAC key in bytes
1930 * \param [in]       pData       Pointer to the input data
1931 * \param [in]       numBytes    Number of bytes to perform HMAC on
1932 * \param [in,out]   pOutput     Pointer to the output location
1933 *
1934 ********************************************************************************** */
1935secResultType_t SecLib_HMAC_SHA256(
1936    const uint8_t *pKey, uint32_t keyLen, const uint8_t *pData, uint32_t numBytes, uint8_t *pOutput)
1937{
1938    secResultType_t st;
1939    do
1940    {
1941        HMAC_SHA256_context_t context;
1942
1943        st = SecLib_HMAC_SHA256_Init(&context, pKey, keyLen);
1944        if (st != gSecSuccess_c)
1945        {
1946            break;
1947        }
1948        st = SecLib_HMAC_SHA256_Update(&context, pData, numBytes);
1949        if (st != gSecSuccess_c)
1950        {
1951            break;
1952        }
1953        st = SecLib_HMAC_SHA256_Finish(&context, pOutput);
1954        if (st != gSecSuccess_c)
1955        {
1956            break;
1957        }
1958    } while (false);
1959    return st;
1960}
1961
1962#if (defined(mDbgRevertKeys_d) && (mDbgRevertKeys_d > 0))
1963static ecdhPublicKey_t  mReversedPublicKey;
1964static ecdhPrivateKey_t mReversedPrivateKey;
1965#endif /* mDbgRevertKeys_d */
1966
1967/* ECDH Sample Data Bluetooth specification V5.0 :
19687.1.2.1 P-256 Data Set 1
1969Private A: 3f49f6d4 a3c55f38 74c9b3e3 d2103f50 4aff607b eb40b799 5899b8a6 cd3c1abd
1970Private B: 55188b3d 32f6bb9a 900afcfb eed4e72a 59cb9ac2 f19d7cfb 6b4fdd49 f47fc5fd
1971Public A(x): 20b003d2 f297be2c 5e2c83a7 e9f9a5b9 eff49111 acf4fddb cc030148 0e359de6
1972Public A(y): dc809c49 652aeb6d 63329abf 5a52155c 766345c2 8fed3024 741c8ed0 1589d28b
1973Public B(x): 1ea1f0f0 1faf1d96 09592284 f19e4c00 47b58afd 8615a69f 559077b2 2faaa190
1974Public B(y): 4c55f33e 429dad37 7356703a 9ab85160 472d1130 e28e3676 5f89aff9 15b1214a
1975DHKey: ec0234a3 57c8ad05 341010a6 0a397d9b 99796b13 b4f866f1 868d34f3 73bfa698
19767.1.2.2 P-256 Data Set 2
1977Private A: 06a51669 3c9aa31a 6084545d 0c5db641 b48572b9 7203ddff b7ac73f7 d0457663
1978Private B: 529aa067 0d72cd64 97502ed4 73502b03 7e8803b5 c60829a5 a3caa219 505530ba
1979Public A(x): 2c31a47b 5779809e f44cb5ea af5c3e43 d5f8faad 4a8794cb 987e9b03 745c78dd
1980Public A(y): 91951218 3898dfbe cd52e240 8e43871f d0211091 17bd3ed4 eaf84377 43715d4f
1981Public B(x): f465e43f f23d3f1b 9dc7dfc0 4da87581 84dbc966 204796ec cf0d6cf5 e16500cc
1982Public B(y): 0201d048 bcbbd899 eeefc424 164e33c2 01c2b010 ca6b4d43 a8a155ca d8ecb279
1983DHKey: ab85843a 2f6d883f 62e5684b 38e30733 5fe6e194 5ecd1960 4105c6f2 3221eb69
1984*/
1985
1986/************************************************************************************
1987 * \brief Generates a public key from a scalar given as input
1988 *
1989 * This function performs the multiplication of the scalar by the EC P 256 G point.
1990 * The resulting point is the public key corresponding to the private key constituted by the scalar.
1991 * This calculation is also involved in the compute L stage if the SPAKE2+ not necessarily.
1992 *
1993 * \return gSecSuccess_c or error
1994 *
1995 ************************************************************************************/
1996secEcp256Status_t ECP256_GeneratePublicKey(uint8_t       *pOutPublicKey,
1997                                           const uint8_t *pInPrivateKey,
1998                                           void          *pMultiplicationBuffer)
1999{
2000    secEcp256Status_t ret = gSecEcp256BadParameters_c;
2001    if ((pOutPublicKey != NULL) && (pInPrivateKey != NULL))
2002    {
2003#if !(defined gSecLibUseDspExtension_d && (gSecLibUseDspExtension_d == 1))
2004        if (pMultiplicationBuffer != NULL)
2005        {
2006            big_int256_t  privKey;
2007            ecp256Point_t out;
2008            FLib_MemCpyReverseOrder((uint8_t *)&privKey, pInPrivateKey, sizeof(big_int256_t));
2009            ret = ECP256_GeneratePublicKeySeg(&out.raw[0], (uint8_t *)&privKey, pMultiplicationBuffer);
2010            ECP256_PointCopy_and_change_endianness((uint8_t *)pOutPublicKey, &out.raw[0]);
2011        }
2012#else
2013        NOT_USED(pMultiplicationBuffer);
2014        ret = ECP256_GeneratePublicKeyUltraFast(pOutPublicKey, pInPrivateKey);
2015#endif
2016    }
2017    return ret;
2018}
2019/************************************************************************************
2020 * \brief Generates a new ECDH P256 Private/Public key pair
2021 *
2022 * \return gSecSuccess_c or error
2023 *
2024 ************************************************************************************/
2025secResultType_t ECDH_P256_GenerateKeys(ecdhPublicKey_t *pOutPublicKey, ecdhPrivateKey_t *pOutPrivateKey)
2026{
2027    secResultType_t result;
2028
2029    do
2030    {
2031        if ((pOutPublicKey == NULL) || (pOutPrivateKey == NULL))
2032        {
2033            result = gSecBadArgument_c;
2034            break;
2035        }
2036
2037#if !(defined(gSecLibUseBleDebugKeys_d) && (gSecLibUseBleDebugKeys_d > 0))
2038#if !(defined gSecLibUseDspExtension_d && (gSecLibUseDspExtension_d == 1))
2039        void *pMultiplicationBuffer = MEM_BufferAlloc(gEcP256_MultiplicationBufferSize_c);
2040        if (NULL == pMultiplicationBuffer)
2041        {
2042            result = gSecAllocError_c;
2043            break;
2044        }
2045#if (defined(mDbgRevertKeys_d) && (mDbgRevertKeys_d > 0))
2046        if (gSecEcp256Success_c !=
2047            ECP256_GenerateKeyPair(&mReversedPublicKey, &mReversedPrivateKey, pMultiplicationBuffer))
2048#else  /* !mDbgRevertKeys_d */
2049        if (gSecEcp256Success_c != ECP256_GenerateKeyPair(pOutPublicKey, pOutPrivateKey, pMultiplicationBuffer))
2050#endif /* mDbgRevertKeys_d */
2051        {
2052            result = gSecError_c;
2053            break;
2054        }
2055        else
2056        {
2057            result = gSecSuccess_c;
2058#if (defined(mDbgRevertKeys_d) && (mDbgRevertKeys_d > 0))
2059            FLib_MemCpyReverseOrder(pOutPublicKey->components_8bit.x, mReversedPublicKey.components_8bit.x, 32);
2060            FLib_MemCpyReverseOrder(pOutPublicKey->components_8bit.y, mReversedPublicKey.components_8bit.y, 32);
2061            FLib_MemCpyReverseOrder(pOutPrivateKey->raw_8bit, mReversedPrivateKey.raw_8bit, 32);
2062#endif /* mDbgRevertKeys_d */
2063            result = gSecSuccess_c;
2064
2065            (void)MEM_BufferFree(pMultiplicationBuffer);
2066        }
2067#else
2068        ecp256KeyPair_t KeyPair;
2069        if (gSecEcp256Success_c != ECP256_GenerateKeyPairUltraFast(&KeyPair.public_key, &KeyPair.private_key))
2070        {
2071            result = gSecError_c;
2072            break;
2073        }
2074
2075        result = gSecSuccess_c;
2076        /* The NCCL output is BE and BLE expected LE */
2077        ECP256_PointCopy_and_change_endianness((uint8_t *)pOutPublicKey, (const uint8_t *)&KeyPair.public_key);
2078        ECP256_coordinate_copy_and_change_endianness((uint8_t *)pOutPrivateKey, (const uint8_t *)&KeyPair.private_key);
2079#endif
2080#else  /* gSecLibUseBleDebugKeys_d */
2081        /* The NCCL output is BE and BLE expected LE */
2082        ECP256_PointCopy_and_change_endianness((uint8_t *)pOutPublicKey, (const uint8_t *)&mBleDebugKeyPair.public_key);
2083        ECP256_coordinate_copy_and_change_endianness((uint8_t *)pOutPrivateKey,
2084                                                     (const uint8_t *)&mBleDebugKeyPair.private_key);
2085        result = gSecSuccess_c;
2086#endif /* gSecLibUseBleDebugKeys_d */
2087    } while (false);
2088    return result;
2089}
2090
2091/************************************************************************************
2092 * \brief Generates a new ECDH P256 Private/Public key pair. This function starts the
2093 *        ECDH generate procedure. The pDhKeyData must be allocated and kept
2094 *        allocated for the time of the computation procedure.
2095 *        When the result is gSecResultPending_c the memory should be kept until the
2096 *        last step.
2097 *        In any other result messages the data shall be cleared after this call.
2098 *
2099 * \param[in]  pDhKeyData Pointer to the structure holding information about the
2100 *                        multiplication
2101 *
2102 * \return gSecSuccess_c, gSecResultPending_c or error
2103 *
2104 ************************************************************************************/
2105secResultType_t ECDH_P256_GenerateKeysSeg(computeDhKeyParam_t *pDhKeyData)
2106{
2107    secResultType_t result;
2108
2109    do
2110    {
2111        if (pDhKeyData == NULL)
2112        {
2113            RAISE_ERROR(result, gSecBadArgument_c);
2114        }
2115        /* The callback is NULL when there is no async ECDH */
2116        if (pfSecLibMultCallback == NULL)
2117        {
2118            result = ECDH_P256_GenerateKeys(&pDhKeyData->outPoint, &pDhKeyData->privateKey);
2119        }
2120        else
2121        {
2122            void *pMultiplicationBuffer = MEM_BufferAlloc(gEcP256_MultiplicationBufferSize_c);
2123
2124            if (NULL == pMultiplicationBuffer)
2125            {
2126                RAISE_ERROR(result, gSecAllocError_c);
2127            }
2128
2129            pDhKeyData->pWorkBuffer = pMultiplicationBuffer;
2130            if (gSecEcdhSuccess_c != Ecdh_GenerateNewKeysSeg(pDhKeyData))
2131            {
2132                (void)MEM_BufferFree(pDhKeyData->pWorkBuffer);
2133                pDhKeyData->pWorkBuffer = NULL;
2134                RAISE_ERROR(result, gSecError_c);
2135            }
2136            result = gSecResultPending_c;
2137        }
2138    } while (false);
2139    return result;
2140}
2141
2142/************************************************************************************
2143 * \brief Function used to create the mac key and LTK using Bluetooth F5 algorithm
2144 *
2145 * \param  [out] pMacKey 128 bit MacKey output location (pointer)
2146 * \param  [out] pLtk    128 bit LTK output location (pointer)
2147 * \param  [in] pW       256 bit W (pointer) (DHKey)
2148 * \param  [in] pN1      128 bit N1 (pointer) (Na)
2149 * \param  [in] pN2      128 bit N2 (pointer) (Nb)
2150 * \param  [in] a1at     8 bit A1 address type, 0 = Public, 1 = Random
2151 * \param  [in] pA1      48 bit A1 (pointer) (A)
2152 * \param  [in] a2at     8 bit A2 address type, 0 = Public, 1 = Random
2153 * \param  [in] pA2      48 bit A2 (pointer) (B)
2154 *
2155 * \retval gSecSuccess_c operation succeeded
2156 * \retval gSecError_c operation failed
2157 ************************************************************************************/
2158secResultType_t SecLib_GenerateBluetoothF5Keys(uint8_t       *pMacKey,
2159                                               uint8_t       *pLtk,
2160                                               const uint8_t *pW,
2161                                               const uint8_t *pN1,
2162                                               const uint8_t *pN2,
2163                                               const uint8_t  a1at,
2164                                               const uint8_t *pA1,
2165                                               const uint8_t  a2at,
2166                                               const uint8_t *pA2)
2167{
2168    secResultType_t result     = gSecError_c;
2169    const uint8_t   f5KeyId[4] = {0x62, 0x74, 0x6c, 0x65}; /*!< Big Endian, "btle" */
2170    uint8_t         f5CmacBuffer[1 + 4 + 16 + 16 + 7 + 7 + 2];
2171    /* Counter[1] || keyId[4] || N1[16] || N2[16] || A1[7] || A2[7] || Length[2] = 53 */
2172
2173    uint8_t       f5T[16]    = {0};
2174    const uint8_t f5Salt[16] = {0x6C, 0x88, 0x83, 0x91, 0xAA, 0xF5, 0xA5, 0x38,
2175                                0x60, 0x37, 0x0B, 0xDB, 0x5A, 0x60, 0x83, 0xBE}; /*!< Big endian */
2176    do
2177    {
2178        uint8_t tempOut[16];
2179
2180        /*! Check for NULL output pointers and return with proper status if this is the case. */
2181        if ((NULL == pMacKey) || (NULL == pLtk) || (NULL == pW) || (NULL == pN1) || (NULL == pN2) || (NULL == pA1) ||
2182            (NULL == pA2))
2183        {
2184#if defined(gSmDebugEnabled_d) && (gSmDebugEnabled_d == 1U)
2185            SmDebug_Log(gSmDebugFileSmCrypto_c, __LINE__, smDebugLogTypeError_c, 0);
2186#endif /* gSmDebugEnabled_d */
2187            RAISE_ERROR(result, gSecBadArgument_c);
2188        }
2189
2190        /*! Compute the f5 function key T using the predefined salt as key for AES-128-CAMC */
2191        AES_128_CMAC_LsbFirstInput((const uint8_t *)pW, 32, (const uint8_t *)f5Salt, f5T);
2192
2193        /*! Build the most significant part of the f5 input data to compute the MacKey */
2194        f5CmacBuffer[0] = 0; /* Counter = 0 */
2195        FLib_MemCpy(&f5CmacBuffer[1], (const uint8_t *)f5KeyId, 4);
2196        FLib_MemCpyReverseOrder(&f5CmacBuffer[5], (const uint8_t *)pN1, 16);
2197        FLib_MemCpyReverseOrder(&f5CmacBuffer[21], (const uint8_t *)pN2, 16);
2198        f5CmacBuffer[37] = 0x01U & a1at;
2199        FLib_MemCpyReverseOrder(&f5CmacBuffer[38], (const uint8_t *)pA1, 6);
2200        f5CmacBuffer[44] = 0x01U & a2at;
2201        FLib_MemCpyReverseOrder(&f5CmacBuffer[45], (const uint8_t *)pA2, 6);
2202        f5CmacBuffer[51] = 0x01; /* Length msB big endian = 0x01, Length = 256 */
2203        f5CmacBuffer[52] = 0x00; /* Length lsB big endian = 0x00, Length = 256 */
2204
2205        /*! Compute the MacKey into the temporary buffer. */
2206        result = SecLib_AES_128_CMAC(f5CmacBuffer, sizeof(f5CmacBuffer), f5T, tempOut);
2207        if (result != gSecSuccess_c)
2208        {
2209            break;
2210        }
2211        /*! Copy the MacKey to the output location
2212         *  in reverse order. The CMAC result is generated MSB first. */
2213        FLib_MemCpyReverseOrder(pMacKey, (const uint8_t *)tempOut, 16);
2214
2215        /*! Build the least significant part of the f5 input data to compute the MacKey.
2216         *  It is identical to the most significant part with the exception of the counter. */
2217        f5CmacBuffer[0] = 1; /* Counter = 1 */
2218
2219        /*! Compute the LTK into the temporary buffer. */
2220        result = SecLib_AES_128_CMAC(f5CmacBuffer, sizeof(f5CmacBuffer), f5T, tempOut);
2221        if (result != gSecSuccess_c)
2222        {
2223            break;
2224        }
2225
2226        /*! Copy the LTK to the output location
2227         *  in reverse order. The CMAC result is generated MSB first. */
2228        FLib_MemCpyReverseOrder(pLtk, (const uint8_t *)tempOut, 16);
2229
2230        result = gSecSuccess_c;
2231
2232    } while (false);
2233
2234    return result;
2235}
2236
2237#if (defined(mDbgRevertKeys_d) && (mDbgRevertKeys_d > 0))
2238static ecdhDhKey_t mReversedEcdhKey;
2239#endif /* mDbgRevertKeys_d */
2240
2241secResultType_t ECDH_P256_ComputeDhKey(const ecdhPrivateKey_t *pInPrivateKey,
2242                                       const ecdhPublicKey_t  *pInPeerPublicKey,
2243                                       ecdhDhKey_t            *pOutDhKey,
2244                                       const bool_t            keepBlobDhKey)
2245{
2246    secResultType_t result = gSecSuccess_c;
2247    secEcdhStatus_t ecdhStatus;
2248    NOT_USED(keepBlobDhKey);
2249    do
2250    {
2251        if ((pInPrivateKey == NULL) || (pInPeerPublicKey == NULL) || (pOutDhKey == NULL))
2252        {
2253            RAISE_ERROR(result, gSecBadArgument_c);
2254        }
2255        if (!ECP256_LePointValid(pInPeerPublicKey))
2256        {
2257            RAISE_ERROR(result, gSecInvalidPublicKey_c);
2258        }
2259#if !(defined gSecLibUseDspExtension_d && (gSecLibUseDspExtension_d == 1))
2260
2261        void *pMultiplicationBuffer = MEM_BufferAlloc(gEcP256_MultiplicationBufferSize_c);
2262        if (NULL == pMultiplicationBuffer)
2263        {
2264            RAISE_ERROR(result, gSecAllocError_c);
2265        }
2266
2267#if (defined(mDbgRevertKeys_d) && (mDbgRevertKeys_d > 0))
2268        FLib_MemCpyReverseOrder(mReversedPublicKey.components_8bit.x, pInPeerPublicKey->components_8bit.x, 32);
2269        FLib_MemCpyReverseOrder(mReversedPublicKey.components_8bit.y, pInPeerPublicKey->components_8bit.y, 32);
2270        FLib_MemCpyReverseOrder(mReversedPrivateKey.raw_8bit, pInPrivateKey->raw_8bit, 32);
2271#endif /* mDbgRevertKeys_d */
2272
2273#if (defined(mDbgRevertKeys_d) && (mDbgRevertKeys_d > 0))
2274        ecdhStatus =
2275            Ecdh_ComputeDhKey(&mReversedPrivateKey, &mReversedPublicKey, &mReversedEcdhKey, pMultiplicationBuffer);
2276#else  /* !mDbgRevertKeys_d */
2277        ecdhStatus = Ecdh_ComputeDhKey(pInPrivateKey, pInPeerPublicKey, pOutDhKey, pMultiplicationBuffer);
2278#endif /* mDbgRevertKeys_d */
2279        if (gSecEcdhInvalidPublicKey_c == ecdhStatus)
2280        {
2281            RAISE_ERROR(result, gSecInvalidPublicKey_c);
2282        }
2283        else if (gSecEcdhSuccess_c != ecdhStatus)
2284        {
2285            RAISE_ERROR(result, gSecError_c);
2286        }
2287        else
2288        {
2289#if (defined(mDbgRevertKeys_d) && (mDbgRevertKeys_d > 0))
2290            FLib_MemCpyReverseOrder(pOutDhKey->components_8bit.x, mReversedEcdhKey.components_8bit.x, 32);
2291            FLib_MemCpyReverseOrder(pOutDhKey->components_8bit.y, mReversedEcdhKey.components_8bit.y, 32);
2292#endif /* mDbgRevertKeys_d */
2293        }
2294
2295        (void)MEM_BufferFree(pMultiplicationBuffer);
2296
2297#else
2298        ecp256Point_t      peer_public_key;
2299        ecp256Coordinate_t self_private_key;
2300        ecp256Point_t      dh_secret;
2301        ECP256_PointCopy_and_change_endianness(&peer_public_key.raw[0], (const uint8_t *)pInPeerPublicKey);
2302        ECP256_coordinate_copy_and_change_endianness(&self_private_key.raw_8bit[0], (const uint8_t *)pInPrivateKey);
2303        ecdhStatus = Ecdh_ComputeDhKeyUltraFast(&self_private_key, &peer_public_key, &dh_secret);
2304        if (ecdhStatus == gSecEcdhSuccess_c)
2305        {
2306            ECP256_PointCopy_and_change_endianness(&pOutDhKey->raw[0], (const uint8_t *)&dh_secret);
2307        }
2308        else
2309        {
2310            RAISE_ERROR(result, gSecError_c);
2311        }
2312#endif
2313    } while (false);
2314    return result;
2315}
2316
2317/************************************************************************************
2318 * \brief Checks whether a public key is valid (point is on the curve).
2319 *
2320 * \return TRUE if valid, FALSE if not
2321 *
2322 ************************************************************************************/
2323bool_t ECP256_IsKeyValid(const ecp256Point_t *pKey)
2324{
2325    bool_t ret = false;
2326
2327    if (ECP256_LePointValid(pKey))
2328    {
2329        ret = true;
2330    }
2331
2332    return ret;
2333}
2334
2335/*! *********************************************************************************
2336 * \brief  This function implements the SMP ah cryptographic toolbox function which calculates the
2337 *         hash part of a Resolvable Private Address.
2338 *         The key is kept in plaintext.
2339 *
2340 * \param[out]  pHash  Pointer where the 24 bit hash value will be written.
2341 *                     24 bit hash field of a Resolvable Private Address (output)
2342 *
2343 * \param[in]  pKey  Pointer to the 128 bit key.
2344 *
2345 * \param[in]  pR   Pointer to the 24 bit random value (Prand).
2346 *                  The most significant bits of this field must be 0b01 for Resolvable Private Addresses.
2347 *
2348 * \retval  gSecSuccess_c  All operations were successful.
2349 * \retval  gSecError_c The call failed.
2350 *
2351 ********************************************************************************** */
2352secResultType_t SecLib_VerifyBluetoothAh(uint8_t *pHash, const uint8_t *pKey, const uint8_t *pR)
2353{
2354    secResultType_t result           = gSecError_c;
2355    uint8_t         tempAddrPart[16] = {0};
2356    uint8_t         tempOutHash[16];
2357    uint8_t         tempKey[16];
2358    do
2359    {
2360        /*! Check for NULL output pointers and return with proper status if this is the case. */
2361        if ((NULL == pHash) || (NULL == pKey) || (NULL == pR))
2362        {
2363            RAISE_ERROR(result, gSecBadArgument_c);
2364        }
2365        /* Initialize the r' value in the temporary location. 3 bytes of ramdom value.
2366         *  Initialize it reversed for AES.
2367         */
2368        for (int i = 0; i < 3; i++)
2369        {
2370            tempAddrPart[15 - i] = pR[i];
2371        }
2372        /* Regular operation with plaintext key */
2373        /*! Reverse the Key and place it in a temporary location. */
2374        FLib_MemCpyReverseOrder(tempKey, (const uint8_t *)pKey, 16);
2375
2376        /*! Compute the hash. */
2377        AES_128_Encrypt(tempAddrPart, tempKey, tempOutHash);
2378
2379        /*! Copy the relevant bytes to the output. */
2380        pHash[0] = tempOutHash[15];
2381        pHash[1] = tempOutHash[14];
2382        pHash[2] = tempOutHash[13];
2383
2384        result = gSecSuccess_c;
2385
2386    } while (false);
2387
2388    return result;
2389}
2390
2391/************************************************************************************
2392 * \brief Computes the Diffie-Hellman Key for an ECDH P256 key pair. This function
2393 *        starts the ECDH key pair generate procedure. The pDhKeyData must be
2394 *        allocated and kept allocated for the time of the computation procedure.
2395 *        When the result is gSecResultPending_c the memory should be kept until the
2396 *        last step, when it can be safely freed.
2397 *        In any other result messages the data shall be cleared after this call.
2398 *
2399 * \param[in]  pDhKeyData Pointer to the structure holding information about the
2400 *                        multiplication
2401 *
2402 * \return gSecSuccess_c or error
2403 *
2404 ************************************************************************************/
2405secResultType_t ECDH_P256_ComputeDhKeySeg(computeDhKeyParam_t *pDhKeyData)
2406{
2407    secResultType_t result;
2408#if !(defined gSecLibUseDspExtension_d && (gSecLibUseDspExtension_d == 1))
2409    do
2410    {
2411        secEcdhStatus_t ecdhStatus;
2412        void           *pMultiplicationBuffer;
2413
2414        if (pDhKeyData == NULL)
2415        {
2416            RAISE_ERROR(result, gSecBadArgument_c);
2417        }
2418
2419        if (pfSecLibMultCallback == NULL)
2420        {
2421            /* One shot operation */
2422            result = ECDH_P256_ComputeDhKey(&pDhKeyData->privateKey, &pDhKeyData->peerPublicKey, &pDhKeyData->outPoint,
2423                                            FALSE);
2424            break;
2425        }
2426
2427        pMultiplicationBuffer = MEM_BufferAlloc(gEcP256_MultiplicationBufferSize_c);
2428        if (NULL == pMultiplicationBuffer)
2429        {
2430            RAISE_ERROR(result, gSecAllocError_c);
2431        }
2432        else
2433        {
2434            pDhKeyData->pWorkBuffer = pMultiplicationBuffer;
2435            ecdhStatus              = Ecdh_ComputeDhKeySeg(pDhKeyData);
2436            result                  = gSecResultPending_c;
2437
2438            if (gSecEcdhInvalidPublicKey_c == ecdhStatus)
2439            {
2440                result = gSecInvalidPublicKey_c;
2441            }
2442            else if (gSecEcdhSuccess_c != ecdhStatus)
2443            {
2444                result = gSecError_c;
2445            }
2446            if (result != gSecResultPending_c)
2447            {
2448                (void)MEM_BufferFree(pDhKeyData->pWorkBuffer);
2449                pDhKeyData->pWorkBuffer = NULL;
2450            }
2451        }
2452    } while (false);
2453#else
2454    result = ECDH_P256_ComputeDhKey(&pDhKeyData->privateKey, &pDhKeyData->peerPublicKey, &pDhKeyData->outPoint, FALSE);
2455#endif
2456    return result;
2457}
2458
2459#if !(defined gSecLibUseDspExtension_d && (gSecLibUseDspExtension_d == 1))
2460/************************************************************************************
2461 * \brief Handle one step of ECDH multiplication depending on the number of steps at
2462 *        a time according to gSecLibEcStepsAtATime. After the last step is completed
2463 *        the function returns TRUE and the upper layer is responsible for clearing
2464 *        pData.
2465 *
2466 * \param[in]  pData Pointer to the structure holding information about the
2467 *                   multiplication
2468 *
2469 * \return TRUE if the multiplication is completed
2470 *         FALSE when the function needs to be called again
2471 *
2472 ************************************************************************************/
2473bool_t SecLib_HandleMultiplyStep(computeDhKeyParam_t *pData)
2474{
2475    bool_t        result = FALSE;
2476    const uint8_t steps  = ((255U + 1U) / gSecLibEcStepsAtATime);
2477
2478    /* Intermediate step */
2479    if (pData->procStep < steps)
2480    {
2481        /* Compute step */
2482        Ecdh_ComputeJacobiChunk(255U - (pData->procStep * gSecLibEcStepsAtATime), gSecLibEcStepsAtATime, pData);
2483        /* Go to the next step */
2484        pData->procStep++;
2485        pData->result = gSecResultPending_c;
2486        result        = FALSE;
2487    }
2488    /* Final step was completed -> resume SecLib procedure */
2489    else
2490    {
2491        Ecdh_JacobiCompleteMult(pData);
2492
2493#if (defined(mDbgRevertKeys_d) && (mDbgRevertKeys_d > 0))
2494        {
2495            FLib_MemCpyReverseOrder(mReversedEcdhKey.components_8bit.x, pData->outX,
2496                                    sizeof(mReversedEcdhKey.components_8bit.x));
2497            FLib_MemCpyReverseOrder(mReversedEcdhKey.components_8bit.y, pData->outY,
2498                                    sizeof(mReversedEcdhKey.components_8bit.y));
2499            FLib_MemCpyReverseOrder(pData->outX, mReversedEcdhKey.components_8bit.x, sizeof(pData->outX));
2500            FLib_MemCpyReverseOrder(pData->outY, mReversedEcdhKey.components_8bit.y, sizeof(pData->outY));
2501        }
2502#endif /* mDbgRevertKeys_d */
2503        pData->result = gSecSuccess_c;
2504        result        = TRUE;
2505    }
2506    return result;
2507}
2508#endif
2509
2510secResultType_t SecLib_GenerateBluetoothF5KeysSecure(uint8_t       *pMacKey,
2511                                                     uint8_t       *pLtk,
2512                                                     const uint8_t *pW,
2513                                                     const uint8_t *pN1,
2514                                                     const uint8_t *pN2,
2515                                                     const uint8_t  a1at,
2516                                                     const uint8_t *pA1,
2517                                                     const uint8_t  a2at,
2518                                                     const uint8_t *pA2)
2519{
2520    NOT_USED(pMacKey);
2521    NOT_USED(pLtk);
2522    NOT_USED(pW);
2523    NOT_USED(pN1);
2524    NOT_USED(pN2);
2525    NOT_USED(a1at);
2526    NOT_USED(pA1);
2527    NOT_USED(a2at);
2528    NOT_USED(pA2);
2529    return gSecError_c;
2530}
2531
2532/************************************************************************************
2533 * \brief Converts a plaintext symmetric key into a blob of blobType. Reverses key beforehand.
2534 *
2535 * \param[in]  pKey      Pointer to the key.
2536 *
2537 * \param[out] pBlob     Pointer to the blob (shall be allocated, 40 or 16, depending on blobType)
2538 *
2539 * \param[in]  blobType  Blob type.
2540 *
2541 * \return gSecSuccess_c or error
2542 *
2543 ************************************************************************************/
2544secResultType_t SecLib_ObfuscateKeySecure(const uint8_t *pKey, uint8_t *pBlob, const uint8_t blobType)
2545{
2546    NOT_USED(pKey);
2547    NOT_USED(pBlob);
2548    NOT_USED(blobType);
2549    return gSecError_c;
2550}
2551
2552/************************************************************************************
2553 * \brief Converts a blob of a symmetric key into the plaintext. Reverses key afterwards.
2554 *
2555 * \param[in]  pBlob    Pointer to the blob.
2556 *
2557 * \param[out] pKey     Pointer to the key.
2558 *
2559 * \return gSecSuccess_c or error
2560 *
2561 ************************************************************************************/
2562secResultType_t SecLib_DeobfuscateKeySecure(const uint8_t *pBlob, uint8_t *pKey)
2563{
2564    NOT_USED(pBlob);
2565    NOT_USED(pKey);
2566    return gSecError_c;
2567}
2568
2569/************************************************************************************
2570 * \brief Function used to derive the Bluetooth SKD used in LL encryption.
2571 *        Available on EdgeLock (SSS only)
2572 *
2573 * \param  [in] pInSKD   pointer to the received SKD (16-byte array)
2574 * \param  [in] pLtkBlob pointer to the blob (40-byte array)
2575 * \param  [in] bOpenKey  if TRUE sends derived key to NBU
2576 * \param  [out] pOutSKD pointer to the resulted SKD (16-byte array)
2577 *
2578 * \retval gSecSuccess_c operation succeeded
2579 * \retval gSecError_c operation failed / not implemented
2580 ************************************************************************************/
2581secResultType_t SecLib_DeriveBluetoothSKDSecure(const uint8_t *pInSKD,
2582                                                const uint8_t *pLtkBlob,
2583                                                bool_t         bOpenKey,
2584                                                uint8_t       *pOutSKD)
2585{
2586    NOT_USED(pInSKD);
2587    NOT_USED(pLtkBlob);
2588    NOT_USED(bOpenKey);
2589    NOT_USED(pOutSKD);
2590
2591    return gSecError_c;
2592}
2593
2594secResultType_t SecLib_GenerateSymmetricKey(const uint32_t keySize, const bool_t blobOutput, void *pOut)
2595{
2596    NOT_USED(keySize);
2597    NOT_USED(blobOutput);
2598    NOT_USED(pOut);
2599    return gSecError_c;
2600}
2601
2602secResultType_t SecLib_GenerateBluetoothEIRKBlobSecure(const void  *pIRK,
2603                                                       const bool_t blobInput,
2604                                                       const bool_t generateDKeyIRK,
2605                                                       uint8_t     *pOutEIRKblob)
2606{
2607    NOT_USED(pIRK);
2608    NOT_USED(blobInput);
2609    NOT_USED(generateDKeyIRK);
2610    NOT_USED(pOutEIRKblob);
2611    return gSecError_c;
2612}
2613secResultType_t ECDH_P256_ComputeA2BKeySecure(const ecdhPublicKey_t *pInPeerPublicKey, ecdhDhKey_t *pOutE2EKey)
2614{
2615    NOT_USED(pInPeerPublicKey);
2616    NOT_USED(pOutE2EKey);
2617    return gSecError_c;
2618}
2619
2620secResultType_t SecLib_ExportA2BBlobSecure(const void *pKey, const secInputKeyType_t keyType, uint8_t *pOutKey)
2621{
2622    NOT_USED(pKey);
2623    NOT_USED(keyType);
2624    NOT_USED(pOutKey);
2625    return gSecError_c;
2626}
2627
2628void ECDH_P256_FreeDhKeyDataSecure(computeDhKeyParam_t *pDhKeyData)
2629{
2630    NOT_USED(pDhKeyData);
2631}
2632
2633secResultType_t SecLib_ImportA2BBlobSecure(const uint8_t *pKey, const secInputKeyType_t keyType, uint8_t *pOutKey)
2634{
2635    NOT_USED(pKey);
2636    NOT_USED(keyType);
2637    NOT_USED(pOutKey);
2638    return gSecError_c;
2639}
2640
2641secResultType_t ECDH_P256_FreeE2EKeyDataSecure(ecdhDhKey_t *pE2EKeyData)
2642{
2643    NOT_USED(pE2EKeyData);
2644    return gSecError_c;
2645}
2646
2647secResultType_t SecLib_VerifyBluetoothAhSecure(uint8_t *pHash, const uint8_t *pKey, const uint8_t *pR)
2648{
2649    NOT_USED(pHash);
2650    NOT_USED(pKey);
2651    NOT_USED(pR);
2652    return gSecError_c;
2653}
2654
2655/*! *********************************************************************************
2656*************************************************************************************
2657* Private functions
2658*************************************************************************************
2659********************************************************************************** */
2660
2661/*! *********************************************************************************
2662 * \brief  This function performs SHA256 on multiple blocks
2663 *
2664 * \param [in]    pData      Pointer to the input data
2665 * \param [in]    nBlk       Number of SHA256 blocks to hash
2666 * \param [in]    context        Pointer to the SHA256 context data
2667 *
2668 ********************************************************************************** */
2669static void SHA256_hash_n(const uint8_t *pData, uint32_t nBlk, uint32_t *pHash)
2670{
2671    if (nBlk < (UINT32_MAX / SHA256_BLOCK_SIZE))
2672    {
2673#if (defined(FSL_FEATURE_SOC_MMCAU_COUNT) && (FSL_FEATURE_SOC_MMCAU_COUNT > 0))
2674        SECLIB_MUTEX_LOCK();
2675        mmcau_sha256_hash_n(pData, nBlk, (unsigned int *)pHash);
2676        SECLIB_MUTEX_UNLOCK();
2677#else
2678        sw_sha256_hash_n(pData, nBlk, pHash);
2679#endif
2680    }
2681    else
2682    {
2683        assert(0);
2684    }
2685}
2686
2687#if (defined FSL_FEATURE_SOC_AES_HW && (FSL_FEATURE_SOC_AES_HW > 0))
2688/*! *********************************************************************************
2689 * \brief  This function performs hardware AES-128 ECB encryption
2690 *
2691 * \param [in]    ECB_p      Pointer to AES parameter structure
2692 *
2693 ********************************************************************************** */
2694static void AES_128_ECB_Enc_HW(AES_param_t *ECB_p)
2695{
2696    uint8_t tempBuffIn[AES_BLOCK_SIZE]  = {0};
2697    uint8_t tempBuffOut[AES_BLOCK_SIZE] = {0};
2698
2699    /* If remaining data bigger than one AES block size */
2700    while (ECB_p->Len > AES_BLOCK_SIZE)
2701    {
2702        AES_128_Encrypt(ECB_p->pPlain, ECB_p->Key, ECB_p->pCipher);
2703        ECB_p->pPlain += AES_BLOCK_SIZE;
2704        ECB_p->pCipher += AES_BLOCK_SIZE;
2705        ECB_p->Len -= AES_BLOCK_SIZE;
2706    }
2707
2708    /* If remaining data is smaller then one AES block size */
2709    FLib_MemCpy(tempBuffIn, ECB_p->pPlain, ECB_p->Len);
2710    AES_128_Encrypt(tempBuffIn, ECB_p->Key, tempBuffOut);
2711    FLib_MemCpy(ECB_p->pCipher, tempBuffOut, AES_BLOCK_SIZE);
2712#if (defined(USE_TASK_FOR_HW_AES) && (USE_TASK_FOR_HW_AES > 0))
2713    AESM_Complete(AES128ECB_Enc_Id);
2714#endif
2715}
2716
2717/*! *********************************************************************************
2718 * \brief  This function performs hardware AES-128 ECB decryption
2719 *
2720 * \param [in]    ECB_p      Pointer to AES parameter structure
2721 *
2722 ********************************************************************************** */
2723static void AES_128_ECB_Dec_HW(AES_param_t *ECB_p)
2724{
2725    uint8_t tempBuffIn[AES_BLOCK_SIZE]  = {0};
2726    uint8_t tempBuffOut[AES_BLOCK_SIZE] = {0};
2727
2728    /* If remaining data bigger than one AES block size */
2729    while (ECB_p->Len > AES_BLOCK_SIZE)
2730    {
2731        AES_128_Decrypt(ECB_p->pCipher, ECB_p->Key, ECB_p->pPlain);
2732        ECB_p->pPlain += AES_BLOCK_SIZE;
2733        ECB_p->pCipher += AES_BLOCK_SIZE;
2734        ECB_p->Len -= AES_BLOCK_SIZE;
2735    }
2736
2737    /* If remaining data is smaller then one AES block size */
2738    FLib_MemCpy(tempBuffIn, ECB_p->pCipher, ECB_p->Len);
2739    AES_128_Decrypt(tempBuffIn, ECB_p->Key, tempBuffOut);
2740    FLib_MemCpy(ECB_p->pPlain, tempBuffOut, ECB_p->Len);
2741#if (defined(USE_TASK_FOR_HW_AES) && (USE_TASK_FOR_HW_AES > 0))
2742    AESM_Complete(AES128ECB_Dec_Id);
2743#endif /* USE_TASK_FOR_HW_AES */
2744}
2745
2746/*! *********************************************************************************
2747 * \brief  This function performs hardware AES-128 ECB block encryption
2748 *
2749 * \param [in]    ECB_p      Pointer to AES parameter structure
2750 *
2751 ********************************************************************************** */
2752static void AES_128_ECB_Block_Enc_HW(AES_param_t *ECBB_p)
2753{
2754    while (ECBB_p->Blocks > 0u)
2755    {
2756        AES_128_Encrypt(ECBB_p->pPlain, ECBB_p->Key, ECBB_p->pCipher);
2757        ECBB_p->Blocks--;
2758        ECBB_p->pPlain += AES_BLOCK_SIZE;
2759        ECBB_p->pCipher += AES_BLOCK_SIZE;
2760    }
2761#if (defined(USE_TASK_FOR_HW_AES) && (USE_TASK_FOR_HW_AES > 0))
2762    AESM_Complete(AES128ECBB_Enc_Id);
2763#endif
2764}
2765
2766/*! *********************************************************************************
2767 * \brief  This function performs hardware AES-128 ECB block decryption
2768 *
2769 * \param [in]    ECB_p      Pointer to AES parameter structure
2770 *
2771 ********************************************************************************** */
2772static void AES_128_ECB_Block_Dec_HW(AES_param_t *ECBB_p)
2773{
2774    while (ECBB_p->Blocks > 0u)
2775    {
2776        AES_128_Decrypt(ECBB_p->pCipher, ECBB_p->Key, ECBB_p->pPlain);
2777        ECBB_p->Blocks--;
2778        ECBB_p->pPlain += AES_BLOCK_SIZE;
2779        ECBB_p->pCipher += AES_BLOCK_SIZE;
2780    }
2781#if (defined(USE_TASK_FOR_HW_AES) && (USE_TASK_FOR_HW_AES > 0))
2782    AESM_Complete(AES128ECBB_Dec_Id);
2783#endif
2784}
2785
2786/*! *********************************************************************************
2787 * \brief  This function performs hardware AES-128 CTR encryption
2788 *
2789 * \param [in]    CTR_p      Pointer to AES parameter structure
2790 *
2791 ********************************************************************************** */
2792static void AES_128_CTR_Enc_HW(AES_param_t *CTR_p)
2793{
2794    uint8_t tempBuffIn[AES_BLOCK_SIZE] = {0};
2795    uint8_t encrCtr[AES_BLOCK_SIZE]    = {0};
2796
2797    /* If remaining data bigger than one AES block size */
2798    while (CTR_p->Len > AES_BLOCK_SIZE)
2799    {
2800        FLib_MemCpy(tempBuffIn, CTR_p->pPlain, AES_BLOCK_SIZE);
2801        AES_128_Encrypt(CTR_p->CTR_counter, CTR_p->Key, encrCtr);
2802        SecLib_XorN(tempBuffIn, encrCtr, AES_BLOCK_SIZE);
2803        FLib_MemCpy(CTR_p->pCipher, tempBuffIn, AES_BLOCK_SIZE);
2804        CTR_p->pPlain += AES_BLOCK_SIZE;
2805        CTR_p->pCipher += AES_BLOCK_SIZE;
2806        CTR_p->Len -= AES_BLOCK_SIZE;
2807        AES_128_IncrementCounter(CTR_p->CTR_counter);
2808    }
2809
2810    /* If remaining data is smaller then one AES block size  */
2811    FLib_MemCpy(tempBuffIn, CTR_p->pPlain, CTR_p->Len);
2812    SecLib_AES_128_Encrypt(CTR_p->CTR_counter, CTR_p->Key, encrCtr);
2813    SecLib_XorN(tempBuffIn, encrCtr, AES_BLOCK_SIZE);
2814    FLib_MemCpy(CTR_p->pCipher, tempBuffIn, CTR_p->Len);
2815    AES_128_IncrementCounter(CTR_p->CTR_counter);
2816#if (defined(USE_TASK_FOR_HW_AES) && (USE_TASK_FOR_HW_AES > 0))
2817    AESM_Complete(AES128CTR_Enc_Id);
2818#endif
2819}
2820
2821/*! *********************************************************************************
2822 * \brief  This function performs hardware AES-128 CTR decryption
2823 *
2824 * \param [in]    CTR_p      Pointer to AES parameter structure
2825 *
2826 ********************************************************************************** */
2827static void AES_128_CTR_Dec_HW(AES_param_t *CTR_p)
2828{
2829    uint8_t tempBuffIn[AES_BLOCK_SIZE] = {0};
2830    uint8_t encrCtr[AES_BLOCK_SIZE]    = {0};
2831
2832    /* If remaining data bigger than one AES block size */
2833    while (CTR_p->Len > AES_BLOCK_SIZE)
2834    {
2835        FLib_MemCpy(tempBuffIn, CTR_p->pCipher, AES_BLOCK_SIZE);
2836        AES_128_Encrypt(CTR_p->CTR_counter, CTR_p->Key, encrCtr);
2837        SecLib_XorN(tempBuffIn, encrCtr, AES_BLOCK_SIZE);
2838        FLib_MemCpy(CTR_p->pPlain, tempBuffIn, AES_BLOCK_SIZE);
2839        CTR_p->pPlain += AES_BLOCK_SIZE;
2840        CTR_p->pCipher += AES_BLOCK_SIZE;
2841        CTR_p->Len -= AES_BLOCK_SIZE;
2842        AES_128_IncrementCounter(CTR_p->CTR_counter);
2843    }
2844
2845    /* If remaining data is smaller then one AES block size  */
2846    FLib_MemCpy(tempBuffIn, CTR_p->pCipher, CTR_p->Len);
2847    SecLib_AES_128_Encrypt(CTR_p->CTR_counter, CTR_p->Key, encrCtr);
2848    SecLib_XorN(tempBuffIn, encrCtr, AES_BLOCK_SIZE);
2849    FLib_MemCpy(CTR_p->pPlain, tempBuffIn, CTR_p->Len);
2850    AES_128_IncrementCounter(CTR_p->CTR_counter);
2851#if (defined(USE_TASK_FOR_HW_AES) && (USE_TASK_FOR_HW_AES > 0))
2852    AESM_Complete(AES128CTR_Dec_Id);
2853#endif
2854}
2855
2856/*! *********************************************************************************
2857 * \brief  This function performs hardware AES-128 CMAC encryption
2858 *
2859 * \param [in]    CMAC_p      Pointer to AES parameter structure
2860 *
2861 ********************************************************************************** */
2862static void AES_128_CMAC_HW(AES_param_t *CMAC_p)
2863{
2864    uint8_t X[16];
2865    uint8_t Y[16];
2866    uint8_t M_last[16] = {0};
2867    uint8_t padded[16] = {0};
2868
2869    uint8_t K1[16] = {0};
2870    uint8_t K2[16] = {0};
2871
2872    uint32_t n;
2873    uint32_t i;
2874    uint8_t  flag;
2875    /* CERT ARR30-C (CID 53857250): removed duplicate 'uint8_t n;' declaration */
2876    uint32_t residual_len;
2877
2878    AES_128_CMAC_Generate_Subkey(CMAC_p->Key, K1, K2);
2879
2880    n            = AES_TOTAL_BLOCK_NB(CMAC_p->Len); /* n is number of rounds */
2881    residual_len = AES_PARTIAL_BLOCK_BYTES(CMAC_p->Len);
2882
2883    if (n == 0u)
2884    {
2885        n    = 1u;
2886        flag = 0u;
2887    }
2888    else
2889    {
2890        if (residual_len == 0u)
2891        { /* last block is a complete block */
2892            flag = 1u;
2893        }
2894        else
2895        { /* last block is not complete block */
2896            flag = 0u;
2897        }
2898    }
2899
2900    /* Process the last block  - the last part the MSB first input data */
2901    /* CERT ARR30-C (CID 53857250): n >= 1u is guaranteed by the if(n==0u) block above */
2902    if (flag > 0u)
2903    { /* last block is complete block */
2904        SecLib_Xor128(&CMAC_p->pPlain[16u * (n - 1u)], K1, M_last);
2905    }
2906    else
2907    {
2908        (void)SecLib_Padding(&CMAC_p->pPlain[AES_BLOCK_SIZE * (n - 1u)], padded, residual_len);
2909        SecLib_Xor128(padded, K2, M_last);
2910    }
2911
2912    for (i = 0u; i < 16u; i++)
2913    {
2914        X[i] = 0u;
2915    }
2916
2917    for (i = 0u; i < n - 1u; i++)
2918    {
2919        SecLib_Xor128(X, &CMAC_p->pPlain[AES_BLOCK_SIZE * i], Y); /* Y := Mi (+) X  */
2920        AES_128_Encrypt(Y, CMAC_p->Key, X);                       /* X := AES-128(KEY, Y) */
2921    }
2922
2923    SecLib_Xor128(X, M_last, Y);
2924    AES_128_Encrypt(Y, CMAC_p->Key, X);
2925
2926    for (i = 0u; i < 16u; i++)
2927    {
2928        CMAC_p->pCipher[i] = X[i];
2929    }
2930#if (defined(USE_TASK_FOR_HW_AES) && (USE_TASK_FOR_HW_AES > 0))
2931    AESM_Complete(AES128CMAC_Id);
2932#endif
2933}
2934
2935#endif /* FSL_FEATURE_SOC_AES_HW */
2936
2937/*! *********************************************************************************
2938 * \brief  This function pads an incomplete 16 byte block of data, where padding is
2939 *         the concatenation of x and a single '1',
2940 *         followed by the minimum number of '0's, so that the total length is equal to 128 bits.
2941 * Padding scheme is ISO/IEC 7816-4: one 80h byte (1 bit), followed by as many 00h as
2942 * required to fill a 128 bit block.
2943 *
2944 * \param[in, out] lastb Pointer to the last block of message to be padded
2945 *
2946 * \param[in]  pad_block Padded block destination
2947 *
2948 * \param[in]  length    Number of message bytes in the block to be padded : must be in [0..AES_BLOCK_SIZE-1]
2949 *
2950 * \return  length of padding [1..AES_BLOCK_SIZE] if ok, 0 otherwise
2951 *
2952 ********************************************************************************** */
2953static uint8_t SecLib_Padding(const uint8_t *lastb, uint8_t pad_block[AES_BLOCK_SIZE], uint8_t length)
2954{
2955    uint8_t  padding_sz = 0;
2956    uint32_t j;
2957    if (length < AES_BLOCK_SIZE)
2958    {
2959        for (j = 0u; j < AES_BLOCK_SIZE; j++)
2960        {
2961            /* there may be 0 bytes to copy if message was a multiple of AES_BLOCK_SIZE */
2962            if (j < length)
2963            {
2964                /* original last block */
2965                pad_block[j] = lastb[j];
2966            }
2967            else if (j == length)
2968            {
2969                pad_block[j] = 0x80u;
2970            }
2971            else
2972            {
2973                pad_block[j] = 0x00u;
2974            }
2975        }
2976        padding_sz = AES_BLOCK_SIZE - length;
2977    }
2978    return padding_sz;
2979}
2980/*! *********************************************************************************
2981 * \brief  This function removes padding from an octet string (at most 16 bytes of data).
2982 *
2983 * \param[in] pIn Pointer to start of last AES block of a message to be depadded
2984 *
2985 * \return  if > 0 Final size of padding to be removed : must be in [1..AES_BLOCK_SIZE].
2986 *          if 0 : error occurred the last block does not contain expected padding patter.
2987 *
2988 ********************************************************************************** */
2989static uint8_t SecLib_DePadding(const uint8_t pad_block[AES_BLOCK_SIZE])
2990{
2991    uint8_t padding_sz = 0u;
2992
2993    for (uint8_t i = AES_BLOCK_SIZE; i > 0u; i--)
2994    {
2995        uint8_t ch = pad_block[i - 1u];
2996        if (ch == 0x80u)
2997        {
2998            padding_sz = AES_BLOCK_SIZE - i + 1u;
2999            break;
3000        }
3001        else if (ch != 0x00u)
3002        {
3003            /* not padding */
3004            padding_sz = 0u;
3005            break;
3006        }
3007        else
3008        {
3009            /* MISRA rule 15.7 but useless */
3010            continue;
3011        }
3012    }
3013    return padding_sz;
3014}
3015
3016/*! *********************************************************************************
3017 * \brief  This function Xors 2 blocks of 128 bits and copies the result to a set destination
3018 *
3019 * \param [in]    a        Pointer to the first block to XOR
3020 *
3021 * \param [in]    b        Pointer to the second block to XOR.
3022 *
3023 * \param [out]   out      Destination pointer
3024 *
3025 * \remarks   This is public open source code! Terms of use must be checked before use!
3026 *
3027 ********************************************************************************** */
3028static void SecLib_Xor128(const uint8_t *a, const uint8_t *b, uint8_t *out)
3029{
3030    uint32_t i;
3031
3032    for (i = 0u; i < AES_BLOCK_SIZE; i++)
3033    {
3034        out[i] = a[i] ^ b[i];
3035    }
3036}
3037/*! *********************************************************************************
3038*************************************************************************************
3039* Private functions
3040*************************************************************************************
3041********************************************************************************** */
3042
3043#if (!defined(FSL_FEATURE_SOC_LTC_COUNT) || (FSL_FEATURE_SOC_LTC_COUNT == 0))
3044/*! *********************************************************************************
3045 * \brief  Increments the value of a given counter vector.
3046 *
3047 * \param [in,out]     ctr         Counter.
3048 *
3049 * \remarks used for AES CTR.
3050 *          The counter is treated as a 128-bit big-endian integer: ctr[0] is the
3051 *           MSB byte. Internally it is stored little-endian in a
3052 *           uuint128_t union for the carry computation.
3053 *
3054 ********************************************************************************** */
3055static void AES_128_IncrementCounter(uint8_t *ctr)
3056{
3057    uint32_t i;
3058    /* Coverity UNINIT and INCONSISTENT_UNION_ACCESS: the uuint128_t union is written through its
3059     * u8[] member (loop below) and subsequently read through its u64[] member to
3060     * perform the 128-bit carry arithmetic. This type punning is intentional and
3061     * required for the big-endian AES CTR counter increment. All 16 bytes of the
3062     * union are written before any u64 access, so no genuinely uninitialized memory
3063     * is ever read. tempLow and tempCtr are explicitly initialized at declaration to
3064     * make the full-initialization intent unambiguous to the static analyzer. */
3065    uint64_t   tempLow = 0ULL;
3066    uuint128_t tempCtr = {.u64 = {0ULL, 0ULL}};
3067
3068    for (i = 0u; i < AES_BLOCK_SIZE; i++)
3069    {
3070        tempCtr.u8[AES_BLOCK_SIZE - i - 1U] = ctr[i];
3071    }
3072
3073    tempLow = tempCtr.u64[0];
3074    tempCtr.u64[0]++;
3075
3076    if (tempLow > tempCtr.u64[0])
3077    {
3078        tempCtr.u64[1]++;
3079    }
3080    /* Byte reversal is required due to endianness conversion for AES CTR where counter is MSB first */
3081    for (i = 0u; i < AES_BLOCK_SIZE; i++)
3082    {
3083        ctr[i] = tempCtr.u8[AES_BLOCK_SIZE - i - 1U];
3084    }
3085}
3086#endif /* !(FSL_FEATURE_SOC_LTC_COUNT) */
3087
3088/*! *********************************************************************************
3089 * \brief  Generates the two subkeys that correspond to an AES key
3090 *
3091 * \param [in]    key        AES Key.
3092 *
3093 * \param [out]   K1         First subkey.
3094 *
3095 * \param [out]   K2         Second subkey.
3096 *
3097 * \remarks   This is public open source code! Terms of use must be checked before use!
3098 *
3099 ********************************************************************************** */
3100static void AES_128_CMAC_Generate_Subkey(const uint8_t *key, uint8_t *K1, uint8_t *K2)
3101{
3102    uint8_t  const_Rb[16] = {0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u,
3103                             0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x87u};
3104    uint8_t  L[16]        = {0};
3105    uint8_t  Z[16];
3106    uint8_t  tmp[16] = {0};
3107    uint32_t i;
3108
3109    for (i = 0u; i < 16u; i++)
3110    {
3111        Z[i] = 0u;
3112    }
3113
3114    AES_128_Encrypt(Z, key, L); /* Initializes L array */
3115
3116    /* coverity[uninit_use:FALSE]: L is zero-initialized at declaration (L[16] = {0})
3117     * and then fully populated by AES_128_Encrypt() above (16-byte output). The analyzer cannot
3118     * see the callee writing the L output parameter, but L[0] is guaranteed initialized here. */
3119    if ((L[0] & 0x80u) == 0u)
3120    {
3121        /* If MSB(L) = 0, then K1 = L << 1 */
3122        SecLib_LeftShiftOneBit(L, K1);
3123    }
3124    else
3125    {
3126        /* Else K1 = ( L << 1 ) (+) Rb */
3127        SecLib_LeftShiftOneBit(L, tmp);
3128        SecLib_Xor128(tmp, const_Rb, K1);
3129    }
3130
3131    if ((K1[0] & 0x80u) == 0u)
3132    {
3133        SecLib_LeftShiftOneBit(K1, K2);
3134    }
3135    else
3136    {
3137        SecLib_LeftShiftOneBit(K1, tmp);
3138        SecLib_Xor128(tmp, const_Rb, K2);
3139    }
3140}
3141
3142/*! *********************************************************************************
3143 * \brief    Shifts a given vector to the left with one bit.
3144 *
3145 * \param [in]      input         Input vector.
3146 *
3147 * \param [out]     output        Output vector.
3148 *
3149 * \remarks   This is public open source code! Terms of use must be checked before use!
3150 *
3151 ********************************************************************************** */
3152static void SecLib_LeftShiftOneBit(uint8_t *input, uint8_t *output)
3153{
3154    int32_t i;
3155    uint8_t overflow = 0u;
3156
3157    for (i = 15; i >= 0; i--)
3158    {
3159        output[i] = input[i] << 1u;
3160        output[i] |= overflow;
3161        overflow = ((input[i] & 0x80u) > 0u) ? 1u : 0u;
3162    }
3163}