Ignore:
Timestamp:
Jun 22, 2021, 9:00:19 PM (3 years ago)
Author:
coas-nagasima
Message:

WolfSSLとAzure IoT SDKを更新

Location:
azure_iot_hub_f767zi/trunk/wolfssl-4.7.0
Files:
26 edited
1 moved

Legend:

Unmodified
Added
Removed
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/aes.c

    r457 r464  
    2020 */
    2121
    22 
     22/*
     23
     24DESCRIPTION
     25This library provides the interfaces to the Advanced Encryption Standard (AES)
     26for encrypting and decrypting data. AES is the standard known for a symmetric
     27block cipher mechanism that uses n-bit binary string parameter key with 128-bits,
     28192-bits, and 256-bits of key sizes.
     29
     30*/
    2331#ifdef HAVE_CONFIG_H
    2432    #include <config.h>
     
    4553
    4654#include <wolfssl/wolfcrypt/aes.h>
     55
     56#ifdef WOLFSSL_AESNI
     57#include <wmmintrin.h>
     58#include <emmintrin.h>
     59#include <smmintrin.h>
     60#endif /* WOLFSSL_AESNI */
     61
    4762#include <wolfssl/wolfcrypt/cpuid.h>
    4863
    4964#ifdef WOLF_CRYPTO_CB
    5065    #include <wolfssl/wolfcrypt/cryptocb.h>
     66#endif
     67
     68#ifdef WOLFSSL_IMXRT_DCP
     69    #include <wolfssl/wolfcrypt/port/nxp/dcp_port.h>
    5170#endif
    5271
     
    289308/* Define AES implementation includes and functions */
    290309#if defined(STM32_CRYPTO)
    291      /* STM32F2/F4/F7/L4 hardware AES support for ECB, CBC, CTR and GCM modes */
     310     /* STM32F2/F4/F7/L4/L5/H7/WB55 hardware AES support for ECB, CBC, CTR and GCM modes */
    292311
    293312#if defined(WOLFSSL_AES_DIRECT) || defined(HAVE_AESGCM) || defined(HAVE_AESCCM)
     
    308327            return ret;
    309328
    310     #ifdef STM32_CRYPTO_AES_ONLY
     329        ret = wolfSSL_CryptHwMutexLock();
     330        if (ret != 0)
     331            return ret;
     332
     333    #if defined(STM32_HAL_V2)
     334        hcryp.Init.Algorithm  = CRYP_AES_ECB;
     335    #elif defined(STM32_CRYPTO_AES_ONLY)
    311336        hcryp.Init.OperatingMode = CRYP_ALGOMODE_ENCRYPT;
    312337        hcryp.Init.ChainingMode  = CRYP_CHAINMODE_AES_ECB;
    313338        hcryp.Init.KeyWriteFlag  = CRYP_KEY_WRITE_ENABLE;
    314     #elif defined(STM32_HAL_V2)
    315         hcryp.Init.Algorithm  = CRYP_AES_ECB;
    316339    #endif
    317340        HAL_CRYP_Init(&hcryp);
    318341
    319     #ifdef STM32_CRYPTO_AES_ONLY
     342    #if defined(STM32_HAL_V2)
     343        ret = HAL_CRYP_Encrypt(&hcryp, (uint32_t*)inBlock, AES_BLOCK_SIZE,
     344            (uint32_t*)outBlock, STM32_HAL_TIMEOUT);
     345    #elif defined(STM32_CRYPTO_AES_ONLY)
    320346        ret = HAL_CRYPEx_AES(&hcryp, (uint8_t*)inBlock, AES_BLOCK_SIZE,
    321347            outBlock, STM32_HAL_TIMEOUT);
    322     #elif defined(STM32_HAL_V2)
    323         ret = HAL_CRYP_Encrypt(&hcryp, (uint32_t*)inBlock, AES_BLOCK_SIZE,
    324             (uint32_t*)outBlock, STM32_HAL_TIMEOUT);
    325348    #else
    326349        ret = HAL_CRYP_AESECB_Encrypt(&hcryp, (uint8_t*)inBlock, AES_BLOCK_SIZE,
     
    332355        HAL_CRYP_DeInit(&hcryp);
    333356
    334     #else /* STD_PERI_LIB */
     357    #else /* Standard Peripheral Library */
    335358        ret = wc_Stm32_Aes_Init(aes, &cryptInit, &keyInit);
     359        if (ret != 0)
     360            return ret;
     361
     362        ret = wolfSSL_CryptHwMutexLock();
    336363        if (ret != 0)
    337364            return ret;
     
    370397        CRYP_Cmd(DISABLE);
    371398    #endif /* WOLFSSL_STM32_CUBEMX */
     399        wolfSSL_CryptHwMutexUnLock();
    372400
    373401        return ret;
     
    392420            return ret;
    393421
    394     #ifdef STM32_CRYPTO_AES_ONLY
    395         hcryp.Init.OperatingMode = CRYP_ALGOMODE_DECRYPT;
     422        ret = wolfSSL_CryptHwMutexLock();
     423        if (ret != 0)
     424            return ret;
     425
     426    #if defined(STM32_HAL_V2)
     427        hcryp.Init.Algorithm  = CRYP_AES_ECB;
     428    #elif defined(STM32_CRYPTO_AES_ONLY)
     429        hcryp.Init.OperatingMode = CRYP_ALGOMODE_KEYDERIVATION_DECRYPT;
    396430        hcryp.Init.ChainingMode  = CRYP_CHAINMODE_AES_ECB;
    397431        hcryp.Init.KeyWriteFlag  = CRYP_KEY_WRITE_ENABLE;
    398     #elif defined(STM32_HAL_V2)
    399         hcryp.Init.Algorithm  = CRYP_AES_ECB;
    400432    #endif
    401433        HAL_CRYP_Init(&hcryp);
    402434
    403     #ifdef STM32_CRYPTO_AES_ONLY
     435    #if defined(STM32_HAL_V2)
     436        ret = HAL_CRYP_Decrypt(&hcryp, (uint32_t*)inBlock, AES_BLOCK_SIZE,
     437            (uint32_t*)outBlock, STM32_HAL_TIMEOUT);
     438    #elif defined(STM32_CRYPTO_AES_ONLY)
    404439        ret = HAL_CRYPEx_AES(&hcryp, (uint8_t*)inBlock, AES_BLOCK_SIZE,
    405440            outBlock, STM32_HAL_TIMEOUT);
    406     #elif defined(STM32_HAL_V2)
    407         ret = HAL_CRYP_Decrypt(&hcryp, (uint32_t*)inBlock, AES_BLOCK_SIZE,
    408             (uint32_t*)outBlock, STM32_HAL_TIMEOUT);
    409441    #else
    410442        ret = HAL_CRYP_AESECB_Decrypt(&hcryp, (uint8_t*)inBlock, AES_BLOCK_SIZE,
     
    416448        HAL_CRYP_DeInit(&hcryp);
    417449
    418     #else /* STD_PERI_LIB */
     450    #else /* Standard Peripheral Library */
    419451        ret = wc_Stm32_Aes_Init(aes, &cryptInit, &keyInit);
     452        if (ret != 0)
     453            return ret;
     454
     455        ret = wolfSSL_CryptHwMutexLock();
    420456        if (ret != 0)
    421457            return ret;
     
    463499        CRYP_Cmd(DISABLE);
    464500    #endif /* WOLFSSL_STM32_CUBEMX */
     501        wolfSSL_CryptHwMutexUnLock();
    465502
    466503        return ret;
     
    481518        #undef NEED_AES_TABLES
    482519        #undef GCM_TABLE
    483     #else
     520    #endif
     521
    484522        /* if LTC doesn't have GCM, use software with LTC AES ECB mode */
    485523        static int wc_AesEncrypt(Aes* aes, const byte* inBlock, byte* outBlock)
    486524        {
    487             wc_AesEncryptDirect(aes, outBlock, inBlock);
     525            word32 keySize = 0;
     526            byte* key = (byte*)aes->key;
     527            wc_AesGetKeySize(aes, &keySize);
     528
     529            if (wolfSSL_CryptHwMutexLock() == 0) {
     530                LTC_AES_EncryptEcb(LTC_BASE, inBlock, outBlock, AES_BLOCK_SIZE,
     531                    key, keySize);
     532                wolfSSL_CryptHwMutexUnLock();
     533            }
    488534            return 0;
    489535        }
     536        #ifdef HAVE_AES_DECRYPT
    490537        static int wc_AesDecrypt(Aes* aes, const byte* inBlock, byte* outBlock)
    491538        {
    492             wc_AesDecryptDirect(aes, outBlock, inBlock);
     539            word32 keySize = 0;
     540            byte* key = (byte*)aes->key;
     541            wc_AesGetKeySize(aes, &keySize);
     542
     543            if (wolfSSL_CryptHwMutexLock() == 0) {
     544                LTC_AES_DecryptEcb(LTC_BASE, inBlock, outBlock, AES_BLOCK_SIZE,
     545                    key, keySize, kLTC_EncryptKey);
     546                wolfSSL_CryptHwMutexUnLock();
     547            }
    493548            return 0;
    494549        }
    495     #endif
     550        #endif
     551
    496552#elif defined(FREESCALE_MMCAU)
    497553    /* Freescale mmCAU hardware AES support for Direct, CBC, CCM, GCM modes
     
    508564    static int wc_AesEncrypt(Aes* aes, const byte* inBlock, byte* outBlock)
    509565    {
    510         int ret;
    511 
    512     #ifdef FREESCALE_MMCAU_CLASSIC
    513         if ((wolfssl_word)outBlock % WOLFSSL_MMCAU_ALIGNMENT) {
    514             WOLFSSL_MSG("Bad cau_aes_encrypt alignment");
    515             return BAD_ALIGN_E;
    516         }
    517     #endif
    518 
    519         ret = wolfSSL_CryptHwMutexLock();
    520         if(ret == 0) {
     566        if (wolfSSL_CryptHwMutexLock() == 0) {
    521567        #ifdef FREESCALE_MMCAU_CLASSIC
     568            if ((wolfssl_word)outBlock % WOLFSSL_MMCAU_ALIGNMENT) {
     569                WOLFSSL_MSG("Bad cau_aes_encrypt alignment");
     570                return BAD_ALIGN_E;
     571            }
    522572            cau_aes_encrypt(inBlock, (byte*)aes->key, aes->rounds, outBlock);
    523573        #else
     
    527577            wolfSSL_CryptHwMutexUnLock();
    528578        }
    529         return ret;
     579        return 0;
    530580    }
    531581    #ifdef HAVE_AES_DECRYPT
    532582    static int wc_AesDecrypt(Aes* aes, const byte* inBlock, byte* outBlock)
    533583    {
    534         int ret;
    535 
    536     #ifdef FREESCALE_MMCAU_CLASSIC
    537         if ((wolfssl_word)outBlock % WOLFSSL_MMCAU_ALIGNMENT) {
    538             WOLFSSL_MSG("Bad cau_aes_decrypt alignment");
    539             return BAD_ALIGN_E;
    540         }
    541     #endif
    542 
    543         ret = wolfSSL_CryptHwMutexLock();
    544         if(ret == 0) {
     584        if (wolfSSL_CryptHwMutexLock() == 0) {
    545585        #ifdef FREESCALE_MMCAU_CLASSIC
     586            if ((wolfssl_word)outBlock % WOLFSSL_MMCAU_ALIGNMENT) {
     587                WOLFSSL_MSG("Bad cau_aes_decrypt alignment");
     588                return BAD_ALIGN_E;
     589            }
    546590            cau_aes_decrypt(inBlock, (byte*)aes->key, aes->rounds, outBlock);
    547591        #else
     
    551595            wolfSSL_CryptHwMutexUnLock();
    552596        }
    553         return ret;
     597        return 0;
    554598    }
    555599    #endif /* HAVE_AES_DECRYPT */
     
    562606    static int wc_AesEncrypt(Aes* aes, const byte* inBlock, byte* outBlock)
    563607    {
     608        /* Thread mutex protection handled in Pic32Crypto */
    564609        return wc_Pic32AesCrypt(aes->key, aes->keylen, NULL, 0,
    565610            outBlock, inBlock, AES_BLOCK_SIZE,
     
    571616    static int wc_AesDecrypt(Aes* aes, const byte* inBlock, byte* outBlock)
    572617    {
     618        /* Thread mutex protection handled in Pic32Crypto */
    573619        return wc_Pic32AesCrypt(aes->key, aes->keylen, NULL, 0,
    574620            outBlock, inBlock, AES_BLOCK_SIZE,
     
    583629    static int wc_AesEncrypt(Aes* aes, const byte* inBlock, byte* outBlock)
    584630    {
    585         return nrf51_aes_encrypt(inBlock, (byte*)aes->key, aes->rounds, outBlock);
     631        int ret;
     632        ret = wolfSSL_CryptHwMutexLock();
     633        if (ret == 0) {
     634            ret = nrf51_aes_encrypt(inBlock, (byte*)aes->key, aes->rounds, outBlock);
     635            wolfSSL_CryptHwMutexUnLock();
     636        }
     637        return ret;
    586638    }
    587639
     
    598650    static int wc_AesEncrypt(Aes* aes, const byte* inBlock, byte* outBlock)
    599651    {
     652        /* Thread mutex protection handled in esp_aes_hw_InUse */
    600653        return wc_esp32AesEncrypt(aes, inBlock, outBlock);
    601654    }
     
    605658    static int wc_AesDecrypt(Aes* aes, const byte* inBlock, byte* outBlock)
    606659    {
     660        /* Thread mutex protection handled in esp_aes_hw_InUse */
    607661       return wc_esp32AesDecrypt(aes, inBlock, outBlock);
    608662    }
     
    722776        {
    723777            int nr;
    724             Aes temp_key;
    725             __m128i *Key_Schedule = (__m128i*)aes->key;
    726             __m128i *Temp_Key_Schedule = (__m128i*)temp_key.key;
     778#ifdef WOLFSSL_SMALL_STACK
     779            Aes *temp_key;
     780#else
     781            Aes temp_key[1];
     782#endif
     783            __m128i *Key_Schedule;
     784            __m128i *Temp_Key_Schedule;
    727785
    728786            if (!userKey || !aes)
    729787                return BAD_FUNC_ARG;
    730788
    731             if (AES_set_encrypt_key(userKey,bits,&temp_key) == BAD_FUNC_ARG)
     789#ifdef WOLFSSL_SMALL_STACK
     790            if ((temp_key = (Aes *)XMALLOC(sizeof *aes, aes->heap,
     791                                           DYNAMIC_TYPE_AES)) == NULL)
     792                return MEMORY_E;
     793#endif
     794
     795            if (AES_set_encrypt_key(userKey,bits,temp_key) == BAD_FUNC_ARG) {
     796#ifdef WOLFSSL_SMALL_STACK
     797                XFREE(temp_key, aes->heap, DYNAMIC_TYPE_AES);
     798#endif
    732799                return BAD_FUNC_ARG;
    733 
    734             nr = temp_key.rounds;
     800            }
     801
     802            Key_Schedule = (__m128i*)aes->key;
     803            Temp_Key_Schedule = (__m128i*)temp_key->key;
     804
     805            nr = temp_key->rounds;
    735806            aes->rounds = nr;
     807
     808            SAVE_VECTOR_REGISTERS();
    736809
    737810            Key_Schedule[nr] = Temp_Key_Schedule[0];
     
    758831            Key_Schedule[0] = Temp_Key_Schedule[nr];
    759832
     833            RESTORE_VECTOR_REGISTERS();
     834
     835#ifdef WOLFSSL_SMALL_STACK
     836            XFREE(temp_key, aes->heap, DYNAMIC_TYPE_AES);
     837#endif
     838
    760839            return 0;
    761840        }
     
    772851
    773852#elif defined(WOLFSSL_AFALG)
     853    /* implemented in wolfcrypt/src/port/af_alg/afalg_aes.c */
     854
    774855#elif defined(WOLFSSL_DEVCRYPTO_AES)
     856    /* implemented in wolfcrypt/src/port/devcrypto/devcrypto_aes.c */
    775857
    776858#elif defined(WOLFSSL_SCE) && !defined(WOLFSSL_SCE_NO_AES)
     
    792874            int sz)
    793875    {
    794         uint32_t ret;
     876        word32 ret;
    795877
    796878        if (WOLFSSL_SCE_GSCE_HANDLE.p_cfg->endian_flag ==
     
    830912
    831913        if (ret != SSP_SUCCESS) {
    832            /* revert input */
     914            /* revert input */
    833915            ByteReverseWords((word32*)inBlock, (word32*)inBlock, sz);
    834916            return WC_HW_E;
     
    850932            int sz)
    851933    {
    852         uint32_t ret;
     934        word32 ret;
    853935
    854936        if (WOLFSSL_SCE_GSCE_HANDLE.p_cfg->endian_flag ==
     
    901983        return 0;
    902984    }
    903 
    904     #endif
     985    #endif /* HAVE_AES_DECRYPT */
    905986
    906987    #if defined(HAVE_AESGCM) || defined(WOLFSSL_AES_DIRECT)
     
    9271008#ifdef NEED_AES_TABLES
    9281009
    929 static const word32 rcon[] = {
     1010static const FLASH_QUALIFIER word32 rcon[] = {
    9301011    0x01000000, 0x02000000, 0x04000000, 0x08000000,
    9311012    0x10000000, 0x20000000, 0x40000000, 0x80000000,
     
    9351016
    9361017#ifndef WOLFSSL_AES_SMALL_TABLES
    937 static const word32 Te[4][256] = {
     1018static const FLASH_QUALIFIER word32 Te[4][256] = {
    9381019{
    9391020    0xc66363a5U, 0xf87c7c84U, 0xee777799U, 0xf67b7b8dU,
     
    12031284
    12041285#ifdef HAVE_AES_DECRYPT
    1205 static const word32 Td[4][256] = {
     1286static const FLASH_QUALIFIER word32 Td[4][256] = {
    12061287{
    12071288    0x51f4a750U, 0x7e416553U, 0x1a17a4c3U, 0x3a275e96U,
     
    14711552};
    14721553#endif /* HAVE_AES_DECRYPT */
    1473 #endif
     1554#endif /* WOLFSSL_AES_SMALL_TABLES */
    14741555
    14751556#ifdef HAVE_AES_DECRYPT
    14761557#if (defined(HAVE_AES_CBC) && !defined(WOLFSSL_DEVCRYPTO_CBC)) \
    1477                         || defined(WOLFSSL_AES_DIRECT)
    1478 static const byte Td4[256] =
     1558            || defined(WOLFSSL_AES_DIRECT)
     1559static const FLASH_QUALIFIER byte Td4[256] =
    14791560{
    14801561    0x52U, 0x09U, 0x6aU, 0xd5U, 0x30U, 0x36U, 0xa5U, 0x38U,
     
    15621643}
    15631644
     1645#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT)
    15641646static word32 inv_col_mul(word32 t, int i9, int ib, int id, int ie)
    15651647{
     
    15721654}
    15731655#endif
    1574 
    1575 #if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) || defined(HAVE_AESGCM)
     1656#endif
     1657
     1658#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_DIRECT) || \
     1659                                    defined(HAVE_AESCCM) || defined(HAVE_AESGCM)
    15761660
    15771661#ifndef WC_CACHE_LINE_SZ
     
    15861670
    15871671
     1672#ifndef WC_NO_CACHE_RESISTANT
    15881673#ifndef WOLFSSL_AES_SMALL_TABLES
    15891674/* load 4 Te Tables into cache by cache line stride */
     
    16141699}
    16151700#endif
     1701#endif
    16161702
    16171703/* Software AES - ECB Encrypt */
     
    16231709    const word32* rk = aes->key;
    16241710
     1711#ifdef DEBUG_WOLFSSL
    16251712    if (r > 7 || r == 0) {
    16261713        WOLFSSL_MSG("AesEncrypt encountered improper key, set it up");
    16271714        return;  /* stop instead of seg-faulting, set up your keys! */
    16281715    }
     1716#endif
    16291717
    16301718#ifdef WOLFSSL_AESNI
     
    16501738
    16511739            XMEMCPY(tmp_align, inBlock, AES_BLOCK_SIZE);
     1740            SAVE_VECTOR_REGISTERS();
    16521741            AES_ECB_encrypt(tmp_align, tmp_align, AES_BLOCK_SIZE,
    16531742                    (byte*)aes->key, aes->rounds);
     1743            RESTORE_VECTOR_REGISTERS();
    16541744            XMEMCPY(outBlock, tmp_align, AES_BLOCK_SIZE);
    16551745            XFREE(tmp, aes->heap, DYNAMIC_TYPE_TMP_BUFFER);
     
    16611751        }
    16621752
     1753        SAVE_VECTOR_REGISTERS();
    16631754        AES_ECB_encrypt(inBlock, outBlock, AES_BLOCK_SIZE, (byte*)aes->key,
    16641755                        aes->rounds);
     1756        RESTORE_VECTOR_REGISTERS();
    16651757
    16661758        return;
     
    16751767    AES_ECB_encrypt(aes, inBlock, outBlock, AES_BLOCK_SIZE);
    16761768    return;
     1769#endif
     1770
     1771#if defined(WOLFSSL_IMXRT_DCP)
     1772    if (aes->keylen == 16) {
     1773        DCPAesEcbEncrypt(aes, outBlock, inBlock, AES_BLOCK_SIZE);
     1774        return;
     1775    }
    16771776#endif
    16781777
     
    16821781     */
    16831782    XMEMCPY(&s0, inBlock,                  sizeof(s0));
    1684     XMEMCPY(&s1, inBlock + sizeof(s0),    sizeof(s1));
     1783    XMEMCPY(&s1, inBlock +     sizeof(s0), sizeof(s1));
    16851784    XMEMCPY(&s2, inBlock + 2 * sizeof(s0), sizeof(s2));
    16861785    XMEMCPY(&s3, inBlock + 3 * sizeof(s0), sizeof(s3));
     
    17001799
    17011800#ifndef WOLFSSL_AES_SMALL_TABLES
     1801#ifndef WC_NO_CACHE_RESISTANT
    17021802    s0 |= PreFetchTe();
    1703 
     1803#endif
     1804
     1805#ifndef WOLFSSL_AES_NO_UNROLL
     1806/* Unroll the loop. */
     1807#define ENC_ROUND_T_S(o)                                          \
     1808    t0 = Te[0][GETBYTE(s0, 3)] ^ Te[1][GETBYTE(s1, 2)] ^          \
     1809         Te[2][GETBYTE(s2, 1)] ^ Te[3][GETBYTE(s3, 0)] ^ rk[o+4]; \
     1810    t1 = Te[0][GETBYTE(s1, 3)] ^ Te[1][GETBYTE(s2, 2)] ^          \
     1811         Te[2][GETBYTE(s3, 1)] ^ Te[3][GETBYTE(s0, 0)] ^ rk[o+5]; \
     1812    t2 = Te[0][GETBYTE(s2, 3)] ^ Te[1][GETBYTE(s3, 2)] ^          \
     1813         Te[2][GETBYTE(s0, 1)] ^ Te[3][GETBYTE(s1, 0)] ^ rk[o+6]; \
     1814    t3 = Te[0][GETBYTE(s3, 3)] ^ Te[1][GETBYTE(s0, 2)] ^          \
     1815         Te[2][GETBYTE(s1, 1)] ^ Te[3][GETBYTE(s2, 0)] ^ rk[o+7]
     1816#define ENC_ROUND_S_T(o)                                          \
     1817    s0 = Te[0][GETBYTE(t0, 3)] ^ Te[1][GETBYTE(t1, 2)] ^          \
     1818         Te[2][GETBYTE(t2, 1)] ^ Te[3][GETBYTE(t3, 0)] ^ rk[o+0]; \
     1819    s1 = Te[0][GETBYTE(t1, 3)] ^ Te[1][GETBYTE(t2, 2)] ^          \
     1820         Te[2][GETBYTE(t3, 1)] ^ Te[3][GETBYTE(t0, 0)] ^ rk[o+1]; \
     1821    s2 = Te[0][GETBYTE(t2, 3)] ^ Te[1][GETBYTE(t3, 2)] ^          \
     1822         Te[2][GETBYTE(t0, 1)] ^ Te[3][GETBYTE(t1, 0)] ^ rk[o+2]; \
     1823    s3 = Te[0][GETBYTE(t3, 3)] ^ Te[1][GETBYTE(t0, 2)] ^          \
     1824         Te[2][GETBYTE(t1, 1)] ^ Te[3][GETBYTE(t2, 0)] ^ rk[o+3]
     1825
     1826                       ENC_ROUND_T_S( 0);
     1827    ENC_ROUND_S_T( 8); ENC_ROUND_T_S( 8);
     1828    ENC_ROUND_S_T(16); ENC_ROUND_T_S(16);
     1829    ENC_ROUND_S_T(24); ENC_ROUND_T_S(24);
     1830    ENC_ROUND_S_T(32); ENC_ROUND_T_S(32);
     1831    if (r > 5) {
     1832        ENC_ROUND_S_T(40); ENC_ROUND_T_S(40);
     1833        if (r > 6) {
     1834            ENC_ROUND_S_T(48); ENC_ROUND_T_S(48);
     1835        }
     1836    }
     1837    rk += r * 8;
     1838#else
    17041839    /*
    17051840     * Nr - 1 full rounds:
     
    17621897            rk[3];
    17631898    }
     1899#endif
    17641900
    17651901    /*
     
    17931929        rk[3];
    17941930#else
     1931#ifndef WC_NO_CACHE_RESISTANT
    17951932    s0 |= PreFetchSBox();
     1933#endif
    17961934
    17971935    r *= 2;
     
    18802018
    18812019    XMEMCPY(outBlock,                  &s0, sizeof(s0));
    1882     XMEMCPY(outBlock + sizeof(s0),    &s1, sizeof(s1));
     2020    XMEMCPY(outBlock +     sizeof(s0), &s1, sizeof(s1));
    18832021    XMEMCPY(outBlock + 2 * sizeof(s0), &s2, sizeof(s2));
    18842022    XMEMCPY(outBlock + 3 * sizeof(s0), &s3, sizeof(s3));
     
    18912029     defined(WOLFSSL_AES_DIRECT)
    18922030
     2031#ifndef WC_NO_CACHE_RESISTANT
    18932032#ifndef WOLFSSL_AES_SMALL_TABLES
    18942033/* load 4 Td Tables into cache by cache line stride */
     
    19192058    return x;
    19202059}
     2060#endif
    19212061
    19222062/* Software AES - ECB Decrypt */
     
    19262066    word32 t0, t1, t2, t3;
    19272067    word32 r = aes->rounds >> 1;
    1928 
    19292068    const word32* rk = aes->key;
     2069
     2070#ifdef DEBUG_WOLFSSL
    19302071    if (r > 7 || r == 0) {
    19312072        WOLFSSL_MSG("AesDecrypt encountered improper key, set it up");
    19322073        return;  /* stop instead of seg-faulting, set up your keys! */
    19332074    }
     2075#endif
     2076
    19342077#ifdef WOLFSSL_AESNI
    19352078    if (haveAESNI && aes->use_aesni) {
     
    19462089        if ((const byte*)aes->tmp != inBlock)
    19472090            XMEMCPY(aes->tmp, inBlock, AES_BLOCK_SIZE);
     2091        SAVE_VECTOR_REGISTERS();
    19482092        AES_ECB_decrypt(inBlock, outBlock, AES_BLOCK_SIZE, (byte*)aes->key,
    19492093                        aes->rounds);
     2094        RESTORE_VECTOR_REGISTERS();
    19502095        return;
    19512096    }
     
    19582103#if defined(WOLFSSL_SCE) && !defined(WOLFSSL_SCE_NO_AES)
    19592104    return AES_ECB_decrypt(aes, inBlock, outBlock, AES_BLOCK_SIZE);
     2105#endif
     2106#if defined(WOLFSSL_IMXRT_DCP)
     2107    if (aes->keylen == 16) {
     2108        DCPAesEcbDecrypt(aes, outBlock, inBlock, AES_BLOCK_SIZE);
     2109        return;
     2110    }
    19602111#endif
    19612112
     
    19822133
    19832134#ifndef WOLFSSL_AES_SMALL_TABLES
     2135#ifndef WC_NO_CACHE_RESISTANT
    19842136    s0 |= PreFetchTd();
     2137#endif
     2138
     2139#ifndef WOLFSSL_AES_NO_UNROLL
     2140/* Unroll the loop. */
     2141#define DEC_ROUND_T_S(o)                                          \
     2142    t0 = Td[0][GETBYTE(s0, 3)] ^ Td[1][GETBYTE(s3, 2)] ^          \
     2143         Td[2][GETBYTE(s2, 1)] ^ Td[3][GETBYTE(s1, 0)] ^ rk[o+4]; \
     2144    t1 = Td[0][GETBYTE(s1, 3)] ^ Td[1][GETBYTE(s0, 2)] ^          \
     2145         Td[2][GETBYTE(s3, 1)] ^ Td[3][GETBYTE(s2, 0)] ^ rk[o+5]; \
     2146    t2 = Td[0][GETBYTE(s2, 3)] ^ Td[1][GETBYTE(s1, 2)] ^          \
     2147         Td[2][GETBYTE(s0, 1)] ^ Td[3][GETBYTE(s3, 0)] ^ rk[o+6]; \
     2148    t3 = Td[0][GETBYTE(s3, 3)] ^ Td[1][GETBYTE(s2, 2)] ^          \
     2149         Td[2][GETBYTE(s1, 1)] ^ Td[3][GETBYTE(s0, 0)] ^ rk[o+7]
     2150#define DEC_ROUND_S_T(o)                                          \
     2151    s0 = Td[0][GETBYTE(t0, 3)] ^ Td[1][GETBYTE(t3, 2)] ^          \
     2152         Td[2][GETBYTE(t2, 1)] ^ Td[3][GETBYTE(t1, 0)] ^ rk[o+0]; \
     2153    s1 = Td[0][GETBYTE(t1, 3)] ^ Td[1][GETBYTE(t0, 2)] ^          \
     2154         Td[2][GETBYTE(t3, 1)] ^ Td[3][GETBYTE(t2, 0)] ^ rk[o+1]; \
     2155    s2 = Td[0][GETBYTE(t2, 3)] ^ Td[1][GETBYTE(t1, 2)] ^          \
     2156         Td[2][GETBYTE(t0, 1)] ^ Td[3][GETBYTE(t3, 0)] ^ rk[o+2]; \
     2157    s3 = Td[0][GETBYTE(t3, 3)] ^ Td[1][GETBYTE(t2, 2)] ^          \
     2158         Td[2][GETBYTE(t1, 1)] ^ Td[3][GETBYTE(t0, 0)] ^ rk[o+3]
     2159
     2160                       DEC_ROUND_T_S( 0);
     2161    DEC_ROUND_S_T( 8); DEC_ROUND_T_S( 8);
     2162    DEC_ROUND_S_T(16); DEC_ROUND_T_S(16);
     2163    DEC_ROUND_S_T(24); DEC_ROUND_T_S(24);
     2164    DEC_ROUND_S_T(32); DEC_ROUND_T_S(32);
     2165    if (r > 5) {
     2166        DEC_ROUND_S_T(40); DEC_ROUND_T_S(40);
     2167        if (r > 6) {
     2168            DEC_ROUND_S_T(48); DEC_ROUND_T_S(48);
     2169        }
     2170    }
     2171    rk += r * 8;
     2172#else
    19852173
    19862174    /*
     
    20442232            rk[3];
    20452233    }
     2234#endif
    20462235    /*
    20472236     * apply last round and
     
    20492238     */
    20502239
     2240#ifndef WC_NO_CACHE_RESISTANT
    20512241    t0 |= PreFetchTd4();
     2242#endif
    20522243
    20532244    s0 =
     
    20762267        rk[3];
    20772268#else
     2269#ifndef WC_NO_CACHE_RESISTANT
    20782270    s0 |= PreFetchTd4();
     2271#endif
    20792272
    20802273    r *= 2;
     
    22022395        aes->left = 0;
    22032396    #endif
    2204 
    22052397        return wc_AesSetIV(aes, iv);
    22062398    }
     
    23892581        aes->keylen = keylen;
    23902582        aes->rounds = keylen/4 + 6;
     2583        XMEMCPY(aes->key, userKey, keylen);
    23912584        ret = nrf51_aes_set_key(userKey);
    23922585
     
    24752668        XMEMCPY(aes->key, userKey, keylen);
    24762669
    2477         aes->ctx.key.pKey = (uint8_t*)aes->key;
     2670        aes->ctx.key.pKey = (byte*)aes->key;
    24782671        aes->ctx.key.keySize= keylen;
    24792672
     
    25172710    /* implemented in wolfcrypt/src/port/devcrypto/devcrypto_aes.c */
    25182711
     2712#elif defined(WOLFSSL_SILABS_SE_ACCEL)
     2713    /* implemented in wolfcrypt/src/port/silabs/silabs_hash.c */
     2714
    25192715#else
    25202716
    25212717    /* Software AES - SetKey */
    25222718    static int wc_AesSetKeyLocal(Aes* aes, const byte* userKey, word32 keylen,
    2523                 const byte* iv, int dir)
     2719                const byte* iv, int dir, int checkKeyLen)
    25242720    {
    2525         word32 *rk = aes->key;
     2721        int ret;
     2722        word32 *rk;
    25262723    #ifdef NEED_AES_TABLES
    25272724        word32 temp;
    25282725        unsigned int i = 0;
    25292726    #endif
    2530 
    2531         #ifdef WOLFSSL_AESNI
    2532             aes->use_aesni = 0;
    2533         #endif /* WOLFSSL_AESNI */
    2534         #if defined(WOLFSSL_AES_CFB) || defined(WOLFSSL_AES_COUNTER) || \
    2535             defined(WOLFSSL_AES_OFB)
    2536             aes->left = 0;
     2727    #ifdef WOLFSSL_IMX6_CAAM_BLOB
     2728        byte   local[32];
     2729        word32 localSz = 32;
     2730    #endif
     2731
     2732    #ifdef WOLFSSL_IMX6_CAAM_BLOB
     2733        if (keylen == (16 + WC_CAAM_BLOB_SZ) ||
     2734            keylen == (24 + WC_CAAM_BLOB_SZ) ||
     2735            keylen == (32 + WC_CAAM_BLOB_SZ)) {
     2736            if (wc_caamOpenBlob((byte*)userKey, keylen, local, &localSz) != 0) {
     2737                return BAD_FUNC_ARG;
     2738            }
     2739
     2740            /* set local values */
     2741            userKey = local;
     2742            keylen = localSz;
     2743        }
     2744    #endif
     2745
     2746    #if defined(WOLF_CRYPTO_CB) || (defined(WOLFSSL_DEVCRYPTO) && \
     2747        (defined(WOLFSSL_DEVCRYPTO_AES) || defined(WOLFSSL_DEVCRYPTO_CBC))) || \
     2748        (defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_AES))
     2749        #ifdef WOLF_CRYPTO_CB
     2750        if (aes->devId != INVALID_DEVID)
    25372751        #endif
     2752        {
     2753            if (keylen > sizeof(aes->devKey)) {
     2754                return BAD_FUNC_ARG;
     2755            }
     2756            XMEMCPY(aes->devKey, userKey, keylen);
     2757        }
     2758    #endif
     2759
     2760        if (checkKeyLen) {
     2761            if (keylen != 16 && keylen != 24 && keylen != 32) {
     2762                return BAD_FUNC_ARG;
     2763            }
     2764        #ifdef AES_MAX_KEY_SIZE
     2765            /* Check key length */
     2766            if (keylen > (AES_MAX_KEY_SIZE / 8)) {
     2767                return BAD_FUNC_ARG;
     2768            }
     2769        #endif
     2770        }
     2771
     2772    #if defined(WOLFSSL_AES_CFB) || defined(WOLFSSL_AES_COUNTER) || \
     2773        defined(WOLFSSL_AES_OFB)
     2774        aes->left = 0;
     2775    #endif
    25382776
    25392777        aes->keylen = keylen;
    25402778        aes->rounds = (keylen/4) + 6;
    25412779
     2780    #ifdef WOLFSSL_AESNI
     2781        aes->use_aesni = 0;
     2782        if (checkAESNI == 0) {
     2783            haveAESNI  = Check_CPU_support_AES();
     2784            checkAESNI = 1;
     2785        }
     2786        if (haveAESNI) {
     2787            aes->use_aesni = 1;
     2788            if (iv)
     2789                XMEMCPY(aes->reg, iv, AES_BLOCK_SIZE);
     2790            else
     2791                XMEMSET(aes->reg, 0, AES_BLOCK_SIZE);
     2792            if (dir == AES_ENCRYPTION)
     2793                return AES_set_encrypt_key(userKey, keylen * 8, aes);
     2794        #ifdef HAVE_AES_DECRYPT
     2795            else
     2796                return AES_set_decrypt_key(userKey, keylen * 8, aes);
     2797        #endif
     2798        }
     2799    #endif /* WOLFSSL_AESNI */
     2800
     2801        if (keylen > sizeof(aes->key)) {
     2802            return BAD_FUNC_ARG;
     2803        }
     2804        rk = aes->key;
    25422805        XMEMCPY(rk, userKey, keylen);
    25432806    #if defined(LITTLE_ENDIAN_ORDER) && !defined(WOLFSSL_PIC32MZ_CRYPT) && \
     
    25452808          defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_AES))
    25462809        ByteReverseWords(rk, rk, keylen);
     2810    #endif
     2811
     2812    #ifdef WOLFSSL_IMXRT_DCP
     2813        /* Implemented in wolfcrypt/src/port/nxp/dcp_port.c */
     2814        temp = 0;
     2815        if (keylen == 16)
     2816            temp = DCPAesSetKey(aes, userKey, keylen, iv, dir);
     2817        if (temp != 0)
     2818            return WC_HW_E;
    25472819    #endif
    25482820
     
    26592931            return BAD_FUNC_ARG;
    26602932        } /* switch */
     2933        ForceZero(&temp, sizeof(temp));
    26612934
    26622935    #if defined(HAVE_AES_DECRYPT)
     
    26722945                temp = rk[i + 3]; rk[i + 3] = rk[j + 3]; rk[j + 3] = temp;
    26732946            }
     2947            ForceZero(&temp, sizeof(temp));
    26742948        #if !defined(WOLFSSL_AES_SMALL_TABLES)
    26752949            /* apply the inverse MixColumn transform to all round keys but the
     
    27132987#endif
    27142988
    2715         return wc_AesSetIV(aes, iv);
    2716     }
    2717 
    2718     int wc_AesSetKey(Aes* aes, const byte* userKey, word32 keylen,
    2719         const byte* iv, int dir)
    2720     {
    2721         int ret;
    2722     #if defined(AES_MAX_KEY_SIZE)
    2723         const word32 max_key_len = (AES_MAX_KEY_SIZE / 8);
    2724     #endif
    2725 
    2726     #ifdef WOLFSSL_IMX6_CAAM_BLOB
    2727         byte   local[32];
    2728         word32 localSz = 32;
    2729 
    2730         if (keylen == (16 + WC_CAAM_BLOB_SZ) ||
    2731                 keylen == (24 + WC_CAAM_BLOB_SZ) ||
    2732                 keylen == (32 + WC_CAAM_BLOB_SZ)) {
    2733             if (wc_caamOpenBlob((byte*)userKey, keylen, local, &localSz) != 0) {
    2734                 return BAD_FUNC_ARG;
    2735             }
    2736 
    2737             /* set local values */
    2738             userKey = local;
    2739             keylen = localSz;
    2740         }
    2741     #endif
    2742         if (aes == NULL ||
    2743                 !((keylen == 16) || (keylen == 24) || (keylen == 32))) {
    2744             return BAD_FUNC_ARG;
    2745         }
    2746 
    2747     #if defined(AES_MAX_KEY_SIZE)
    2748         /* Check key length */
    2749         if (keylen > max_key_len) {
    2750             return BAD_FUNC_ARG;
    2751         }
    2752     #endif
    2753         aes->keylen = keylen;
    2754         aes->rounds = keylen/4 + 6;
    2755 
    2756     #if defined(WOLF_CRYPTO_CB) || (defined(WOLFSSL_DEVCRYPTO) && \
    2757         (defined(WOLFSSL_DEVCRYPTO_AES) || defined(WOLFSSL_DEVCRYPTO_CBC))) || \
    2758         (defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_AES))
    2759         #ifdef WOLF_CRYPTO_CB
    2760         if (aes->devId != INVALID_DEVID)
    2761         #endif
    2762         {
    2763             XMEMCPY(aes->devKey, userKey, keylen);
    2764         }
    2765     #endif
    2766 
    2767     #ifdef WOLFSSL_AESNI
    2768         if (checkAESNI == 0) {
    2769             haveAESNI  = Check_CPU_support_AES();
    2770             checkAESNI = 1;
    2771         }
    2772         if (haveAESNI) {
    2773             #if defined(WOLFSSL_AES_COUNTER) || defined(WOLFSSL_AES_CFB) || \
    2774                 defined(WOLFSSL_AES_OFB)
    2775                 aes->left = 0;
    2776             #endif /* WOLFSSL_AES_COUNTER */
    2777             aes->use_aesni = 1;
    2778             if (iv)
    2779                 XMEMCPY(aes->reg, iv, AES_BLOCK_SIZE);
    2780             else
    2781                 XMEMSET(aes->reg, 0, AES_BLOCK_SIZE);
    2782             if (dir == AES_ENCRYPTION)
    2783                 return AES_set_encrypt_key(userKey, keylen * 8, aes);
    2784         #ifdef HAVE_AES_DECRYPT
    2785             else
    2786                 return AES_set_decrypt_key(userKey, keylen * 8, aes);
    2787         #endif
    2788         }
    2789     #endif /* WOLFSSL_AESNI */
    2790 
    2791         ret = wc_AesSetKeyLocal(aes, userKey, keylen, iv, dir);
     2989        ret = wc_AesSetIV(aes, iv);
    27922990
    27932991    #if defined(WOLFSSL_DEVCRYPTO) && \
     
    28012999    }
    28023000
     3001    int wc_AesSetKey(Aes* aes, const byte* userKey, word32 keylen,
     3002        const byte* iv, int dir)
     3003    {
     3004        if (aes == NULL) {
     3005            return BAD_FUNC_ARG;
     3006        }
     3007        if (keylen > sizeof(aes->key)) {
     3008            return BAD_FUNC_ARG;
     3009        }
     3010
     3011        return wc_AesSetKeyLocal(aes, userKey, keylen, iv, dir, 1);
     3012    }
     3013
    28033014    #if defined(WOLFSSL_AES_DIRECT) || defined(WOLFSSL_AES_COUNTER)
    2804         /* AES-CTR and AES-DIRECT need to use this for key setup, no aesni yet */
     3015        /* AES-CTR and AES-DIRECT need to use this for key setup */
     3016        /* This function allows key sizes that are not 128/192/256 bits */
    28053017        int wc_AesSetKeyDirect(Aes* aes, const byte* userKey, word32 keylen,
    28063018                            const byte* iv, int dir)
    28073019        {
    2808             int ret;
    2809 
    2810         #ifdef WOLFSSL_IMX6_CAAM_BLOB
    2811             byte   local[32];
    2812             word32 localSz = 32;
    2813 
    2814             if (keylen == (16 + WC_CAAM_BLOB_SZ) ||
    2815              keylen == (24 + WC_CAAM_BLOB_SZ) ||
    2816              keylen == (32 + WC_CAAM_BLOB_SZ)) {
    2817                 if (wc_caamOpenBlob((byte*)userKey, keylen, local, &localSz)
    2818                         != 0) {
    2819                     return BAD_FUNC_ARG;
    2820                 }
    2821 
    2822                 /* set local values */
    2823                 userKey = local;
    2824                 keylen = localSz;
     3020            if (aes == NULL) {
     3021                return BAD_FUNC_ARG;
    28253022            }
    2826         #endif
    2827             ret = wc_AesSetKeyLocal(aes, userKey, keylen, iv, dir);
    2828 
    2829         #ifdef WOLFSSL_IMX6_CAAM_BLOB
    2830             ForceZero(local, sizeof(local));
    2831         #endif
    2832 
    2833             return ret;
     3023            if (keylen > sizeof(aes->key)) {
     3024                return BAD_FUNC_ARG;
     3025            }
     3026
     3027            return wc_AesSetKeyLocal(aes, userKey, keylen, iv, dir, 0);
    28343028        }
    28353029    #endif /* WOLFSSL_AES_DIRECT || WOLFSSL_AES_COUNTER */
     
    28473041    else
    28483042        XMEMSET(aes->reg,  0, AES_BLOCK_SIZE);
    2849 
    28503043    return 0;
    28513044}
     
    28563049        #error "Coldfire SEC doesn't yet support AES direct"
    28573050
    2858     #elif defined(FREESCALE_LTC)
    2859         /* Allow direct access to one block encrypt */
    2860         void wc_AesEncryptDirect(Aes* aes, byte* out, const byte* in)
    2861         {
    2862             byte *key;
    2863             uint32_t keySize;
    2864 
    2865             key = (byte*)aes->key;
    2866             wc_AesGetKeySize(aes, &keySize);
    2867 
    2868             LTC_AES_EncryptEcb(LTC_BASE, in, out, AES_BLOCK_SIZE,
    2869                 key, keySize);
    2870         }
    2871 
    2872         /* Allow direct access to one block decrypt */
    2873         void wc_AesDecryptDirect(Aes* aes, byte* out, const byte* in)
    2874         {
    2875             byte *key;
    2876             uint32_t keySize;
    2877 
    2878             key = (byte*)aes->key;
    2879             wc_AesGetKeySize(aes, &keySize);
    2880 
    2881             LTC_AES_DecryptEcb(LTC_BASE, in, out, AES_BLOCK_SIZE,
    2882                 key, keySize, kLTC_EncryptKey);
    2883         }
    2884 
    28853051    #elif defined(WOLFSSL_IMX6_CAAM) && !defined(NO_IMX6_CAAM_AES)
    28863052        /* implemented in wolfcrypt/src/port/caam/caam_aes.c */
     
    28923058        /* implemented in wolfcrypt/src/port/devcrypt/devcrypto_aes.c */
    28933059
    2894     #elif defined(STM32_CRYPTO)
    2895         /* Allow direct access to one block encrypt */
    2896         void wc_AesEncryptDirect(Aes* aes, byte* out, const byte* in)
    2897         {
    2898             if (wolfSSL_CryptHwMutexLock() == 0) {
    2899                 wc_AesEncrypt(aes, in, out);
    2900                 wolfSSL_CryptHwMutexUnLock();
    2901             }
    2902         }
    2903         #ifdef HAVE_AES_DECRYPT
    2904         /* Allow direct access to one block decrypt */
    2905         void wc_AesDecryptDirect(Aes* aes, byte* out, const byte* in)
    2906         {
    2907             if (wolfSSL_CryptHwMutexLock() == 0) {
    2908                 wc_AesDecrypt(aes, in, out);
    2909                 wolfSSL_CryptHwMutexUnLock();
    2910             }
    2911         }
    2912         #endif /* HAVE_AES_DECRYPT */
    2913 
    2914     #elif defined(WOLFSSL_ESP32WROOM32_CRYPT) && \
    2915         !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_AES)
    2916        
    2917         /* Allow direct access to one block encrypt */
    2918         void wc_AesEncryptDirect(Aes* aes, byte* out, const byte* in)
    2919         {
    2920             wc_AesEncrypt(aes, in, out);
    2921         }
    2922         #ifdef HAVE_AES_DECRYPT
    2923         /* Allow direct access to one block decrypt */
    2924         void wc_AesDecryptDirect(Aes* aes, byte* out, const byte* in)
    2925         {
    2926             wc_AesDecrypt(aes, in, out);
    2927         }
    2928         #endif /* HAVE_AES_DECRYPT */
    29293060    #else
    29303061        /* Allow direct access to one block encrypt */
     
    29643095        }
    29653096
    2966     #ifdef STM32_CRYPTO_AES_ONLY
     3097    #if defined(STM32_HAL_V2)
     3098        hcryp.Init.Algorithm  = CRYP_AES_CBC;
     3099        ByteReverseWords(aes->reg, aes->reg, AES_BLOCK_SIZE);
     3100    #elif defined(STM32_CRYPTO_AES_ONLY)
    29673101        hcryp.Init.OperatingMode = CRYP_ALGOMODE_ENCRYPT;
    29683102        hcryp.Init.ChainingMode  = CRYP_CHAINMODE_AES_CBC;
    29693103        hcryp.Init.KeyWriteFlag  = CRYP_KEY_WRITE_ENABLE;
    2970     #elif defined(STM32_HAL_V2)
    2971         hcryp.Init.Algorithm  = CRYP_AES_CBC;
    2972         ByteReverseWords(aes->reg, aes->reg, AES_BLOCK_SIZE);
    29733104    #endif
    29743105        hcryp.Init.pInitVect = (STM_CRYPT_TYPE*)aes->reg;
    29753106        HAL_CRYP_Init(&hcryp);
    29763107
    2977         while (blocks--) {
    2978         #ifdef STM32_CRYPTO_AES_ONLY
    2979             ret = HAL_CRYPEx_AES(&hcryp, (uint8_t*)in, AES_BLOCK_SIZE,
    2980                 out, STM32_HAL_TIMEOUT);
    2981         #elif defined(STM32_HAL_V2)
    2982             ret = HAL_CRYP_Encrypt(&hcryp, (uint32_t*)in, AES_BLOCK_SIZE,
    2983                 (uint32_t*)out, STM32_HAL_TIMEOUT);
    2984         #else
    2985             ret = HAL_CRYP_AESCBC_Encrypt(&hcryp, (uint8_t*)in, AES_BLOCK_SIZE,
    2986                 out, STM32_HAL_TIMEOUT);
    2987         #endif
    2988             if (ret != HAL_OK) {
    2989                 ret = WC_TIMEOUT_E;
    2990                 break;
    2991             }
    2992 
    2993             /* store iv for next call */
    2994             XMEMCPY(aes->reg, out + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE);
    2995 
    2996             sz  -= AES_BLOCK_SIZE;
    2997             in  += AES_BLOCK_SIZE;
    2998             out += AES_BLOCK_SIZE;
    2999         }
     3108    #if defined(STM32_HAL_V2)
     3109        ret = HAL_CRYP_Encrypt(&hcryp, (uint32_t*)in, blocks * AES_BLOCK_SIZE,
     3110            (uint32_t*)out, STM32_HAL_TIMEOUT);
     3111    #elif defined(STM32_CRYPTO_AES_ONLY)
     3112        ret = HAL_CRYPEx_AES(&hcryp, (uint8_t*)in, blocks * AES_BLOCK_SIZE,
     3113            out, STM32_HAL_TIMEOUT);
     3114    #else
     3115        ret = HAL_CRYP_AESCBC_Encrypt(&hcryp, (uint8_t*)in, blocks * AES_BLOCK_SIZE,
     3116            out, STM32_HAL_TIMEOUT);
     3117    #endif
     3118        if (ret != HAL_OK) {
     3119            ret = WC_TIMEOUT_E;
     3120        }
     3121
     3122        /* store iv for next call */
     3123        XMEMCPY(aes->reg, out + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE);
    30003124
    30013125        HAL_CRYP_DeInit(&hcryp);
     
    30243148        XMEMCPY(aes->tmp, in + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE);
    30253149
    3026     #ifdef STM32_CRYPTO_AES_ONLY
     3150    #if defined(STM32_HAL_V2)
     3151        hcryp.Init.Algorithm  = CRYP_AES_CBC;
     3152        ByteReverseWords(aes->reg, aes->reg, AES_BLOCK_SIZE);
     3153    #elif defined(STM32_CRYPTO_AES_ONLY)
    30273154        hcryp.Init.OperatingMode = CRYP_ALGOMODE_KEYDERIVATION_DECRYPT;
    30283155        hcryp.Init.ChainingMode  = CRYP_CHAINMODE_AES_CBC;
    30293156        hcryp.Init.KeyWriteFlag  = CRYP_KEY_WRITE_ENABLE;
    3030     #elif defined(STM32_HAL_V2)
    3031         hcryp.Init.Algorithm  = CRYP_AES_CBC;
    3032         ByteReverseWords(aes->reg, aes->reg, AES_BLOCK_SIZE);
    30333157    #endif
    30343158
     
    30363160        HAL_CRYP_Init(&hcryp);
    30373161
    3038         while (blocks--) {
    3039         #ifdef STM32_CRYPTO_AES_ONLY
    3040             ret = HAL_CRYPEx_AES(&hcryp, (uint8_t*)in, AES_BLOCK_SIZE,
    3041                 out, STM32_HAL_TIMEOUT);
    3042         #elif defined(STM32_HAL_V2)
    3043             ret = HAL_CRYP_Decrypt(&hcryp, (uint32_t*)in, AES_BLOCK_SIZE,
    3044                 (uint32_t*)out, STM32_HAL_TIMEOUT);
    3045         #else
    3046             ret = HAL_CRYP_AESCBC_Decrypt(&hcryp, (uint8_t*)in, AES_BLOCK_SIZE,
    3047                 out, STM32_HAL_TIMEOUT);
    3048         #endif
    3049             if (ret != HAL_OK) {
    3050                 ret = WC_TIMEOUT_E;
    3051                 break;
    3052             }
    3053 
    3054             /* store iv for next call */
    3055             XMEMCPY(aes->reg, aes->tmp, AES_BLOCK_SIZE);
    3056 
    3057             in  += AES_BLOCK_SIZE;
    3058             out += AES_BLOCK_SIZE;
    3059         }
     3162    #if defined(STM32_HAL_V2)
     3163        ret = HAL_CRYP_Decrypt(&hcryp, (uint32_t*)in, blocks * AES_BLOCK_SIZE,
     3164            (uint32_t*)out, STM32_HAL_TIMEOUT);
     3165    #elif defined(STM32_CRYPTO_AES_ONLY)
     3166        ret = HAL_CRYPEx_AES(&hcryp, (uint8_t*)in, blocks * AES_BLOCK_SIZE,
     3167            out, STM32_HAL_TIMEOUT);
     3168    #else
     3169        ret = HAL_CRYP_AESCBC_Decrypt(&hcryp, (uint8_t*)in, blocks * AES_BLOCK_SIZE,
     3170            out, STM32_HAL_TIMEOUT);
     3171    #endif
     3172        if (ret != HAL_OK) {
     3173            ret = WC_TIMEOUT_E;
     3174        }
     3175
     3176        /* store iv for next call */
     3177        XMEMCPY(aes->reg, aes->tmp, AES_BLOCK_SIZE);
    30603178
    30613179        HAL_CRYP_DeInit(&hcryp);
     
    30663184    #endif /* HAVE_AES_DECRYPT */
    30673185
    3068 #else /* STD_PERI_LIB */
     3186#else /* Standard Peripheral Library */
    30693187    int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz)
    30703188    {
     
    33383456    int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz)
    33393457    {
    3340         uint32_t keySize;
     3458        word32 keySize;
    33413459        status_t status;
    33423460        byte *iv, *enc_key;
     
    33513469        }
    33523470
     3471        status = wolfSSL_CryptHwMutexLock();
     3472        if (status != 0)
     3473            return status;
    33533474        status = LTC_AES_EncryptCbc(LTC_BASE, in, out, blocks * AES_BLOCK_SIZE,
    33543475            iv, enc_key, keySize);
     3476        wolfSSL_CryptHwMutexUnLock();
    33553477
    33563478        /* store iv for next call */
     
    33653487    int wc_AesCbcDecrypt(Aes* aes, byte* out, const byte* in, word32 sz)
    33663488    {
    3367         uint32_t keySize;
     3489        word32 keySize;
    33683490        status_t status;
    33693491        byte* iv, *dec_key;
     
    33823504        XMEMCPY(temp_block, in + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE);
    33833505
     3506        status = wolfSSL_CryptHwMutexLock();
     3507        if (status != 0)
     3508            return status;
    33843509        status = LTC_AES_DecryptCbc(LTC_BASE, in, out, blocks * AES_BLOCK_SIZE,
    33853510            iv, dec_key, keySize, kLTC_EncryptKey);
     3511        wolfSSL_CryptHwMutexUnLock();
    33863512
    33873513        /* store IV for next call */
     
    34033529        byte temp_block[AES_BLOCK_SIZE];
    34043530
    3405         iv      = (byte*)aes->reg;
     3531        iv = (byte*)aes->reg;
    34063532
    34073533        while (blocks--) {
     
    34313557        byte temp_block[AES_BLOCK_SIZE];
    34323558
    3433         iv      = (byte*)aes->reg;
     3559        iv = (byte*)aes->reg;
    34343560
    34353561        while (blocks--) {
     
    35143640    int wc_AesCbcEncrypt(Aes* aes, byte* out, const byte* in, word32 sz)
    35153641    {
    3516         return SaSi_AesBlock(&aes->ctx.user_ctx, (uint8_t* )in, sz, out);
     3642        return SaSi_AesBlock(&aes->ctx.user_ctx, (uint8_t*)in, sz, out);
    35173643    }
    35183644    int wc_AesCbcDecrypt(Aes* aes, byte* out, const byte* in, word32 sz)
    35193645    {
    3520         return SaSi_AesBlock(&aes->ctx.user_ctx, (uint8_t* )in, sz, out);
     3646        return SaSi_AesBlock(&aes->ctx.user_ctx, (uint8_t*)in, sz, out);
    35213647    }
    35223648#elif defined(WOLFSSL_IMX6_CAAM) && !defined(NO_IMX6_CAAM_AES)
     
    35283654#elif defined(WOLFSSL_DEVCRYPTO_CBC)
    35293655    /* implemented in wolfcrypt/src/port/devcrypt/devcrypto_aes.c */
     3656
     3657#elif defined(WOLFSSL_SILABS_SE_ACCEL)
     3658    /* implemented in wolfcrypt/src/port/silabs/silabs_hash.c */
    35303659
    35313660#else
     
    35393668            return BAD_FUNC_ARG;
    35403669        }
     3670
     3671        if (sz == 0) {
     3672            return 0;
     3673        }
     3674    #ifdef WOLFSSL_IMXRT_DCP
     3675        /* Implemented in wolfcrypt/src/port/nxp/dcp_port.c */
     3676        if (aes->keylen == 16)
     3677            return DCPAesCbcEncrypt(aes, out, in, sz);
     3678    #endif
    35413679
    35423680    #ifdef WOLF_CRYPTO_CB
     
    35933731                tmp_align = tmp + (AESNI_ALIGN - ((size_t)tmp % AESNI_ALIGN));
    35943732                XMEMCPY(tmp_align, in, sz);
     3733                SAVE_VECTOR_REGISTERS();
    35953734                AES_CBC_encrypt(tmp_align, tmp_align, (byte*)aes->reg, sz,
    35963735                                                  (byte*)aes->key, aes->rounds);
     3736                RESTORE_VECTOR_REGISTERS();
    35973737                /* store iv for next call */
    35983738                XMEMCPY(aes->reg, tmp_align + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE);
     
    36073747            }
    36083748
     3749            SAVE_VECTOR_REGISTERS();
    36093750            AES_CBC_encrypt(in, out, (byte*)aes->reg, sz, (byte*)aes->key,
    36103751                            aes->rounds);
     3752            RESTORE_VECTOR_REGISTERS();
    36113753            /* store iv for next call */
    36123754            XMEMCPY(aes->reg, out + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE);
     
    36383780            return BAD_FUNC_ARG;
    36393781        }
     3782
     3783        if (sz == 0) {
     3784            return 0;
     3785        }
     3786    #ifdef WOLFSSL_IMXRT_DCP
     3787        /* Implemented in wolfcrypt/src/port/nxp/dcp_port.c */
     3788        if (aes->keylen == 16)
     3789            return DCPAesCbcDecrypt(aes, out, in, sz);
     3790    #endif
    36403791
    36413792    #ifdef WOLF_CRYPTO_CB
     
    36843835            /* if input and output same will overwrite input iv */
    36853836            XMEMCPY(aes->tmp, in + sz - AES_BLOCK_SIZE, AES_BLOCK_SIZE);
     3837            SAVE_VECTOR_REGISTERS();
    36863838            #if defined(WOLFSSL_AESNI_BY4)
    36873839            AES_CBC_decrypt_by4(in, out, (byte*)aes->reg, sz, (byte*)aes->key,
     
    36953847            #endif /* WOLFSSL_AESNI_BYx */
    36963848            /* store iv for next call */
     3849            RESTORE_VECTOR_REGISTERS();
    36973850            XMEMCPY(aes->reg, aes->tmp, AES_BLOCK_SIZE);
    36983851            return 0;
     
    37413894        #endif
    37423895
     3896        #ifdef WOLFSSL_STM32_CUBEMX
     3897            ret = wc_Stm32_Aes_Init(aes, &hcryp);
     3898            if (ret != 0) {
     3899                return ret;
     3900            }
     3901
    37433902            ret = wolfSSL_CryptHwMutexLock();
    37443903            if (ret != 0) {
     
    37463905            }
    37473906
    3748         #ifdef WOLFSSL_STM32_CUBEMX
    3749             ret = wc_Stm32_Aes_Init(aes, &hcryp);
    3750             if (ret != 0) {
    3751                 wolfSSL_CryptHwMutexUnLock();
    3752                 return ret;
    3753             }
    3754 
    3755         #ifdef STM32_CRYPTO_AES_ONLY
     3907        #if defined(STM32_HAL_V2)
     3908            hcryp.Init.Algorithm  = CRYP_AES_CTR;
     3909            ByteReverseWords(iv, aes->reg, AES_BLOCK_SIZE);
     3910            hcryp.Init.pInitVect = (STM_CRYPT_TYPE*)iv;
     3911        #elif defined(STM32_CRYPTO_AES_ONLY)
    37563912            hcryp.Init.OperatingMode = CRYP_ALGOMODE_ENCRYPT;
    37573913            hcryp.Init.ChainingMode  = CRYP_CHAINMODE_AES_CTR;
    37583914            hcryp.Init.KeyWriteFlag  = CRYP_KEY_WRITE_ENABLE;
    37593915            hcryp.Init.pInitVect = (STM_CRYPT_TYPE*)aes->reg;
    3760         #elif defined(STM32_HAL_V2)
    3761             hcryp.Init.Algorithm  = CRYP_AES_CTR;
    3762             ByteReverseWords(iv, aes->reg, AES_BLOCK_SIZE);
    3763             hcryp.Init.pInitVect = (STM_CRYPT_TYPE*)iv;
    37643916        #else
    37653917            hcryp.Init.pInitVect = (STM_CRYPT_TYPE*)aes->reg;
     
    37673919            HAL_CRYP_Init(&hcryp);
    37683920
    3769         #ifdef STM32_CRYPTO_AES_ONLY
     3921        #if defined(STM32_HAL_V2)
     3922            ret = HAL_CRYP_Encrypt(&hcryp, (uint32_t*)in, AES_BLOCK_SIZE,
     3923                (uint32_t*)out, STM32_HAL_TIMEOUT);
     3924        #elif defined(STM32_CRYPTO_AES_ONLY)
    37703925            ret = HAL_CRYPEx_AES(&hcryp, (byte*)in, AES_BLOCK_SIZE,
    37713926                out, STM32_HAL_TIMEOUT);
    3772         #elif defined(STM32_HAL_V2)
    3773             ret = HAL_CRYP_Encrypt(&hcryp, (uint32_t*)in, AES_BLOCK_SIZE,
    3774                 (uint32_t*)out, STM32_HAL_TIMEOUT);
    37753927        #else
    37763928            ret = HAL_CRYP_AESCTR_Encrypt(&hcryp, (byte*)in, AES_BLOCK_SIZE,
     
    37823934            HAL_CRYP_DeInit(&hcryp);
    37833935
    3784         #else /* STD_PERI_LIB */
     3936        #else /* Standard Peripheral Library */
    37853937            ret = wc_Stm32_Aes_Init(aes, &cryptInit, &keyInit);
    37863938            if (ret != 0) {
    3787                 wolfSSL_CryptHwMutexUnLock();
     3939                return ret;
     3940            }
     3941
     3942            ret = wolfSSL_CryptHwMutexLock();
     3943            if (ret != 0) {
    37883944                return ret;
    37893945            }
     
    38303986            /* disable crypto processor */
    38313987            CRYP_Cmd(DISABLE);
    3832 
    38333988        #endif /* WOLFSSL_STM32_CUBEMX */
    38343989
     
    38594014        int wc_AesCtrEncrypt(Aes* aes, byte* out, const byte* in, word32 sz)
    38604015        {
    3861             uint32_t keySize;
     4016            int ret = 0;
     4017            word32 keySize;
    38624018            byte *iv, *enc_key;
    38634019            byte* tmp;
     
    38814037                wc_AesGetKeySize(aes, &keySize);
    38824038
     4039                ret = wolfSSL_CryptHwMutexLock();
     4040                if (ret != 0)
     4041                    return ret;
    38834042                LTC_AES_CryptCtr(LTC_BASE, in, out, sz,
    38844043                    iv, enc_key, keySize, (byte*)aes->tmp,
    38854044                    (uint32_t*)&aes->left);
     4045                wolfSSL_CryptHwMutexUnLock();
    38864046            }
    38874047
    3888             return 0;
     4048            return ret;
    38894049        }
    38904050
     
    38974057    #elif defined(WOLFSSL_DEVCRYPTO_AES)
    38984058        /* implemented in wolfcrypt/src/port/devcrypt/devcrypto_aes.c */
    3899    
     4059
    39004060    #elif defined(WOLFSSL_ESP32WROOM32_CRYPT) && \
    39014061        !defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_AES)
     
    40104170    #error "Coldfire SEC doesn't currently support AES-GCM mode"
    40114171
    4012 #elif defined(WOLFSSL_NRF51_AES)
    4013     #error "nRF51 doesn't currently support AES-GCM mode"
    4014 
    40154172#endif
    40164173
     
    40374194    }
    40384195}
    4039 #ifdef STM32_CRYPTO_AES_GCM
    4040 static WC_INLINE void DecrementGcmCounter(byte* inOutCtr)
    4041 {
    4042     int i;
    4043 
    4044     /* in network byte order so start at end and work back */
    4045     for (i = AES_BLOCK_SIZE - 1; i >= AES_BLOCK_SIZE - CTR_SZ; i--) {
    4046         if (--inOutCtr[i] != 0xFF)  /* we're done unless we underflow */
    4047             return;
    4048     }
    4049 }
    4050 #endif /* STM32_CRYPTO_AES_GCM */
    40514196#endif /* !FREESCALE_LTC_AES_GCM */
    40524197
    4053 #if defined(GCM_SMALL) || defined(GCM_TABLE)
     4198#if defined(GCM_SMALL) || defined(GCM_TABLE) || defined(GCM_TABLE_4BIT)
    40544199
    40554200static WC_INLINE void FlattenSzInBits(byte* buf, word32 sz)
     
    40864231}
    40874232
    4088 #endif /* defined(GCM_SMALL) || defined(GCM_TABLE) */
     4233#endif /* defined(GCM_SMALL) || defined(GCM_TABLE) || defined(GCM_TABLE_4BIT) */
    40894234
    40904235
     
    41114256
    41124257    XMEMSET(m[0], 0, AES_BLOCK_SIZE);
     4258}
     4259
     4260#elif defined(GCM_TABLE_4BIT)
     4261
     4262static WC_INLINE void Shift4_M0(byte *r8, byte* z8)
     4263{
     4264    int i;
     4265    for (i = 15; i > 0; i--)
     4266        r8[i] = (z8[i-1] << 4) | (z8[i] >> 4);
     4267    r8[0] = z8[0] >> 4;
     4268}
     4269
     4270static void GenerateM0(Aes* aes)
     4271{
     4272#if !defined(BIG_ENDIAN_ORDER) && !defined(WC_16BIT_CPU)
     4273    int i;
     4274#endif
     4275    byte (*m)[AES_BLOCK_SIZE] = aes->M0;
     4276
     4277    /* 0 times -> 0x0 */
     4278    XMEMSET(m[0x0], 0, AES_BLOCK_SIZE);
     4279    /* 1 times -> 0x8 */
     4280    XMEMCPY(m[0x8], aes->H, AES_BLOCK_SIZE);
     4281    /* 2 times -> 0x4 */
     4282    XMEMCPY(m[0x4], m[0x8], AES_BLOCK_SIZE);
     4283    RIGHTSHIFTX(m[0x4]);
     4284    /* 4 times -> 0x2 */
     4285    XMEMCPY(m[0x2], m[0x4], AES_BLOCK_SIZE);
     4286    RIGHTSHIFTX(m[0x2]);
     4287    /* 8 times -> 0x1 */
     4288    XMEMCPY(m[0x1], m[0x2], AES_BLOCK_SIZE);
     4289    RIGHTSHIFTX(m[0x1]);
     4290
     4291    /* 0x3 */
     4292    XMEMCPY(m[0x3], m[0x2], AES_BLOCK_SIZE);
     4293    xorbuf (m[0x3], m[0x1], AES_BLOCK_SIZE);
     4294
     4295    /* 0x5 -> 0x7 */
     4296    XMEMCPY(m[0x5], m[0x4], AES_BLOCK_SIZE);
     4297    xorbuf (m[0x5], m[0x1], AES_BLOCK_SIZE);
     4298    XMEMCPY(m[0x6], m[0x4], AES_BLOCK_SIZE);
     4299    xorbuf (m[0x6], m[0x2], AES_BLOCK_SIZE);
     4300    XMEMCPY(m[0x7], m[0x4], AES_BLOCK_SIZE);
     4301    xorbuf (m[0x7], m[0x3], AES_BLOCK_SIZE);
     4302
     4303    /* 0x9 -> 0xf */
     4304    XMEMCPY(m[0x9], m[0x8], AES_BLOCK_SIZE);
     4305    xorbuf (m[0x9], m[0x1], AES_BLOCK_SIZE);
     4306    XMEMCPY(m[0xa], m[0x8], AES_BLOCK_SIZE);
     4307    xorbuf (m[0xa], m[0x2], AES_BLOCK_SIZE);
     4308    XMEMCPY(m[0xb], m[0x8], AES_BLOCK_SIZE);
     4309    xorbuf (m[0xb], m[0x3], AES_BLOCK_SIZE);
     4310    XMEMCPY(m[0xc], m[0x8], AES_BLOCK_SIZE);
     4311    xorbuf (m[0xc], m[0x4], AES_BLOCK_SIZE);
     4312    XMEMCPY(m[0xd], m[0x8], AES_BLOCK_SIZE);
     4313    xorbuf (m[0xd], m[0x5], AES_BLOCK_SIZE);
     4314    XMEMCPY(m[0xe], m[0x8], AES_BLOCK_SIZE);
     4315    xorbuf (m[0xe], m[0x6], AES_BLOCK_SIZE);
     4316    XMEMCPY(m[0xf], m[0x8], AES_BLOCK_SIZE);
     4317    xorbuf (m[0xf], m[0x7], AES_BLOCK_SIZE);
     4318
     4319#if !defined(BIG_ENDIAN_ORDER) && !defined(WC_16BIT_CPU)
     4320    for (i = 0; i < 16; i++) {
     4321        Shift4_M0(m[16+i], m[i]);
     4322    }
     4323#endif
    41134324}
    41144325
     
    41594370    if (ret == 0) {
    41604371        wc_AesEncrypt(aes, iv, aes->H);
    4161     #ifdef GCM_TABLE
     4372    #if defined(GCM_TABLE) || defined(GCM_TABLE_4BIT)
    41624373        GenerateM0(aes);
    41634374    #endif /* GCM_TABLE */
     
    41804391    ForceZero(local, sizeof(local));
    41814392#endif
    4182 
    41834393    return ret;
    41844394}
     
    41964406void AES_GCM_encrypt(const unsigned char *in, unsigned char *out,
    41974407                     const unsigned char* addt, const unsigned char* ivec,
    4198                      unsigned char *tag, unsigned int nbytes,
    4199                      unsigned int abytes, unsigned int ibytes,
    4200                      unsigned int tbytes, const unsigned char* key, int nr)
     4408                     unsigned char *tag, word32 nbytes,
     4409                     word32 abytes, word32 ibytes,
     4410                     word32 tbytes, const unsigned char* key, int nr)
    42014411                     XASM_LINK("AES_GCM_encrypt");
    42024412#ifdef HAVE_INTEL_AVX1
    42034413void AES_GCM_encrypt_avx1(const unsigned char *in, unsigned char *out,
    42044414                          const unsigned char* addt, const unsigned char* ivec,
    4205                           unsigned char *tag, unsigned int nbytes,
    4206                           unsigned int abytes, unsigned int ibytes,
    4207                           unsigned int tbytes, const unsigned char* key,
     4415                          unsigned char *tag, word32 nbytes,
     4416                          word32 abytes, word32 ibytes,
     4417                          word32 tbytes, const unsigned char* key,
    42084418                          int nr)
    42094419                          XASM_LINK("AES_GCM_encrypt_avx1");
     
    42114421void AES_GCM_encrypt_avx2(const unsigned char *in, unsigned char *out,
    42124422                          const unsigned char* addt, const unsigned char* ivec,
    4213                           unsigned char *tag, unsigned int nbytes,
    4214                           unsigned int abytes, unsigned int ibytes,
    4215                           unsigned int tbytes, const unsigned char* key,
     4423                          unsigned char *tag, word32 nbytes,
     4424                          word32 abytes, word32 ibytes,
     4425                          word32 tbytes, const unsigned char* key,
    42164426                          int nr)
    42174427                          XASM_LINK("AES_GCM_encrypt_avx2");
     
    42224432void AES_GCM_decrypt(const unsigned char *in, unsigned char *out,
    42234433                     const unsigned char* addt, const unsigned char* ivec,
    4224                      const unsigned char *tag, int nbytes, int abytes,
    4225                      int ibytes, int tbytes, const unsigned char* key, int nr,
    4226                      int* res)
     4434                     const unsigned char *tag, word32 nbytes, word32 abytes,
     4435                     word32 ibytes, word32 tbytes, const unsigned char* key,
     4436                     int nr, int* res)
    42274437                     XASM_LINK("AES_GCM_decrypt");
    42284438#ifdef HAVE_INTEL_AVX1
    42294439void AES_GCM_decrypt_avx1(const unsigned char *in, unsigned char *out,
    42304440                          const unsigned char* addt, const unsigned char* ivec,
    4231                           const unsigned char *tag, int nbytes, int abytes,
    4232                           int ibytes, int tbytes, const unsigned char* key,
    4233                           int nr, int* res)
     4441                          const unsigned char *tag, word32 nbytes,
     4442                          word32 abytes, word32 ibytes, word32 tbytes,
     4443                          const unsigned char* key, int nr, int* res)
    42344444                          XASM_LINK("AES_GCM_decrypt_avx1");
    42354445#ifdef HAVE_INTEL_AVX2
    42364446void AES_GCM_decrypt_avx2(const unsigned char *in, unsigned char *out,
    42374447                          const unsigned char* addt, const unsigned char* ivec,
    4238                           const unsigned char *tag, int nbytes, int abytes,
    4239                           int ibytes, int tbytes, const unsigned char* key,
    4240                           int nr, int* res)
     4448                          const unsigned char *tag, word32 nbytes,
     4449                          word32 abytes, word32 ibytes, word32 tbytes,
     4450                          const unsigned char* key, int nr, int* res)
    42414451                          XASM_LINK("AES_GCM_decrypt_avx2");
    42424452#endif /* HAVE_INTEL_AVX2 */
     
    45854795
    45864796
    4587 static void AES_GCM_encrypt(const unsigned char *in,
    4588                               unsigned char *out,
    4589                               const unsigned char* addt,
    4590                               const unsigned char* ivec,
    4591                               unsigned char *tag, unsigned int nbytes,
    4592                               unsigned int abytes, unsigned int ibytes,
    4593                               unsigned int tbytes,
    4594                               const unsigned char* key, int nr)
     4797static void AES_GCM_encrypt(const unsigned char *in, unsigned char *out,
     4798                            const unsigned char* addt,
     4799                            const unsigned char* ivec, unsigned char *tag,
     4800                            word32 nbytes, word32 abytes, word32 ibytes,
     4801                            wrd32 tbytes, const unsigned char* key, int nr)
    45954802{
    45964803    int i, j ,k;
     
    50135220        X = gfmul_shifted(X, H);
    50145221    }
    5015     tmp1 = _mm_insert_epi64(tmp1, nbytes*8, 0);
    5016     tmp1 = _mm_insert_epi64(tmp1, abytes*8, 1);
     5222    tmp1 = _mm_insert_epi64(tmp1, ((word64)nbytes)*8, 0);
     5223    tmp1 = _mm_insert_epi64(tmp1, ((word64)abytes)*8, 1);
    50175224    X = _mm_xor_si128(X, tmp1);
    50185225    X = gfmul_shifted(X, H);
     
    50215228    /*_mm_storeu_si128((__m128i*)tag, T);*/
    50225229    XMEMCPY(tag, &T, tbytes);
     5230    ForceZero(&lastKey, sizeof(lastKey));
    50235231}
    50245232
    50255233#ifdef HAVE_AES_DECRYPT
    50265234
    5027 static void AES_GCM_decrypt(const unsigned char *in,
    5028                            unsigned char *out,
    5029                            const unsigned char* addt,
    5030                            const unsigned char* ivec,
    5031                            const unsigned char *tag, int nbytes, int abytes,
    5032                            int ibytes, word32 tbytes, const unsigned char* key,
    5033                            int nr, int* res)
     5235static void AES_GCM_decrypt(const unsigned char *in, unsigned char *out,
     5236                            const unsigned char* addt,
     5237                            const unsigned char* ivec, const unsigned char *tag,
     5238                            word32 nbytes, word32 abytes, word32 ibytes,
     5239                            word32 tbytes, const unsigned char* key, int nr,
     5240                            int* res)
    50345241{
    50355242    int i, j ,k;
     
    53375544    }
    53385545
    5339     tmp1 = _mm_insert_epi64(tmp1, nbytes*8, 0);
    5340     tmp1 = _mm_insert_epi64(tmp1, abytes*8, 1);
     5546    tmp1 = _mm_insert_epi64(tmp1, ((word64)nbytes)*8, 0);
     5547    tmp1 = _mm_insert_epi64(tmp1, ((word64)abytes)*8, 1);
    53415548    /* 128 x 128 Carryless Multiply */
    53425549    X = _mm_xor_si128(X, tmp1);
     
    53515558    else
    53525559        *res = 1; /* when successful returns 1 */
     5560    ForceZero(&lastKey, sizeof(lastKey));
    53535561}
    53545562
     
    55105718static void GMULT(byte *x, byte m[256][AES_BLOCK_SIZE])
    55115719{
     5720#if !defined(WORD64_AVAILABLE) || defined(BIG_ENDIAN_ORDER)
    55125721    int i, j;
    55135722    byte Z[AES_BLOCK_SIZE];
     
    55245733        }
    55255734
    5526         Z[0] = R[a][0];
     5735        Z[0]  = R[a][0];
    55275736        Z[1] ^= R[a][1];
    55285737    }
     
    55305739
    55315740    XMEMCPY(x, Z, AES_BLOCK_SIZE);
    5532 }
    5533 
     5741#else
     5742    byte Z[AES_BLOCK_SIZE + AES_BLOCK_SIZE];
     5743    byte a;
     5744    word64* pZ;
     5745    word64* pm;
     5746    word64* px = (word64*)(x);
     5747    int i;
     5748
     5749    pZ = (word64*)(Z + 15 + 1);
     5750    pm = (word64*)(m[x[15]]);
     5751    pZ[0] = pm[0];
     5752    pZ[1] = pm[1];
     5753    a = Z[16 + 15];
     5754    Z[15]  = R[a][0];
     5755    Z[16] ^= R[a][1];
     5756    for (i = 14; i > 0; i--) {
     5757        pZ = (word64*)(Z + i + 1);
     5758        pm = (word64*)(m[x[i]]);
     5759        pZ[0] ^= pm[0];
     5760        pZ[1] ^= pm[1];
     5761        a = Z[16 + i];
     5762        Z[i]    = R[a][0];
     5763        Z[i+1] ^= R[a][1];
     5764    }
     5765    pZ = (word64*)(Z + 1);
     5766    pm = (word64*)(m[x[0]]);
     5767    px[0] = pZ[0] ^ pm[0]; px[1] = pZ[1] ^ pm[1];
     5768#endif
     5769}
    55345770
    55355771void GHASH(Aes* aes, const byte* a, word32 aSz, const byte* c,
     
    55875823
    55885824/* end GCM_TABLE */
     5825#elif defined(GCM_TABLE_4BIT)
     5826
     5827/* remainder = x^7 + x^2 + x^1 + 1 => 0xe1
     5828 *  R shifts right a reverse bit pair of bytes such that:
     5829 *     R(b0, b1) => b1 = (b1 >> 1) | (b0 << 7); b0 >>= 1
     5830 *  0 => 0, 0, 0, 0 => R(R(R(00,00) ^ 00,00) ^ 00,00) ^ 00,00 = 00,00
     5831 *  8 => 0, 0, 0, 1 => R(R(R(00,00) ^ 00,00) ^ 00,00) ^ e1,00 = e1,00
     5832 *  4 => 0, 0, 1, 0 => R(R(R(00,00) ^ 00,00) ^ e1,00) ^ 00,00 = 70,80
     5833 *  2 => 0, 1, 0, 0 => R(R(R(00,00) ^ e1,00) ^ 00,00) ^ 00,00 = 38,40
     5834 *  1 => 1, 0, 0, 0 => R(R(R(e1,00) ^ 00,00) ^ 00,00) ^ 00,00 = 1c,20
     5835 *  To calculate te rest, XOR result for each bit.
     5836 *   e.g. 6 = 4 ^ 2 => 48,c0
     5837 *
     5838 * Second half is same values rotated by 4-bits.
     5839 */
     5840#if defined(BIG_ENDIAN_ORDER) || defined(WC_16BIT_CPU)
     5841static const byte R[16][2] = {
     5842    {0x00, 0x00}, {0x1c, 0x20}, {0x38, 0x40}, {0x24, 0x60},
     5843    {0x70, 0x80}, {0x6c, 0xa0}, {0x48, 0xc0}, {0x54, 0xe0},
     5844    {0xe1, 0x00}, {0xfd, 0x20}, {0xd9, 0x40}, {0xc5, 0x60},
     5845    {0x91, 0x80}, {0x8d, 0xa0}, {0xa9, 0xc0}, {0xb5, 0xe0},
     5846};
     5847#else
     5848static const word16 R[32] = {
     5849          0x0000,       0x201c,       0x4038,       0x6024,
     5850          0x8070,       0xa06c,       0xc048,       0xe054,
     5851          0x00e1,       0x20fd,       0x40d9,       0x60c5,
     5852          0x8091,       0xa08d,       0xc0a9,       0xe0b5,
     5853
     5854          0x0000,       0xc201,       0x8403,       0x4602,
     5855          0x0807,       0xca06,       0x8c04,       0x4e05,
     5856          0x100e,       0xd20f,       0x940d,       0x560c,
     5857          0x1809,       0xda08,       0x9c0a,       0x5e0b,
     5858};
     5859#endif
     5860
     5861/* Multiply in GF(2^128) defined by polynomial:
     5862 *   x^128 + x^7 + x^2 + x^1 + 1.
     5863 *
     5864 * H: hash key = encrypt(key, 0)
     5865 * x = x * H in field
     5866 *
     5867 * x: cumlative result
     5868 * m: 4-bit table
     5869 *    [0..15] * H
     5870 */
     5871#if defined(BIG_ENDIAN_ORDER) || defined(WC_16BIT_CPU)
     5872static void GMULT(byte *x, byte m[16][AES_BLOCK_SIZE])
     5873{
     5874    int i, j, n;
     5875    byte Z[AES_BLOCK_SIZE];
     5876    byte a;
     5877
     5878    XMEMSET(Z, 0, sizeof(Z));
     5879
     5880    for (i = 15; i >= 0; i--) {
     5881        for (n = 0; n < 2; n++) {
     5882            if (n == 0)
     5883                xorbuf(Z, m[x[i] & 0xf], AES_BLOCK_SIZE);
     5884            else {
     5885                xorbuf(Z, m[x[i] >> 4], AES_BLOCK_SIZE);
     5886                if (i == 0)
     5887                    break;
     5888            }
     5889            a = Z[15] & 0xf;
     5890
     5891            for (j = 15; j > 0; j--)
     5892                Z[j] = (Z[j-1] << 4) | (Z[j] >> 4);
     5893            Z[0] >>= 4;
     5894
     5895            Z[0] ^= R[a][0];
     5896            Z[1] ^= R[a][1];
     5897        }
     5898    }
     5899
     5900    XMEMCPY(x, Z, AES_BLOCK_SIZE);
     5901}
     5902#elif defined(WC_32BIT_CPU)
     5903static WC_INLINE void GMULT(byte *x, byte m[32][AES_BLOCK_SIZE])
     5904{
     5905    int i;
     5906    word32 z8[4] = {0, 0, 0, 0};
     5907    byte a;
     5908    word32* x8 = (word32*)x;
     5909    word32* m8;
     5910    byte xi;
     5911    word32 n7, n6, n5, n4, n3, n2, n1, n0;
     5912
     5913    for (i = 15; i > 0; i--) {
     5914        xi = x[i];
     5915
     5916        /* XOR in (msn * H) */
     5917        m8 = (word32*)m[xi & 0xf];
     5918        z8[0] ^= m8[0]; z8[1] ^= m8[1]; z8[2] ^= m8[2]; z8[3] ^= m8[3];
     5919
     5920        /* Cache top byte for remainder calculations - lost in rotate. */
     5921        a = z8[3] >> 24;
     5922
     5923        /* Rotate Z by 8-bits */
     5924        z8[3] = (z8[2] >> 24) | (z8[3] << 8);
     5925        z8[2] = (z8[1] >> 24) | (z8[2] << 8);
     5926        z8[1] = (z8[0] >> 24) | (z8[1] << 8);
     5927        z8[0] <<= 8;
     5928
     5929        /* XOR in (msn * remainder) [pre-rotated by 4 bits] */
     5930        z8[0] ^= (word32)R[16 + (a & 0xf)];
     5931
     5932        xi >>= 4;
     5933        /* XOR in next significant nibble (XORed with H) * remainder */
     5934        m8 = (word32*)m[xi];
     5935        a ^= (byte)(m8[3] >> 20);
     5936        z8[0] ^= (word32)R[a >> 4];
     5937
     5938        /* XOR in (next significant nibble * H) [pre-rotated by 4 bits] */
     5939        m8 = (word32*)m[16 + xi];
     5940        z8[0] ^= m8[0]; z8[1] ^= m8[1];
     5941        z8[2] ^= m8[2]; z8[3] ^= m8[3];
     5942    }
     5943
     5944    xi = x[0];
     5945
     5946    /* XOR in most significant nibble * H */
     5947    m8 = (word32*)m[xi & 0xf];
     5948    z8[0] ^= m8[0]; z8[1] ^= m8[1]; z8[2] ^= m8[2]; z8[3] ^= m8[3];
     5949
     5950    /* Cache top byte for remainder calculations - lost in rotate. */
     5951    a = (z8[3] >> 24) & 0xf;
     5952
     5953    /* Rotate z by 4-bits */
     5954    n7 = z8[3] & 0xf0f0f0f0ULL;
     5955    n6 = z8[3] & 0x0f0f0f0fULL;
     5956    n5 = z8[2] & 0xf0f0f0f0ULL;
     5957    n4 = z8[2] & 0x0f0f0f0fULL;
     5958    n3 = z8[1] & 0xf0f0f0f0ULL;
     5959    n2 = z8[1] & 0x0f0f0f0fULL;
     5960    n1 = z8[0] & 0xf0f0f0f0ULL;
     5961    n0 = z8[0] & 0x0f0f0f0fULL;
     5962    z8[3] = (n7 >> 4) | (n6 << 12) | (n4 >> 20);
     5963    z8[2] = (n5 >> 4) | (n4 << 12) | (n2 >> 20);
     5964    z8[1] = (n3 >> 4) | (n2 << 12) | (n0 >> 20);
     5965    z8[0] = (n1 >> 4) | (n0 << 12);
     5966
     5967    /* XOR in most significant nibble * remainder */
     5968    z8[0] ^= (word32)R[a];
     5969    /* XOR in next significant nibble * H */
     5970    m8 = (word32*)m[xi >> 4];
     5971    z8[0] ^= m8[0]; z8[1] ^= m8[1]; z8[2] ^= m8[2]; z8[3] ^= m8[3];
     5972
     5973    /* Write back result. */
     5974    x8[0] = z8[0]; x8[1] = z8[1]; x8[2] = z8[2]; x8[3] = z8[3];
     5975}
     5976#else
     5977static WC_INLINE void GMULT(byte *x, byte m[32][AES_BLOCK_SIZE])
     5978{
     5979    int i;
     5980    word64 z8[2] = {0, 0};
     5981    byte a;
     5982    word64* x8 = (word64*)x;
     5983    word64* m8;
     5984    word64 n0, n1, n2, n3;
     5985    byte xi;
     5986
     5987    for (i = 15; i > 0; i--) {
     5988        xi = x[i];
     5989
     5990        /* XOR in (msn * H) */
     5991        m8 = (word64*)m[xi & 0xf];
     5992        z8[0] ^= m8[0];
     5993        z8[1] ^= m8[1];
     5994
     5995        /* Cache top byte for remainder calculations - lost in rotate. */
     5996        a = z8[1] >> 56;
     5997
     5998        /* Rotate Z by 8-bits */
     5999        z8[1] = (z8[0] >> 56) | (z8[1] << 8);
     6000        z8[0] <<= 8;
     6001
     6002        /* XOR in (next significant nibble * H) [pre-rotated by 4 bits] */
     6003        m8 = (word64*)m[16 + (xi >> 4)];
     6004        z8[0] ^= m8[0];
     6005        z8[1] ^= m8[1];
     6006
     6007        /* XOR in (msn * remainder) [pre-rotated by 4 bits] */
     6008        z8[0] ^= (word64)R[16 + (a & 0xf)];
     6009        /* XOR in next significant nibble (XORed with H) * remainder */
     6010        m8 = (word64*)m[xi >> 4];
     6011        a ^= (byte)(m8[1] >> 52);
     6012        z8[0] ^= (word64)R[a >> 4];
     6013    }
     6014
     6015    xi = x[0];
     6016
     6017    /* XOR in most significant nibble * H */
     6018    m8 = (word64*)m[xi & 0xf];
     6019    z8[0] ^= m8[0];
     6020    z8[1] ^= m8[1];
     6021
     6022    /* Cache top byte for remainder calculations - lost in rotate. */
     6023    a = (z8[1] >> 56) & 0xf;
     6024
     6025    /* Rotate z by 4-bits */
     6026    n3 = z8[1] & 0xf0f0f0f0f0f0f0f0ULL;
     6027    n2 = z8[1] & 0x0f0f0f0f0f0f0f0fULL;
     6028    n1 = z8[0] & 0xf0f0f0f0f0f0f0f0ULL;
     6029    n0 = z8[0] & 0x0f0f0f0f0f0f0f0fULL;
     6030    z8[1] = (n3 >> 4) | (n2 << 12) | (n0 >> 52);
     6031    z8[0] = (n1 >> 4) | (n0 << 12);
     6032
     6033    /* XOR in next significant nibble * H */
     6034    m8 = (word64*)m[xi >> 4];
     6035    z8[0] ^= m8[0];
     6036    z8[1] ^= m8[1];
     6037    /* XOR in most significant nibble * remainder */
     6038    z8[0] ^= (word64)R[a];
     6039
     6040    /* Write back result. */
     6041    x8[0] = z8[0];
     6042    x8[1] = z8[1];
     6043}
     6044#endif
     6045
     6046void GHASH(Aes* aes, const byte* a, word32 aSz, const byte* c,
     6047    word32 cSz, byte* s, word32 sSz)
     6048{
     6049    byte x[AES_BLOCK_SIZE];
     6050    byte scratch[AES_BLOCK_SIZE];
     6051    word32 blocks, partial;
     6052
     6053    XMEMSET(x, 0, AES_BLOCK_SIZE);
     6054
     6055    /* Hash in A, the Additional Authentication Data */
     6056    if (aSz != 0 && a != NULL) {
     6057        blocks = aSz / AES_BLOCK_SIZE;
     6058        partial = aSz % AES_BLOCK_SIZE;
     6059        while (blocks--) {
     6060            xorbuf(x, a, AES_BLOCK_SIZE);
     6061            GMULT(x, aes->M0);
     6062            a += AES_BLOCK_SIZE;
     6063        }
     6064        if (partial != 0) {
     6065            XMEMSET(scratch, 0, AES_BLOCK_SIZE);
     6066            XMEMCPY(scratch, a, partial);
     6067            xorbuf(x, scratch, AES_BLOCK_SIZE);
     6068            GMULT(x, aes->M0);
     6069        }
     6070    }
     6071
     6072    /* Hash in C, the Ciphertext */
     6073    if (cSz != 0 && c != NULL) {
     6074        blocks = cSz / AES_BLOCK_SIZE;
     6075        partial = cSz % AES_BLOCK_SIZE;
     6076        while (blocks--) {
     6077            xorbuf(x, c, AES_BLOCK_SIZE);
     6078            GMULT(x, aes->M0);
     6079            c += AES_BLOCK_SIZE;
     6080        }
     6081        if (partial != 0) {
     6082            XMEMSET(scratch, 0, AES_BLOCK_SIZE);
     6083            XMEMCPY(scratch, c, partial);
     6084            xorbuf(x, scratch, AES_BLOCK_SIZE);
     6085            GMULT(x, aes->M0);
     6086        }
     6087    }
     6088
     6089    /* Hash in the lengths of A and C in bits */
     6090    FlattenSzInBits(&scratch[0], aSz);
     6091    FlattenSzInBits(&scratch[8], cSz);
     6092    xorbuf(x, scratch, AES_BLOCK_SIZE);
     6093    GMULT(x, aes->M0);
     6094
     6095    /* Copy the result into s. */
     6096    XMEMCPY(s, x, sSz);
     6097}
     6098
    55896099#elif defined(WORD64_AVAILABLE) && !defined(GCM_WORD32)
    55906100
     
    55956105    word64 V[2];
    55966106    int i, j;
     6107#ifdef AES_GCM_GMULT_CT
     6108    word64 v1;
     6109#endif
    55976110    V[0] = X[0];  V[1] = X[1];
    55986111
     
    56026115        for (j = 0; j < 64; j++)
    56036116        {
     6117#ifdef AES_GCM_GMULT_CT
     6118            word64 mask = 0 - (y >> 63);
     6119            Z[0] ^= V[0] & mask;
     6120            Z[1] ^= V[1] & mask;
     6121#else
    56046122            if (y & 0x8000000000000000ULL) {
    56056123                Z[0] ^= V[0];
    56066124                Z[1] ^= V[1];
    56076125            }
    5608 
     6126#endif
     6127
     6128#ifdef AES_GCM_GMULT_CT
     6129            v1 = (0 - (V[1] & 1)) & 0xE100000000000000ULL;
     6130            V[1] >>= 1;
     6131            V[1] |= V[0] << 63;
     6132            V[0] >>= 1;
     6133            V[0] ^= v1;
     6134#else
    56096135            if (V[1] & 0x0000000000000001) {
    56106136                V[1] >>= 1;
     
    56206146                V[0] >>= 1;
    56216147            }
     6148#endif
    56226149            y <<= 1;
    56236150        }
     
    59056432        return status;
    59066433
     6434    status = wolfSSL_CryptHwMutexLock();
     6435    if (status != 0)
     6436        return status;
     6437
    59076438    status = LTC_AES_EncryptTagGcm(LTC_BASE, in, out, sz, iv, ivSz,
    59086439        authIn, authInSz, (byte*)aes->key, keySize, authTag, authTagSz);
     6440    wolfSSL_CryptHwMutexUnLock();
    59096441
    59106442    return (status == kStatus_Success) ? 0 : AES_GCM_AUTH_E;
     
    59166448
    59176449/* this function supports inline encrypt */
     6450/* define STM32_AESGCM_PARTIAL for newer STM Cube HAL's with workaround
     6451   for handling partial packets to improve auth tag calculation performance by
     6452   using hardware */
    59186453static int wc_AesGcmEncrypt_STM32(Aes* aes, byte* out, const byte* in, word32 sz,
    59196454                                  const byte* iv, word32 ivSz,
     
    59286463#endif
    59296464    word32 keySize;
     6465#ifdef WOLFSSL_STM32_CUBEMX
    59306466    int status = HAL_OK;
    59316467    word32 blocks = sz / AES_BLOCK_SIZE;
     6468    word32 partialBlock[AES_BLOCK_SIZE/sizeof(word32)];
     6469#else
     6470    int status = SUCCESS;
     6471#endif
    59326472    word32 partial = sz % AES_BLOCK_SIZE;
    5933     byte tag[AES_BLOCK_SIZE];
    5934     byte partialBlock[AES_BLOCK_SIZE];
    5935     byte ctr[AES_BLOCK_SIZE];
     6473    word32 tag[AES_BLOCK_SIZE/sizeof(word32)];
     6474    word32 ctrInit[AES_BLOCK_SIZE/sizeof(word32)];
     6475    word32 ctr[AES_BLOCK_SIZE/sizeof(word32)];
     6476    word32 authhdr[AES_BLOCK_SIZE/sizeof(word32)];
    59366477    byte* authInPadded = NULL;
    5937     int authPadSz;
     6478    int authPadSz, wasAlloc = 0, useSwGhash = 0;
    59386479
    59396480    ret = wc_AesGetKeySize(aes, &keySize);
     
    59476488#endif
    59486489
    5949     ret = wolfSSL_CryptHwMutexLock();
    5950     if (ret != 0) {
    5951         return ret;
    5952     }
    5953 
    59546490    XMEMSET(ctr, 0, AES_BLOCK_SIZE);
    59556491    if (ivSz == GCM_NONCE_MID_SZ) {
     6492        byte* pCtr = (byte*)ctr;
    59566493        XMEMCPY(ctr, iv, ivSz);
    5957         ctr[AES_BLOCK_SIZE - 1] = 1;
     6494        pCtr[AES_BLOCK_SIZE - 1] = 1;
    59586495    }
    59596496    else {
    5960         GHASH(aes, NULL, 0, iv, ivSz, ctr, AES_BLOCK_SIZE);
    5961     }
    5962     /* Hardware requires counter + 1 */
    5963     IncrementGcmCounter(ctr);
    5964 
    5965     if (authInSz == 0 || (authInSz % AES_BLOCK_SIZE) != 0) {
    5966         /* Need to pad the AAD to a full block with zeros. */
    5967         authPadSz = ((authInSz / AES_BLOCK_SIZE) + 1) * AES_BLOCK_SIZE;
    5968         authInPadded = (byte*)XMALLOC(authPadSz, aes->heap,
    5969             DYNAMIC_TYPE_TMP_BUFFER);
    5970         if (authInPadded == NULL) {
    5971             wolfSSL_CryptHwMutexUnLock();
    5972             return MEMORY_E;
     6497        GHASH(aes, NULL, 0, iv, ivSz, (byte*)ctr, AES_BLOCK_SIZE);
     6498    }
     6499    XMEMCPY(ctrInit, ctr, sizeof(ctr)); /* save off initial counter for GMAC */
     6500
     6501    /* Authentication buffer - must be 4-byte multiple zero padded */
     6502    authPadSz = authInSz % sizeof(word32);
     6503    if (authPadSz != 0) {
     6504        authPadSz = authInSz + sizeof(word32) - authPadSz;
     6505        if (authPadSz <= sizeof(authhdr)) {
     6506            authInPadded = (byte*)authhdr;
     6507        }
     6508        else {
     6509            authInPadded = (byte*)XMALLOC(authPadSz, aes->heap,
     6510                DYNAMIC_TYPE_TMP_BUFFER);
     6511            if (authInPadded == NULL) {
     6512                wolfSSL_CryptHwMutexUnLock();
     6513                return MEMORY_E;
     6514            }
     6515            wasAlloc = 1;
    59736516        }
    59746517        XMEMSET(authInPadded, 0, authPadSz);
     
    59796522    }
    59806523
     6524    /* for cases where hardware cannot be used for authTag calculate it */
     6525    /* if IV is not 12 calculate GHASH using software */
     6526    if (ivSz != GCM_NONCE_MID_SZ
     6527#ifndef STM32_AESGCM_PARTIAL
     6528        /* or authIn is not a multiple of 4  */
     6529        || authPadSz != authInSz || sz == 0 || partial != 0
     6530#endif
     6531    ) {
     6532        useSwGhash = 1;
     6533    }
     6534
     6535    /* Hardware requires counter + 1 */
     6536    IncrementGcmCounter((byte*)ctr);
     6537
     6538    ret = wolfSSL_CryptHwMutexLock();
     6539    if (ret != 0) {
     6540        return ret;
     6541    }
    59816542#ifdef WOLFSSL_STM32_CUBEMX
    59826543    hcryp.Init.pInitVect = (STM_CRYPT_TYPE*)ctr;
    59836544    hcryp.Init.Header = (STM_CRYPT_TYPE*)authInPadded;
    5984     hcryp.Init.HeaderSize = authInSz;
    5985 
    5986 #ifdef STM32_CRYPTO_AES_ONLY
     6545
     6546#if defined(STM32_HAL_V2)
     6547    hcryp.Init.Algorithm = CRYP_AES_GCM;
     6548    hcryp.Init.HeaderSize = authPadSz/sizeof(word32);
     6549    #ifdef STM32_AESGCM_PARTIAL
     6550    hcryp.Init.HeaderPadSize = authPadSz - authInSz;
     6551    #endif
     6552    ByteReverseWords(partialBlock, ctr, AES_BLOCK_SIZE);
     6553    hcryp.Init.pInitVect = (STM_CRYPT_TYPE*)partialBlock;
     6554    HAL_CRYP_Init(&hcryp);
     6555
     6556    /* GCM payload phase - can handle partial blocks */
     6557    status = HAL_CRYP_Encrypt(&hcryp, (uint32_t*)in,
     6558        (blocks * AES_BLOCK_SIZE) + partial, (uint32_t*)out, STM32_HAL_TIMEOUT);
     6559    if (status == HAL_OK && !useSwGhash) {
     6560        /* Compute the authTag */
     6561        status = HAL_CRYPEx_AESGCM_GenerateAuthTAG(&hcryp, (uint32_t*)tag,
     6562            STM32_HAL_TIMEOUT);
     6563    }
     6564#elif defined(STM32_CRYPTO_AES_ONLY)
    59876565    /* Set the CRYP parameters */
     6566    hcryp.Init.HeaderSize = authPadSz;
     6567    if (authPadSz == 0)
     6568        hcryp.Init.Header = NULL; /* cannot pass pointer here when authIn == 0 */
    59886569    hcryp.Init.ChainingMode  = CRYP_CHAINMODE_AES_GCM_GMAC;
    59896570    hcryp.Init.OperatingMode = CRYP_ALGOMODE_ENCRYPT;
     
    59956576    if (status == HAL_OK) {
    59966577        /* GCM header phase */
    5997         hcryp.Init.GCMCMACPhase  = CRYP_HEADER_PHASE;
     6578        hcryp.Init.GCMCMACPhase = CRYP_HEADER_PHASE;
    59986579        status = HAL_CRYPEx_AES_Auth(&hcryp, NULL, 0, NULL, STM32_HAL_TIMEOUT);
    59996580    }
    60006581    if (status == HAL_OK) {
    60016582        /* GCM payload phase - blocks */
    6002         hcryp.Init.GCMCMACPhase  = CRYP_PAYLOAD_PHASE;
     6583        hcryp.Init.GCMCMACPhase = CRYP_PAYLOAD_PHASE;
    60036584        if (blocks) {
    60046585            status = HAL_CRYPEx_AES_Auth(&hcryp, (byte*)in,
     
    60066587        }
    60076588    }
    6008     if (status == HAL_OK && (partial != 0 || blocks == 0)) {
     6589    if (status == HAL_OK && (partial != 0 || (sz > 0 && blocks == 0))) {
    60096590        /* GCM payload phase - partial remainder */
    60106591        XMEMSET(partialBlock, 0, sizeof(partialBlock));
    60116592        XMEMCPY(partialBlock, in + (blocks * AES_BLOCK_SIZE), partial);
    6012         status = HAL_CRYPEx_AES_Auth(&hcryp, partialBlock, partial,
    6013             partialBlock, STM32_HAL_TIMEOUT);
     6593        status = HAL_CRYPEx_AES_Auth(&hcryp, (uint8_t*)partialBlock, partial,
     6594                (uint8_t*)partialBlock, STM32_HAL_TIMEOUT);
    60146595        XMEMCPY(out + (blocks * AES_BLOCK_SIZE), partialBlock, partial);
    60156596    }
    6016     if (status == HAL_OK) {
     6597    if (status == HAL_OK && !useSwGhash) {
    60176598        /* GCM final phase */
    60186599        hcryp.Init.GCMCMACPhase  = CRYP_FINAL_PHASE;
    6019         status = HAL_CRYPEx_AES_Auth(&hcryp, NULL, sz, tag, STM32_HAL_TIMEOUT);
    6020     }
    6021 #elif defined(STM32_HAL_V2)
    6022     hcryp.Init.Algorithm  = CRYP_AES_GCM;
    6023     ByteReverseWords((word32*)partialBlock, (word32*)ctr, AES_BLOCK_SIZE);
    6024     hcryp.Init.pInitVect = (STM_CRYPT_TYPE*)partialBlock;
    6025     HAL_CRYP_Init(&hcryp);
    6026 
    6027     /* GCM payload phase - can handle partial blocks */
    6028     status = HAL_CRYP_Encrypt(&hcryp, (uint32_t*)in,
    6029         (blocks * AES_BLOCK_SIZE) + partial, (uint32_t*)out, STM32_HAL_TIMEOUT);
    6030     if (status == HAL_OK) {
    6031         /* Compute the authTag */
    6032         status = HAL_CRYPEx_AESGCM_GenerateAuthTAG(&hcryp, (uint32_t*)tag,
    6033             STM32_HAL_TIMEOUT);
     6600        status = HAL_CRYPEx_AES_Auth(&hcryp, NULL, sz, (uint8_t*)tag, STM32_HAL_TIMEOUT);
    60346601    }
    60356602#else
     6603    hcryp.Init.HeaderSize = authPadSz;
    60366604    HAL_CRYP_Init(&hcryp);
    60376605    if (blocks) {
     
    60446612        XMEMSET(partialBlock, 0, sizeof(partialBlock));
    60456613        XMEMCPY(partialBlock, in + (blocks * AES_BLOCK_SIZE), partial);
    6046         status = HAL_CRYPEx_AESGCM_Encrypt(&hcryp, partialBlock, partial,
    6047             partialBlock, STM32_HAL_TIMEOUT);
     6614        status = HAL_CRYPEx_AESGCM_Encrypt(&hcryp, (uint8_t*)partialBlock, partial,
     6615            (uint8_t*)partialBlock, STM32_HAL_TIMEOUT);
    60486616        XMEMCPY(out + (blocks * AES_BLOCK_SIZE), partialBlock, partial);
    60496617    }
    6050     if (status == HAL_OK) {
     6618    if (status == HAL_OK && !useSwGhash) {
    60516619        /* Compute the authTag */
    6052         status = HAL_CRYPEx_AESGCM_Finish(&hcryp, sz, tag, STM32_HAL_TIMEOUT);
     6620        status = HAL_CRYPEx_AESGCM_Finish(&hcryp, sz, (uint8_t*)tag, STM32_HAL_TIMEOUT);
    60536621    }
    60546622#endif
     
    60586626    HAL_CRYP_DeInit(&hcryp);
    60596627
    6060 #else /* STD_PERI_LIB */
     6628#else /* Standard Peripheral Library */
    60616629    ByteReverseWords(keyCopy, (word32*)aes->key, keySize);
    60626630    status = CRYP_AES_GCM(MODE_ENCRYPT, (uint8_t*)ctr,
     
    60646632                         (uint8_t*)in,           sz,
    60656633                         (uint8_t*)authInPadded, authInSz,
    6066                          (uint8_t*)out,          tag);
     6634                         (uint8_t*)out,          (uint8_t*)tag);
    60676635    if (status != SUCCESS)
    60686636        ret = AES_GCM_AUTH_E;
    60696637#endif /* WOLFSSL_STM32_CUBEMX */
     6638    wolfSSL_CryptHwMutexUnLock();
    60706639
    60716640    if (ret == 0) {
    60726641        /* return authTag */
    60736642        if (authTag) {
    6074             /* STM32 GCM won't compute Auth correctly for partial or
    6075                 when IV != 12, so use software here */
    6076             if (sz == 0 || partial != 0 || ivSz != GCM_NONCE_MID_SZ) {
    6077                 DecrementGcmCounter(ctr); /* hardware requires +1, so subtract it */
     6643            if (useSwGhash) {
    60786644                GHASH(aes, authIn, authInSz, out, sz, authTag, authTagSz);
    6079                 wc_AesEncrypt(aes, ctr, tag);
     6645                wc_AesEncrypt(aes, (byte*)ctrInit, (byte*)tag);
    60806646                xorbuf(authTag, tag, authTagSz);
    60816647            }
    60826648            else {
     6649                /* use hardware calculated tag */
    60836650                XMEMCPY(authTag, tag, authTagSz);
    60846651            }
     
    60866653    }
    60876654
    6088     /* Free memory if not a multiple of AES_BLOCK_SZ */
    6089     if (authInPadded != authIn) {
     6655    /* Free memory */
     6656    if (wasAlloc) {
    60906657        XFREE(authInPadded, aes->heap, DYNAMIC_TYPE_TMP_BUFFER);
    60916658    }
    6092 
    6093     wolfSSL_CryptHwMutexUnLock();
    60946659
    60956660    return ret;
     
    61166681    const byte* p = in;
    61176682    byte* c = out;
    6118     byte counter[AES_BLOCK_SIZE];
    6119     byte initialCounter[AES_BLOCK_SIZE];
    6120     byte *ctr;
    6121     byte scratch[AES_BLOCK_SIZE];
     6683    ALIGN32 byte counter[AES_BLOCK_SIZE];
     6684    ALIGN32 byte initialCounter[AES_BLOCK_SIZE];
     6685    ALIGN32 byte scratch[AES_BLOCK_SIZE];
     6686
     6687    if (ivSz == GCM_NONCE_MID_SZ) {
     6688        /* Counter is IV with bottom 4 bytes set to: 0x00,0x00,0x00,0x01. */
     6689        XMEMCPY(counter, iv, ivSz);
     6690        XMEMSET(counter + GCM_NONCE_MID_SZ, 0,
     6691                                         AES_BLOCK_SIZE - GCM_NONCE_MID_SZ - 1);
     6692        counter[AES_BLOCK_SIZE - 1] = 1;
     6693    }
     6694    else {
     6695        /* Counter is GHASH of IV. */
    61226696#ifdef OPENSSL_EXTRA
    6123     word32 aadTemp;
    6124 #endif
    6125     ctr = counter;
    6126     XMEMSET(initialCounter, 0, AES_BLOCK_SIZE);
    6127     XMEMSET(scratch, 0, AES_BLOCK_SIZE);
    6128     if (ivSz == GCM_NONCE_MID_SZ) {
    6129         XMEMCPY(initialCounter, iv, ivSz);
    6130         initialCounter[AES_BLOCK_SIZE - 1] = 1;
    6131     }
    6132     else {
    6133 #ifdef OPENSSL_EXTRA
    6134         aadTemp = aes->aadLen;
     6697        word32 aadTemp = aes->aadLen;
    61356698        aes->aadLen = 0;
    61366699#endif
    6137         GHASH(aes, NULL, 0, iv, ivSz, initialCounter, AES_BLOCK_SIZE);
     6700        GHASH(aes, NULL, 0, iv, ivSz, counter, AES_BLOCK_SIZE);
    61386701#ifdef OPENSSL_EXTRA
    61396702        aes->aadLen = aadTemp;
    61406703#endif
    61416704    }
    6142     XMEMCPY(ctr, initialCounter, AES_BLOCK_SIZE);
     6705    XMEMCPY(initialCounter, counter, AES_BLOCK_SIZE);
    61436706
    61446707#ifdef WOLFSSL_PIC32MZ_CRYPT
    61456708    if (blocks) {
    61466709        /* use initial IV for HW, but don't use it below */
    6147         XMEMCPY(aes->reg, ctr, AES_BLOCK_SIZE);
     6710        XMEMCPY(aes->reg, counter, AES_BLOCK_SIZE);
    61486711
    61496712        ret = wc_Pic32AesCrypt(
     
    61626725    if (c != p && blocks > 0) { /* can not handle inline encryption */
    61636726        while (blocks--) {
    6164             IncrementGcmCounter(ctr);
    6165             XMEMCPY(c, ctr, AES_BLOCK_SIZE);
     6727            IncrementGcmCounter(counter);
     6728            XMEMCPY(c, counter, AES_BLOCK_SIZE);
    61666729            c += AES_BLOCK_SIZE;
    61676730        }
     
    61756738    else
    61766739#endif /* HAVE_AES_ECB && !WOLFSSL_PIC32MZ_CRYPT */
    6177 
    6178     while (blocks--) {
    6179         IncrementGcmCounter(ctr);
    6180     #if !defined(WOLFSSL_PIC32MZ_CRYPT)
    6181         wc_AesEncrypt(aes, ctr, scratch);
    6182         xorbuf(scratch, p, AES_BLOCK_SIZE);
    6183         XMEMCPY(c, scratch, AES_BLOCK_SIZE);
    6184     #endif
    6185         p += AES_BLOCK_SIZE;
    6186         c += AES_BLOCK_SIZE;
     6740    {
     6741        while (blocks--) {
     6742            IncrementGcmCounter(counter);
     6743        #if !defined(WOLFSSL_PIC32MZ_CRYPT)
     6744            wc_AesEncrypt(aes, counter, scratch);
     6745            xorbufout(c, scratch, p, AES_BLOCK_SIZE);
     6746        #endif
     6747            p += AES_BLOCK_SIZE;
     6748            c += AES_BLOCK_SIZE;
     6749        }
    61876750    }
    61886751
    61896752    if (partial != 0) {
    6190         IncrementGcmCounter(ctr);
    6191         wc_AesEncrypt(aes, ctr, scratch);
    6192         xorbuf(scratch, p, partial);
    6193         XMEMCPY(c, scratch, partial);
     6753        IncrementGcmCounter(counter);
     6754        wc_AesEncrypt(aes, counter, scratch);
     6755        xorbufout(c, scratch, p, partial);
    61946756    }
    61956757    if (authTag) {
     
    62696831#endif /* WOLFSSL_ASYNC_CRYPT */
    62706832
     6833#ifdef WOLFSSL_SILABS_SE_ACCEL
     6834    return wc_AesGcmEncrypt_silabs(
     6835        aes, out, in, sz,
     6836        iv, ivSz,
     6837        authTag, authTagSz,
     6838        authIn, authInSz);
     6839#endif
     6840
    62716841#ifdef STM32_CRYPTO_AES_GCM
    6272     /* The STM standard peripheral library API's doesn't support partial blocks */
    6273     #ifdef STD_PERI_LIB
    6274     if (partial == 0)
    6275     #endif
    6276     {
    6277         return wc_AesGcmEncrypt_STM32(
    6278             aes, out, in, sz, iv, ivSz,
    6279             authTag, authTagSz, authIn, authInSz);
    6280     }
     6842    return wc_AesGcmEncrypt_STM32(
     6843        aes, out, in, sz, iv, ivSz,
     6844        authTag, authTagSz, authIn, authInSz);
    62816845#endif /* STM32_CRYPTO_AES_GCM */
    62826846
     
    62846848    #ifdef HAVE_INTEL_AVX2
    62856849    if (IS_INTEL_AVX2(intel_flags)) {
     6850        SAVE_VECTOR_REGISTERS();
    62866851        AES_GCM_encrypt_avx2(in, out, authIn, iv, authTag, sz, authInSz, ivSz,
    62876852                                 authTagSz, (const byte*)aes->key, aes->rounds);
     6853        RESTORE_VECTOR_REGISTERS();
    62886854        return 0;
    62896855    }
     
    62926858    #ifdef HAVE_INTEL_AVX1
    62936859    if (IS_INTEL_AVX1(intel_flags)) {
     6860        SAVE_VECTOR_REGISTERS();
    62946861        AES_GCM_encrypt_avx1(in, out, authIn, iv, authTag, sz, authInSz, ivSz,
    62956862                                 authTagSz, (const byte*)aes->key, aes->rounds);
     6863        RESTORE_VECTOR_REGISTERS();
    62966864        return 0;
    62976865    }
     
    63416909    }
    63426910
     6911    status = wolfSSL_CryptHwMutexLock();
     6912    if (status != 0)
     6913        return status;
     6914
    63436915    status = LTC_AES_DecryptTagGcm(LTC_BASE, in, out, sz, iv, ivSz,
    63446916        authIn, authInSz, (byte*)aes->key, keySize, authTag, authTagSz);
     6917    wolfSSL_CryptHwMutexUnLock();
    63456918
    63466919    return (status == kStatus_Success) ? 0 : AES_GCM_AUTH_E;
     
    63596932    int ret;
    63606933#ifdef WOLFSSL_STM32_CUBEMX
     6934    int status = HAL_OK;
    63616935    CRYP_HandleTypeDef hcryp;
     6936    word32 blocks = sz / AES_BLOCK_SIZE;
    63626937#else
     6938    int status = SUCCESS;
    63636939    word32 keyCopy[AES_256_KEY_SIZE/sizeof(word32)];
    63646940#endif
    63656941    word32 keySize;
    6366     int status = HAL_OK;
    6367     word32 blocks = sz / AES_BLOCK_SIZE;
    63686942    word32 partial = sz % AES_BLOCK_SIZE;
    6369     byte tag[AES_BLOCK_SIZE];
    6370     byte partialBlock[AES_BLOCK_SIZE];
    6371     byte ctr[AES_BLOCK_SIZE];
     6943    word32 tag[AES_BLOCK_SIZE/sizeof(word32)];
     6944    word32 tagExpected[AES_BLOCK_SIZE/sizeof(word32)];
     6945    word32 partialBlock[AES_BLOCK_SIZE/sizeof(word32)];
     6946    word32 ctr[AES_BLOCK_SIZE/sizeof(word32)];
     6947    word32 authhdr[AES_BLOCK_SIZE/sizeof(word32)];
    63726948    byte* authInPadded = NULL;
    6373     int authPadSz;
     6949    int authPadSz, wasAlloc = 0, tagComputed = 0;
    63746950
    63756951    ret = wc_AesGetKeySize(aes, &keySize);
     
    63836959#endif
    63846960
     6961    XMEMSET(ctr, 0, AES_BLOCK_SIZE);
     6962    if (ivSz == GCM_NONCE_MID_SZ) {
     6963        byte* pCtr = (byte*)ctr;
     6964        XMEMCPY(ctr, iv, ivSz);
     6965        pCtr[AES_BLOCK_SIZE - 1] = 1;
     6966    }
     6967    else {
     6968        GHASH(aes, NULL, 0, iv, ivSz, (byte*)ctr, AES_BLOCK_SIZE);
     6969    }
     6970
     6971    /* Make copy of expected authTag, which could get corrupted in some
     6972     * Cube HAL versions without proper partial block support.
     6973     * For TLS blocks the authTag is after the output buffer, so save it */
     6974    XMEMCPY(tagExpected, authTag, authTagSz);
     6975
     6976    /* Authentication buffer - must be 4-byte multiple zero padded */
     6977    authPadSz = authInSz % sizeof(word32);
     6978    if (authPadSz != 0) {
     6979        authPadSz = authInSz + sizeof(word32) - authPadSz;
     6980    }
     6981    else {
     6982        authPadSz = authInSz;
     6983    }
     6984
     6985    /* for cases where hardware cannot be used for authTag calculate it */
     6986    /* if IV is not 12 calculate GHASH using software */
     6987    if (ivSz != GCM_NONCE_MID_SZ || sz == 0 || partial != 0
     6988#ifndef STM32_AESGCM_PARTIAL
     6989        /* or authIn is not a multiple of 4  */
     6990        || authPadSz != authInSz
     6991#endif
     6992    ) {
     6993                GHASH(aes, authIn, authInSz, in, sz, (byte*)tag, sizeof(tag));
     6994                wc_AesEncrypt(aes, (byte*)ctr, (byte*)partialBlock);
     6995                xorbuf(tag, partialBlock, sizeof(tag));
     6996                tagComputed = 1;
     6997    }
     6998
     6999    /* if using hardware for authentication tag make sure its aligned and zero padded */
     7000    if (authPadSz != authInSz && !tagComputed) {
     7001        if (authPadSz <= sizeof(authhdr)) {
     7002            authInPadded = (byte*)authhdr;
     7003        }
     7004        else {
     7005            authInPadded = (byte*)XMALLOC(authPadSz, aes->heap,
     7006                DYNAMIC_TYPE_TMP_BUFFER);
     7007            if (authInPadded == NULL) {
     7008                wolfSSL_CryptHwMutexUnLock();
     7009                return MEMORY_E;
     7010            }
     7011            wasAlloc = 1;
     7012        }
     7013        XMEMSET(authInPadded, 0, authPadSz);
     7014        XMEMCPY(authInPadded, authIn, authInSz);
     7015    } else {
     7016        authInPadded = (byte*)authIn;
     7017    }
     7018
     7019    /* Hardware requires counter + 1 */
     7020    IncrementGcmCounter((byte*)ctr);
     7021
    63857022    ret = wolfSSL_CryptHwMutexLock();
    63867023    if (ret != 0) {
    63877024        return ret;
    63887025    }
    6389 
    6390     XMEMSET(ctr, 0, AES_BLOCK_SIZE);
    6391     if (ivSz == GCM_NONCE_MID_SZ) {
    6392         XMEMCPY(ctr, iv, ivSz);
    6393         ctr[AES_BLOCK_SIZE - 1] = 1;
    6394     }
    6395     else {
    6396         GHASH(aes, NULL, 0, iv, ivSz, ctr, AES_BLOCK_SIZE);
    6397     }
    6398     /* Hardware requires counter + 1 */
    6399     IncrementGcmCounter(ctr);
    6400 
    6401     if (authInSz == 0 || (authInSz % AES_BLOCK_SIZE) != 0) {
    6402         /* Need to pad the AAD to a full block with zeros. */
    6403         authPadSz = ((authInSz / AES_BLOCK_SIZE) + 1) * AES_BLOCK_SIZE;
    6404         authInPadded = (byte*)XMALLOC(authPadSz, aes->heap,
    6405             DYNAMIC_TYPE_TMP_BUFFER);
    6406         if (authInPadded == NULL) {
    6407             wolfSSL_CryptHwMutexUnLock();
    6408             return MEMORY_E;
    6409         }
    6410         XMEMSET(authInPadded, 0, authPadSz);
    6411         XMEMCPY(authInPadded, authIn, authInSz);
    6412     } else {
    6413         authPadSz = authInSz;
    6414         authInPadded = (byte*)authIn;
    6415     }
    6416 
    64177026#ifdef WOLFSSL_STM32_CUBEMX
    64187027    hcryp.Init.pInitVect = (STM_CRYPT_TYPE*)ctr;
    64197028    hcryp.Init.Header = (STM_CRYPT_TYPE*)authInPadded;
    6420     hcryp.Init.HeaderSize = authInSz;
    6421 
    6422 #ifdef STM32_CRYPTO_AES_ONLY
     7029
     7030#if defined(STM32_HAL_V2)
     7031    hcryp.Init.Algorithm = CRYP_AES_GCM;
     7032    hcryp.Init.HeaderSize = authPadSz/sizeof(word32);
     7033    #ifdef STM32_AESGCM_PARTIAL
     7034    hcryp.Init.HeaderPadSize = authPadSz - authInSz;
     7035    #endif
     7036    ByteReverseWords(partialBlock, ctr, AES_BLOCK_SIZE);
     7037    hcryp.Init.pInitVect = (STM_CRYPT_TYPE*)partialBlock;
     7038    HAL_CRYP_Init(&hcryp);
     7039
     7040    /* GCM payload phase - can handle partial blocks */
     7041    status = HAL_CRYP_Decrypt(&hcryp, (uint32_t*)in,
     7042        (blocks * AES_BLOCK_SIZE) + partial, (uint32_t*)out, STM32_HAL_TIMEOUT);
     7043    if (status == HAL_OK && tagComputed == 0) {
     7044        /* Compute the authTag */
     7045        status = HAL_CRYPEx_AESGCM_GenerateAuthTAG(&hcryp, (uint32_t*)tag,
     7046            STM32_HAL_TIMEOUT);
     7047    }
     7048#elif defined(STM32_CRYPTO_AES_ONLY)
    64237049    /* Set the CRYP parameters */
     7050    hcryp.Init.HeaderSize = authPadSz;
     7051    if (authPadSz == 0)
     7052        hcryp.Init.Header = NULL; /* cannot pass pointer when authIn == 0 */
    64247053    hcryp.Init.ChainingMode  = CRYP_CHAINMODE_AES_GCM_GMAC;
    64257054    hcryp.Init.OperatingMode = CRYP_ALGOMODE_DECRYPT;
     
    64367065    if (status == HAL_OK) {
    64377066        /* GCM payload phase - blocks */
    6438         hcryp.Init.GCMCMACPhase  = CRYP_PAYLOAD_PHASE;
     7067        hcryp.Init.GCMCMACPhase = CRYP_PAYLOAD_PHASE;
    64397068        if (blocks) {
    64407069            status = HAL_CRYPEx_AES_Auth(&hcryp, (byte*)in,
     
    64427071        }
    64437072    }
    6444     if (status == HAL_OK && (partial != 0 || blocks == 0)) {
     7073    if (status == HAL_OK && (partial != 0 || (sz > 0 && blocks == 0))) {
    64457074        /* GCM payload phase - partial remainder */
    64467075        XMEMSET(partialBlock, 0, sizeof(partialBlock));
    64477076        XMEMCPY(partialBlock, in + (blocks * AES_BLOCK_SIZE), partial);
    6448         status = HAL_CRYPEx_AES_Auth(&hcryp, partialBlock, partial,
    6449             partialBlock, STM32_HAL_TIMEOUT);
     7077        status = HAL_CRYPEx_AES_Auth(&hcryp, (byte*)partialBlock, partial,
     7078            (byte*)partialBlock, STM32_HAL_TIMEOUT);
    64507079        XMEMCPY(out + (blocks * AES_BLOCK_SIZE), partialBlock, partial);
    64517080    }
    6452     if (status == HAL_OK) {
     7081    if (status == HAL_OK && tagComputed == 0) {
    64537082        /* GCM final phase */
    64547083        hcryp.Init.GCMCMACPhase = CRYP_FINAL_PHASE;
    6455         status = HAL_CRYPEx_AES_Auth(&hcryp, NULL, sz, tag, STM32_HAL_TIMEOUT);
    6456     }
    6457 #elif defined(STM32_HAL_V2)
    6458     hcryp.Init.Algorithm = CRYP_AES_GCM;
    6459     ByteReverseWords((word32*)partialBlock, (word32*)ctr, AES_BLOCK_SIZE);
    6460     hcryp.Init.pInitVect = (STM_CRYPT_TYPE*)partialBlock;
    6461     HAL_CRYP_Init(&hcryp);
    6462 
    6463     /* GCM payload phase - can handle partial blocks */
    6464     status = HAL_CRYP_Decrypt(&hcryp, (uint32_t*)in,
    6465         (blocks * AES_BLOCK_SIZE) + partial, (uint32_t*)out, STM32_HAL_TIMEOUT);
    6466     if (status == HAL_OK) {
    6467         /* Compute the authTag */
    6468         status = HAL_CRYPEx_AESGCM_GenerateAuthTAG(&hcryp, (uint32_t*)tag,
    6469             STM32_HAL_TIMEOUT);
     7084        status = HAL_CRYPEx_AES_Auth(&hcryp, NULL, sz, (byte*)tag, STM32_HAL_TIMEOUT);
    64707085    }
    64717086#else
     7087    hcryp.Init.HeaderSize = authPadSz;
    64727088    HAL_CRYP_Init(&hcryp);
    64737089    if (blocks) {
     
    64807096        XMEMSET(partialBlock, 0, sizeof(partialBlock));
    64817097        XMEMCPY(partialBlock, in + (blocks * AES_BLOCK_SIZE), partial);
    6482         status = HAL_CRYPEx_AESGCM_Decrypt(&hcryp, partialBlock, partial,
    6483             partialBlock, STM32_HAL_TIMEOUT);
     7098        status = HAL_CRYPEx_AESGCM_Decrypt(&hcryp, (byte*)partialBlock, partial,
     7099            (byte*)partialBlock, STM32_HAL_TIMEOUT);
    64847100        XMEMCPY(out + (blocks * AES_BLOCK_SIZE), partialBlock, partial);
    64857101    }
    6486     if (status == HAL_OK) {
     7102    if (status == HAL_OK && tagComputed == 0) {
    64877103        /* Compute the authTag */
    6488         status = HAL_CRYPEx_AESGCM_Finish(&hcryp, sz, tag, STM32_HAL_TIMEOUT);
     7104        status = HAL_CRYPEx_AESGCM_Finish(&hcryp, sz, (byte*)tag, STM32_HAL_TIMEOUT);
    64897105    }
    64907106#endif
     
    64957111    HAL_CRYP_DeInit(&hcryp);
    64967112
    6497 #else /* STD_PERI_LIB */
     7113#else /* Standard Peripheral Library */
    64987114    ByteReverseWords(keyCopy, (word32*)aes->key, aes->keylen);
    64997115
     
    65017117     * they are not block aligned, because this length (in bits) is used
    65027118     * in the final GHASH. */
     7119    XMEMSET(partialBlock, 0, sizeof(partialBlock)); /* use this to get tag */
    65037120    status = CRYP_AES_GCM(MODE_DECRYPT, (uint8_t*)ctr,
    65047121                         (uint8_t*)keyCopy,      keySize * 8,
    65057122                         (uint8_t*)in,           sz,
    65067123                         (uint8_t*)authInPadded, authInSz,
    6507                          (uint8_t*)out,          tag);
     7124                         (uint8_t*)out,          (uint8_t*)partialBlock);
    65087125    if (status != SUCCESS)
    65097126        ret = AES_GCM_AUTH_E;
     7127    if (tagComputed == 0)
     7128        XMEMCPY(tag, partialBlock, authTagSz);
    65107129#endif /* WOLFSSL_STM32_CUBEMX */
    6511 
    6512     /* STM32 GCM hardware only supports IV of 12 bytes, so use software for auth */
    6513     if (sz == 0 || ivSz != GCM_NONCE_MID_SZ) {
    6514         DecrementGcmCounter(ctr); /* hardware requires +1, so subtract it */
    6515         GHASH(aes, authIn, authInSz, in, sz, tag, sizeof(tag));
    6516         wc_AesEncrypt(aes, ctr, partialBlock);
    6517         xorbuf(tag, partialBlock, sizeof(tag));
    6518     }
    6519 
    6520     if (ConstantCompare(authTag, tag, authTagSz) != 0) {
     7130    wolfSSL_CryptHwMutexUnLock();
     7131
     7132    /* Check authentication tag */
     7133    if (ConstantCompare((const byte*)tagExpected, (byte*)tag, authTagSz) != 0) {
    65217134        ret = AES_GCM_AUTH_E;
    65227135    }
    65237136
    6524     /* Free memory if not a multiple of AES_BLOCK_SZ */
    6525     if (authInPadded != authIn) {
     7137    /* Free memory */
     7138    if (wasAlloc) {
    65267139        XFREE(authInPadded, aes->heap, DYNAMIC_TYPE_TMP_BUFFER);
    65277140    }
    6528 
    6529     wolfSSL_CryptHwMutexUnLock();
    65307141
    65317142    return ret;
     
    65527163    const byte* c = in;
    65537164    byte* p = out;
    6554     byte counter[AES_BLOCK_SIZE];
    6555     byte initialCounter[AES_BLOCK_SIZE];
    6556     byte *ctr;
    6557     byte scratch[AES_BLOCK_SIZE];
    6558     byte Tprime[AES_BLOCK_SIZE];
    6559     byte EKY0[AES_BLOCK_SIZE];
     7165    ALIGN32 byte counter[AES_BLOCK_SIZE];
     7166    ALIGN32 byte scratch[AES_BLOCK_SIZE];
     7167    ALIGN32 byte Tprime[AES_BLOCK_SIZE];
     7168    ALIGN32 byte EKY0[AES_BLOCK_SIZE];
     7169
     7170    if (ivSz == GCM_NONCE_MID_SZ) {
     7171        /* Counter is IV with bottom 4 bytes set to: 0x00,0x00,0x00,0x01. */
     7172        XMEMCPY(counter, iv, ivSz);
     7173        XMEMSET(counter + GCM_NONCE_MID_SZ, 0,
     7174                                         AES_BLOCK_SIZE - GCM_NONCE_MID_SZ - 1);
     7175        counter[AES_BLOCK_SIZE - 1] = 1;
     7176    }
     7177    else {
     7178        /* Counter is GHASH of IV. */
    65607179#ifdef OPENSSL_EXTRA
    6561     word32 aadTemp;
    6562 #endif
    6563     ctr = counter;
    6564     XMEMSET(initialCounter, 0, AES_BLOCK_SIZE);
    6565     if (ivSz == GCM_NONCE_MID_SZ) {
    6566         XMEMCPY(initialCounter, iv, ivSz);
    6567         initialCounter[AES_BLOCK_SIZE - 1] = 1;
    6568     }
    6569     else {
    6570 #ifdef OPENSSL_EXTRA
    6571         aadTemp = aes->aadLen;
     7180        word32 aadTemp = aes->aadLen;
    65727181        aes->aadLen = 0;
    65737182#endif
    6574         GHASH(aes, NULL, 0, iv, ivSz, initialCounter, AES_BLOCK_SIZE);
     7183        GHASH(aes, NULL, 0, iv, ivSz, counter, AES_BLOCK_SIZE);
    65757184#ifdef OPENSSL_EXTRA
    65767185        aes->aadLen = aadTemp;
    65777186#endif
    65787187    }
    6579     XMEMCPY(ctr, initialCounter, AES_BLOCK_SIZE);
    6580 
    6581     /* Calc the authTag again using the received auth data and the cipher text */
     7188
     7189    /* Calc the authTag again using received auth data and the cipher text */
    65827190    GHASH(aes, authIn, authInSz, in, sz, Tprime, sizeof(Tprime));
    6583     wc_AesEncrypt(aes, ctr, EKY0);
     7191    wc_AesEncrypt(aes, counter, EKY0);
    65847192    xorbuf(Tprime, EKY0, sizeof(Tprime));
    65857193
     
    65987206    if (blocks) {
    65997207        /* use initial IV for HW, but don't use it below */
    6600         XMEMCPY(aes->reg, ctr, AES_BLOCK_SIZE);
     7208        XMEMCPY(aes->reg, counter, AES_BLOCK_SIZE);
    66017209
    66027210        ret = wc_Pic32AesCrypt(
     
    66157223    if (c != p && blocks > 0) { /* can not handle inline decryption */
    66167224        while (blocks--) {
    6617             IncrementGcmCounter(ctr);
    6618             XMEMCPY(p, ctr, AES_BLOCK_SIZE);
     7225            IncrementGcmCounter(counter);
     7226            XMEMCPY(p, counter, AES_BLOCK_SIZE);
    66197227            p += AES_BLOCK_SIZE;
    66207228        }
     
    66297237    else
    66307238#endif /* HAVE_AES_ECB && !PIC32MZ */
    6631     while (blocks--) {
    6632         IncrementGcmCounter(ctr);
    6633     #if !defined(WOLFSSL_PIC32MZ_CRYPT)
    6634         wc_AesEncrypt(aes, ctr, scratch);
    6635         xorbuf(scratch, c, AES_BLOCK_SIZE);
    6636         XMEMCPY(p, scratch, AES_BLOCK_SIZE);
    6637     #endif
    6638         p += AES_BLOCK_SIZE;
    6639         c += AES_BLOCK_SIZE;
     7239    {
     7240        while (blocks--) {
     7241            IncrementGcmCounter(counter);
     7242        #if !defined(WOLFSSL_PIC32MZ_CRYPT)
     7243            wc_AesEncrypt(aes, counter, scratch);
     7244            xorbufout(p, scratch, c, AES_BLOCK_SIZE);
     7245        #endif
     7246            p += AES_BLOCK_SIZE;
     7247            c += AES_BLOCK_SIZE;
     7248        }
    66407249    }
    66417250
    66427251    if (partial != 0) {
    6643         IncrementGcmCounter(ctr);
    6644         wc_AesEncrypt(aes, ctr, scratch);
     7252        IncrementGcmCounter(counter);
     7253        wc_AesEncrypt(aes, counter, scratch);
    66457254        xorbuf(scratch, c, partial);
    66467255        XMEMCPY(p, scratch, partial);
     
    67167325#endif /* WOLFSSL_ASYNC_CRYPT */
    67177326
     7327#ifdef WOLFSSL_SILABS_SE_ACCEL
     7328    return wc_AesGcmDecrypt_silabs(
     7329        aes, out, in, sz, iv, ivSz,
     7330        authTag, authTagSz, authIn, authInSz);
     7331
     7332#endif
     7333
    67187334#ifdef STM32_CRYPTO_AES_GCM
    67197335    /* The STM standard peripheral library API's doesn't support partial blocks */
    6720     #ifdef STD_PERI_LIB
    6721     if (partial == 0)
    6722     #endif
    6723     {
    6724         return wc_AesGcmDecrypt_STM32(
    6725             aes, out, in, sz, iv, ivSz,
    6726             authTag, authTagSz, authIn, authInSz);
    6727     }
     7336    return wc_AesGcmDecrypt_STM32(
     7337        aes, out, in, sz, iv, ivSz,
     7338        authTag, authTagSz, authIn, authInSz);
    67287339#endif /* STM32_CRYPTO_AES_GCM */
    67297340
     
    67317342    #ifdef HAVE_INTEL_AVX2
    67327343    if (IS_INTEL_AVX2(intel_flags)) {
     7344        SAVE_VECTOR_REGISTERS();
    67337345        AES_GCM_decrypt_avx2(in, out, authIn, iv, authTag, sz, authInSz, ivSz,
    67347346                                 authTagSz, (byte*)aes->key, aes->rounds, &res);
     7347        RESTORE_VECTOR_REGISTERS();
    67357348        if (res == 0)
    67367349            return AES_GCM_AUTH_E;
     
    67417354    #ifdef HAVE_INTEL_AVX1
    67427355    if (IS_INTEL_AVX1(intel_flags)) {
     7356        SAVE_VECTOR_REGISTERS();
    67437357        AES_GCM_decrypt_avx1(in, out, authIn, iv, authTag, sz, authInSz, ivSz,
    67447358                                 authTagSz, (byte*)aes->key, aes->rounds, &res);
     7359        RESTORE_VECTOR_REGISTERS();
    67457360        if (res == 0)
    67467361            return AES_GCM_AUTH_E;
     
    68767491            byte* authTag, word32 authTagSz, WC_RNG* rng)
    68777492{
    6878     Aes aes;
     7493#ifdef WOLFSSL_SMALL_STACK
     7494    Aes *aes = NULL;
     7495#else
     7496    Aes aes[1];
     7497#endif
    68797498    int ret;
    68807499
     
    68857504    }
    68867505
    6887     ret = wc_AesInit(&aes, NULL, INVALID_DEVID);
     7506#ifdef WOLFSSL_SMALL_STACK
     7507    if ((aes = (Aes *)XMALLOC(sizeof *aes, NULL,
     7508                              DYNAMIC_TYPE_AES)) == NULL)
     7509        return MEMORY_E;
     7510#endif
     7511
     7512    ret = wc_AesInit(aes, NULL, INVALID_DEVID);
    68887513    if (ret == 0) {
    6889         ret = wc_AesGcmSetKey(&aes, key, keySz);
     7514        ret = wc_AesGcmSetKey(aes, key, keySz);
    68907515        if (ret == 0)
    6891             ret = wc_AesGcmSetIV(&aes, ivSz, NULL, 0, rng);
     7516            ret = wc_AesGcmSetIV(aes, ivSz, NULL, 0, rng);
    68927517        if (ret == 0)
    6893             ret = wc_AesGcmEncrypt_ex(&aes, NULL, NULL, 0, iv, ivSz,
     7518            ret = wc_AesGcmEncrypt_ex(aes, NULL, NULL, 0, iv, ivSz,
    68947519                                  authTag, authTagSz, authIn, authInSz);
    6895         wc_AesFree(&aes);
    6896     }
    6897     ForceZero(&aes, sizeof(aes));
     7520        wc_AesFree(aes);
     7521    }
     7522    ForceZero(aes, sizeof *aes);
     7523#ifdef WOLFSSL_SMALL_STACK
     7524    XFREE(aes, NULL, DYNAMIC_TYPE_AES);
     7525#endif
    68987526
    68997527    return ret;
     
    69067534{
    69077535    int ret;
    6908 #ifndef NO_AES_DECRYPT
    6909     Aes aes;
     7536#ifdef HAVE_AES_DECRYPT
     7537#ifdef WOLFSSL_SMALL_STACK
     7538    Aes *aes = NULL;
     7539#else
     7540    Aes aes[1];
     7541#endif
    69107542
    69117543    if (key == NULL || iv == NULL || (authIn == NULL && authInSz != 0) ||
     
    69157547    }
    69167548
    6917     ret = wc_AesInit(&aes, NULL, INVALID_DEVID);
     7549#ifdef WOLFSSL_SMALL_STACK
     7550    if ((aes = (Aes *)XMALLOC(sizeof *aes, NULL,
     7551                              DYNAMIC_TYPE_AES)) == NULL)
     7552        return MEMORY_E;
     7553#endif
     7554
     7555    ret = wc_AesInit(aes, NULL, INVALID_DEVID);
    69187556    if (ret == 0) {
    6919         ret = wc_AesGcmSetKey(&aes, key, keySz);
     7557        ret = wc_AesGcmSetKey(aes, key, keySz);
    69207558        if (ret == 0)
    6921             ret = wc_AesGcmDecrypt(&aes, NULL, NULL, 0, iv, ivSz,
     7559            ret = wc_AesGcmDecrypt(aes, NULL, NULL, 0, iv, ivSz,
    69227560                                  authTag, authTagSz, authIn, authInSz);
    6923         wc_AesFree(&aes);
    6924     }
    6925     ForceZero(&aes, sizeof(aes));
     7561        wc_AesFree(aes);
     7562    }
     7563    ForceZero(aes, sizeof *aes);
     7564#ifdef WOLFSSL_SMALL_STACK
     7565    XFREE(aes, NULL, DYNAMIC_TYPE_AES);
     7566#endif
    69267567#else
    69277568    (void)key;
     
    69717612}
    69727613
     7614
     7615/* Checks if the tag size is an accepted value based on RFC 3610 section 2
     7616 * returns 0 if tag size is ok
     7617 */
     7618int wc_AesCcmCheckTagSize(int sz)
     7619{
     7620    /* values here are from RFC 3610 section 2 */
     7621    if (sz != 4 && sz != 6 && sz != 8 && sz != 10 && sz != 12 && sz != 14
     7622            && sz != 16) {
     7623        WOLFSSL_MSG("Bad auth tag size AES-CCM");
     7624        return BAD_FUNC_ARG;
     7625    }
     7626    return 0;
     7627}
     7628
    69737629#ifdef WOLFSSL_ARMASM
    69747630    /* implementation located in wolfcrypt/src/port/arm/armv8-aes.c */
     
    69807636    /* implemented in wolfcrypt/src/port/caam_aes.c */
    69817637
     7638#elif defined(WOLFSSL_SILABS_SE_ACCEL)
     7639    /* implemented in wolfcrypt/src/port/silabs/silabs_aes.c */
     7640int wc_AesCcmEncrypt(Aes* aes, byte* out, const byte* in, word32 inSz,
     7641                   const byte* nonce, word32 nonceSz,
     7642                   byte* authTag, word32 authTagSz,
     7643                   const byte* authIn, word32 authInSz)
     7644{
     7645    return wc_AesCcmEncrypt_silabs(
     7646        aes, out, in, inSz,
     7647        nonce, nonceSz,
     7648        authTag, authTagSz,
     7649        authIn, authInSz);
     7650}
     7651
     7652#ifdef HAVE_AES_DECRYPT
     7653int  wc_AesCcmDecrypt(Aes* aes, byte* out, const byte* in, word32 inSz,
     7654                   const byte* nonce, word32 nonceSz,
     7655                   const byte* authTag, word32 authTagSz,
     7656                   const byte* authIn, word32 authInSz)
     7657{
     7658    return wc_AesCcmDecrypt_silabs(
     7659        aes, out, in, inSz,
     7660        nonce, nonceSz,
     7661        authTag, authTagSz,
     7662        authIn, authInSz);
     7663}
     7664#endif
    69827665#elif defined(FREESCALE_LTC)
    69837666
     
    69897672{
    69907673    byte *key;
    6991     uint32_t keySize;
     7674    word32 keySize;
    69927675    status_t status;
    69937676
    69947677    /* sanity check on arguments */
     7678    /* note, LTC_AES_EncryptTagCcm() doesn't allow null src or dst
     7679     * ptrs even if inSz is zero (ltc_aes_ccm_check_input_args()), so
     7680     * don't allow it here either.
     7681     */
    69957682    if (aes == NULL || out == NULL || in == NULL || nonce == NULL
    6996             || authTag == NULL || nonceSz < 7 || nonceSz > 13)
     7683            || authTag == NULL || nonceSz < 7 || nonceSz > 13) {
    69977684        return BAD_FUNC_ARG;
     7685    }
     7686
     7687    if (wc_AesCcmCheckTagSize(authTagSz) != 0) {
     7688        return BAD_FUNC_ARG;
     7689    }
    69987690
    69997691    key = (byte*)aes->key;
     
    70047696    }
    70057697
     7698    status = wolfSSL_CryptHwMutexLock();
     7699    if (status != 0)
     7700        return status;
     7701
    70067702    status = LTC_AES_EncryptTagCcm(LTC_BASE, in, out, inSz,
    70077703        nonce, nonceSz, authIn, authInSz, key, keySize, authTag, authTagSz);
     7704    wolfSSL_CryptHwMutexUnLock();
    70087705
    70097706    return (kStatus_Success == status) ? 0 : BAD_FUNC_ARG;
     
    70177714{
    70187715    byte *key;
    7019     uint32_t keySize;
     7716    word32 keySize;
    70207717    status_t status;
    70217718
    70227719    /* sanity check on arguments */
    70237720    if (aes == NULL || out == NULL || in == NULL || nonce == NULL
    7024             || authTag == NULL || nonceSz < 7 || nonceSz > 13)
     7721            || authTag == NULL || nonceSz < 7 || nonceSz > 13) {
    70257722        return BAD_FUNC_ARG;
     7723    }
    70267724
    70277725    key = (byte*)aes->key;
     
    70317729        return status;
    70327730    }
    7033 
     7731   
     7732    status = wolfSSL_CryptHwMutexLock();
     7733    if (status != 0)
     7734        return status;
    70347735    status = LTC_AES_DecryptTagCcm(LTC_BASE, in, out, inSz,
    70357736        nonce, nonceSz, authIn, authInSz, key, keySize, authTag, authTagSz);
    7036 
    7037     if (status == kStatus_Success) {
    7038         return 0;
    7039     }
    7040     else {
     7737    wolfSSL_CryptHwMutexUnLock();
     7738
     7739    if (status != kStatus_Success) {
    70417740        XMEMSET(out, 0, inSz);
    70427741        return AES_CCM_AUTH_E;
    70437742    }
     7743    return 0;
    70447744}
    70457745#endif /* HAVE_AES_DECRYPT */
     
    71317831
    71327832    for (i = 0; i < lenSz; i++) {
    7133         if (++B[AES_BLOCK_SIZE * 1 - 1 - i] != 0) break;
    7134     }
    7135     B[AES_BLOCK_SIZE * 2 - 1] += 2;
    7136     if (B[AES_BLOCK_SIZE * 2 - 1] < 2) {
    7137         for (i = 1; i < lenSz; i++) {
    7138             if (++B[AES_BLOCK_SIZE * 2 - 1 - i] != 0) break;
    7139         }
    7140     }
    7141     B[AES_BLOCK_SIZE * 3 - 1] += 3;
    7142     if (B[AES_BLOCK_SIZE * 3 - 1] < 3) {
     7833        if (++B[AES_BLOCK_SIZE * 2 - 1 - i] != 0) break;
     7834    }
     7835    B[AES_BLOCK_SIZE * 3 - 1] += 2;
     7836    if (B[AES_BLOCK_SIZE * 3 - 1] < 2) {
    71437837        for (i = 1; i < lenSz; i++) {
    71447838            if (++B[AES_BLOCK_SIZE * 3 - 1 - i] != 0) break;
     7839        }
     7840    }
     7841    B[AES_BLOCK_SIZE * 4 - 1] += 3;
     7842    if (B[AES_BLOCK_SIZE * 4 - 1] < 3) {
     7843        for (i = 1; i < lenSz; i++) {
     7844            if (++B[AES_BLOCK_SIZE * 4 - 1 - i] != 0) break;
    71457845        }
    71467846    }
     
    71807880
    71817881    /* sanity check on arguments */
    7182     if (aes == NULL || out == NULL || in == NULL || nonce == NULL
    7183             || authTag == NULL || nonceSz < 7 || nonceSz > 13 ||
     7882    if (aes == NULL || (inSz != 0 && (in == NULL || out == NULL)) ||
     7883        nonce == NULL || authTag == NULL || nonceSz < 7 || nonceSz > 13 ||
    71847884            authTagSz > AES_BLOCK_SIZE)
    71857885        return BAD_FUNC_ARG;
     7886
     7887    /* sanity check on tag size */
     7888    if (wc_AesCcmCheckTagSize(authTagSz) != 0) {
     7889        return BAD_FUNC_ARG;
     7890    }
    71867891
    71877892    XMEMSET(A, 0, sizeof(A));
     
    72177922            AesCcmCtrIncSet4(B, lenSz);
    72187923
     7924            SAVE_VECTOR_REGISTERS();
    72197925            AES_ECB_encrypt(B, A, AES_BLOCK_SIZE * 4, (byte*)aes->key,
    72207926                            aes->rounds);
     7927            RESTORE_VECTOR_REGISTERS();
     7928
    72217929            xorbuf(A, in, AES_BLOCK_SIZE * 4);
    72227930            XMEMCPY(out, A, AES_BLOCK_SIZE * 4);
     
    72267934            out += AES_BLOCK_SIZE * 4;
    72277935
    7228             if (inSz < AES_BLOCK_SIZE * 4) {
    7229                 AesCcmCtrInc4(B, lenSz);
    7230             }
     7936            AesCcmCtrInc4(B, lenSz);
    72317937        }
    72327938    }
     
    72767982
    72777983    /* sanity check on arguments */
    7278     if (aes == NULL || out == NULL || in == NULL || nonce == NULL
    7279             || authTag == NULL || nonceSz < 7 || nonceSz > 13 ||
    7280             authTagSz > AES_BLOCK_SIZE)
     7984    if (aes == NULL || (inSz != 0 && (in == NULL || out == NULL)) ||
     7985        nonce == NULL || authTag == NULL || nonceSz < 7 || nonceSz > 13 ||
     7986        authTagSz > AES_BLOCK_SIZE)
    72817987        return BAD_FUNC_ARG;
     7988
     7989    /* sanity check on tag size */
     7990    if (wc_AesCcmCheckTagSize(authTagSz) != 0) {
     7991        return BAD_FUNC_ARG;
     7992    }
    72827993
    72837994    o = out;
     
    72968007            AesCcmCtrIncSet4(B, lenSz);
    72978008
     8009            SAVE_VECTOR_REGISTERS();
    72988010            AES_ECB_encrypt(B, A, AES_BLOCK_SIZE * 4, (byte*)aes->key,
    72998011                            aes->rounds);
     8012            RESTORE_VECTOR_REGISTERS();
     8013
    73008014            xorbuf(A, in, AES_BLOCK_SIZE * 4);
    73018015            XMEMCPY(o, A, AES_BLOCK_SIZE * 4);
     
    73058019            o += AES_BLOCK_SIZE * 4;
    73068020
    7307             if (oSz < AES_BLOCK_SIZE * 4) {
    7308                 AesCcmCtrInc4(B, lenSz);
    7309             }
     8021            AesCcmCtrInc4(B, lenSz);
    73108022        }
    73118023    }
     
    73608072         * Unfortunately, you need the decrypted data to calculate the
    73618073         * check value. */
    7362         XMEMSET(out, 0, inSz);
     8074        #if defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) && \
     8075            defined(ACVP_VECTOR_TESTING)
     8076            WOLFSSL_MSG("Preserve output for vector responses");
     8077        #else
     8078            if (inSz > 0)
     8079                XMEMSET(out, 0, inSz);
     8080        #endif
    73638081        result = AES_CCM_AUTH_E;
    73648082    }
     
    74768194    XMEMSET(&aes->ctx, 0, sizeof(aes->ctx));
    74778195#endif
     8196#if defined(WOLFSSL_IMXRT_DCP)
     8197    DCPAesInit(aes);
     8198#endif
     8199
     8200
    74788201#ifdef HAVE_AESGCM
    74798202#ifdef OPENSSL_EXTRA
     
    74968219
    74978220    if (ret == 0)
    7498         ret  = wc_AesInit(aes, heap, devId);
     8221        ret = wc_AesInit(aes, heap, devId);
    74998222    if (ret == 0) {
    75008223        XMEMCPY(aes->id, id, len);
    75018224        aes->idLen = len;
     8225        aes->labelLen = 0;
     8226    }
     8227
     8228    return ret;
     8229}
     8230
     8231int wc_AesInit_Label(Aes* aes, const char* label, void* heap, int devId)
     8232{
     8233    int ret = 0;
     8234    int labelLen = 0;
     8235
     8236    if (aes == NULL || label == NULL)
     8237        ret = BAD_FUNC_ARG;
     8238    if (ret == 0) {
     8239        labelLen = (int)XSTRLEN(label);
     8240        if (labelLen == 0 || labelLen > AES_MAX_LABEL_LEN)
     8241            ret = BUFFER_E;
     8242    }
     8243
     8244    if (ret == 0)
     8245        ret = wc_AesInit(aes, heap, devId);
     8246    if (ret == 0) {
     8247        XMEMCPY(aes->label, label, labelLen);
     8248        aes->labelLen = labelLen;
     8249        aes->idLen = 0;
    75028250    }
    75038251
     
    75328280    ForceZero((byte*)aes->devKey, AES_MAX_KEY_SIZE/WOLFSSL_BIT_SIZE);
    75338281#endif
     8282#if defined(WOLFSSL_IMXRT_DCP)
     8283    DCPAesFree(aes);
     8284#endif
    75348285}
    75358286
     
    75908341        return BAD_FUNC_ARG;
    75918342
    7592         return AES_ECB_encrypt(aes, in, out, sz);
     8343    return AES_ECB_encrypt(aes, in, out, sz);
    75938344}
    75948345
     
    75998350        return BAD_FUNC_ARG;
    76008351
    7601         return AES_ECB_decrypt(aes, in, out, sz);
     8352    return AES_ECB_decrypt(aes, in, out, sz);
    76028353}
    76038354
     
    76118362    if ((in == NULL) || (out == NULL) || (aes == NULL))
    76128363      return BAD_FUNC_ARG;
    7613     while (blocks>0) {
     8364#ifdef WOLFSSL_IMXRT_DCP
     8365    if (aes->keylen == 16)
     8366        return DCPAesEcbEncrypt(aes, out, in, sz);
     8367#endif
     8368    while (blocks > 0) {
    76148369      wc_AesEncryptDirect(aes, out, in);
    76158370      out += AES_BLOCK_SIZE;
     
    76288383    if ((in == NULL) || (out == NULL) || (aes == NULL))
    76298384      return BAD_FUNC_ARG;
    7630     while (blocks>0) {
     8385#ifdef WOLFSSL_IMXRT_DCP
     8386    if (aes->keylen == 16)
     8387        return DCPAesEcbDecrypt(aes, out, in, sz);
     8388#endif
     8389    while (blocks > 0) {
    76318390      wc_AesDecryptDirect(aes, out, in);
    76328391      out += AES_BLOCK_SIZE;
     
    79108669
    79118670        /* MSB + XOR */
     8671    #ifdef BIG_ENDIAN_ORDER
     8672        ByteReverseWords(aes->tmp, aes->tmp, AES_BLOCK_SIZE);
     8673    #endif
    79128674        out[0] = aes->tmp[0] ^ in[0];
    79138675        if (dir == AES_ENCRYPTION) {
     
    81418903                  byte* out, word32 outSz, const byte* iv)
    81428904{
    8143     Aes aes;
     8905#ifdef WOLFSSL_SMALL_STACK
     8906    Aes *aes = NULL;
     8907#else
     8908    Aes aes[1];
     8909#endif
     8910    int aes_inited = 0;
    81448911    byte* r;
    81458912    word32 i;
     
    81578924    if (inSz % KEYWRAP_BLOCK_SIZE != 0)
    81588925        return BAD_FUNC_ARG;
     8926
     8927#ifdef WOLFSSL_SMALL_STACK
     8928    if ((aes = (Aes *)XMALLOC(sizeof *aes, NULL,
     8929                              DYNAMIC_TYPE_AES)) == NULL)
     8930        return MEMORY_E;
     8931#endif
    81598932
    81608933    /* user IV is optional */
     
    81698942    XMEMSET(t, 0, sizeof(t));
    81708943
    8171     ret = wc_AesInit(&aes, NULL, INVALID_DEVID);
     8944    ret = wc_AesInit(aes, NULL, INVALID_DEVID);
    81728945    if (ret != 0)
    8173         return ret;
    8174 
    8175     ret = wc_AesSetKey(&aes, key, keySz, NULL, AES_ENCRYPTION);
     8946        goto out;
     8947    else
     8948        aes_inited = 1;
     8949
     8950    ret = wc_AesSetKey(aes, key, keySz, NULL, AES_ENCRYPTION);
    81768951    if (ret != 0)
    8177         return ret;
     8952        goto out;
    81788953
    81798954    for (j = 0; j <= 5; j++) {
     
    81838958            XMEMCPY(tmp + KEYWRAP_BLOCK_SIZE, r, KEYWRAP_BLOCK_SIZE);
    81848959
    8185             wc_AesEncryptDirect(&aes, tmp, tmp);
     8960            wc_AesEncryptDirect(aes, tmp, tmp);
    81868961
    81878962            /* calculate new A */
     
    81998974    XMEMCPY(out, tmp, KEYWRAP_BLOCK_SIZE);
    82008975
    8201     wc_AesFree(&aes);
    8202 
    8203     return inSz + KEYWRAP_BLOCK_SIZE;
     8976    ret = 0;
     8977
     8978  out:
     8979
     8980    if (aes_inited)
     8981        wc_AesFree(aes);
     8982#ifdef WOLFSSL_SMALL_STACK
     8983    if (aes)
     8984        XFREE(aes, NULL, DYNAMIC_TYPE_AES);
     8985#endif
     8986
     8987    if (ret != 0)
     8988        return ret;
     8989    else
     8990        return inSz + KEYWRAP_BLOCK_SIZE;
    82048991}
    82058992
     
    82078994                    byte* out, word32 outSz, const byte* iv)
    82088995{
    8209     Aes aes;
     8996#ifdef WOLFSSL_SMALL_STACK
     8997    Aes *aes = NULL;
     8998#else
     8999    Aes aes[1];
     9000#endif
     9001    int aes_inited = 0;
    82109002    byte* r;
    82119003    word32 i, n;
     
    82299021    if (inSz % KEYWRAP_BLOCK_SIZE != 0)
    82309022        return BAD_FUNC_ARG;
     9023
     9024#ifdef WOLFSSL_SMALL_STACK
     9025    if ((aes = (Aes *)XMALLOC(sizeof *aes, NULL,
     9026                              DYNAMIC_TYPE_AES)) == NULL)
     9027        return MEMORY_E;
     9028#endif
    82319029
    82329030    /* user IV optional */
     
    82429040    XMEMSET(t, 0, sizeof(t));
    82439041
    8244     ret = wc_AesInit(&aes, NULL, INVALID_DEVID);
     9042    ret = wc_AesInit(aes, NULL, INVALID_DEVID);
    82459043    if (ret != 0)
    8246         return ret;
    8247 
    8248     ret = wc_AesSetKey(&aes, key, keySz, NULL, AES_DECRYPTION);
     9044        goto out;
     9045    else
     9046        aes_inited = 1;
     9047
     9048    ret = wc_AesSetKey(aes, key, keySz, NULL, AES_DECRYPTION);
    82499049    if (ret != 0)
    8250         return ret;
     9050        goto out;
    82519051
    82529052    /* initialize counter to 6n */
     
    82649064            r = out + ((i - 1) * KEYWRAP_BLOCK_SIZE);
    82659065            XMEMCPY(tmp + KEYWRAP_BLOCK_SIZE, r, KEYWRAP_BLOCK_SIZE);
    8266             wc_AesDecryptDirect(&aes, tmp, tmp);
     9066            wc_AesDecryptDirect(aes, tmp, tmp);
    82679067
    82689068            /* save R[i] */
     
    82719071    }
    82729072
    8273     wc_AesFree(&aes);
    8274 
    82759073    /* verify IV */
    8276     if (XMEMCMP(tmp, expIv, KEYWRAP_BLOCK_SIZE) != 0)
    8277         return BAD_KEYWRAP_IV_E;
    8278 
    8279     return inSz - KEYWRAP_BLOCK_SIZE;
     9074    if (XMEMCMP(tmp, expIv, KEYWRAP_BLOCK_SIZE) != 0) {
     9075        ret = BAD_KEYWRAP_IV_E;
     9076        goto out;
     9077    }
     9078
     9079  out:
     9080
     9081    if (aes_inited)
     9082        wc_AesFree(aes);
     9083#ifdef WOLFSSL_SMALL_STACK
     9084    if (aes)
     9085        XFREE(aes, NULL, DYNAMIC_TYPE_AES);
     9086#endif
     9087
     9088    if (ret != 0)
     9089        return ret;
     9090    else
     9091        return inSz - KEYWRAP_BLOCK_SIZE;
    82809092}
    82819093
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/asn.c

    r457 r464  
    2020 */
    2121
    22 
     22/*
     23
     24DESCRIPTION
     25This library provides the interface to Abstract Syntax Notation One (ASN.1) objects.
     26ASN.1 is a standard interface description language for defining data structures
     27that can be serialized and deserialized in a cross-platform way.
     28
     29*/
    2330#ifdef HAVE_CONFIG_H
    2431    #include <config.h>
     
    6774#include <wolfssl/wolfcrypt/des3.h>
    6875#include <wolfssl/wolfcrypt/aes.h>
     76#include <wolfssl/wolfcrypt/rc2.h>
    6977#include <wolfssl/wolfcrypt/wc_encrypt.h>
    7078#include <wolfssl/wolfcrypt/logging.h>
     
    114122#endif
    115123
     124#ifndef NO_DSA
     125    #include <wolfssl/wolfcrypt/dsa.h>
     126#else
     127    typedef void* DsaKey;
     128#endif
     129
    116130#ifdef WOLF_CRYPTO_CB
    117131    #include <wolfssl/wolfcrypt/cryptocb.h>
     
    129143#define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; }
    130144
    131 #if defined(HAVE_SELFTEST) || ( !defined(NO_SKID) && \
    132                                 ( !defined(HAVE_FIPS) || \
    133                                   !defined(HAVE_FIPS_VERSION) ))
     145#if !defined(NO_SKID) && (!defined(HAVE_FIPS) || !defined(HAVE_FIPS_VERSION))
     146    #if !defined(HAVE_SELFTEST) || (defined(HAVE_SELFTEST) && \
     147                                   (!defined(HAVE_SELFTEST_VERSION) || \
     148                                    HAVE_SELFTEST_VERSION < 2))
    134149    #ifndef WOLFSSL_AES_KEY_SIZE_ENUM
    135150    #define WOLFSSL_AES_KEY_SIZE_ENUM
     
    141156    };
    142157    #endif
     158    #endif /* HAVE_SELFTEST */
    143159#endif
    144160#ifdef WOLFSSL_RENESAS_TSIP_TLS
     
    456472
    457473    if (*len > 0) {
     474
     475#ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
     476        /* check for invalid padding on negative integer.
     477         * c.f. X.690 (ISO/IEC 8825-2:2003 (E)) 10.4.6; RFC 5280 4.1
     478         */
     479        if (*len > 1) {
     480            if ((input[*inOutIdx] == 0xff) && (input[*inOutIdx + 1] & 0x80))
     481                return ASN_PARSE_E;
     482        }
     483#endif
     484
    458485        /* remove leading zero, unless there is only one 0x00 byte */
    459486        if ((input[*inOutIdx] == 0x00) && (*len > 1)) {
     
    461488            (*len)--;
    462489
     490#ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
    463491            if (*len > 0 && (input[*inOutIdx] & 0x80) == 0)
    464492                return ASN_PARSE_E;
     493#endif
    465494        }
    466495    }
     
    502531#if !defined(NO_DSA) && !defined(NO_SHA)
    503532static const char sigSha1wDsaName[] = "SHAwDSA";
     533static const char sigSha256wDsaName[] = "SHA256wDSA";
    504534#endif /* NO_DSA */
    505535#ifndef NO_RSA
     
    555585        case CTC_SHAwDSA:
    556586            return sigSha1wDsaName;
     587        case CTC_SHA256wDSA:
     588            return sigSha256wDsaName;
    557589    #endif /* NO_DSA && NO_SHA */
    558590    #ifndef NO_RSA
     
    625657 * returns the number of bytes added to the buffer.
    626658 */
    627 static int SetASNInt(int len, byte firstByte, byte* output)
     659int SetASNInt(int len, byte firstByte, byte* output)
    628660{
    629661    word32 idx = 0;
     
    668700    leadingBit = mp_leading_bit(n);
    669701    length = mp_unsigned_bin_size(n);
     702    if (maxSz >= 0 && (1 + length + (leadingBit ? 1 : 0)) > maxSz)
     703        return BUFFER_E;
    670704    idx = SetASNInt(length, leadingBit ? 0x80 : 0x00, output);
    671705    if (maxSz >= 0 && (idx + length) > maxSz)
     
    840874
    841875    if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
     876        int ret;
     877
    842878        *inOutIdx = ++idx;  /* skip header */
    843         return GetMyVersion(input, inOutIdx, version, maxIdx);
     879        ret = GetMyVersion(input, inOutIdx, version, maxIdx);
     880        if (ret >= 0) {
     881            /* check if version is expected value rfc 5280 4.1 {0, 1, 2} */
     882            if (*version > MAX_X509_VERSION || *version < MIN_X509_VERSION) {
     883                WOLFSSL_MSG("Unexpected certificate version");
     884                ret = ASN_VERSION_E;
     885            }
     886        }
     887        return ret;
    844888    }
    845889
     
    881925
    882926#if (!defined(WOLFSSL_KEY_GEN) && !defined(OPENSSL_EXTRA) && defined(RSA_LOW_MEM)) \
    883     || defined(WOLFSSL_RSA_PUBLIC_ONLY) || (!defined(NO_DSA) && defined(WOLFSSL_QT))
    884 #if !defined(NO_RSA) && !defined(HAVE_USER_RSA)
     927    || defined(WOLFSSL_RSA_PUBLIC_ONLY) || (!defined(NO_DSA))
     928#if (!defined(NO_RSA) && !defined(HAVE_USER_RSA)) || !defined(NO_DSA)
    885929static int SkipInt(const byte* input, word32* inOutIdx, word32 maxIdx)
    886930{
     
    900944#endif
    901945
    902 static int CheckBitString(const byte* input, word32* inOutIdx, int* len,
     946int CheckBitString(const byte* input, word32* inOutIdx, int* len,
    903947                          word32 maxIdx, int zeroBits, byte* unusedBits)
    904948{
     
    9561000    (defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)) || \
    9571001    ((defined(HAVE_ED25519) || defined(HAVE_ED448)) && \
    958         (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)))
     1002        (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA))) || \
     1003    (!defined(NO_DSA) && !defined(HAVE_SELFTEST) && defined(WOLFSSL_KEY_GEN))
    9591004
    9601005/* Set the DER/BER encoding of the ASN.1 BIT_STRING header.
     
    11581203
    11591204#ifdef WOLFSSL_SMALL_STACK
    1160     indefItems = XMALLOC(sizeof(IndefItems), NULL, DYNAMIC_TYPE_TMP_BUFFER);
     1205    indefItems = (IndefItems *)XMALLOC(sizeof(IndefItems), NULL, DYNAMIC_TYPE_TMP_BUFFER);
    11611206    if (indefItems == NULL) {
    11621207        ret = MEMORY_E;
     
    13571402#endif
    13581403
    1359 #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN)
    1360 
    1361 #if (!defined(NO_RSA) && !defined(HAVE_USER_RSA)) || \
    1362     defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448)
    1363 
    1364 #ifdef WOLFSSL_CERT_EXT
     1404#if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN)
    13651405/* Set the DER/BER encoding of the ASN.1 BIT_STRING with a 16-bit value.
    13661406 *
     
    13951435    return idx;
    13961436}
    1397 #endif /* WOLFSSL_CERT_EXT */
    1398 #endif /* !NO_RSA || HAVE_ECC || HAVE_ED25519 || defined(HAVE_ED448) */
    1399 #endif /* WOLFSSL_CERT_GEN || WOLFSSL_KEY_GEN */
    1400 
    1401 
     1437#endif /* WOLFSSL_CERT_EXT || WOLFSSL_CERT_GEN */
    14021438
    14031439/* hashType */
     
    14431479#if !defined(NO_DSA) && !defined(NO_SHA)
    14441480    static const byte sigSha1wDsaOid[] = {42, 134, 72, 206, 56, 4, 3};
     1481    static const byte sigSha256wDsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 2};
    14451482#endif /* NO_DSA */
    14461483#ifndef NO_RSA
     
    15101547    static const byte keyEd448Oid[] = {43, 101, 113};
    15111548#endif /* HAVE_ED448 */
    1512 #if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
     1549#ifndef NO_DH
    15131550    static const byte keyDhOid[] = {42, 134, 72, 134, 247, 13, 1, 3, 1};
    1514 #endif /* ! NO_DH ... */
     1551#endif /* !NO_DH */
    15151552
    15161553/* curveType */
     
    15941631/* ocspType */
    15951632#ifdef HAVE_OCSP
    1596     static const byte ocspBasicOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 1};
    1597     static const byte ocspNonceOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 2};
     1633    static const byte ocspBasicOid[]    = {43, 6, 1, 5, 5, 7, 48, 1, 1};
     1634    static const byte ocspNonceOid[]    = {43, 6, 1, 5, 5, 7, 48, 1, 2};
     1635    static const byte ocspNoCheckOid[]  = {43, 6, 1, 5, 5, 7, 48, 1, 5};
    15981636#endif /* HAVE_OCSP */
    15991637
     
    16331671static const byte extExtKeyUsageTimestampOid[]    = {43, 6, 1, 5, 5, 7, 3, 8};
    16341672static const byte extExtKeyUsageOcspSignOid[]     = {43, 6, 1, 5, 5, 7, 3, 9};
     1673
     1674#ifdef WOLFSSL_CERT_REQ
     1675/* csrAttrType */
     1676static const byte attrChallengePasswordOid[] = {42, 134, 72, 134, 247, 13, 1, 9, 7};
     1677static const byte attrSerialNumberOid[] = {85, 4, 5};
     1678#endif
    16351679
    16361680/* kdfType */
     
    17251769                    oid = sigSha1wDsaOid;
    17261770                    *oidSz = sizeof(sigSha1wDsaOid);
     1771                    break;
     1772                case CTC_SHA256wDSA:
     1773                    oid = sigSha256wDsaOid;
     1774                    *oidSz = sizeof(sigSha256wDsaOid);
    17271775                    break;
    17281776                #endif /* NO_DSA */
     
    18581906                    break;
    18591907                #endif /* HAVE_ED448 */
    1860                 #if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
     1908                #ifndef NO_DH
    18611909                case DHk:
    18621910                    oid = keyDhOid;
    18631911                    *oidSz = sizeof(keyDhOid);
    18641912                    break;
    1865                 #endif /* ! NO_DH && (WOLFSSL_QT || OPENSSL_ALL */
     1913                #endif /* !NO_DH */
    18661914                default:
    18671915                    break;
     
    20152063                    break;
    20162064            #endif
     2065            #ifdef HAVE_OCSP
     2066                case OCSP_NOCHECK_OID:
     2067                    oid = ocspNoCheckOid;
     2068                    *oidSz = sizeof(ocspNoCheckOid);
     2069                    break;
     2070            #endif
    20172071            }
    20182072            break;
     
    22552309            break;
    22562310#endif /* WOLFSSL_APACHE_HTTPD */
     2311#ifdef WOLFSSL_CERT_REQ
     2312        case oidCsrAttrType:
     2313            switch (id) {
     2314                case CHALLENGE_PASSWORD_OID:
     2315                    oid = attrChallengePasswordOid;
     2316                    *oidSz = sizeof(attrChallengePasswordOid);
     2317                    break;
     2318                case SERIAL_NUMBER_OID:
     2319                    oid = attrSerialNumberOid;
     2320                    *oidSz = sizeof(attrSerialNumberOid);
     2321                    break;
     2322            }
     2323            break;
     2324#endif
    22572325        case oidIgnoreType:
    22582326        default:
     
    24222490    int idx = 0;
    24232491
    2424     output[idx++] = ASN_OBJECT_ID;
    2425     idx += SetLength(len, output + idx);
     2492    if (output)
     2493        output[idx++] = ASN_OBJECT_ID;
     2494    else
     2495        idx++;
     2496    idx += SetLength(len, output ? output + idx : NULL);
    24262497
    24272498    return idx;
     
    25702641    int version, length;
    25712642
    2572     if (inOutIdx == NULL) {
     2643    if (inOutIdx == NULL || input == NULL || key == NULL) {
    25732644        return BAD_FUNC_ARG;
    25742645    }
     
    26832754    if (length < 0)
    26842755        return length;
     2756
     2757    if (length + inOutIdx > sz)
     2758        return BUFFER_E;
    26852759
    26862760    XMEMMOVE(input, input + inOutIdx, length);
     
    28312905
    28322906#if defined(HAVE_PKCS12) || !defined(NO_CHECK_PRIVATE_KEY)
    2833 /* check that the private key is a pair for the public key in certificate
     2907/* check that the private key is a pair for the public key
    28342908 * return 1 (true) on match
    28352909 * return 0 or negative value on failure/error
    28362910 *
    2837  * key   : buffer holding DER format key
    2838  * keySz : size of key buffer
    2839  * der   : a initialized and parsed DecodedCert holding a certificate */
    2840 int wc_CheckPrivateKey(byte* key, word32 keySz, DecodedCert* der)
     2911 * privKey   : buffer holding DER format private key
     2912 * privKeySz : size of private key buffer
     2913 * pubKey    : buffer holding DER format public key
     2914 * pubKeySz  : size of public key buffer
     2915 * ks        : type of key */
     2916int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz,
     2917                       const byte* pubKey, word32 pubKeySz, enum Key_Sum ks)
    28412918{
    28422919    int ret;
    2843     (void)keySz;
    2844 
    2845     if (key == NULL || der == NULL) {
     2920    (void)privKeySz;
     2921    (void)pubKeySz;
     2922    (void)ks;
     2923
     2924    if (privKey == NULL || pubKey == NULL) {
    28462925        return BAD_FUNC_ARG;
    28472926    }
     
    28492928    #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
    28502929    /* test if RSA key */
    2851     if (der->keyOID == RSAk) {
     2930    if (ks == RSAk) {
    28522931    #ifdef WOLFSSL_SMALL_STACK
    28532932        RsaKey* a;
     
    28842963            return ret;
    28852964        }
    2886         if ((ret = wc_RsaPrivateKeyDecode(key, &keyIdx, a, keySz)) == 0) {
     2965        if ((ret = wc_RsaPrivateKeyDecode(privKey, &keyIdx, a, privKeySz)) == 0) {
    28872966            WOLFSSL_MSG("Checking RSA key pair");
    28882967            keyIdx = 0; /* reset to 0 for parsing public key */
    28892968
    2890             if ((ret = wc_RsaPublicKeyDecode(der->publicKey, &keyIdx, b,
    2891                                                        der->pubKeySize)) == 0) {
     2969            if ((ret = wc_RsaPublicKeyDecode(pubKey, &keyIdx, b,
     2970                    pubKeySz)) == 0) {
    28922971                /* limit for user RSA crypto because of RsaKey
    28932972                 * dereference. */
     
    29182997
    29192998    #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
    2920     if (der->keyOID == ECDSAk) {
     2999    if (ks == ECDSAk) {
    29213000    #ifdef WOLFSSL_SMALL_STACK
    29223001        ecc_key* key_pair;
     
    29483027        }
    29493028
    2950         if ((ret = wc_EccPrivateKeyDecode(key, &keyIdx, key_pair,
    2951                                                                  keySz)) == 0) {
     3029        if ((ret = wc_EccPrivateKeyDecode(privKey, &keyIdx, key_pair,
     3030                privKeySz)) == 0) {
    29523031            WOLFSSL_MSG("Checking ECC key pair");
    29533032
     
    29573036                ret = wc_ecc_init(key_pair);
    29583037                if (ret == 0) {
    2959                     ret = wc_ecc_import_private_key((const byte*)privDer,
    2960                                             privSz, (const byte*)der->publicKey,
    2961                                             der->pubKeySize, key_pair);
     3038                    ret = wc_ecc_import_private_key(privDer,
     3039                                            privSz, pubKey,
     3040                                            pubKeySz, key_pair);
    29623041                }
    29633042
     
    29833062
    29843063    #if defined(HAVE_ED25519) && !defined(NO_ASN_CRYPT)
    2985     if (der->keyOID == ED25519k) {
     3064    if (ks == ED25519k) {
    29863065    #ifdef WOLFSSL_SMALL_STACK
    29873066        ed25519_key* key_pair;
     
    30043083            return ret;
    30053084        }
    3006         if ((ret = wc_Ed25519PrivateKeyDecode(key, &keyIdx, key_pair,
    3007                                                                  keySz)) == 0) {
     3085        if ((ret = wc_Ed25519PrivateKeyDecode(privKey, &keyIdx, key_pair,
     3086                privKeySz)) == 0) {
    30083087            WOLFSSL_MSG("Checking ED25519 key pair");
    30093088            keyIdx = 0;
    3010             if ((ret = wc_ed25519_import_public(der->publicKey, der->pubKeySize,
    3011                                                               key_pair)) == 0) {
     3089            if ((ret = wc_ed25519_import_public(pubKey, pubKeySz,
     3090                    key_pair)) == 0) {
    30123091                /* public and private extracted successfully no check if is
    30133092                 * a pair and also do sanity checks on key. wc_ecc_check_key
     
    30263105
    30273106    #if defined(HAVE_ED448) && !defined(NO_ASN_CRYPT)
    3028     if (der->keyOID == ED448k) {
     3107    if (ks == ED448k) {
    30293108    #ifdef WOLFSSL_SMALL_STACK
    30303109        ed448_key* key_pair = NULL;
     
    30473126            return ret;
    30483127        }
    3049         if ((ret = wc_Ed448PrivateKeyDecode(key, &keyIdx, key_pair,
    3050                                                                  keySz)) == 0) {
     3128        if ((ret = wc_Ed448PrivateKeyDecode(privKey, &keyIdx, key_pair,
     3129                privKeySz)) == 0) {
    30513130            WOLFSSL_MSG("Checking ED448 key pair");
    30523131            keyIdx = 0;
    3053             if ((ret = wc_ed448_import_public(der->publicKey, der->pubKeySize,
    3054                                                               key_pair)) == 0) {
     3132            if ((ret = wc_ed448_import_public(pubKey, pubKeySz,
     3133                    key_pair)) == 0) {
    30553134                /* public and private extracted successfully no check if is
    30563135                 * a pair and also do sanity checks on key. wc_ecc_check_key
     
    30713150    }
    30723151
    3073     (void)keySz;
    3074 
    30753152    return ret;
     3153}
     3154
     3155/* check that the private key is a pair for the public key in certificate
     3156 * return 1 (true) on match
     3157 * return 0 or negative value on failure/error
     3158 *
     3159 * key   : buffer holding DER format key
     3160 * keySz : size of key buffer
     3161 * der   : a initialized and parsed DecodedCert holding a certificate */
     3162int wc_CheckPrivateKeyCert(const byte* key, word32 keySz, DecodedCert* der)
     3163{
     3164    if (key == NULL || der == NULL) {
     3165        return BAD_FUNC_ARG;
     3166    }
     3167
     3168    return wc_CheckPrivateKey(key, keySz, der->publicKey,
     3169            der->pubKeySize, (enum Key_Sum) der->keyOID);
    30763170}
    30773171
     
    31103204            return 0;
    31113205    #endif
     3206    #ifdef WC_RC2
     3207        case PBE_SHA1_40RC2_CBC:
     3208            *id = PBE_SHA1_40RC2_CBC;
     3209            *version = PKCS12v1;
     3210            if (blockSz) *blockSz = RC2_BLOCK_SIZE;
     3211            return 0;
     3212    #endif
    31123213#endif /* !NO_SHA */
    31133214        default:
     
    31973298    #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
    31983299    {
    3199         RsaKey rsa;
    3200 
    3201         wc_InitRsaKey(&rsa, heap);
    3202         if (wc_RsaPrivateKeyDecode(key, &tmpIdx, &rsa, keySz) == 0) {
     3300        RsaKey *rsa = (RsaKey *)XMALLOC(sizeof *rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
     3301        if (rsa == NULL)
     3302            return MEMORY_E;
     3303
     3304        wc_InitRsaKey(rsa, heap);
     3305        if (wc_RsaPrivateKeyDecode(key, &tmpIdx, rsa, keySz) == 0) {
    32033306            *algoID = RSAk;
    32043307        }
     
    32063309            WOLFSSL_MSG("Not RSA DER key");
    32073310        }
    3208         wc_FreeRsaKey(&rsa);
     3311        wc_FreeRsaKey(rsa);
     3312        XFREE(rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
    32093313    }
    32103314    #endif /* !NO_RSA && !NO_ASN_CRYPT */
    32113315    #if defined(HAVE_ECC) && !defined(NO_ASN_CRYPT)
    32123316    if (*algoID == 0) {
    3213         ecc_key ecc;
     3317        ecc_key *ecc = (ecc_key *)XMALLOC(sizeof *ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
     3318        if (ecc == NULL)
     3319            return MEMORY_E;
    32143320
    32153321        tmpIdx = 0;
    3216         wc_ecc_init_ex(&ecc, heap, INVALID_DEVID);
    3217         if (wc_EccPrivateKeyDecode(key, &tmpIdx, &ecc, keySz) == 0) {
     3322        wc_ecc_init_ex(ecc, heap, INVALID_DEVID);
     3323        if (wc_EccPrivateKeyDecode(key, &tmpIdx, ecc, keySz) == 0) {
    32183324            *algoID = ECDSAk;
    32193325
    32203326            /* now find oid */
    3221             if (wc_ecc_get_oid(ecc.dp->oidSum, curveOID, oidSz) < 0) {
     3327            if (wc_ecc_get_oid(ecc->dp->oidSum, curveOID, oidSz) < 0) {
    32223328                WOLFSSL_MSG("Error getting ECC curve OID");
    3223                 wc_ecc_free(&ecc);
     3329                wc_ecc_free(ecc);
     3330                XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
    32243331                return BAD_FUNC_ARG;
    32253332            }
     
    32283335            WOLFSSL_MSG("Not ECC DER key either");
    32293336        }
    3230         wc_ecc_free(&ecc);
     3337        wc_ecc_free(ecc);
     3338        XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
    32313339    }
    32323340#endif /* HAVE_ECC && !NO_ASN_CRYPT */
    32333341#if defined(HAVE_ED25519) && !defined(NO_ASN_CRYPT)
    32343342    if (*algoID != RSAk && *algoID != ECDSAk) {
    3235         ed25519_key ed25519;
     3343        ed25519_key *ed25519 = (ed25519_key *)XMALLOC(sizeof *ed25519, heap, DYNAMIC_TYPE_TMP_BUFFER);
     3344        if (ed25519 == NULL)
     3345            return MEMORY_E;
    32363346
    32373347        tmpIdx = 0;
    3238         if (wc_ed25519_init(&ed25519) == 0) {
    3239             if (wc_Ed25519PrivateKeyDecode(key, &tmpIdx, &ed25519, keySz)
    3240                                                                          == 0) {
     3348        if (wc_ed25519_init(ed25519) == 0) {
     3349            if (wc_Ed25519PrivateKeyDecode(key, &tmpIdx, ed25519, keySz) == 0) {
    32413350                *algoID = ED25519k;
    32423351            }
     
    32443353                WOLFSSL_MSG("Not ED25519 DER key");
    32453354            }
    3246             wc_ed25519_free(&ed25519);
     3355            wc_ed25519_free(ed25519);
    32473356        }
    32483357        else {
    32493358            WOLFSSL_MSG("GetKeyOID wc_ed25519_init failed");
    32503359        }
     3360        XFREE(ed25519, heap, DYNAMIC_TYPE_TMP_BUFFER);
    32513361    }
    32523362#endif /* HAVE_ED25519 && !NO_ASN_CRYPT */
    32533363#if defined(HAVE_ED448) && !defined(NO_ASN_CRYPT)
    32543364    if (*algoID != RSAk && *algoID != ECDSAk && *algoID != ED25519k) {
    3255         ed448_key ed448;
     3365        ed448_key *ed448 = (ed448_key *)XMALLOC(sizeof *ed448, heap, DYNAMIC_TYPE_TMP_BUFFER);
     3366        if (ed448 == NULL)
     3367            return MEMORY_E;
    32563368
    32573369        tmpIdx = 0;
    3258         if (wc_ed448_init(&ed448) == 0) {
    3259             if (wc_Ed448PrivateKeyDecode(key, &tmpIdx, &ed448, keySz) == 0) {
     3370        if (wc_ed448_init(ed448) == 0) {
     3371            if (wc_Ed448PrivateKeyDecode(key, &tmpIdx, ed448, keySz) == 0) {
    32603372                *algoID = ED448k;
    32613373            }
     
    32633375                WOLFSSL_MSG("Not ED448 DER key");
    32643376            }
    3265             wc_ed448_free(&ed448);
     3377            wc_ed448_free(ed448);
    32663378        }
    32673379        else {
    32683380            WOLFSSL_MSG("GetKeyOID wc_ed448_init failed");
    32693381        }
     3382        XFREE(ed448, heap, DYNAMIC_TYPE_TMP_BUFFER);
    32703383    }
    32713384#endif /* HAVE_ED448 && !NO_ASN_CRYPT */
     
    34053518        ret = SetShortInt(out, &inOutIdx, itt, *outSz);
    34063519        if (ret < 0) {
     3520        #ifdef WOLFSSL_SMALL_STACK
     3521            if (saltTmp != NULL)
     3522                XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
     3523        #endif
    34073524            return ret;
    34083525        }
     
    34283545    if ((ret = wc_GetKeyOID(key, keySz, &curveOID, &oidSz, &algoID, heap))< 0) {
    34293546        WOLFSSL_MSG("Error getting key OID");
     3547    #ifdef WOLFSSL_SMALL_STACK
     3548        if (saltTmp != NULL)
     3549            XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
     3550    #endif
    34303551        return ret;
    34313552    }
     
    34543575        *outSz = tmpSz + MAX_ALGO_SZ + MAX_LENGTH_SZ +MAX_LENGTH_SZ + MAX_SEQ_SZ
    34553576            + MAX_LENGTH_SZ + MAX_SEQ_SZ + 3;
     3577    #ifdef WOLFSSL_SMALL_STACK
     3578        if (saltTmp != NULL)
     3579            XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
     3580    #endif
    34563581        return LENGTH_ONLY_E;
    34573582    }
     
    34873612        if (saltTmp != NULL)
    34883613            XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
    3489         XFREE(salt, heap, DYNAMIC_TYPE_TMP_BUFFER);
     3614        XFREE(tmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
    34903615        return MEMORY_E;
    34913616    }
     
    43904515
    43914516#ifndef NO_DH
    4392 
     4517/* Supports either:
     4518 * - DH params G/P (PKCS#3 DH) file or
     4519 * - DH key file (if WOLFSSL_DH_EXTRA enabled) */
     4520/* The wc_DhParamsLoad function also loads DH params, but directly into buffers, not DhKey */
    43934521int wc_DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz)
    43944522{
    43954523    int ret = 0;
    43964524    int length;
    4397     #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
     4525#ifdef WOLFSSL_DH_EXTRA
     4526    #if !defined(HAVE_FIPS) || \
     4527        (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
    43984528    word32 oid = 0, temp = 0;
    43994529    #endif
     4530#endif
    44004531
    44014532    WOLFSSL_ENTER("wc_DhKeyDecode");
     
    44074538        return ASN_PARSE_E;
    44084539
    4409     #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
     4540#ifdef WOLFSSL_DH_EXTRA
     4541    #if !defined(HAVE_FIPS) || \
     4542        (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
    44104543    temp = *inOutIdx;
    44114544    #endif
    4412 
     4545#endif
    44134546    /* Assume input started after 1.2.840.113549.1.3.1 dhKeyAgreement */
    4414     if (GetInt(&key->p,  input, inOutIdx, inSz) < 0 ||
    4415         GetInt(&key->g,  input, inOutIdx, inSz) < 0) {
     4547    if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
    44164548        ret = ASN_DH_KEY_E;
    44174549    }
    4418 
    4419     #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
     4550    if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
     4551        mp_clear(&key->p);
     4552        ret = ASN_DH_KEY_E;
     4553    }
     4554
     4555#ifdef WOLFSSL_DH_EXTRA
     4556    #if !defined(HAVE_FIPS) || \
     4557        (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
    44204558    /* If ASN_DH_KEY_E: Check if input started at beginning of key */
    44214559    if (ret == ASN_DH_KEY_E) {
    4422         /* rewind back to after the first sequence */
    44234560        *inOutIdx = temp;
     4561
     4562        /* the version (0) */
     4563        if (GetASNInt(input, inOutIdx, &length, inSz) < 0) {
     4564            return ASN_PARSE_E;
     4565        }
     4566        *inOutIdx += length;
     4567
     4568        /* Size of dhKeyAgreement section */
    44244569        if (GetSequence(input, inOutIdx, &length, inSz) < 0)
    44254570            return ASN_PARSE_E;
     
    44334578            return ASN_PARSE_E;
    44344579
    4435         if (GetInt(&key->p,  input, inOutIdx, inSz) < 0 ||
    4436             GetInt(&key->g,  input, inOutIdx, inSz) < 0) {
     4580        if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
     4581            return ASN_DH_KEY_E;
     4582        }
     4583        if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
     4584            mp_clear(&key->p);
    44374585            return ASN_DH_KEY_E;
    44384586        }
     
    44544602            if (GetInt(&key->priv, input, inOutIdx, inSz) == 0) {
    44554603                WOLFSSL_MSG("Found Private Key");
    4456                 ret = 0;
     4604
     4605                /* Compute public */
     4606                ret = mp_exptmod(&key->g, &key->priv, &key->p, &key->pub);
    44574607            }
    44584608        } else {
     
    44624612        }
    44634613    }
    4464     #endif /* WOLFSSL_QT || OPENSSL_ALL */
    4465 
    4466     WOLFSSL_MSG("wc_DhKeyDecode Success");
     4614    #endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
     4615#endif /* WOLFSSL_DH_EXTRA */
     4616
     4617    WOLFSSL_LEAVE("wc_DhKeyDecode", ret);
    44674618
    44684619    return ret;
    44694620}
    4470 
    44714621
    44724622int wc_DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz,
     
    45074657    return 0;
    45084658}
    4509 #endif /* NO_DH */
     4659#endif /* !NO_DH */
    45104660
    45114661
     
    46634813}
    46644814
    4665 #if !defined(HAVE_SELFTEST) && defined(WOLFSSL_KEY_GEN)
     4815#if !defined(HAVE_SELFTEST) && (defined(WOLFSSL_KEY_GEN) || \
     4816        defined(WOLFSSL_CERT_GEN))
    46664817/* Write a public DSA key to output */
    46674818int wc_SetDsaPublicKey(byte* output, DsaKey* key,
     
    48525003    return wc_SetDsaPublicKey(output, key, inLen, 1);
    48535004}
    4854 #endif /* !HAVE_SELFTEST && WOLFSSL_KEY_GEN */
     5005#endif /* !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) */
    48555006
    48565007/* Convert private DsaKey key to DER format, write to output (inLen),
     
    49995150    if (cert->altEmailNames)
    50005151        FreeAltNames(cert->altEmailNames, cert->heap);
     5152    if (cert->altDirNames)
     5153        FreeAltNames(cert->altDirNames, cert->heap);
    50015154    if (cert->permittedNames)
    50025155        FreeNameSubtrees(cert->permittedNames, cert->heap);
     
    50095162    XFREE(cert->hwSerialNum, cert->heap, DYNAMIC_TYPE_X509_EXT);
    50105163#endif /* WOLFSSL_SEP */
    5011 #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    5012     if (cert->issuerName.fullName != NULL)
    5013         XFREE(cert->issuerName.fullName, cert->heap, DYNAMIC_TYPE_X509);
    5014     if (cert->subjectName.fullName != NULL)
    5015         XFREE(cert->subjectName.fullName, cert->heap, DYNAMIC_TYPE_X509);
     5164#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
     5165    !defined(WOLFCRYPT_ONLY)
     5166    if (cert->issuerName != NULL)
     5167        wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->issuerName);
     5168    if (cert->subjectName != NULL)
     5169        wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->subjectName);
    50165170#endif /* OPENSSL_EXTRA */
    50175171#ifdef WOLFSSL_RENESAS_TSIP_TLS
     
    51015255{
    51025256    int length;
    5103 #if !defined(NO_DSA) && defined(WOLFSSL_QT)
     5257#ifndef NO_DSA
    51045258    int tmpLen;
    51055259#endif
    5106 #if defined(HAVE_ECC) || defined(HAVE_NTRU)
     5260#if defined(HAVE_ECC) || defined(HAVE_NTRU) || !defined(NO_DSA)
    51075261    int tmpIdx = cert->srcIdx;
    51085262#endif
     
    51115265        return ASN_PARSE_E;
    51125266
    5113 #if !defined(NO_DSA) && defined(WOLFSSL_QT)
     5267#ifndef NO_DSA
    51145268    tmpLen = length + 4;
    51155269#endif
     
    53245478        }
    53255479    #endif /* HAVE_ED448 */
    5326     #if !defined(NO_DSA) && defined(WOLFSSL_QT)
     5480    #ifndef NO_DSA
    53275481        case DSAk:
    53285482        {
     
    53575511            return 0;
    53585512        }
    5359     #endif /* NO_DSA && QT */
     5513    #endif /* NO_DSA */
    53605514        default:
     5515            WOLFSSL_MSG("Unknown or not compiled in key OID");
    53615516            return ASN_UNKNOWN_OID_E;
    53625517    }
     
    54495604        {WOLFSSL_EMAIL_ADDR, NID_emailAddress},
    54505605        {NULL, -1}};
    5451 
    54525606    int i;
    54535607    #ifdef HAVE_ECC
     5608    char curveName[16]; /* Same as MAX_CURVE_NAME_SZ but can't include that
     5609                         * symbol in this file */
    54545610    int eccEnum;
    54555611    #endif
     
    54645620    if (XSTRNCMP(sn, "prime256v1", 10) == 0)
    54655621        sn = "SECP256R1";
    5466     if (XSTRNCMP(sn, "secp384r1", 10) == 0)
    5467         sn = "SECP384R1";
     5622    /* OpenSSL allows lowercase curve names */
     5623    for (i = 0; i < (int)(sizeof(curveName) - 1) && *sn; i++) {
     5624        curveName[i] = (char)XTOUPPER(*sn++);
     5625    }
     5626    curveName[i] = '\0';
    54685627    /* find based on name and return NID */
    5469     for (i = 0; ecc_sets[i].size != 0 && ecc_sets[i].name != NULL; i++) {
    5470         if (XSTRNCMP(sn, ecc_sets[i].name, ECC_MAXNAME) == 0) {
     5628    for (i = 0;
     5629#ifndef WOLFSSL_ECC_CURVE_STATIC
     5630         ecc_sets[i].size != 0 && ecc_sets[i].name != NULL;
     5631#else
     5632         ecc_sets[i].size != 0;
     5633#endif
     5634         i++) {
     5635        if (XSTRNCMP(curveName, ecc_sets[i].name, ECC_MAXNAME) == 0) {
    54715636            eccEnum = ecc_sets[i].id;
    54725637            /* Convert enum value in ecc_curve_id to OpenSSL NID */
     
    54845649{
    54855650    int ret;
    5486 
    5487 #ifdef WOLF_CRYPTO_CB
    5488     /* try to use a registered crypto callback */
    5489     ret = wc_CryptoCb_Sha256Hash(NULL, data, len, hash);
    5490     if (ret != CRYPTOCB_UNAVAILABLE)
    5491         return ret;
    5492     /* fall-through when unavailable */
    5493 #endif
    54945651
    54955652#if defined(NO_SHA) && !defined(NO_SHA256)
     
    55045661}
    55055662
    5506 /* process NAME, either issuer or subject */
    5507 static int GetName(DecodedCert* cert, int nameType, int maxIdx)
     5663/* process NAME, either issuer or subject
     5664 * returns 0 on success and negative values on fail */
     5665int GetName(DecodedCert* cert, int nameType, int maxIdx)
    55085666{
    55095667    int    length;  /* length of all distinguished names */
     
    55145672    word32 idx, localIdx = 0;
    55155673    byte   tag;
    5516     #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    5517         DecodedName* dName =
    5518                   (nameType == ISSUER) ? &cert->issuerName : &cert->subjectName;
    5519         int dcnum = 0;
    5520         #ifdef OPENSSL_EXTRA
    5521         int count = 0;
    5522         #endif
    5523     #endif /* OPENSSL_EXTRA */
     5674#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
     5675            !defined(WOLFCRYPT_ONLY)
     5676    WOLFSSL_X509_NAME* dName;
     5677#endif /* OPENSSL_EXTRA */
    55245678
    55255679    WOLFSSL_MSG("Getting Cert Name");
     
    55785732    }
    55795733#endif
     5734#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
     5735    !defined(WOLFCRYPT_ONLY)
     5736    dName = wolfSSL_X509_NAME_new();
     5737    if (dName == NULL) {
     5738        return MEMORY_E;
     5739    }
     5740#endif /* OPENSSL_EXTRA */
    55805741
    55815742    while (cert->srcIdx < (word32)length) {
     
    55885749        int         strLen  = 0;
    55895750        byte        id      = 0;
     5751    #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
     5752                && !defined(WOLFCRYPT_ONLY)
     5753         int        nid = NID_undef;
     5754         int        enc;
     5755    #endif /* OPENSSL_EXTRA */
    55905756
    55915757        if (GetSet(cert->source, &cert->srcIdx, &dummy, maxIdx) < 0) {
     
    55935759        }
    55945760
    5595         if (GetSequence(cert->source, &cert->srcIdx, &dummy, maxIdx) <= 0)
     5761        if (GetSequence(cert->source, &cert->srcIdx, &dummy, maxIdx) <= 0) {
     5762        #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
     5763            !defined(WOLFCRYPT_ONLY)
     5764            wolfSSL_X509_NAME_free(dName);
     5765        #endif /* OPENSSL_EXTRA */
    55965766            return ASN_PARSE_E;
     5767        }
    55975768
    55985769        ret = GetASNObjectId(cert->source, &cert->srcIdx, &oidSz, maxIdx);
    5599         if (ret != 0)
     5770        if (ret != 0) {
     5771        #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
     5772            !defined(WOLFCRYPT_ONLY)
     5773            wolfSSL_X509_NAME_free(dName);
     5774        #endif /* OPENSSL_EXTRA */
    56005775            return ret;
     5776        }
    56015777
    56025778        /* make sure there is room for joint */
    5603         if ((cert->srcIdx + sizeof(joint)) > (word32)maxIdx)
     5779        if ((cert->srcIdx + sizeof(joint)) > (word32)maxIdx) {
     5780        #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
     5781            !defined(WOLFCRYPT_ONLY)
     5782            wolfSSL_X509_NAME_free(dName);
     5783        #endif /* OPENSSL_EXTRA */
    56045784            return ASN_PARSE_E;
     5785        }
    56055786
    56065787        XMEMCPY(joint, &cert->source[cert->srcIdx], sizeof(joint));
     
    56125793            if (GetHeader(cert->source, &b, &cert->srcIdx, &strLen,
    56135794                          maxIdx, 1) < 0) {
     5795            #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
     5796            !defined(WOLFCRYPT_ONLY)
     5797                wolfSSL_X509_NAME_free(dName);
     5798            #endif /* OPENSSL_EXTRA */
    56145799                return ASN_PARSE_E;
    56155800            }
     
    56245809                copy = WOLFSSL_COMMON_NAME;
    56255810                copyLen = sizeof(WOLFSSL_COMMON_NAME) - 1;
    5626                 #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    5627                     dName->cnIdx = cert->srcIdx;
    5628                     dName->cnLen = strLen;
    5629                 #endif /* OPENSSL_EXTRA */
     5811            #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
     5812                && !defined(WOLFCRYPT_ONLY)
     5813                nid = NID_commonName;
     5814            #endif /* OPENSSL_EXTRA */
    56305815            }
    56315816            else if (id == ASN_SUR_NAME) {
     
    56395824                    }
    56405825                #endif /* WOLFSSL_CERT_GEN */
    5641                 #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    5642                     dName->snIdx = cert->srcIdx;
    5643                     dName->snLen = strLen;
     5826                #if (defined(OPENSSL_EXTRA) || \
     5827                        defined(OPENSSL_EXTRA_X509_SMALL)) \
     5828                        && !defined(WOLFCRYPT_ONLY)
     5829                    nid = NID_surname;
    56445830                #endif /* OPENSSL_EXTRA */
    56455831            }
     
    56545840                    }
    56555841                #endif /* WOLFSSL_CERT_GEN */
    5656                 #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    5657                     dName->cIdx = cert->srcIdx;
    5658                     dName->cLen = strLen;
     5842                #if (defined(OPENSSL_EXTRA) || \
     5843                        defined(OPENSSL_EXTRA_X509_SMALL)) \
     5844                        && !defined(WOLFCRYPT_ONLY)
     5845                    nid = NID_countryName;
    56595846                #endif /* OPENSSL_EXTRA */
    56605847            }
     
    56695856                    }
    56705857                #endif /* WOLFSSL_CERT_GEN */
    5671                 #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    5672                     dName->lIdx = cert->srcIdx;
    5673                     dName->lLen = strLen;
     5858                #if (defined(OPENSSL_EXTRA) || \
     5859                        defined(OPENSSL_EXTRA_X509_SMALL)) \
     5860                        && !defined(WOLFCRYPT_ONLY)
     5861                    nid = NID_localityName;
    56745862                #endif /* OPENSSL_EXTRA */
    56755863            }
     
    56845872                    }
    56855873                #endif /* WOLFSSL_CERT_GEN */
    5686                 #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    5687                     dName->stIdx = cert->srcIdx;
    5688                     dName->stLen = strLen;
     5874                #if (defined(OPENSSL_EXTRA) || \
     5875                        defined(OPENSSL_EXTRA_X509_SMALL)) \
     5876                        && !defined(WOLFCRYPT_ONLY)
     5877                    nid = NID_stateOrProvinceName;
    56895878                #endif /* OPENSSL_EXTRA */
    56905879            }
     
    56995888                    }
    57005889                #endif /* WOLFSSL_CERT_GEN */
    5701                 #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    5702                     dName->oIdx = cert->srcIdx;
    5703                     dName->oLen = strLen;
     5890                #if (defined(OPENSSL_EXTRA) || \
     5891                        defined(OPENSSL_EXTRA_X509_SMALL)) \
     5892                        && !defined(WOLFCRYPT_ONLY)
     5893                    nid = NID_organizationName;
    57045894                #endif /* OPENSSL_EXTRA */
    57055895            }
     
    57145904                    }
    57155905                #endif /* WOLFSSL_CERT_GEN */
    5716                 #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    5717                     dName->ouIdx = cert->srcIdx;
    5718                     dName->ouLen = strLen;
     5906                #if (defined(OPENSSL_EXTRA) || \
     5907                        defined(OPENSSL_EXTRA_X509_SMALL)) \
     5908                        && !defined(WOLFCRYPT_ONLY)
     5909                    nid = NID_organizationalUnitName;
    57195910                #endif /* OPENSSL_EXTRA */
    57205911            }
     
    57295920                    }
    57305921                #endif /* WOLFSSL_CERT_GEN */
    5731                 #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    5732                     dName->snIdx = cert->srcIdx;
    5733                     dName->snLen = strLen;
     5922                #if (defined(OPENSSL_EXTRA) || \
     5923                        defined(OPENSSL_EXTRA_X509_SMALL)) \
     5924                        && !defined(WOLFCRYPT_ONLY)
     5925                    nid = NID_serialNumber;
    57345926                #endif /* OPENSSL_EXTRA */
    57355927            }
     
    57455937                }
    57465938            #endif /* WOLFSSL_CERT_GEN */
    5747             #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    5748                 dName->bcIdx = cert->srcIdx;
    5749                 dName->bcLen = strLen;
     5939            #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
     5940                        && !defined(WOLFCRYPT_ONLY)
     5941                nid = NID_businessCategory;
    57505942            #endif /* OPENSSL_EXTRA */
    57515943            }
     
    57645956
    57655957            if (GetLength(cert->source, &cert->srcIdx, &strLen,
    5766                           maxIdx) < 0)
     5958                          maxIdx) < 0) {
     5959            #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
     5960            !defined(WOLFCRYPT_ONLY)
     5961                wolfSSL_X509_NAME_free(dName);
     5962            #endif /* OPENSSL_EXTRA */
    57675963                return ASN_PARSE_E;
     5964            }
    57685965
    57695966            /* Check for jurisdiction of incorporation country name */
     
    57785975                    }
    57795976                #endif /* WOLFSSL_CERT_GEN */
    5780                 #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    5781                     dName->jcIdx = cert->srcIdx;
    5782                     dName->jcLen = strLen;
     5977                #if (defined(OPENSSL_EXTRA) || \
     5978                        defined(OPENSSL_EXTRA_X509_SMALL)) \
     5979                        && !defined(WOLFCRYPT_ONLY)
     5980                    nid = NID_jurisdictionCountryName;
    57835981                #endif /* OPENSSL_EXTRA */
    57845982            }
     
    57955993                    }
    57965994                #endif /* WOLFSSL_CERT_GEN */
    5797                 #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    5798                     dName->jsIdx = cert->srcIdx;
    5799                     dName->jsLen = strLen;
     5995                #if (defined(OPENSSL_EXTRA) || \
     5996                        defined(OPENSSL_EXTRA_X509_SMALL)) \
     5997                        && !defined(WOLFCRYPT_ONLY)
     5998                    nid = NID_jurisdictionStateOrProvinceName;
    58005999                #endif /* OPENSSL_EXTRA */
    58016000            }
     
    58256024            cert->srcIdx += oidSz + 1;
    58266025
    5827             if (GetLength(cert->source, &cert->srcIdx, &strLen, maxIdx) < 0)
     6026            if (GetLength(cert->source, &cert->srcIdx, &strLen, maxIdx) < 0) {
     6027            #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
     6028            !defined(WOLFCRYPT_ONLY)
     6029                wolfSSL_X509_NAME_free(dName);
     6030            #endif /* OPENSSL_EXTRA */
    58286031                return ASN_PARSE_E;
     6032            }
    58296033
    58306034            if (strLen > (int)(ASN_NAME_MAX - idx)) {
     
    58496053                    }
    58506054                #endif /* WOLFSSL_CERT_GEN */
    5851                 #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    5852                     dName->emailIdx = cert->srcIdx;
    5853                     dName->emailLen = strLen;
     6055                #if (defined(OPENSSL_EXTRA) || \
     6056                        defined(OPENSSL_EXTRA_X509_SMALL)) \
     6057                        && !defined(WOLFCRYPT_ONLY)
     6058                    nid = NID_emailAddress;
    58546059                #endif /* OPENSSL_EXTRA */
    58556060                #ifndef IGNORE_NAME_CONSTRAINTS
     
    58616066                        if (emailName == NULL) {
    58626067                            WOLFSSL_MSG("\tOut of Memory");
     6068                        #if (defined(OPENSSL_EXTRA) || \
     6069                                defined(OPENSSL_EXTRA_X509_SMALL)) && \
     6070                                !defined(WOLFCRYPT_ONLY)
     6071                            wolfSSL_X509_NAME_free(dName);
     6072                        #endif /* OPENSSL_EXTRA */
    58636073                            return MEMORY_E;
    58646074                        }
     
    58696079                            WOLFSSL_MSG("\tOut of Memory");
    58706080                            XFREE(emailName, cert->heap, DYNAMIC_TYPE_ALTNAME);
     6081                        #if (defined(OPENSSL_EXTRA) || \
     6082                                defined(OPENSSL_EXTRA_X509_SMALL)) && \
     6083                                !defined(WOLFCRYPT_ONLY)
     6084                            wolfSSL_X509_NAME_free(dName);
     6085                        #endif /* OPENSSL_EXTRA */
    58716086                            return MEMORY_E;
    58726087                        }
     
    58876102                        copy = WOLFSSL_USER_ID;
    58886103                        copyLen = sizeof(WOLFSSL_USER_ID) - 1;
    5889                     #if defined(OPENSSL_EXTRA) || \
    5890                         defined(OPENSSL_EXTRA_X509_SMALL)
    5891                         dName->uidIdx = cert->srcIdx;
    5892                         dName->uidLen = strLen;
     6104                    #if (defined(OPENSSL_EXTRA) || \
     6105                        defined(OPENSSL_EXTRA_X509_SMALL)) \
     6106                        && !defined(WOLFCRYPT_ONLY)
     6107                        nid = NID_userId;
    58936108                    #endif /* OPENSSL_EXTRA */
    58946109                        break;
     
    58976112                        copy = WOLFSSL_DOMAIN_COMPONENT;
    58986113                        copyLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
    5899                     #if defined(OPENSSL_EXTRA) || \
    5900                         defined(OPENSSL_EXTRA_X509_SMALL)
    5901                         dName->dcIdx[dcnum] = cert->srcIdx;
    5902                         dName->dcLen[dcnum] = strLen;
    5903                         dName->dcNum = dcnum + 1;
    5904                         dcnum++;
     6114                    #if (defined(OPENSSL_EXTRA) || \
     6115                        defined(OPENSSL_EXTRA_X509_SMALL)) \
     6116                        && !defined(WOLFCRYPT_ONLY)
     6117                        nid = NID_domainComponent;
    59056118                    #endif /* OPENSSL_EXTRA */
    59066119                        break;
     
    59086121                    default:
    59096122                        WOLFSSL_MSG("Unknown pilot attribute type");
     6123                    #if (defined(OPENSSL_EXTRA) || \
     6124                                defined(OPENSSL_EXTRA_X509_SMALL)) && \
     6125                                !defined(WOLFCRYPT_ONLY)
     6126                        wolfSSL_X509_NAME_free(dName);
     6127                    #endif /* OPENSSL_EXTRA */
    59106128                        return ASN_PARSE_E;
    59116129                }
     
    59226140            XMEMCPY(&full[idx], &cert->source[cert->srcIdx], strLen);
    59236141            idx += strLen;
    5924 
    5925         #ifdef OPENSSL_EXTRA
    5926             if (count < DOMAIN_COMPONENT_MAX) {
    5927                 /* store order that DN was parsed */
    5928                 dName->loc[count++] = id;
    5929             }
    5930         #endif
    5931         }
     6142        }
     6143        #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
     6144            !defined(WOLFCRYPT_ONLY)
     6145        switch (b) {
     6146            case CTC_UTF8:
     6147                enc = MBSTRING_UTF8;
     6148                break;
     6149            case CTC_PRINTABLE:
     6150                enc = V_ASN1_PRINTABLESTRING;
     6151                break;
     6152            default:
     6153                WOLFSSL_MSG("Unknown encoding type, using UTF8 by default");
     6154                enc = MBSTRING_UTF8;
     6155        }
     6156
     6157        if (nid != NID_undef) {
     6158            if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc,
     6159                            &cert->source[cert->srcIdx], strLen, -1, -1) !=
     6160                            WOLFSSL_SUCCESS) {
     6161                wolfSSL_X509_NAME_free(dName);
     6162                return ASN_PARSE_E;
     6163            }
     6164        }
     6165        #endif /* OPENSSL_EXTRA */
    59326166        cert->srcIdx += strLen;
    59336167    }
    59346168    full[idx++] = 0;
    5935 #if defined(OPENSSL_EXTRA)
    5936     /* store order that DN was parsed */
    5937     dName->locSz = count;
    5938 #endif
    5939 
    5940     #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    5941     {
    5942         int totalLen = 0;
    5943         int i = 0;
    5944 
    5945         if (dName->cnLen != 0)
    5946             totalLen += dName->cnLen + 4;
    5947         if (dName->snLen != 0)
    5948             totalLen += dName->snLen + 4;
    5949         if (dName->cLen != 0)
    5950             totalLen += dName->cLen + 3;
    5951         if (dName->lLen != 0)
    5952             totalLen += dName->lLen + 3;
    5953         if (dName->stLen != 0)
    5954             totalLen += dName->stLen + 4;
    5955         if (dName->oLen != 0)
    5956             totalLen += dName->oLen + 3;
    5957         if (dName->ouLen != 0)
    5958             totalLen += dName->ouLen + 4;
    5959         if (dName->emailLen != 0)
    5960             totalLen += dName->emailLen + 14;
    5961         if (dName->uidLen != 0)
    5962             totalLen += dName->uidLen + 5;
    5963         if (dName->serialLen != 0)
    5964             totalLen += dName->serialLen + 14;
    5965         if (dName->dcNum != 0){
    5966             for (i = 0;i < dName->dcNum;i++)
    5967                 totalLen += dName->dcLen[i] + 4;
    5968         }
    5969 
    5970         dName->fullName = (char*)XMALLOC(totalLen + 1, cert->heap,
    5971                                                              DYNAMIC_TYPE_X509);
    5972         if (dName->fullName != NULL) {
    5973             idx = 0;
    5974 
    5975             if (dName->cnLen != 0) {
    5976                 dName->entryCount++;
    5977                 XMEMCPY(&dName->fullName[idx], WOLFSSL_COMMON_NAME, 4);
    5978                 dName->cnNid = wc_OBJ_sn2nid((const char *)WOLFSSL_COMMON_NAME);
    5979                 idx += 4;
    5980                 XMEMCPY(&dName->fullName[idx],
    5981                                      &cert->source[dName->cnIdx], dName->cnLen);
    5982                 dName->cnIdx = idx;
    5983                 idx += dName->cnLen;
    5984             }
    5985             if (dName->snLen != 0) {
    5986                 dName->entryCount++;
    5987                 XMEMCPY(&dName->fullName[idx], WOLFSSL_SUR_NAME, 4);
    5988                 dName->snNid = wc_OBJ_sn2nid((const char *)WOLFSSL_SUR_NAME);
    5989                 idx += 4;
    5990                 XMEMCPY(&dName->fullName[idx],
    5991                                      &cert->source[dName->snIdx], dName->snLen);
    5992                 dName->snIdx = idx;
    5993                 idx += dName->snLen;
    5994             }
    5995             if (dName->cLen != 0) {
    5996                 dName->entryCount++;
    5997                 XMEMCPY(&dName->fullName[idx], WOLFSSL_COUNTRY_NAME, 3);
    5998                 dName->cNid = wc_OBJ_sn2nid((const char *)WOLFSSL_COUNTRY_NAME);
    5999                 idx += 3;
    6000                 XMEMCPY(&dName->fullName[idx],
    6001                                        &cert->source[dName->cIdx], dName->cLen);
    6002                 dName->cIdx = idx;
    6003                 idx += dName->cLen;
    6004             }
    6005             if (dName->lLen != 0) {
    6006                 dName->entryCount++;
    6007                 XMEMCPY(&dName->fullName[idx], WOLFSSL_LOCALITY_NAME, 3);
    6008                 dName->lNid = wc_OBJ_sn2nid((const char *)WOLFSSL_LOCALITY_NAME);
    6009                 idx += 3;
    6010                 XMEMCPY(&dName->fullName[idx],
    6011                                        &cert->source[dName->lIdx], dName->lLen);
    6012                 dName->lIdx = idx;
    6013                 idx += dName->lLen;
    6014             }
    6015             if (dName->stLen != 0) {
    6016                 dName->entryCount++;
    6017                 XMEMCPY(&dName->fullName[idx], WOLFSSL_STATE_NAME, 4);
    6018                 dName->stNid = wc_OBJ_sn2nid((const char *)WOLFSSL_STATE_NAME);
    6019                 idx += 4;
    6020                 XMEMCPY(&dName->fullName[idx],
    6021                                      &cert->source[dName->stIdx], dName->stLen);
    6022                 dName->stIdx = idx;
    6023                 idx += dName->stLen;
    6024             }
    6025             if (dName->oLen != 0) {
    6026                 dName->entryCount++;
    6027                 XMEMCPY(&dName->fullName[idx], WOLFSSL_ORG_NAME, 3);
    6028                 dName->oNid = wc_OBJ_sn2nid((const char *)WOLFSSL_ORG_NAME);
    6029                 idx += 3;
    6030                 XMEMCPY(&dName->fullName[idx],
    6031                                        &cert->source[dName->oIdx], dName->oLen);
    6032                 dName->oIdx = idx;
    6033                 idx += dName->oLen;
    6034             }
    6035             if (dName->ouLen != 0) {
    6036                 dName->entryCount++;
    6037                 XMEMCPY(&dName->fullName[idx], WOLFSSL_ORGUNIT_NAME, 4);
    6038                 dName->ouNid = wc_OBJ_sn2nid((const char *)WOLFSSL_ORGUNIT_NAME);
    6039                 idx += 4;
    6040                 XMEMCPY(&dName->fullName[idx],
    6041                                      &cert->source[dName->ouIdx], dName->ouLen);
    6042                 dName->ouIdx = idx;
    6043                 idx += dName->ouLen;
    6044             }
    6045             if (dName->emailLen != 0) {
    6046                 dName->entryCount++;
    6047                 XMEMCPY(&dName->fullName[idx], "/emailAddress=", 14);
    6048                 dName->emailNid = wc_OBJ_sn2nid((const char *)"/emailAddress=");
    6049                 idx += 14;
    6050                 XMEMCPY(&dName->fullName[idx],
    6051                                &cert->source[dName->emailIdx], dName->emailLen);
    6052                 dName->emailIdx = idx;
    6053                 idx += dName->emailLen;
    6054             }
    6055             for (i = 0;i < dName->dcNum;i++){
    6056                 if (dName->dcLen[i] != 0) {
    6057                     dName->entryCount++;
    6058                     XMEMCPY(&dName->fullName[idx], WOLFSSL_DOMAIN_COMPONENT, 4);
    6059                     idx += 4;
    6060                     XMEMCPY(&dName->fullName[idx],
    6061                                     &cert->source[dName->dcIdx[i]], dName->dcLen[i]);
    6062                     dName->dcIdx[i] = idx;
    6063                     idx += dName->dcLen[i];
    6064                 }
    6065             }
    6066             if (dName->uidLen != 0) {
    6067                 dName->entryCount++;
    6068                 XMEMCPY(&dName->fullName[idx], "/UID=", 5);
    6069                 dName->uidNid = wc_OBJ_sn2nid((const char *)"/UID=");
    6070                 idx += 5;
    6071                 XMEMCPY(&dName->fullName[idx],
    6072                                    &cert->source[dName->uidIdx], dName->uidLen);
    6073                 dName->uidIdx = idx;
    6074                 idx += dName->uidLen;
    6075             }
    6076             if (dName->serialLen != 0) {
    6077                 dName->entryCount++;
    6078                 XMEMCPY(&dName->fullName[idx], WOLFSSL_SERIAL_NUMBER, 14);
    6079                 dName->serialNid = wc_OBJ_sn2nid((const char *)WOLFSSL_SERIAL_NUMBER);
    6080                 idx += 14;
    6081                 XMEMCPY(&dName->fullName[idx],
    6082                              &cert->source[dName->serialIdx], dName->serialLen);
    6083                 dName->serialIdx = idx;
    6084                 idx += dName->serialLen;
    6085             }
    6086             dName->fullName[idx] = '\0';
    6087             dName->fullNameLen = totalLen;
    6088         }
    6089     }
    6090     #endif /* OPENSSL_EXTRA */
    6091 
     6169
     6170
     6171#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
     6172            !defined(WOLFCRYPT_ONLY)
     6173    if (nameType == ISSUER) {
     6174        cert->issuerName = dName;
     6175    }
     6176    else {
     6177        cert->subjectName = dName;
     6178    }
     6179#endif
    60926180    return 0;
    60936181}
     
    61136201    return 0;
    61146202}
     6203
     6204#ifdef WOLFSSL_LINUXKM
     6205static WC_INLINE int GetTime_Long(long* value, const byte* date, int* idx)
     6206{
     6207    int i = *idx;
     6208
     6209    if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
     6210                                                             date[i+1] > 0x39) {
     6211        return ASN_PARSE_E;
     6212    }
     6213
     6214    *value += (long)btoi(date[i++]) * 10;
     6215    *value += (long)btoi(date[i++]);
     6216
     6217    *idx = i;
     6218
     6219    return 0;
     6220}
     6221#endif
    61156222
    61166223int ExtractDate(const unsigned char* date, unsigned char format,
     
    61266233    }
    61276234    else  { /* format == GENERALIZED_TIME */
     6235#ifdef WOLFSSL_LINUXKM
     6236        if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
     6237#else
    61286238        if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
     6239#endif
    61296240        certTime->tm_year *= 100;
    61306241    }
    61316242
     6243#ifdef AVR
     6244    /* Extract the time from the struct tm and adjust tm_year, tm_mon */
     6245    /* AVR libc stores these as uint8_t instead of int */
     6246    /* AVR time_t also offsets from midnight 1 Jan 2000 */
     6247    int tm_year = certTime->tm_year - 2000;
     6248    int tm_mon  = certTime->tm_mon - 1;
     6249    int tm_mday = certTime->tm_mday;
     6250    int tm_hour = certTime->tm_hour;
     6251    int tm_min  = certTime->tm_min;
     6252    int tm_sec  = certTime->tm_sec;
     6253
     6254#ifdef WOLFSSL_LINUXKM
     6255    if (GetTime_Long(&tm_year, date, idx) != 0) return 0;
     6256#else
     6257    if (GetTime(&tm_year, date, idx) != 0) return 0;
     6258#endif
     6259    if (GetTime(&tm_mon , date, idx) != 0) return 0;
     6260    if (GetTime(&tm_mday, date, idx) != 0) return 0;
     6261    if (GetTime(&tm_hour, date, idx) != 0) return 0;
     6262    if (GetTime(&tm_min , date, idx) != 0) return 0;
     6263    if (GetTime(&tm_sec , date, idx) != 0) return 0;
     6264
     6265    /* Re-populate certTime with computed values */
     6266    certTime->tm_year = tm_year;
     6267    certTime->tm_mon  = tm_mon;
     6268    certTime->tm_mday = tm_mday;
     6269    certTime->tm_hour = tm_hour;
     6270    certTime->tm_min  = tm_min;
     6271    certTime->tm_sec  = tm_sec;
     6272#else
    61326273    /* adjust tm_year, tm_mon */
     6274#ifdef WOLFSSL_LINUXKM
     6275    if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
     6276#else
    61336277    if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
     6278#endif
    61346279    certTime->tm_year -= 1900;
    61356280    if (GetTime(&certTime->tm_mon , date, idx) != 0) return 0;
     
    61396284    if (GetTime(&certTime->tm_min , date, idx) != 0) return 0;
    61406285    if (GetTime(&certTime->tm_sec , date, idx) != 0) return 0;
     6286#endif
    61416287
    61426288    return 1;
     
    61826328
    61836329    XSNPRINTF(buf + idx, len - idx, "%2d %02d:%02d:%02d %d GMT",
    6184               t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, t.tm_year + 1900);
     6330              t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, (int)t.tm_year + 1900);
    61856331
    61866332    return 1;
     
    61996345    struct tm* ts      = NULL;
    62006346    struct tm* tmpTime = NULL;
     6347    byte* data_ptr  = buf;
     6348    word32 data_len = 0;
     6349    int year, mon, day, hour, mini, sec;
    62016350#if defined(NEED_TMP_TIME)
    62026351    struct tm tmpTimeStorage;
     
    62056354    (void)tmpTime;
    62066355#endif
    6207     byte* data_ptr  = buf;
    6208     word32 data_len = 0;
    6209     int year, mon, day, hour, mini, sec;
    62106356
    62116357    WOLFSSL_ENTER("SetAsnTimeString");
     
    63206466/* like atoi but only use first byte */
    63216467/* Make sure before and after dates are valid */
    6322 int ValidateDate(const byte* date, byte format, int dateType)
     6468int wc_ValidateDate(const byte* date, byte format, int dateType)
    63236469{
    63246470    time_t ltime;
     
    65926738    WOLFSSL_MSG("Got Cert Header");
    65936739
    6594     /* Using the sigIndex as the upper bound because that's where the
    6595      * actual certificate data ends. */
    6596     if ( (ret = GetAlgoId(cert->source, &cert->srcIdx, &cert->signatureOID,
    6597                           oidSigType, cert->sigIndex)) < 0)
    6598         return ret;
    6599 
    6600     WOLFSSL_MSG("Got Algo ID");
    6601 
    6602     if ( (ret = GetName(cert, ISSUER, cert->sigIndex)) < 0)
    6603         return ret;
    6604 
    6605     if ( (ret = GetValidity(cert, verify, cert->sigIndex)) < 0)
    6606         *badDate = ret;
     6740#ifdef WOLFSSL_CERT_REQ
     6741    if (!cert->isCSR) {
     6742#endif
     6743        /* Using the sigIndex as the upper bound because that's where the
     6744         * actual certificate data ends. */
     6745        if ( (ret = GetAlgoId(cert->source, &cert->srcIdx, &cert->signatureOID,
     6746                              oidSigType, cert->sigIndex)) < 0)
     6747            return ret;
     6748
     6749        WOLFSSL_MSG("Got Algo ID");
     6750
     6751        if ( (ret = GetName(cert, ISSUER, cert->sigIndex)) < 0)
     6752            return ret;
     6753
     6754        if ( (ret = GetValidity(cert, verify, cert->sigIndex)) < 0)
     6755            *badDate = ret;
     6756#ifdef WOLFSSL_CERT_REQ
     6757    }
     6758#endif
    66076759
    66086760    if ( (ret = GetName(cert, SUBJECT, cert->sigIndex)) < 0)
     
    66416793    int length;
    66426794    int ret;
     6795
    66436796    ret = CheckBitString(cert->source, &cert->srcIdx, &length, cert->maxIdx, 1,
    66446797                         NULL);
     
    66496802    cert->signature = &cert->source[cert->srcIdx];
    66506803    cert->srcIdx += cert->sigLength;
     6804
     6805    if (cert->srcIdx != cert->maxIdx)
     6806        return ASN_PARSE_E;
    66516807
    66526808    return 0;
     
    69037059        sigCtx->digest = NULL;
    69047060    }
    6905 #ifndef NO_RSA
    6906     if (sigCtx->plain) {
    6907         XFREE(sigCtx->plain, sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
    6908         sigCtx->plain = NULL;
     7061#if !(defined(NO_RSA) && defined(NO_DSA))
     7062    if (sigCtx->sigCpy) {
     7063        XFREE(sigCtx->sigCpy, sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
     7064        sigCtx->sigCpy = NULL;
    69097065    }
    69107066#endif
     
    69187074                break;
    69197075        #endif /* !NO_RSA */
     7076        #ifndef NO_DSA
     7077            case DSAk:
     7078                wc_FreeDsaKey(sigCtx->key.dsa);
     7079                XFREE(sigCtx->key.dsa, sigCtx->heap, DYNAMIC_TYPE_DSA);
     7080                break;
     7081        #endif
    69207082        #ifdef HAVE_ECC
    69217083            case ECDSAk:
     
    69987160        case CTC_SHA256wRSA:
    69997161        case CTC_SHA256wECDSA:
     7162        case CTC_SHA256wDSA:
    70007163            if ((ret = wc_Sha256Hash(buf, bufSz, digest)) == 0) {
    70017164                *typeH    = SHA256h;
     
    71057268                    sigCtx->key.rsa = (RsaKey*)XMALLOC(sizeof(RsaKey),
    71067269                                                sigCtx->heap, DYNAMIC_TYPE_RSA);
    7107                     sigCtx->plain = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
     7270                    sigCtx->sigCpy = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
    71087271                                         sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
    7109                     if (sigCtx->key.rsa == NULL || sigCtx->plain == NULL) {
     7272                    if (sigCtx->key.rsa == NULL || sigCtx->sigCpy == NULL) {
    71107273                        ERROR_OUT(MEMORY_E, exit_cs);
    71117274                    }
     
    71237286                        goto exit_cs;
    71247287                    }
    7125                     XMEMCPY(sigCtx->plain, sig, sigSz);
     7288                    XMEMCPY(sigCtx->sigCpy, sig, sigSz);
    71267289                    sigCtx->out = NULL;
    71277290
     
    71327295                }
    71337296            #endif /* !NO_RSA */
     7297            #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
     7298                case DSAk:
     7299                {
     7300                    word32 idx = 0;
     7301
     7302                    if (sigSz < DSA_SIG_SIZE) {
     7303                        WOLFSSL_MSG("Verify Signature is too small");
     7304                        ERROR_OUT(BUFFER_E, exit_cs);
     7305                    }
     7306                    sigCtx->key.dsa = (DsaKey*)XMALLOC(sizeof(DsaKey),
     7307                                                sigCtx->heap, DYNAMIC_TYPE_DSA);
     7308                    sigCtx->sigCpy = (byte*)XMALLOC(sigSz,
     7309                                         sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
     7310                    if (sigCtx->key.dsa == NULL || sigCtx->sigCpy == NULL) {
     7311                        ERROR_OUT(MEMORY_E, exit_cs);
     7312                    }
     7313                    if ((ret = wc_InitDsaKey_h(sigCtx->key.dsa, sigCtx->heap)) != 0) {
     7314                        WOLFSSL_MSG("wc_InitDsaKey_h error");
     7315                        goto exit_cs;
     7316                    }
     7317                    if ((ret = wc_DsaPublicKeyDecode(key, &idx, sigCtx->key.dsa,
     7318                                                                 keySz)) != 0) {
     7319                        WOLFSSL_MSG("ASN Key decode error RSA");
     7320                        goto exit_cs;
     7321                    }
     7322                    if (sigSz != DSA_SIG_SIZE) {
     7323                #ifdef HAVE_ECC
     7324                        /* Try to parse it as the contents of a bitstring */
     7325                        mp_int r, s;
     7326                        idx = 0;
     7327                        if (DecodeECC_DSA_Sig(sig + idx, sigSz - idx,
     7328                                              &r, &s) != 0) {
     7329                            WOLFSSL_MSG("DSA Sig is in unrecognized or "
     7330                                        "incorrect format");
     7331                            ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
     7332                        }
     7333                        if (mp_to_unsigned_bin_len(&r, sigCtx->sigCpy,
     7334                                DSA_HALF_SIZE) != MP_OKAY ||
     7335                            mp_to_unsigned_bin_len(&s,
     7336                                    sigCtx->sigCpy + DSA_HALF_SIZE,
     7337                                    DSA_HALF_SIZE) != MP_OKAY) {
     7338                            WOLFSSL_MSG("DSA Sig is in unrecognized or "
     7339                                        "incorrect format");
     7340                            ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
     7341                        }
     7342                        mp_free(&r);
     7343                        mp_free(&s);
     7344                #else
     7345                        WOLFSSL_MSG("DSA Sig is in unrecognized or "
     7346                                    "incorrect format");
     7347                        ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
     7348                #endif
     7349                    }
     7350                    else {
     7351                        XMEMCPY(sigCtx->sigCpy, sig, DSA_SIG_SIZE);
     7352                    }
     7353                    break;
     7354                }
     7355            #endif /* !NO_DSA && !HAVE_SELFTEST */
    71347356            #ifdef HAVE_ECC
    71357357                case ECDSAk:
     
    72397461                    if (sigCtx->pkCbRsa) {
    72407462                        ret = sigCtx->pkCbRsa(
    7241                                 sigCtx->plain, sigSz, &sigCtx->out,
     7463                                sigCtx->sigCpy, sigSz, &sigCtx->out,
    72427464                                key, keySz,
    72437465                                sigCtx->pkCtxRsa);
     
    72497471                        if (rsaKeyIdx != NULL)
    72507472                        {
    7251                             ret = tsip_tls_CertVerify(buf, bufSz, sigCtx->plain,
     7473                            ret = tsip_tls_CertVerify(buf, bufSz, sigCtx->sigCpy,
    72527474                                sigSz,
    72537475                                sigCtx->pubkey_n_start - sigCtx->certBegin,
     
    72667488                        } else
    72677489                    #endif
    7268                         ret = wc_RsaSSL_VerifyInline(sigCtx->plain, sigSz,
     7490                        ret = wc_RsaSSL_VerifyInline(sigCtx->sigCpy, sigSz,
    72697491                                                 &sigCtx->out, sigCtx->key.rsa);
    72707492                    }
     
    72727494                }
    72737495            #endif /* !NO_RSA */
     7496            #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
     7497                case DSAk:
     7498                {
     7499                    ret = wc_DsaVerify(sigCtx->digest, sigCtx->sigCpy,
     7500                            sigCtx->key.dsa, &sigCtx->verify);
     7501                    break;
     7502                }
     7503            #endif /* !NO_DSA && !HAVE_SELFTEST */
    72747504            #if defined(HAVE_ECC)
    72757505                case ECDSAk:
     
    73707600                }
    73717601            #endif /* NO_RSA */
     7602            #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
     7603                case DSAk:
     7604                {
     7605                    if (sigCtx->verify == 1) {
     7606                        ret = 0;
     7607                    }
     7608                    else {
     7609                        WOLFSSL_MSG("DSA Verify didn't match");
     7610                        ret = ASN_SIG_CONFIRM_E;
     7611                    }
     7612                    break;
     7613                }
     7614            #endif /* !NO_DSA && !HAVE_SELFTEST */
    73727615            #ifdef HAVE_ECC
    73737616                case ECDSAk:
     
    75477790                        return 0;
    75487791                    }
     7792                    #ifndef WOLFSSL_NO_ASN_STRICT
     7793                    /* RFC 5280 section 4.2.1.10
     7794                       "Restrictions of the form directoryName MUST be
     7795                        applied to the subject field .... and to any names
     7796                        of type directoryName in the subjectAltName
     7797                        extension"
     7798                    */
     7799                    if (cert->altDirNames != NULL) {
     7800                        DNS_entry* cur = cert->altDirNames;
     7801                        while (cur != NULL) {
     7802                            if (XMEMCMP(cur->name, base->name, base->nameSz)
     7803                                    == 0) {
     7804                                WOLFSSL_MSG("DIR alt name constraint err");
     7805                                return 0;
     7806                            }
     7807                            cur = cur->next;
     7808                        }
     7809                    }
     7810                    #endif /* !WOLFSSL_NO_ASN_STRICT */
    75497811                    break;
    75507812                }
     
    76057867                                                        base->nameSz) == 0) {
    76067868                        matchDir = 1;
     7869
     7870                        #ifndef WOLFSSL_NO_ASN_STRICT
     7871                        /* RFC 5280 section 4.2.1.10
     7872                           "Restrictions of the form directoryName MUST be
     7873                            applied to the subject field .... and to any names
     7874                            of type directoryName in the subjectAltName
     7875                            extension"
     7876                        */
     7877                        if (cert->altDirNames != NULL) {
     7878                            DNS_entry* cur = cert->altDirNames;
     7879                            while (cur != NULL) {
     7880                                if (XMEMCMP(cur->name, base->name, base->nameSz)
     7881                                        != 0) {
     7882                                    WOLFSSL_MSG("DIR alt name constraint err");
     7883                                    matchDir = 0; /* did not match */
     7884                                }
     7885                                cur = cur->next;
     7886                            }
     7887                        }
     7888                        #endif /* !WOLFSSL_NO_ASN_STRICT */
    76077889                    }
    76087890                    break;
     
    76897971        }
    76907972    #ifndef IGNORE_NAME_CONSTRAINTS
     7973        else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
     7974            DNS_entry* dirEntry;
     7975            int strLen;
     7976            word32 lenStartIdx = idx;
     7977
     7978            if (GetLength(input, &idx, &strLen, sz) < 0) {
     7979                WOLFSSL_MSG("\tfail: str length");
     7980                return ASN_PARSE_E;
     7981            }
     7982
     7983            if (GetSequence(input, &idx, &strLen, sz) < 0) {
     7984                WOLFSSL_MSG("\tfail: seq length");
     7985                return ASN_PARSE_E;
     7986            }
     7987            length -= (idx - lenStartIdx);
     7988
     7989            dirEntry = (DNS_entry*)XMALLOC(sizeof(DNS_entry), cert->heap,
     7990                                        DYNAMIC_TYPE_ALTNAME);
     7991            if (dirEntry == NULL) {
     7992                WOLFSSL_MSG("\tOut of Memory");
     7993                return MEMORY_E;
     7994            }
     7995
     7996            dirEntry->type = ASN_DIR_TYPE;
     7997            dirEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
     7998                                         DYNAMIC_TYPE_ALTNAME);
     7999            if (dirEntry->name == NULL) {
     8000                WOLFSSL_MSG("\tOut of Memory");
     8001                XFREE(dirEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
     8002                return MEMORY_E;
     8003            }
     8004            dirEntry->len = strLen;
     8005            XMEMCPY(dirEntry->name, &input[idx], strLen);
     8006            dirEntry->name[strLen] = '\0';
     8007
     8008            dirEntry->next = cert->altDirNames;
     8009            cert->altDirNames = dirEntry;
     8010
     8011            length -= strLen;
     8012            idx    += strLen;
     8013        }
    76918014        else if (b == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
    76928015            DNS_entry* emailEntry;
     
    77968119            idx    += strLen;
    77978120        }
    7798 #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
     8121#if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
    77998122        else if (b == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
    78008123            DNS_entry* ipAddr;
     
    83968719        }
    83978720
    8398         DecodeSubtree(input + idx, length, subtree, cert->heap);
     8721        if (DecodeSubtree(input + idx, length, subtree, cert->heap) < 0) {
     8722            WOLFSSL_MSG("\terror parsing subtree");
     8723            return ASN_PARSE_E;
     8724        }
    83998725
    84008726        idx += length;
     
    84058731#endif /* IGNORE_NAME_CONSTRAINTS */
    84068732
    8407 #if (defined(WOLFSSL_CERT_EXT) && !defined(WOLFSSL_SEP)) || defined(OPENSSL_EXTRA)
     8733#if (defined(WOLFSSL_CERT_EXT) && !defined(WOLFSSL_SEP)) || \
     8734    defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    84088735
    84098736/* Decode ITU-T X.690 OID format to a string representation
     
    85978924        return BAD_FUNC_ARG;
    85988925
    8599     if (GetASNTag(input, &idx, &tag, sz) < 0) {
    8600         return ASN_PARSE_E;
    8601     }
    8602 
    8603     if (tag != ASN_EXTENSIONS) {
    8604         WOLFSSL_MSG("\tfail: should be an EXTENSIONS");
    8605         return ASN_PARSE_E;
    8606     }
    8607 
    8608     if (GetLength(input, &idx, &length, sz) < 0) {
    8609         WOLFSSL_MSG("\tfail: invalid length");
    8610         return ASN_PARSE_E;
     8926#ifdef WOLFSSL_CERT_REQ
     8927    if (!cert->isCSR)
     8928#endif
     8929    { /* Not included in CSR */
     8930        if (GetASNTag(input, &idx, &tag, sz) < 0) {
     8931            return ASN_PARSE_E;
     8932        }
     8933
     8934        if (tag != ASN_EXTENSIONS) {
     8935            WOLFSSL_MSG("\tfail: should be an EXTENSIONS");
     8936            return ASN_PARSE_E;
     8937        }
     8938
     8939        if (GetLength(input, &idx, &length, sz) < 0) {
     8940            WOLFSSL_MSG("\tfail: invalid length");
     8941            return ASN_PARSE_E;
     8942        }
    86118943    }
    86128944
     
    88079139                break;
    88089140        #endif
    8809 
     9141        #ifdef HAVE_OCSP
     9142            case OCSP_NOCHECK_OID:
     9143                VERIFY_AND_SET_OID(cert->ocspNoCheckSet);
     9144                ret = GetASNNull(input, &idx, sz);
     9145                length = 0; /* idx is already incremented, reset length to 0 */
     9146                if (ret != 0)
     9147                    return ASN_PARSE_E;
     9148                break;
     9149        #endif
    88109150            default:
    88119151            #ifndef WOLFSSL_NO_ASN_STRICT
     
    89149254 * in certificate signature verification.
    89159255 * Must use the signature OID from the signed part of the certificate.
     9256 * Works also on certificate signing requests.
    89169257 *
    89179258 * This is only for minimizing dynamic memory usage during TLS certificate
     
    89219262 */
    89229263static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap,
    8923         void* cm, const byte* pubKey, word32 pubKeySz, int pubKeyOID)
     9264        void* cm, const byte* pubKey, word32 pubKeySz, int pubKeyOID, int req)
    89249265{
    89259266#ifndef WOLFSSL_SMALL_STACK
     
    89989339
    89999340        /* signature */
    9000         if (GetAlgoId(cert, &idx, &signatureOID, oidSigType, certSz) < 0)
     9341        if (!req &&
     9342                GetAlgoId(cert, &idx, &signatureOID, oidSigType, certSz) < 0)
    90019343            ret = ASN_PARSE_E;
    90029344    }
     
    90049346    if (ret == 0) {
    90059347        issuerIdx = idx;
    9006         /* issuer */
     9348        /* issuer for cert or subject for csr */
    90079349        if (GetSequence(cert, &idx, &len, certSz) < 0)
    90089350            ret = ASN_PARSE_E;
     
    90129354    }
    90139355#ifndef NO_SKID
    9014     if (ret == 0) {
     9356    if (!req && ret == 0) {
    90159357        idx += len;
    90169358
     
    90199361            ret = ASN_PARSE_E;
    90209362    }
    9021     if (ret == 0) {
     9363    if (!req && ret == 0) {
    90229364        idx += len;
    90239365
     
    90339375            ret = ASN_PARSE_E;
    90349376    }
    9035     if (ret == 0) {
     9377    if (req && ret == 0) {
    90369378        idx += len;
    90379379
    9038         if ((idx + 1) > certSz)
    9039             ret = BUFFER_E;
    9040     }
    9041     if (ret == 0) {
    9042         /* issuerUniqueID - optional */
     9380        /* attributes */
     9381        if (GetASNHeader_ex(cert,
     9382                ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &idx,
     9383                &len, certSz, 1) < 0)
     9384            ret = ASN_PARSE_E;
     9385    }
     9386    if (!req) {
     9387        if (ret == 0) {
     9388            idx += len;
     9389
     9390            if ((idx + 1) > certSz)
     9391                ret = BUFFER_E;
     9392        }
     9393        if (ret == 0) {
     9394            /* issuerUniqueID - optional */
     9395            localIdx = idx;
     9396            if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
     9397                if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)) {
     9398                    idx++;
     9399                    if (GetLength(cert, &idx, &len, certSz) < 0)
     9400                        ret = ASN_PARSE_E;
     9401                    idx += len;
     9402                }
     9403            }
     9404        }
     9405        if (ret == 0) {
     9406            if ((idx + 1) > certSz)
     9407                ret = BUFFER_E;
     9408        }
     9409        if (ret == 0) {
     9410            /* subjectUniqueID - optional */
     9411            localIdx = idx;
     9412            if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
     9413                if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)) {
     9414                    idx++;
     9415                    if (GetLength(cert, &idx, &len, certSz) < 0)
     9416                        ret = ASN_PARSE_E;
     9417                    idx += len;
     9418                }
     9419            }
     9420        }
     9421
     9422        if (ret == 0) {
     9423            if ((idx + 1) > certSz)
     9424                ret = BUFFER_E;
     9425        }
     9426        /* extensions - optional */
    90439427        localIdx = idx;
    9044         if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
    9045             if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)) {
    9046                 idx++;
    9047                 if (GetLength(cert, &idx, &len, certSz) < 0)
     9428        if (ret == 0 && GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
     9429                tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)) {
     9430            idx++;
     9431            if (GetLength(cert, &idx, &extLen, certSz) < 0)
     9432                ret = ASN_PARSE_E;
     9433            if (ret == 0) {
     9434                if (GetSequence(cert, &idx, &extLen, certSz) < 0)
    90489435                    ret = ASN_PARSE_E;
    9049                 idx += len;
    9050             }
    9051         }
    9052     }
    9053     if (ret == 0) {
    9054         if ((idx + 1) > certSz)
    9055             ret = BUFFER_E;
    9056     }
    9057     if (ret == 0) {
    9058         /* subjectUniqueID - optional */
    9059         localIdx = idx;
    9060         if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
    9061             if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)) {
    9062                 idx++;
    9063                 if (GetLength(cert, &idx, &len, certSz) < 0)
    9064                     ret = ASN_PARSE_E;
    9065                 idx += len;
    9066             }
    9067         }
    9068     }
    9069 
    9070     if (ret == 0) {
    9071         if ((idx + 1) > certSz)
    9072             ret = BUFFER_E;
    9073     }
    9074     /* extensions - optional */
    9075     localIdx = idx;
    9076     if (ret == 0 && GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
    9077             tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)) {
    9078         idx++;
    9079         if (GetLength(cert, &idx, &extLen, certSz) < 0)
    9080             ret = ASN_PARSE_E;
    9081         if (ret == 0) {
    9082             if (GetSequence(cert, &idx, &extLen, certSz) < 0)
    9083                 ret = ASN_PARSE_E;
    9084         }
    9085         if (ret == 0) {
    9086             extEndIdx = idx + extLen;
    9087 
    9088             /* Check each extension for the ones we want. */
    9089             while (ret == 0 && idx < extEndIdx) {
    9090                 if (GetSequence(cert, &idx, &len, certSz) < 0)
    9091                     ret = ASN_PARSE_E;
    9092                 if (ret == 0) {
    9093                     extIdx = idx;
    9094                     if (GetObjectId(cert, &extIdx, &oid, oidCertExtType,
    9095                                                                   certSz) < 0) {
     9436            }
     9437            if (ret == 0) {
     9438                extEndIdx = idx + extLen;
     9439
     9440                /* Check each extension for the ones we want. */
     9441                while (ret == 0 && idx < extEndIdx) {
     9442                    if (GetSequence(cert, &idx, &len, certSz) < 0)
    90969443                        ret = ASN_PARSE_E;
     9444                    if (ret == 0) {
     9445                        extIdx = idx;
     9446                        if (GetObjectId(cert, &extIdx, &oid, oidCertExtType,
     9447                                                                      certSz) < 0) {
     9448                            ret = ASN_PARSE_E;
     9449                        }
     9450
     9451                        if (ret == 0) {
     9452                            if ((extIdx + 1) > certSz)
     9453                                ret = BUFFER_E;
     9454                        }
    90979455                    }
    90989456
    90999457                    if (ret == 0) {
    9100                         if ((extIdx + 1) > certSz)
    9101                             ret = BUFFER_E;
     9458                        localIdx = extIdx;
     9459                        if (GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
     9460                                tag == ASN_BOOLEAN) {
     9461                            if (GetBoolean(cert, &extIdx, certSz) < 0)
     9462                                ret = ASN_PARSE_E;
     9463                        }
    91029464                    }
    9103                 }
    9104 
    9105                 if (ret == 0) {
    9106                     localIdx = extIdx;
    9107                     if (GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
    9108                             tag == ASN_BOOLEAN) {
    9109                         if (GetBoolean(cert, &extIdx, certSz) < 0)
     9465                    if (ret == 0) {
     9466                        if (GetOctetString(cert, &extIdx, &extLen, certSz) < 0)
    91109467                            ret = ASN_PARSE_E;
    91119468                    }
    9112                 }
    9113                 if (ret == 0) {
    9114                     if (GetOctetString(cert, &extIdx, &extLen, certSz) < 0)
    9115                         ret = ASN_PARSE_E;
    9116                 }
    9117 
    9118                 if (ret == 0) {
    9119                     switch (oid) {
    9120                     case AUTH_KEY_OID:
    9121                         if (GetSequence(cert, &extIdx, &extLen, certSz) < 0)
    9122                             ret = ASN_PARSE_E;
    9123 
    9124                         if (ret == 0 && (extIdx + 1) >= certSz)
    9125                             ret = BUFFER_E;
    9126 
    9127                         if (ret == 0 &&
    9128                                 GetASNTag(cert, &extIdx, &tag, certSz) == 0 &&
    9129                                 tag == (ASN_CONTEXT_SPECIFIC | 0)) {
    9130                             if (GetLength(cert, &extIdx, &extLen, certSz) <= 0)
     9469
     9470                    if (ret == 0) {
     9471                        switch (oid) {
     9472                        case AUTH_KEY_OID:
     9473                            if (GetSequence(cert, &extIdx, &extLen, certSz) < 0)
    91319474                                ret = ASN_PARSE_E;
    9132                             if (ret == 0) {
    9133                                 extAuthKeyIdSet = 1;
    9134                                 if (extLen == KEYID_SIZE)
    9135                                     XMEMCPY(hash, cert + extIdx, extLen);
    9136                                 else {
    9137                                     ret = CalcHashId(cert + extIdx, extLen,
    9138                                                                           hash);
     9475
     9476                            if (ret == 0 && (extIdx + 1) >= certSz)
     9477                                ret = BUFFER_E;
     9478
     9479                            if (ret == 0 &&
     9480                                    GetASNTag(cert, &extIdx, &tag, certSz) == 0 &&
     9481                                    tag == (ASN_CONTEXT_SPECIFIC | 0)) {
     9482                                if (GetLength(cert, &extIdx, &extLen, certSz) <= 0)
     9483                                    ret = ASN_PARSE_E;
     9484                                if (ret == 0) {
     9485                                    extAuthKeyIdSet = 1;
     9486                                    if (extLen == KEYID_SIZE)
     9487                                        XMEMCPY(hash, cert + extIdx, extLen);
     9488                                    else {
     9489                                        ret = CalcHashId(cert + extIdx, extLen,
     9490                                                                              hash);
     9491                                    }
    91399492                                }
    91409493                            }
     9494                            break;
     9495
     9496                        default:
     9497                            break;
    91419498                        }
    9142                         break;
    9143 
    9144                     default:
    9145                         break;
    91469499                    }
     9500                    idx += len;
    91479501                }
    9148                 idx += len;
    9149             }
    9150         }
     9502            }
     9503        }
     9504    }
     9505    else if (ret == 0) {
     9506        idx += len;
    91519507    }
    91529508
     
    91759531        if (GetAlgoId(cert, &idx, &oid, oidSigType, certSz) < 0)
    91769532            ret = ASN_PARSE_E;
     9533        /* In CSR signature data is not present in body */
     9534        if (req)
     9535            signatureOID = oid;
    91779536    }
    91789537    if (ret == 0) {
     
    92199578{
    92209579    return CheckCertSignature_ex(cert, certSz, heap, NULL,
    9221             pubKey, pubKeySz, pubKeyOID);
    9222 }
     9580            pubKey, pubKeySz, pubKeyOID, 0);
     9581}
     9582#ifdef WOLFSSL_CERT_REQ
     9583int CheckCSRSignaturePubKey(const byte* cert, word32 certSz, void* heap,
     9584        const byte* pubKey, word32 pubKeySz, int pubKeyOID)
     9585{
     9586    return CheckCertSignature_ex(cert, certSz, heap, NULL,
     9587            pubKey, pubKeySz, pubKeyOID, 1);
     9588}
     9589#endif /* WOLFSSL_CERT_REQ */
    92239590#endif /* OPENSSL_EXTRA */
    92249591#ifdef WOLFSSL_SMALL_CERT_VERIFY
     
    92279594int CheckCertSignature(const byte* cert, word32 certSz, void* heap, void* cm)
    92289595{
    9229     return CheckCertSignature_ex(cert, certSz, heap, cm, NULL, 0, 0);
     9596    return CheckCertSignature_ex(cert, certSz, heap, cm, NULL, 0, 0, 0);
    92309597}
    92319598#endif /* WOLFSSL_SMALL_CERT_VERIFY */
     
    92379604    int    checkPathLen = 0;
    92389605    int    decrementMaxPathLen = 0;
    9239     word32 confirmOID;
     9606    word32 confirmOID = 0;
    92409607#if defined(WOLFSSL_RENESAS_TSIP)
    92419608    int    idx = 0;
    92429609#endif
    92439610    byte*  tsip_encRsaKeyIdx;
     9611#ifdef WOLFSSL_CERT_REQ
     9612    int    len = 0;
     9613#endif
    92449614
    92459615    if (cert == NULL) {
    92469616        return BAD_FUNC_ARG;
    92479617    }
     9618
     9619#ifdef WOLFSSL_CERT_REQ
     9620    if (type == CERTREQ_TYPE)
     9621        cert->isCSR = 1;
     9622#endif
    92489623
    92499624    if (cert->sigCtx.state == SIG_STATE_BEGIN) {
     
    92599634        WOLFSSL_MSG("Parsed Past Key");
    92609635
     9636
     9637#ifdef WOLFSSL_CERT_REQ
     9638        /* Read attributes */
     9639        if (cert->isCSR) {
     9640            if (GetASNHeader_ex(cert->source,
     9641                    ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &cert->srcIdx,
     9642                    &len, cert->maxIdx, 1) < 0) {
     9643                WOLFSSL_MSG("GetASNHeader_ex error");
     9644                return ASN_PARSE_E;
     9645            }
     9646
     9647            if (len) {
     9648                word32 attrMaxIdx = cert->srcIdx + len;
     9649                word32 oid;
     9650                byte   tag;
     9651
     9652                if (attrMaxIdx > cert->maxIdx) {
     9653                    WOLFSSL_MSG("Attribute length greater than CSR length");
     9654                    return ASN_PARSE_E;
     9655                }
     9656
     9657                while (cert->srcIdx < attrMaxIdx) {
     9658                    /* Attributes have the structure:
     9659                     * SEQ -> OID -> SET -> ATTRIBUTE */
     9660                    if (GetSequence(cert->source, &cert->srcIdx, &len,
     9661                            attrMaxIdx) < 0) {
     9662                        WOLFSSL_MSG("attr GetSequence error");
     9663                        return ASN_PARSE_E;
     9664                    }
     9665                    if (GetObjectId(cert->source, &cert->srcIdx, &oid,
     9666                            oidCsrAttrType, attrMaxIdx) < 0) {
     9667                        WOLFSSL_MSG("attr GetObjectId error");
     9668                        return ASN_PARSE_E;
     9669                    }
     9670                    if (GetSet(cert->source, &cert->srcIdx, &len,
     9671                            attrMaxIdx) < 0) {
     9672                        WOLFSSL_MSG("attr GetSet error");
     9673                        return ASN_PARSE_E;
     9674                    }
     9675                    switch (oid) {
     9676                    case CHALLENGE_PASSWORD_OID:
     9677                        if (GetHeader(cert->source, &tag,
     9678                                &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
     9679                            WOLFSSL_MSG("attr GetHeader error");
     9680                            return ASN_PARSE_E;
     9681                        }
     9682                        if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
     9683                                tag != ASN_IA5_STRING) {
     9684                            WOLFSSL_MSG("Unsupported attribute value format");
     9685                            return ASN_PARSE_E;
     9686                        }
     9687                        cert->cPwd = (char*)cert->source + cert->srcIdx;
     9688                        cert->cPwdLen = len;
     9689                        cert->srcIdx += len;
     9690                        break;
     9691                    case SERIAL_NUMBER_OID:
     9692                        if (GetHeader(cert->source, &tag,
     9693                                &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
     9694                            WOLFSSL_MSG("attr GetHeader error");
     9695                            return ASN_PARSE_E;
     9696                        }
     9697                        if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
     9698                                tag != ASN_IA5_STRING) {
     9699                            WOLFSSL_MSG("Unsupported attribute value format");
     9700                            return ASN_PARSE_E;
     9701                        }
     9702                        cert->sNum = (char*)cert->source + cert->srcIdx;
     9703                        cert->sNumLen = len;
     9704                        cert->srcIdx += len;
     9705                        if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
     9706                            XMEMCPY(cert->serial, cert->sNum, cert->sNumLen);
     9707                            cert->serialSz = cert->sNumLen;
     9708                        }
     9709                        break;
     9710                    case EXTENSION_REQUEST_OID:
     9711                        /* save extensions */
     9712                        cert->extensions    = &cert->source[cert->srcIdx];
     9713                        cert->extensionsSz  = len;
     9714                        cert->extensionsIdx = cert->srcIdx;   /* for potential later use */
     9715
     9716                        if ((ret = DecodeCertExtensions(cert)) < 0) {
     9717                            if (ret == ASN_CRIT_EXT_E)
     9718                                cert->criticalExt = ret;
     9719                            else
     9720                                return ret;
     9721                        }
     9722                        cert->srcIdx += len;
     9723                        break;
     9724                    default:
     9725                        WOLFSSL_MSG("Unsupported attribute type");
     9726                        return ASN_PARSE_E;
     9727                    }
     9728                }
     9729            }
     9730        }
     9731#endif
     9732
    92619733        if (cert->srcIdx < cert->sigIndex) {
    92629734        #ifndef ALLOW_V1_EXTENSIONS
     
    92799751            }
    92809752
     9753        #ifdef HAVE_OCSP
     9754            /* trust for the lifetime of the responder's cert*/
     9755            if (cert->ocspNoCheckSet && verify == VERIFY_OCSP)
     9756                verify = NO_VERIFY;
     9757        #endif
    92819758            /* advance past extensions */
    92829759            cert->srcIdx = cert->sigIndex;
    92839760        }
    92849761
    9285         if ((ret = GetAlgoId(cert->source, &cert->srcIdx, &confirmOID,
    9286                              oidSigType, cert->maxIdx)) < 0)
     9762        if ((ret = GetAlgoId(cert->source, &cert->srcIdx,
     9763#ifdef WOLFSSL_CERT_REQ
     9764                !cert->isCSR ? &confirmOID : &cert->signatureOID,
     9765#else
     9766                &confirmOID,
     9767#endif
     9768                oidSigType, cert->maxIdx)) < 0)
    92879769            return ret;
    92889770
     
    92909772            return ret;
    92919773
    9292         if (confirmOID != cert->signatureOID)
     9774        if (confirmOID != cert->signatureOID
     9775#ifdef WOLFSSL_CERT_REQ
     9776                && !cert->isCSR
     9777#endif
     9778                )
    92939779            return ASN_SIG_OID_E;
    92949780
     
    93419827            cert->ca = GetCA(cm, cert->issuerHash);
    93429828    #endif /* !NO_SKID */
     9829
     9830            if (cert->ca) {
     9831                WOLFSSL_MSG("CA found");
     9832            }
    93439833        }
    93449834
     
    94259915                }
    94269916            }
    9427             #ifdef HAVE_OCSP
    9428             if (verify != NO_VERIFY && type != CA_TYPE &&
    9429                                                     type != TRUSTED_PEER_TYPE) {
    9430                 if (cert->ca) {
    9431                     /* Need the CA's public key hash for OCSP */
    9432                     XMEMCPY(cert->issuerKeyHash, cert->ca->subjectKeyHash,
    9433                                                                     KEYID_SIZE);
    9434                 }
    9435 
    9436             }
    9437             #endif /* HAVE_OCSP */
    9438         }
     9917        }
     9918
     9919        #ifdef HAVE_OCSP
     9920        if (verify != NO_VERIFY && type != CA_TYPE &&
     9921                                                type != TRUSTED_PEER_TYPE) {
     9922            if (cert->ca) {
     9923                /* Need the CA's public key hash for OCSP */
     9924                XMEMCPY(cert->issuerKeyHash, cert->ca->subjectKeyHash,
     9925                                                                KEYID_SIZE);
     9926            }
     9927        }
     9928        #endif /* HAVE_OCSP */
    94399929    }
    94409930#if defined(WOLFSSL_RENESAS_TSIP)
     
    979910289#if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
    980010290
    9801 /* Max X509 header length indicates the max length + 2 ('\n', '\0') */
    9802 #define MAX_X509_HEADER_SZ  (37 + 2)
    9803 
     10291/* Note: If items added make sure MAX_X509_HEADER_SZ is
     10292    updated to reflect maximum length and pem_struct_min_sz
     10293    to reflect minimum size */
    980410294wcchar BEGIN_CERT           = "-----BEGIN CERTIFICATE-----";
    980510295wcchar END_CERT             = "-----END CERTIFICATE-----";
     
    984410334    wcchar END_EDDSA_PRIV   = "-----END EDDSA PRIVATE KEY-----";
    984510335#endif
    9846 #ifdef HAVE_CRL
    9847     const char *const BEGIN_CRL = "-----BEGIN X509 CRL-----";
    9848     wcchar END_CRL   = "-----END X509 CRL-----";
    9849 #endif
    9850 
     10336
     10337const int pem_struct_min_sz = XSTR_SIZEOF("-----BEGIN X509 CRL-----"
     10338                                             "-----END X509 CRL-----");
    985110339
    985210340static WC_INLINE char* SkipEndOfLineChars(char* line, const char* endOfLine)
     
    994010428            ret = 0;
    994110429            break;
    9942     #if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
     10430    #ifndef NO_DH
    994310431        case DH_PRIVATEKEY_TYPE:
    994410432    #endif
     
    1037410862        } else
    1037510863#ifdef HAVE_CRL
    10376         if ((type == CRL_TYPE) && (header != BEGIN_CRL)) {
    10377             header =  BEGIN_CRL;                footer = END_CRL;
     10864        if ((type == CRL_TYPE) && (header != BEGIN_X509_CRL)) {
     10865            header =  BEGIN_X509_CRL;           footer = END_X509_CRL;
    1037810866        } else
    1037910867#endif
     
    1038510873    if (!headerEnd) {
    1038610874#ifdef OPENSSL_EXTRA
    10387         char* beginEnd;
    10388         int endLen;
    10389         /* see if there is a -----BEGIN * PRIVATE KEY----- header */
    10390         headerEnd = XSTRNSTR((char*)buff, PRIV_KEY_SUFFIX, sz);
    10391         if (headerEnd) {
    10392             beginEnd = headerEnd + XSTR_SIZEOF(PRIV_KEY_SUFFIX);
    10393             /* back up to BEGIN_PRIV_KEY_PREFIX */
    10394             headerEnd -= XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX);
    10395             while (headerEnd > (char*)buff &&
    10396                     XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
    10397                             XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0) {
    10398                 headerEnd--;
    10399             }
    10400             if (headerEnd <= (char*)buff ||
    10401                     XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
    10402                     XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 ||
    10403                     beginEnd - headerEnd > PEM_LINE_LEN) {
    10404                 WOLFSSL_MSG("Couldn't find PEM header");
    10405                 return ASN_NO_PEM_HEADER;
    10406             }
    10407             /* headerEnd now points to beginning of header */
    10408             XMEMCPY(beginBuf, headerEnd, beginEnd - headerEnd);
    10409             beginBuf[beginEnd - headerEnd] = '\0';
    10410             /* look for matching footer */
    10411             footer = XSTRNSTR(beginEnd,
    10412                             beginBuf + XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX),
    10413                             (unsigned int)((char*)buff + sz - beginEnd));
    10414             if (!footer) {
    10415                 WOLFSSL_MSG("Couldn't find PEM footer");
    10416                 return ASN_NO_PEM_HEADER;
    10417             }
    10418             footer -= XSTR_SIZEOF(END_PRIV_KEY_PREFIX);
    10419             endLen = (unsigned int)(beginEnd - headerEnd -
    10420                         (XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX) -
    10421                                 XSTR_SIZEOF(END_PRIV_KEY_PREFIX)));
    10422             XMEMCPY(endBuf, footer, endLen);
    10423             endBuf[endLen] = '\0';
    10424 
    10425             header = beginBuf;
    10426             footer = endBuf;
    10427             headerEnd = beginEnd;
    10428         } else {
     10875        if (type == PRIVATEKEY_TYPE) {
     10876            char* beginEnd;
     10877            int endLen;
     10878            /* see if there is a -----BEGIN * PRIVATE KEY----- header */
     10879            headerEnd = XSTRNSTR((char*)buff, PRIV_KEY_SUFFIX, sz);
     10880            if (headerEnd) {
     10881                beginEnd = headerEnd + XSTR_SIZEOF(PRIV_KEY_SUFFIX);
     10882                if (beginEnd >= (char*)buff + sz) {
     10883                    return BUFFER_E;
     10884                }
     10885
     10886                /* back up to BEGIN_PRIV_KEY_PREFIX */
     10887                while (headerEnd > (char*)buff &&
     10888                        XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
     10889                                XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 &&
     10890                        *headerEnd != '\n') {
     10891                    headerEnd--;
     10892                }
     10893                if (headerEnd <= (char*)buff ||
     10894                        XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
     10895                        XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 ||
     10896                        beginEnd - headerEnd > PEM_LINE_LEN) {
     10897                    WOLFSSL_MSG("Couldn't find PEM header");
     10898                    return ASN_NO_PEM_HEADER;
     10899                }
     10900
     10901                /* headerEnd now points to beginning of header */
     10902                XMEMCPY(beginBuf, headerEnd, beginEnd - headerEnd);
     10903                beginBuf[beginEnd - headerEnd] = '\0';
     10904                /* look for matching footer */
     10905                footer = XSTRNSTR(beginEnd,
     10906                                beginBuf + XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX),
     10907                                (unsigned int)((char*)buff + sz - beginEnd));
     10908                if (!footer) {
     10909                    WOLFSSL_MSG("Couldn't find PEM footer");
     10910                    return ASN_NO_PEM_HEADER;
     10911                }
     10912
     10913                footer -= XSTR_SIZEOF(END_PRIV_KEY_PREFIX);
     10914                if (footer > (char*)buff + sz - XSTR_SIZEOF(END_PRIV_KEY_PREFIX)
     10915                        || XSTRNCMP(footer, END_PRIV_KEY_PREFIX,
     10916                            XSTR_SIZEOF(END_PRIV_KEY_PREFIX)) != 0) {
     10917                    WOLFSSL_MSG("Unexpected footer for PEM");
     10918                    return BUFFER_E;
     10919                }
     10920
     10921                endLen = (unsigned int)(beginEnd - headerEnd -
     10922                            (XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX) -
     10923                                    XSTR_SIZEOF(END_PRIV_KEY_PREFIX)));
     10924                XMEMCPY(endBuf, footer, endLen);
     10925                endBuf[endLen] = '\0';
     10926
     10927                header = beginBuf;
     10928                footer = endBuf;
     10929                headerEnd = beginEnd;
     10930            }
     10931        }
     10932
     10933        if (!headerEnd) {
    1042910934            WOLFSSL_MSG("Couldn't find PEM header");
    1043010935            return ASN_NO_PEM_HEADER;
     
    1058311088                #ifndef NO_DES3
    1058411089                    if (info->cipherType == WC_CIPHER_DES3) {
    10585                         padVal = der->buffer[der->length-1];
    10586                         if (padVal <= DES_BLOCK_SIZE) {
    10587                             der->length -= padVal;
     11090                        /* Assuming there is padding:
     11091                         *      (der->length > 0 && der->length > DES_BLOCK_SIZE &&
     11092                         *       (der->length % DES_BLOCK_SIZE) != 0)
     11093                         * and assuming the last value signifies the number of
     11094                         * padded bytes IE if last value is 0x08 then there are
     11095                         * 8 bytes of padding:
     11096                         *      padVal = der->buffer[der->length-1];
     11097                         * then strip this padding before proceeding:
     11098                         * der->length -= padVal;
     11099                         */
     11100                        if (der->length > 0 &&
     11101                            der->length > DES_BLOCK_SIZE &&
     11102                            (der->length % DES_BLOCK_SIZE) != 0) {
     11103                            padVal = der->buffer[der->length-1];
     11104                            if (padVal < DES_BLOCK_SIZE) {
     11105                                der->length -= padVal;
     11106                            }
    1058811107                        }
    1058911108                    }
     
    1082211341
    1082311342        if (ret == 0) {
    10824             if ( (ret = (int)XFREAD(fileBuf, 1, sz, file)) != sz) {
     11343            if ((size_t)XFREAD(fileBuf, 1, sz, file) != (size_t)sz) {
    1082511344                ret = BUFFER_E;
    1082611345            }
     
    1090211421        }
    1090311422        if (ret == 0) {
    10904             if ( (ret = (int)XFREAD(fileBuf, 1, sz, file)) != sz) {
     11423            if ((size_t)XFREAD(fileBuf, 1, sz, file) != (size_t)sz) {
    1090511424                ret = BUFFER_E;
    1090611425            }
     
    1147711996#endif
    1147811997
    11479 #ifdef HAVE_SELFTEST
     11998#if defined(HAVE_SELFTEST) || defined(HAVE_FIPS)
    1148011999    /* older version of ecc.c can not handle dp being NULL */
    1148112000    if (key != NULL && key->dp == NULL) {
     
    1158412103    }
    1158512104
    11586 #ifdef HAVE_SELFTEST
     12105#if defined(HAVE_SELFTEST) || defined(HAVE_FIPS)
    1158712106    /* older version of ecc.c can not handle dp being NULL */
    1158812107    if (key != NULL && key->dp == NULL) {
     
    1164812167    if (idx != 0) {
    1164912168#ifdef WOLFSSL_SMALL_STACK
    11650         XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     12169        XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    1165112170#endif
    1165212171        return idx;
     
    1165812177        algo = (byte*)XMALLOC(MAX_ALGO_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    1165912178        if (algo == NULL) {
    11660             XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     12179            XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    1166112180            return MEMORY_E;
    1166212181        }
     
    1175212271    if (idx != 0) {
    1175312272#ifdef WOLFSSL_SMALL_STACK
    11754         XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     12273        XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    1175512274#endif
    1175612275        return idx;
     
    1176212281        algo = (byte*)XMALLOC(MAX_ALGO_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    1176312282        if (algo == NULL) {
    11764             XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     12283            XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    1176512284            return MEMORY_E;
    1176612285        }
     
    1188712406
    1188812407#endif
    11889 
    11890 
    11891 /* Set Date validity from now until now + daysValid
    11892  * return size in bytes written to output, 0 on error */
    11893 static int SetValidity(byte* output, int daysValid)
    11894 {
    11895     byte before[MAX_DATE_SIZE];
    11896     byte  after[MAX_DATE_SIZE];
    11897 
    11898     int beforeSz;
    11899     int afterSz;
    11900     int seqSz;
    11901 
    11902     time_t now;
    11903     time_t then;
    11904     struct tm* tmpTime;
    11905     struct tm* expandedTime;
    11906     struct tm localTime;
    11907 
    11908 #if defined(NEED_TMP_TIME)
    11909     /* for use with gmtime_r */
    11910     struct tm tmpTimeStorage;
    11911     tmpTime = &tmpTimeStorage;
    11912 #else
    11913     tmpTime = NULL;
    11914 #endif
    11915     (void)tmpTime;
    11916 
    11917     now = XTIME(0);
    11918 
    11919     /* before now */
    11920     before[0] = ASN_GENERALIZED_TIME;
    11921     beforeSz = SetLength(ASN_GEN_TIME_SZ, before + 1) + 1;  /* gen tag */
    11922 
    11923     /* subtract 1 day of seconds for more compliance */
    11924     then = now - 86400;
    11925     expandedTime = XGMTIME(&then, tmpTime);
    11926     if (expandedTime == NULL) {
    11927         WOLFSSL_MSG("XGMTIME failed");
    11928         return 0;   /* error */
    11929     }
    11930     localTime = *expandedTime;
    11931 
    11932     /* adjust */
    11933     localTime.tm_year += 1900;
    11934     localTime.tm_mon +=    1;
    11935 
    11936     SetTime(&localTime, before + beforeSz);
    11937     beforeSz += ASN_GEN_TIME_SZ;
    11938 
    11939     after[0] = ASN_GENERALIZED_TIME;
    11940     afterSz  = SetLength(ASN_GEN_TIME_SZ, after + 1) + 1;  /* gen tag */
    11941 
    11942     /* add daysValid of seconds */
    11943     then = now + (daysValid * (time_t)86400);
    11944     expandedTime = XGMTIME(&then, tmpTime);
    11945     if (expandedTime == NULL) {
    11946         WOLFSSL_MSG("XGMTIME failed");
    11947         return 0;   /* error */
    11948     }
    11949     localTime = *expandedTime;
    11950 
    11951     /* adjust */
    11952     localTime.tm_year += 1900;
    11953     localTime.tm_mon  +=    1;
    11954 
    11955     SetTime(&localTime, after + afterSz);
    11956     afterSz += ASN_GEN_TIME_SZ;
    11957 
    11958     /* headers and output */
    11959     seqSz = SetSequence(beforeSz + afterSz, output);
    11960     XMEMCPY(output + seqSz, before, beforeSz);
    11961     XMEMCPY(output + seqSz + beforeSz, after, afterSz);
    11962 
    11963     return seqSz + beforeSz + afterSz;
    11964 }
    11965 
    1196612408
    1196712409/* ASN Encoded Name field */
     
    1197612418
    1197712419/* Get Which Name from index */
    11978 static const char* GetOneName(CertName* name, int idx)
     12420const char* GetOneCertName(CertName* name, int idx)
    1197912421{
    1198012422    switch (idx) {
     
    1206512507
    1206612508/* Get ASN Name from index */
    12067 static byte GetNameId(int idx)
     12509byte GetCertNameId(int idx)
    1206812510{
    1206912511    switch (idx) {
     
    1210612548    }
    1210712549}
     12550
    1210812551
    1210912552/*
     
    1252812971    curName = names;
    1252912972    do {
    12530         output[idx++] = ASN_CONTEXT_SPECIFIC | curName->type;
     12973        output[idx] = ASN_CONTEXT_SPECIFIC | curName->type;
     12974        if (curName->type == ASN_DIR_TYPE) {
     12975            output[idx] |= ASN_CONSTRUCTED;
     12976        }
     12977        idx++;
    1253112978        idx += SetLength(curName->len, output + idx);
    1253212979        XMEMCPY(output + idx, curName->name, curName->len);
     
    1257413021        /* Restrict country code size */
    1257513022        if (ASN_COUNTRY_NAME == type && strLen != CTC_COUNTRY_SIZE) {
     13023            WOLFSSL_MSG("Country code size error");
    1257613024            return ASN_COUNTRY_SIZE_E;
    1257713025        }
     
    1267113119}
    1267213120
     13121
     13122
     13123
     13124/* Guarded by either
     13125 * A) WOLFSSL_WPAS_SMALL is on or
     13126 * B) (OPENSSL_EXTRA or OPENSSL_EXTRA_X509_SMALL) + WOLFSSL_CERT_GEN +
     13127 *    (WOLFSSL_CERT_REQ or WOLFSSL_CERT_EXT or OPENSSL_EXTRA) has been
     13128 *    defined
     13129 */
     13130#if defined(WOLFSSL_WPAS_SMALL) || \
     13131    (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
     13132    defined(WOLFSSL_CERT_GEN) && \
     13133    (defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_EXT) || \
     13134     defined(OPENSSL_EXTRA))
     13135/* Converts from NID_* value to wolfSSL value if needed */
     13136static int ConvertNIDToWolfSSL(int nid)
     13137{
     13138    switch (nid) {
     13139        case NID_commonName : return ASN_COMMON_NAME;
     13140        case NID_surname :    return ASN_SUR_NAME;
     13141        case NID_countryName: return ASN_COUNTRY_NAME;
     13142        case NID_localityName: return ASN_LOCALITY_NAME;
     13143        case NID_stateOrProvinceName: return ASN_STATE_NAME;
     13144        case NID_organizationName: return ASN_ORG_NAME;
     13145        case NID_organizationalUnitName: return ASN_ORGUNIT_NAME;
     13146        case NID_emailAddress: return ASN_EMAIL_NAME;
     13147        case NID_serialNumber: return ASN_SERIAL_NUMBER;
     13148        case NID_businessCategory: return ASN_BUS_CAT;
     13149        case NID_domainComponent: return ASN_DOMAIN_COMPONENT;
     13150        default:
     13151            WOLFSSL_MSG("Attribute NID not found");
     13152            return -1;
     13153    }
     13154}
     13155
     13156
     13157/* Converts the x509 name structure into DER format.
     13158 *
     13159 * out  pointer to either a pre setup buffer or a pointer to null for
     13160 *      creating a dynamic buffer. In the case that a pre-existing buffer is
     13161 *      used out will be incremented the size of the DER buffer on success.
     13162 *
     13163 * returns the size of the buffer on success, or negative value with failure
     13164 */
     13165int wolfSSL_i2d_X509_NAME(WOLFSSL_X509_NAME* name, unsigned char** out)
     13166{
     13167    int  totalBytes = 0, i, idx;
     13168    byte temp[MAX_SEQ_SZ];
     13169    byte *output, *local = NULL;
     13170#ifdef WOLFSSL_SMALL_STACK
     13171    EncodedName* names = NULL;
     13172#else
     13173    EncodedName  names[MAX_NAME_ENTRIES];
     13174#endif
     13175
     13176    if (out == NULL || name == NULL)
     13177        return BAD_FUNC_ARG;
     13178
     13179#ifdef WOLFSSL_SMALL_STACK
     13180    names = (EncodedName*)XMALLOC(sizeof(EncodedName) * MAX_NAME_ENTRIES, NULL,
     13181                                                       DYNAMIC_TYPE_TMP_BUFFER);
     13182    if (names == NULL)
     13183        return MEMORY_E;
     13184#endif
     13185
     13186    XMEMSET(names, 0, sizeof(EncodedName) * MAX_NAME_ENTRIES);
     13187
     13188    for (i = 0; i < MAX_NAME_ENTRIES; i++) {
     13189        WOLFSSL_X509_NAME_ENTRY* entry;
     13190        int ret;
     13191
     13192        entry = wolfSSL_X509_NAME_get_entry(name, i);
     13193        if (entry != NULL && entry->set == 1) {
     13194            const char* nameStr;
     13195            int type;
     13196            WOLFSSL_ASN1_STRING* data;
     13197
     13198            data = wolfSSL_X509_NAME_ENTRY_get_data(entry);
     13199            if (data == NULL) {
     13200            #ifdef WOLFSSL_SMALL_STACK
     13201                XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     13202            #endif
     13203                WOLFSSL_MSG("Error getting entry data");
     13204                return WOLFSSL_FATAL_ERROR;
     13205            }
     13206
     13207            nameStr = (const char*)wolfSSL_ASN1_STRING_data(data);
     13208            type    = wolfSSL_ASN1_STRING_type(data);
     13209
     13210            switch (type) {
     13211                case MBSTRING_UTF8:
     13212                    type = CTC_UTF8;
     13213                    break;
     13214                case V_ASN1_PRINTABLESTRING:
     13215                    type = CTC_PRINTABLE;
     13216                    break;
     13217                default:
     13218                    WOLFSSL_MSG("Unknown encoding type conversion UTF8 by default");
     13219                    type = CTC_UTF8;
     13220            }
     13221            ret = wc_EncodeName(&names[i], nameStr, type,
     13222                ConvertNIDToWolfSSL(entry->nid));
     13223            if (ret < 0) {
     13224            #ifdef WOLFSSL_SMALL_STACK
     13225                XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     13226            #endif
     13227                WOLFSSL_MSG("EncodeName failed");
     13228                return WOLFSSL_FATAL_ERROR;
     13229            }
     13230            totalBytes += ret;
     13231        }
     13232    }
     13233
     13234    /* header */
     13235    idx = SetSequence(totalBytes, temp);
     13236    if (totalBytes + idx > ASN_NAME_MAX) {
     13237#ifdef WOLFSSL_SMALL_STACK
     13238        XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     13239#endif
     13240        WOLFSSL_MSG("Total Bytes is greater than ASN_NAME_MAX");
     13241        return BUFFER_E;
     13242    }
     13243
     13244    /* check if using buffer passed in */
     13245    if (*out == NULL) {
     13246        *out = local = (unsigned char*)XMALLOC(totalBytes + idx, NULL,
     13247                DYNAMIC_TYPE_OPENSSL);
     13248        if (*out == NULL) {
     13249            return MEMORY_E;
     13250        }
     13251    }
     13252    output = *out;
     13253
     13254    idx = SetSequence(totalBytes, output);
     13255    totalBytes += idx;
     13256    for (i = 0; i < MAX_NAME_ENTRIES; i++) {
     13257        if (names[i].used) {
     13258            XMEMCPY(output + idx, names[i].encoded, names[i].totalLen);
     13259            idx += names[i].totalLen;
     13260        }
     13261    }
     13262
     13263#ifdef WOLFSSL_SMALL_STACK
     13264    XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     13265#endif
     13266
     13267    /* used existing buffer passed in, so increment pointer */
     13268    if (local == NULL) {
     13269        *out += totalBytes;
     13270    }
     13271    return totalBytes;
     13272}
     13273#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
     13274
     13275
    1267313276/* encode CertName into output, return total bytes written */
    1267413277int SetName(byte* output, word32 outputSz, CertName* name)
     
    1270013303    for (i = 0; i < NAME_ENTRIES; i++) {
    1270113304        int ret;
    12702         const char* nameStr = GetOneName(name, i);
     13305        const char* nameStr = GetOneCertName(name, i);
    1270313306
    1270413307        ret = wc_EncodeName(&names[i], nameStr, GetNameType(name, i),
    12705                           GetNameId(i));
     13308                          GetCertNameId(i));
    1270613309        if (ret < 0) {
    1270713310        #ifdef WOLFSSL_SMALL_STACK
    12708                 XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     13311            XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    1270913312        #endif
    12710                 return BUFFER_E;
     13313            WOLFSSL_MSG("EncodeName failed");
     13314            return BUFFER_E;
    1271113315        }
    1271213316        totalBytes += ret;
     
    1272213326                XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    1272313327            #endif
     13328                WOLFSSL_MSG("EncodeName on multiple attributes failed\n");
    1272413329                return BUFFER_E;
    1272513330            }
     
    1273913344        XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    1274013345#endif
     13346        WOLFSSL_MSG("Total Bytes is greater than ASN_NAME_MAX");
    1274113347        return BUFFER_E;
    1274213348    }
     
    1274413350    for (i = 0; i < NAME_ENTRIES; i++) {
    1274513351    #ifdef WOLFSSL_MULTI_ATTRIB
    12746         type = GetNameId(i);
     13352        type = GetCertNameId(i);
    1274713353
    1274813354        /* list all DC values before OUs */
     
    1275513361                        XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    1275613362                    #endif
     13363                        WOLFSSL_MSG("Not enough space left for DC value");
    1275713364                        return BUFFER_E;
    1275813365                    }
     
    1280313410}
    1280413411
     13412/* Set Date validity from now until now + daysValid
     13413 * return size in bytes written to output, 0 on error */
     13414static int SetValidity(byte* output, int daysValid)
     13415{
     13416    byte before[MAX_DATE_SIZE];
     13417    byte  after[MAX_DATE_SIZE];
     13418
     13419    int beforeSz;
     13420    int afterSz;
     13421    int seqSz;
     13422
     13423    time_t now;
     13424    time_t then;
     13425    struct tm* tmpTime;
     13426    struct tm* expandedTime;
     13427    struct tm localTime;
     13428
     13429#if defined(NEED_TMP_TIME)
     13430    /* for use with gmtime_r */
     13431    struct tm tmpTimeStorage;
     13432    tmpTime = &tmpTimeStorage;
     13433#else
     13434    tmpTime = NULL;
     13435#endif
     13436    (void)tmpTime;
     13437
     13438    now = XTIME(0);
     13439
     13440    /* before now */
     13441    before[0] = ASN_GENERALIZED_TIME;
     13442    beforeSz = SetLength(ASN_GEN_TIME_SZ, before + 1) + 1;  /* gen tag */
     13443
     13444    /* subtract 1 day of seconds for more compliance */
     13445    then = now - 86400;
     13446    expandedTime = XGMTIME(&then, tmpTime);
     13447    if (expandedTime == NULL) {
     13448        WOLFSSL_MSG("XGMTIME failed");
     13449        return 0;   /* error */
     13450    }
     13451    localTime = *expandedTime;
     13452
     13453    /* adjust */
     13454    localTime.tm_year += 1900;
     13455    localTime.tm_mon +=    1;
     13456
     13457    SetTime(&localTime, before + beforeSz);
     13458    beforeSz += ASN_GEN_TIME_SZ;
     13459
     13460    after[0] = ASN_GENERALIZED_TIME;
     13461    afterSz  = SetLength(ASN_GEN_TIME_SZ, after + 1) + 1;  /* gen tag */
     13462
     13463    /* add daysValid of seconds */
     13464    then = now + (daysValid * (time_t)86400);
     13465    expandedTime = XGMTIME(&then, tmpTime);
     13466    if (expandedTime == NULL) {
     13467        WOLFSSL_MSG("XGMTIME failed");
     13468        return 0;   /* error */
     13469    }
     13470    localTime = *expandedTime;
     13471
     13472    /* adjust */
     13473    localTime.tm_year += 1900;
     13474    localTime.tm_mon  +=    1;
     13475
     13476    SetTime(&localTime, after + afterSz);
     13477    afterSz += ASN_GEN_TIME_SZ;
     13478
     13479    /* headers and output */
     13480    seqSz = SetSequence(beforeSz + afterSz, output);
     13481    XMEMCPY(output + seqSz, before, beforeSz);
     13482    XMEMCPY(output + seqSz + beforeSz, after, afterSz);
     13483
     13484    return seqSz + beforeSz + afterSz;
     13485}
     13486
    1280513487/* encode info from cert into DER encoded format */
    1280613488static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey,
    12807                       WC_RNG* rng, const byte* ntruKey, word16 ntruSz,
     13489                      WC_RNG* rng, const byte* ntruKey, word16 ntruSz, DsaKey* dsaKey,
    1280813490                      ed25519_key* ed25519Key, ed448_key* ed448Key)
    1280913491{
     
    1281513497    /* make sure at least one key type is provided */
    1281613498    if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
    12817                                           ed448Key == NULL && ntruKey == NULL) {
     13499            dsaKey == NULL && ed448Key == NULL && ntruKey == NULL) {
    1281813500        return PUBLIC_KEY_E;
    1281913501    }
     
    1286313545#endif
    1286413546
     13547#if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
     13548    if (cert->keyType == DSA_KEY) {
     13549        if (dsaKey == NULL)
     13550            return PUBLIC_KEY_E;
     13551        der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
     13552                                           sizeof(der->publicKey), 1);
     13553    }
     13554#endif
     13555
    1286513556#ifdef HAVE_ED25519
    1286613557    if (cert->keyType == ED25519_KEY) {
     
    1292613617
    1292713618    /* subject name */
    12928 #ifdef WOLFSSL_CERT_EXT
     13619#if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
    1292913620    if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
    1293013621        /* Use the raw subject */
     
    1295413645
    1295513646    /* issuer name */
    12956 #ifdef WOLFSSL_CERT_EXT
     13647#if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
    1295713648    if (XSTRLEN((const char*)cert->issRaw) > 0) {
    1295813649        /* Use the raw issuer */
     
    1296113652        der->issuerSz = min(sizeof(der->issuer),
    1296213653                (word32)XSTRLEN((const char*)cert->issRaw));
     13654
    1296313655        /* header */
    1296413656        idx = SetSequence(der->issuerSz, der->issuer);
     
    1333714029/* add signature to end of buffer, size of buffer assumed checked, return
    1333814030   new length */
    13339 static int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz,
     14031int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz,
    1334014032                        int sigAlgoType)
    1334114033{
     
    1336614058static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz,
    1336714059                       RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng,
    13368                        const byte* ntruKey, word16 ntruSz,
     14060                       DsaKey* dsaKey, const byte* ntruKey, word16 ntruSz,
    1336914061                       ed25519_key* ed25519Key, ed448_key* ed448Key)
    1337014062{
     
    1337614068#endif
    1337714069
    13378     if (derBuffer == NULL) {
     14070    if (derBuffer == NULL)
    1337914071        return BAD_FUNC_ARG;
    13380     }
    13381 
    13382     cert->keyType = eccKey ? ECC_KEY : (rsaKey ? RSA_KEY :
    13383             (ed25519Key ? ED25519_KEY : (ed448Key ? ED448_KEY : NTRU_KEY)));
     14072
     14073    if (eccKey)
     14074        cert->keyType = ECC_KEY;
     14075    else if (rsaKey)
     14076        cert->keyType = RSA_KEY;
     14077    else if (dsaKey)
     14078        cert->keyType = DSA_KEY;
     14079    else if (ed25519Key)
     14080        cert->keyType = ED25519_KEY;
     14081    else if (ed448Key)
     14082        cert->keyType = ED448_KEY;
     14083    else if (ntruKey)
     14084        cert->keyType = NTRU_KEY;
     14085    else
     14086        return BAD_FUNC_ARG;
    1338414087
    1338514088#ifdef WOLFSSL_SMALL_STACK
     
    1338914092#endif
    1339014093
    13391     ret = EncodeCert(cert, der, rsaKey, eccKey, rng, ntruKey, ntruSz,
     14094    ret = EncodeCert(cert, der, rsaKey, eccKey, rng, ntruKey, ntruSz, dsaKey,
    1339214095                     ed25519Key, ed448Key);
    1339314096    if (ret == 0) {
     
    1341114114{
    1341214115    RsaKey*      rsaKey = NULL;
     14116    DsaKey*      dsaKey = NULL;
    1341314117    ecc_key*     eccKey = NULL;
    1341414118    ed25519_key* ed25519Key = NULL;
     
    1341714121    if (keyType == RSA_TYPE)
    1341814122        rsaKey = (RsaKey*)key;
     14123    else if (keyType == DSA_TYPE)
     14124        dsaKey = (DsaKey*)key;
    1341914125    else if (keyType == ECC_TYPE)
    1342014126        eccKey = (ecc_key*)key;
     
    1342414130        ed448Key = (ed448_key*)key;
    1342514131
    13426     return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, NULL, 0,
    13427                        ed25519Key, ed448Key);
     14132    return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, dsaKey,
     14133                       NULL, 0, ed25519Key, ed448Key);
    1342814134}
    1342914135/* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
     
    1343114137             ecc_key* eccKey, WC_RNG* rng)
    1343214138{
    13433     return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, NULL, 0,
     14139    return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, NULL, NULL, 0,
    1343414140                       NULL, NULL);
    1343514141}
     
    1344114147                  const byte* ntruKey, word16 keySz, WC_RNG* rng)
    1344214148{
    13443     return MakeAnyCert(cert, derBuffer, derSz, NULL, NULL, rng, ntruKey, keySz, NULL);
     14149    return MakeAnyCert(cert, derBuffer, derSz, NULL, NULL, rng, NULL,
     14150            ntruKey, keySz, NULL, NULL);
    1344414151}
    1344514152
     
    1345214159                        int extSz)
    1345314160{
    13454     const byte cpOid[] =
    13455         { ASN_OBJECT_ID, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01,
    13456                          0x09, 0x07 };
    1345714161    const byte erOid[] =
    1345814162        { ASN_OBJECT_ID, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01,
     
    1347414178    byte erSet[MAX_SET_SZ];
    1347514179
    13476     output[0] = 0xa0;
     14180    output[0] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
    1347714181    sz++;
    1347814182
     
    1348514189        }
    1348614190        cpSetSz = SetSet(cpStrSz + pwSz, cpSet);
    13487         cpSeqSz = SetSequence(sizeof(cpOid) + cpSetSz + cpStrSz + pwSz, cpSeq);
    13488         cpSz = cpSeqSz + sizeof(cpOid) + cpSetSz + cpStrSz + pwSz;
     14191        /* +2 for tag and length parts of the TLV triplet */
     14192        cpSeqSz = SetSequence(2 + sizeof(attrChallengePasswordOid) + cpSetSz +
     14193                cpStrSz + pwSz, cpSeq);
     14194        cpSz = cpSeqSz + 2 + sizeof(attrChallengePasswordOid) + cpSetSz +
     14195                cpStrSz + pwSz;
    1348914196    }
    1349014197
     
    1350114208        XMEMCPY(&output[sz], cpSeq, cpSeqSz);
    1350214209        sz += cpSeqSz;
    13503         XMEMCPY(&output[sz], cpOid, sizeof(cpOid));
    13504         sz += sizeof(cpOid);
     14210        sz += SetObjectId(sizeof(attrChallengePasswordOid), output + sz);
     14211        XMEMCPY(&output[sz], attrChallengePasswordOid,
     14212                sizeof(attrChallengePasswordOid));
     14213        sz += sizeof(attrChallengePasswordOid);
    1350514214        XMEMCPY(&output[sz], cpSet, cpSetSz);
    1350614215        sz += cpSetSz;
     
    1352714236/* encode info from cert into DER encoded format */
    1352814237static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey,
    13529                          ecc_key* eccKey, ed25519_key* ed25519Key,
    13530                          ed448_key* ed448Key)
     14238                         DsaKey* dsaKey, ecc_key* eccKey,
     14239                         ed25519_key* ed25519Key, ed448_key* ed448Key)
    1353114240{
    1353214241    (void)eccKey;
     
    1353814247
    1353914248    if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
    13540                                                             ed448Key == NULL) {
     14249            dsaKey == NULL && ed448Key == NULL) {
    1354114250            return PUBLIC_KEY_E;
    1354214251    }
     
    1354914258
    1355014259    /* subject name */
    13551     der->subjectSz = SetName(der->subject, sizeof(der->subject), &cert->subject);
     14260#if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
     14261    if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
     14262        /* Use the raw subject */
     14263        int idx;
     14264
     14265        der->subjectSz = min(sizeof(der->subject),
     14266                (word32)XSTRLEN((const char*)cert->sbjRaw));
     14267        /* header */
     14268        idx = SetSequence(der->subjectSz, der->subject);
     14269        if (der->subjectSz + idx > (int)sizeof(der->subject)) {
     14270            return SUBJECT_E;
     14271        }
     14272
     14273        XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
     14274                der->subjectSz);
     14275        der->subjectSz += idx;
     14276    }
     14277    else
     14278#endif
     14279    {
     14280        der->subjectSz = SetName(der->subject, sizeof(der->subject),
     14281                &cert->subject);
     14282    }
    1355214283    if (der->subjectSz <= 0)
    1355314284        return SUBJECT_E;
     
    1356314294#endif
    1356414295
     14296#if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
     14297    if (cert->keyType == DSA_KEY) {
     14298        if (dsaKey == NULL)
     14299            return PUBLIC_KEY_E;
     14300        der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
     14301                                           sizeof(der->publicKey), 1);
     14302    }
     14303#endif
     14304
    1356514305#ifdef HAVE_ECC
    1356614306    if (cert->keyType == ECC_KEY) {
     14307        if (eccKey == NULL)
     14308            return PUBLIC_KEY_E;
    1356714309        der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey, 1);
    1356814310    }
     
    1360014342    else
    1360114343        der->caSz = 0;
     14344
     14345#ifdef WOLFSSL_ALT_NAMES
     14346    /* Alternative Name */
     14347    if (cert->altNamesSz) {
     14348        der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
     14349                                      cert->altNames, cert->altNamesSz);
     14350        if (der->altNamesSz <= 0)
     14351            return ALT_NAME_E;
     14352
     14353        der->extensionsSz += der->altNamesSz;
     14354    }
     14355    else
     14356        der->altNamesSz = 0;
     14357#endif
    1360214358
    1360314359#ifdef WOLFSSL_CERT_EXT
     
    1366114417                return EXTENSIONS_E;
    1366214418        }
     14419
     14420#ifdef WOLFSSL_ALT_NAMES
     14421        /* put Alternative Names */
     14422        if (der->altNamesSz) {
     14423            ret = SetExtensions(der->extensions, sizeof(der->extensions),
     14424                                &der->extensionsSz,
     14425                                der->altNames, der->altNamesSz);
     14426            if (ret <= 0)
     14427                return EXTENSIONS_E;
     14428        }
     14429#endif
    1366314430
    1366414431#ifdef WOLFSSL_CERT_EXT
     
    1375114518
    1375214519static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
    13753                    RsaKey* rsaKey, ecc_key* eccKey, ed25519_key* ed25519Key,
    13754                    ed448_key* ed448Key)
     14520                   RsaKey* rsaKey, DsaKey* dsaKey, ecc_key* eccKey,
     14521                   ed25519_key* ed25519Key, ed448_key* ed448Key)
    1375514522{
    1375614523    int ret;
     
    1376114528#endif
    1376214529
    13763     cert->keyType = eccKey ? ECC_KEY : (ed25519Key ? ED25519_KEY :
    13764                                        (ed448Key ? ED448_KEY: RSA_KEY));
     14530    if (eccKey)
     14531        cert->keyType = ECC_KEY;
     14532    else if (rsaKey)
     14533        cert->keyType = RSA_KEY;
     14534    else if (dsaKey)
     14535        cert->keyType = DSA_KEY;
     14536    else if (ed25519Key)
     14537        cert->keyType = ED25519_KEY;
     14538    else if (ed448Key)
     14539        cert->keyType = ED448_KEY;
     14540    else
     14541        return BAD_FUNC_ARG;
    1376514542
    1376614543#ifdef WOLFSSL_SMALL_STACK
     
    1377114548#endif
    1377214549
    13773     ret = EncodeCertReq(cert, der, rsaKey, eccKey, ed25519Key, ed448Key);
     14550    ret = EncodeCertReq(cert, der, rsaKey, dsaKey, eccKey, ed25519Key, ed448Key);
    1377414551
    1377514552    if (ret == 0) {
     
    1379114568{
    1379214569    RsaKey*      rsaKey = NULL;
     14570    DsaKey*      dsaKey = NULL;
    1379314571    ecc_key*     eccKey = NULL;
    1379414572    ed25519_key* ed25519Key = NULL;
     
    1379714575    if (keyType == RSA_TYPE)
    1379814576        rsaKey = (RsaKey*)key;
     14577    else if (keyType == DSA_TYPE)
     14578        dsaKey = (DsaKey*)key;
    1379914579    else if (keyType == ECC_TYPE)
    1380014580        eccKey = (ecc_key*)key;
     
    1380414584        ed448Key = (ed448_key*)key;
    1380514585
    13806     return MakeCertReq(cert, derBuffer, derSz, rsaKey, eccKey, ed25519Key,
     14586    return MakeCertReq(cert, derBuffer, derSz, rsaKey, dsaKey, eccKey, ed25519Key,
    1380714587                       ed448Key);
    1380814588}
     
    1381114591                   RsaKey* rsaKey, ecc_key* eccKey)
    1381214592{
    13813     return MakeCertReq(cert, derBuffer, derSz, rsaKey, eccKey, NULL, NULL);
     14593    return MakeCertReq(cert, derBuffer, derSz, rsaKey, NULL, eccKey, NULL, NULL);
    1381414594}
    1381514595#endif /* WOLFSSL_CERT_REQ */
     
    1400314783    /* ED448 public key */
    1400414784    if (ed448Key != NULL)
    14005         bufferSz = SetEd448PublicKey(buffer, ed448Key, 0);
     14785        bufferSz = SetEd448PublicKey(buf, ed448Key, 0);
    1400614786#endif
    1400714787
     
    1443115211{
    1443215212    int ret = 0;
    14433     byte tag;
    14434 
    14435     if (decoded->extensions) {
    14436         int    length;
    14437         word32 maxExtensionsIdx;
    14438 
    14439         decoded->srcIdx = decoded->extensionsIdx;
    14440         if (GetASNTag(decoded->source, &decoded->srcIdx, &tag, decoded->maxIdx)
    14441                 != 0) {
    14442             return ASN_PARSE_E;
    14443         }
    14444 
    14445         if (tag != ASN_EXTENSIONS) {
    14446             ret = ASN_PARSE_E;
    14447         }
    14448         else if (GetLength(decoded->source, &decoded->srcIdx, &length,
    14449                                                          decoded->maxIdx) < 0) {
    14450             ret = ASN_PARSE_E;
    14451         }
    14452         else if (GetSequence(decoded->source, &decoded->srcIdx, &length,
    14453                                                          decoded->maxIdx) < 0) {
    14454             ret = ASN_PARSE_E;
    14455         }
    14456         else {
    14457             maxExtensionsIdx = decoded->srcIdx + length;
    14458 
    14459             while (decoded->srcIdx < maxExtensionsIdx) {
    14460                 word32 oid;
    14461                 word32 startIdx = decoded->srcIdx;
    14462                 word32 tmpIdx;
    14463 
    14464                 if (GetSequence(decoded->source, &decoded->srcIdx, &length,
    14465                             decoded->maxIdx) < 0) {
    14466                     ret = ASN_PARSE_E;
    14467                     break;
    14468                 }
    14469 
    14470                 tmpIdx = decoded->srcIdx;
    14471                 decoded->srcIdx = startIdx;
    14472 
    14473                 if (GetAlgoId(decoded->source, &decoded->srcIdx, &oid,
    14474                               oidCertExtType, decoded->maxIdx) < 0) {
    14475                     ret = ASN_PARSE_E;
    14476                     break;
    14477                 }
    14478 
    14479                 if (oid == ALT_NAMES_OID) {
    14480                     cert->altNamesSz = length + (tmpIdx - startIdx);
    14481 
    14482                     if (cert->altNamesSz < (int)sizeof(cert->altNames))
    14483                         XMEMCPY(cert->altNames, &decoded->source[startIdx],
    14484                                 cert->altNamesSz);
    14485                     else {
    14486                         cert->altNamesSz = 0;
    14487                         WOLFSSL_MSG("AltNames extensions too big");
    14488                         ret = ALT_NAME_E;
    14489                         break;
    14490                     }
    14491                 }
    14492                 decoded->srcIdx = tmpIdx + length;
    14493             }
     15213
     15214    cert->altNamesSz = 0;
     15215    if (decoded->altNames) {
     15216        ret = FlattenAltNames(cert->altNames,
     15217            sizeof(cert->altNames), decoded->altNames);
     15218        if (ret >= 0) {
     15219            cert->altNamesSz = ret;
     15220            ret = 0;
    1449415221        }
    1449515222    }
     
    1487815605
    1487915606        if (ret >= 0) {
    14880             if ((((DecodedCert*)cert->decodedCert)->issuerRaw) &&
    14881                 (((DecodedCert*)cert->decodedCert)->issuerRawLen <=
     15607            if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
     15608                (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
    1488215609                        (int)sizeof(CertName))) {
     15610                /* Copy the subject to the issuer field */
    1488315611                XMEMCPY(cert->issRaw,
    14884                         ((DecodedCert*)cert->decodedCert)->issuerRaw,
    14885                         ((DecodedCert*)cert->decodedCert)->issuerRawLen);
     15612                        ((DecodedCert*)cert->decodedCert)->subjectRaw,
     15613                        ((DecodedCert*)cert->decodedCert)->subjectRawLen);
    1488615614            }
    1488715615#ifndef WOLFSSL_CERT_GEN_CACHE
     
    1490215630
    1490315631    if (cert == NULL) {
    14904      ret = BAD_FUNC_ARG;
     15632       ret = BAD_FUNC_ARG;
    1490515633    }
    1490615634    else {
     
    1508815816    return 0;
    1508915817}
    15090 #endif /* !NO_DH && WOLFSSL_QT || OPENSSL_ALL */
     15818#endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */
    1509115819
    1509215820#ifdef HAVE_ECC
     
    1511315841
    1511415842    /* store r */
    15115     rSz = SetASNIntMP(r, -1, &out[idx]);
     15843    rSz = SetASNIntMP(r, *outLen - idx, &out[idx]);
    1511615844    if (rSz < 0)
    1511715845        return rSz;
     
    1511915847
    1512015848    /* store s */
    15121     sSz = SetASNIntMP(s, -1, &out[idx]);
     15849    sSz = SetASNIntMP(s, *outLen - idx, &out[idx]);
    1512215850    if (sSz < 0)
    1512315851        return sSz;
     
    1512915857}
    1513015858
    15131 
    15132 /* Der Decode ECC-DSA Signature, r & s stored as big ints */
    15133 int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s)
    15134 {
     15859/* determine if leading bit is set */
     15860static int is_leading_bit_set(const byte* input, word32 sz)
     15861{
     15862    byte c = 0;
     15863    if (sz > 0)
     15864        c = input[0];
     15865    return (c & 0x80) != 0;
     15866}
     15867static int trim_leading_zeros(const byte** input, word32 sz)
     15868{
     15869    int i, leadingZeroCount = 0;
     15870    const byte* tmp = *input;
     15871    for (i=0; i<(int)sz; i++) {
     15872        if (tmp[i] != 0)
     15873            break;
     15874        leadingZeroCount++;
     15875    }
     15876    /* catch all zero case */
     15877    if (sz > 0 && leadingZeroCount == (int)sz) {
     15878        leadingZeroCount--;
     15879    }
     15880    *input += leadingZeroCount;
     15881    sz -= leadingZeroCount;
     15882    return sz;
     15883}
     15884
     15885/* Der Encode r & s ints into out, outLen is (in/out) size */
     15886/* All input/outputs are assumed to be big-endian */
     15887int StoreECC_DSA_Sig_Bin(byte* out, word32* outLen, const byte* r, word32 rLen,
     15888    const byte* s, word32 sLen)
     15889{
     15890    int ret;
     15891    word32 idx;
     15892    word32 headerSz = 4;   /* 2*ASN_TAG + 2*LEN(ENUM) */
     15893    int rAddLeadZero, sAddLeadZero;
     15894
     15895    if ((out == NULL) || (outLen == NULL) || (r == NULL) || (s == NULL))
     15896        return BAD_FUNC_ARG;
     15897
     15898    /* Trim leading zeros */
     15899    rLen = trim_leading_zeros(&r, rLen);
     15900    sLen = trim_leading_zeros(&s, sLen);
     15901    /* If the leading bit on the INTEGER is a 1, add a leading zero */
     15902    /* Add leading zero if MSB is set */
     15903    rAddLeadZero = is_leading_bit_set(r, rLen);
     15904    sAddLeadZero = is_leading_bit_set(s, sLen);
     15905
     15906    if (*outLen < (rLen + rAddLeadZero + sLen + sAddLeadZero +
     15907                   headerSz + 2))  /* SEQ_TAG + LEN(ENUM) */
     15908        return BUFFER_E;
     15909
     15910    idx = SetSequence(rLen+rAddLeadZero + sLen+sAddLeadZero + headerSz, out);
     15911
     15912    /* store r */
     15913    ret = SetASNInt(rLen, rAddLeadZero ? 0x80 : 0x00, &out[idx]);
     15914    if (ret < 0)
     15915        return ret;
     15916    idx += ret;
     15917    XMEMCPY(&out[idx], r, rLen);
     15918    idx += rLen;
     15919
     15920    /* store s */
     15921    ret = SetASNInt(sLen, sAddLeadZero ? 0x80 : 0x00, &out[idx]);
     15922    if (ret < 0)
     15923        return ret;
     15924    idx += ret;
     15925    XMEMCPY(&out[idx], s, sLen);
     15926    idx += sLen;
     15927
     15928    *outLen = idx;
     15929
     15930    return 0;
     15931}
     15932
     15933/* Der Decode ECC-DSA Signature with R/S as unsigned bin */
     15934/* All input/outputs are assumed to be big-endian */
     15935int DecodeECC_DSA_Sig_Bin(const byte* sig, word32 sigLen, byte* r, word32* rLen,
     15936    byte* s, word32* sLen)
     15937{
     15938    int    ret;
    1513515939    word32 idx = 0;
    1513615940    int    len = 0;
     
    1515215956#endif
    1515315957
     15958    ret = GetASNInt(sig, &idx, &len, sigLen);
     15959    if (ret != 0)
     15960        return ret;
     15961    if (rLen)
     15962        *rLen = len;
     15963    if (r)
     15964        XMEMCPY(r, (byte*)sig + idx, len);
     15965    idx += len;
     15966
     15967    ret = GetASNInt(sig, &idx, &len, sigLen);
     15968    if (ret != 0)
     15969        return ret;
     15970    if (sLen)
     15971        *sLen = len;
     15972    if (s)
     15973        XMEMCPY(s, (byte*)sig + idx, len);
     15974
     15975    return ret;
     15976}
     15977#endif
     15978
     15979#if defined(HAVE_ECC) || !defined(NO_DSA)
     15980int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s)
     15981{
     15982    word32 idx = 0;
     15983    int    len = 0;
     15984
     15985    if (GetSequence(sig, &idx, &len, sigLen) < 0) {
     15986        return ASN_ECC_KEY_E;
     15987    }
     15988
     15989#ifndef NO_STRICT_ECDSA_LEN
     15990    /* enable strict length checking for signature */
     15991    if (sigLen != idx + (word32)len) {
     15992        return ASN_ECC_KEY_E;
     15993    }
     15994#else
     15995    /* allow extra signature bytes at end */
     15996    if ((word32)len > (sigLen - idx)) {
     15997        return ASN_ECC_KEY_E;
     15998    }
     15999#endif
     16000
    1515416001    if (GetInt(r, sig, &idx, sigLen) < 0) {
    1515516002        return ASN_ECC_KEY_E;
     
    1515716004
    1515816005    if (GetInt(s, sig, &idx, sigLen) < 0) {
     16006        mp_clear(r);
    1515916007        return ASN_ECC_KEY_E;
    1516016008    }
     
    1516216010    return 0;
    1516316011}
    15164 
    15165 
     16012#endif
     16013
     16014#ifdef HAVE_ECC
    1516616015int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key,
    1516716016                        word32 inSz)
     
    1517516024#ifdef WOLFSSL_SMALL_STACK
    1517616025    byte* priv;
    15177     byte* pub;
     16026    byte* pub = NULL;
    1517816027#else
    1517916028    byte priv[ECC_MAXSIZE+1];
     
    1520316052    if (GetLength(input, inOutIdx, &length, inSz) < 0)
    1520416053        return ASN_PARSE_E;
    15205 
    15206     if (length > ECC_MAXSIZE)
     16054    privSz = length;
     16055
     16056    if (privSz > ECC_MAXSIZE)
    1520716057        return BUFFER_E;
    1520816058
    1520916059#ifdef WOLFSSL_SMALL_STACK
    15210     priv = (byte*)XMALLOC(ECC_MAXSIZE+1, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     16060    priv = (byte*)XMALLOC(privSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    1521116061    if (priv == NULL)
    1521216062        return MEMORY_E;
    15213 
    15214     pub = (byte*)XMALLOC(2*(ECC_MAXSIZE+1), key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    15215     if (pub == NULL) {
    15216         XFREE(priv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    15217         return MEMORY_E;
    15218     }
    1521916063#endif
    1522016064
    1522116065    /* priv key */
    15222     privSz = length;
    1522316066    XMEMCPY(priv, &input[*inOutIdx], privSz);
    1522416067    *inOutIdx += length;
     
    1526416107                /* pub key */
    1526516108                pubSz = length;
    15266                 if (pubSz < 2*(ECC_MAXSIZE+1)) {
    15267                     XMEMCPY(pub, &input[*inOutIdx], pubSz);
    15268                     *inOutIdx += length;
    15269                     pubData = pub;
     16109                if (pubSz > 2*(ECC_MAXSIZE+1))
     16110                    ret = BUFFER_E;
     16111                else {
     16112            #ifdef WOLFSSL_SMALL_STACK
     16113                    pub = (byte*)XMALLOC(pubSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     16114                    if (pub == NULL)
     16115                        ret = MEMORY_E;
     16116                    else
     16117            #endif
     16118                    {
     16119                        XMEMCPY(pub, &input[*inOutIdx], pubSz);
     16120                        *inOutIdx += length;
     16121                        pubData = pub;
     16122                    }
    1527016123                }
    15271                 else
    15272                     ret = BUFFER_E;
    1527316124            }
    1527416125        }
     
    1537016221                          ecc_key* key, word32 inSz)
    1537116222{
    15372     int    length;
    1537316223    int    ret;
     16224    int    version, length;
    1537416225    int    curve_id = ECC_CURVE_DEF;
    1537516226    word32 oidSum, localIdx;
    15376     byte   tag;
     16227    byte   tag, isPrivFormat = 0;
    1537716228
    1537816229    if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
     
    1538216233        return ASN_PARSE_E;
    1538316234
    15384     if (GetSequence(input, inOutIdx, &length, inSz) < 0)
    15385         return ASN_PARSE_E;
    15386 
    15387     ret = SkipObjectId(input, inOutIdx, inSz);
    15388     if (ret != 0)
    15389         return ret;
     16235    /* Check if ECC private key is being used and skip private portion */
     16236    if (GetMyVersion(input, inOutIdx, &version, inSz) >= 0) {
     16237        isPrivFormat = 1;
     16238
     16239        /* Type private key */
     16240        if (*inOutIdx >= inSz)
     16241            return ASN_PARSE_E;
     16242        tag = input[*inOutIdx];
     16243        *inOutIdx += 1;
     16244        if (tag != 4 && tag != 6 && tag != 7)
     16245            return ASN_PARSE_E;
     16246
     16247        /* Skip Private Key */
     16248        if (GetLength(input, inOutIdx, &length, inSz) < 0)
     16249            return ASN_PARSE_E;
     16250        if (length > ECC_MAXSIZE)
     16251            return BUFFER_E;
     16252        *inOutIdx += length;
     16253
     16254        /* Private Curve Header */
     16255        if (*inOutIdx >= inSz)
     16256            return ASN_PARSE_E;
     16257        tag = input[*inOutIdx];
     16258        *inOutIdx += 1;
     16259        if (tag != ECC_PREFIX_0)
     16260            return ASN_ECC_KEY_E;
     16261        if (GetLength(input, inOutIdx, &length, inSz) <= 0)
     16262            return ASN_PARSE_E;
     16263    }
     16264    /* Standard ECC public key */
     16265    else {
     16266        if (GetSequence(input, inOutIdx, &length, inSz) < 0)
     16267            return ASN_PARSE_E;
     16268
     16269        ret = SkipObjectId(input, inOutIdx, inSz);
     16270        if (ret != 0)
     16271            return ret;
     16272    }
    1539016273
    1539116274    if (*inOutIdx >= inSz) {
     
    1554216425
    1554316426        /* get curve id */
    15544         curve_id = wc_ecc_get_oid(oidSum, NULL, 0);
    15545         if (curve_id < 0)
     16427        if ((ret = CheckCurve(oidSum)) < 0)
    1554616428            return ECC_CURVE_OID_E;
     16429        else {
     16430            curve_id = ret;
     16431        }
     16432    }
     16433
     16434    if (isPrivFormat) {
     16435        /* Public Curve Header - skip */
     16436        if (*inOutIdx >= inSz)
     16437            return ASN_PARSE_E;
     16438        tag = input[*inOutIdx];
     16439        *inOutIdx += 1;
     16440        if (tag != ECC_PREFIX_1)
     16441            return ASN_ECC_KEY_E;
     16442        if (GetLength(input, inOutIdx, &length, inSz) <= 0)
     16443            return ASN_PARSE_E;
    1554716444    }
    1554816445
     
    1557216469    byte   ver[MAX_VERSION_SZ];
    1557316470    byte   seq[MAX_SEQ_SZ];
    15574     byte   *prv = NULL, *pub = NULL;
    1557516471    int    ret, totalSz, curveSz, verSz;
    1557616472    int    privHdrSz  = ASN_ECC_HEADER_SZ;
    1557716473    int    pubHdrSz   = ASN_ECC_CONTEXT_SZ + ASN_ECC_HEADER_SZ;
     16474#ifdef WOLFSSL_NO_MALLOC
     16475    byte   prv[MAX_ECC_BYTES + ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
     16476    byte   pub[(MAX_ECC_BYTES * 2) + 1 + ASN_ECC_CONTEXT_SZ +
     16477                              ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
     16478#else
     16479    byte   *prv = NULL, *pub = NULL;
     16480#endif
    1557816481
    1557916482    word32 idx = 0, prvidx = 0, pubidx = 0, curveidx = 0;
     
    1559516498    /* private */
    1559616499    privSz = key->dp->size;
     16500#ifndef WOLFSSL_NO_MALLOC
    1559716501    prv = (byte*)XMALLOC(privSz + privHdrSz + MAX_SEQ_SZ,
    1559816502                         key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     
    1560016504        return MEMORY_E;
    1560116505    }
     16506#else
     16507    if (sizeof(prv) < privSz + privHdrSz + MAX_SEQ_SZ) {
     16508        return BUFFER_E;
     16509    }
     16510#endif
    1560216511    prvidx += SetOctetString8Bit(key->dp->size, &prv[prvidx]);
    1560316512    ret = wc_ecc_export_private_only(key, prv + prvidx, &privSz);
    1560416513    if (ret < 0) {
     16514    #ifndef WOLFSSL_NO_MALLOC
    1560516515        XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     16516    #endif
    1560616517        return ret;
    1560716518    }
     
    1561216523        ret = wc_ecc_export_x963(key, NULL, &pubSz);
    1561316524        if (ret != LENGTH_ONLY_E) {
     16525        #ifndef WOLFSSL_NO_MALLOC
    1561416526            XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     16527        #endif
    1561516528            return ret;
    1561616529        }
    1561716530
     16531    #ifndef WOLFSSL_NO_MALLOC
    1561816532        pub = (byte*)XMALLOC(pubSz + pubHdrSz + MAX_SEQ_SZ,
    1561916533                             key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     
    1562216536            return MEMORY_E;
    1562316537        }
     16538    #else
     16539        if (sizeof(pub) < pubSz + pubHdrSz + MAX_SEQ_SZ) {
     16540            return BUFFER_E;
     16541        }
     16542    #endif
    1562416543
    1562516544        pub[pubidx++] = ECC_PREFIX_1;
     
    1563316552        ret = wc_ecc_export_x963(key, pub + pubidx, &pubSz);
    1563416553        if (ret != 0) {
     16554        #ifndef WOLFSSL_NO_MALLOC
    1563516555            XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    1563616556            XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     16557        #endif
    1563716558            return ret;
    1563816559        }
     
    1564616567    totalSz = prvidx + pubidx + curveidx + verSz + seqSz;
    1564716568    if (totalSz > (int)inLen) {
     16569        #ifndef WOLFSSL_NO_MALLOC
    1564816570        XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    1564916571        if (pubIn) {
    1565016572            XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    1565116573        }
     16574        #endif
    1565216575        return BAD_FUNC_ARG;
    1565316576    }
     
    1566516588    XMEMCPY(output + idx, prv, prvidx);
    1566616589    idx += prvidx;
     16590#ifndef WOLFSSL_NO_MALLOC
    1566716591    XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     16592#endif
    1566816593
    1566916594    /* curve */
     
    1567516600        XMEMCPY(output + idx, pub, pubidx);
    1567616601        /* idx += pubidx;  not used after write, if more data remove comment */
     16602    #ifndef WOLFSSL_NO_MALLOC
    1567716603        XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     16604    #endif
    1567816605    }
    1567916606
     
    1569716624
    1569816625#ifdef HAVE_PKCS8
    15699 /* Write only private ecc key to unencrypted PKCS#8 format.
     16626/* Write only private ecc key or both private and public parts to unencrypted
     16627 * PKCS#8 format.
    1570016628 *
    1570116629 * If output is NULL, places required PKCS#8 buffer size in outLen and
     
    1570316631 *
    1570416632 * return length on success else < 0 */
    15705 int wc_EccPrivateKeyToPKCS8(ecc_key* key, byte* output, word32* outLen)
     16633static int eccToPKCS8(ecc_key* key, byte* output, word32* outLen,
     16634        int includePublic)
    1570616635{
    1570716636    int ret, tmpDerSz;
     
    1571016639    word32 pkcs8Sz = 0;
    1571116640    const byte* curveOID = NULL;
     16641#ifdef WOLFSSL_NO_MALLOC
     16642    byte  tmpDer[ECC_BUFSIZE];
     16643#else
    1571216644    byte* tmpDer = NULL;
    15713 
    15714     if (key == NULL || outLen == NULL)
     16645#endif
     16646
     16647    if (key == NULL || key->dp == NULL || outLen == NULL)
    1571516648        return BAD_FUNC_ARG;
    1571616649
     
    1572116654        return ret;
    1572216655
     16656#ifndef WOLFSSL_NO_MALLOC
    1572316657    /* temp buffer for plain DER key */
    1572416658    tmpDer = (byte*)XMALLOC(ECC_BUFSIZE, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    1572516659    if (tmpDer == NULL)
    1572616660        return MEMORY_E;
    15727 
     16661#endif
    1572816662    XMEMSET(tmpDer, 0, ECC_BUFSIZE);
    1572916663
    15730     tmpDerSz = wc_BuildEccKeyDer(key, tmpDer, ECC_BUFSIZE, 0);
     16664    tmpDerSz = wc_BuildEccKeyDer(key, tmpDer, ECC_BUFSIZE, includePublic);
    1573116665    if (tmpDerSz < 0) {
     16666    #ifndef WOLFSSL_NO_MALLOC
    1573216667        XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     16668    #endif
    1573316669        return tmpDerSz;
    1573416670    }
     
    1573816674                            curveOID, oidSz);
    1573916675    if (ret != LENGTH_ONLY_E) {
     16676    #ifndef WOLFSSL_NO_MALLOC
    1574016677        XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     16678    #endif
    1574116679        return ret;
    1574216680    }
    1574316681
    1574416682    if (output == NULL) {
     16683    #ifndef WOLFSSL_NO_MALLOC
    1574516684        XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     16685    #endif
    1574616686        *outLen = pkcs8Sz;
    1574716687        return LENGTH_ONLY_E;
    1574816688
    15749     } else if (*outLen < pkcs8Sz) {
     16689    }
     16690    else if (*outLen < pkcs8Sz) {
     16691    #ifndef WOLFSSL_NO_MALLOC
    1575016692        XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     16693    #endif
    1575116694        WOLFSSL_MSG("Input buffer too small for ECC PKCS#8 key");
    1575216695        return BUFFER_E;
     
    1575616699                            algoID, curveOID, oidSz);
    1575716700    if (ret < 0) {
     16701    #ifndef WOLFSSL_NO_MALLOC
    1575816702        XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     16703    #endif
    1575916704        return ret;
    1576016705    }
    1576116706
     16707#ifndef WOLFSSL_NO_MALLOC
    1576216708    XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     16709#endif
    1576316710
    1576416711    *outLen = ret;
    1576516712    return ret;
     16713}
     16714
     16715/* Write only private ecc key to unencrypted PKCS#8 format.
     16716 *
     16717 * return length on success else < 0 */
     16718int wc_EccPrivateKeyToPKCS8(ecc_key* key, byte* output, word32* outLen)
     16719{
     16720    return eccToPKCS8(key, output, outLen, 0);
     16721}
     16722
     16723/* Write both private and public ecc keys to unencrypted PKCS#8 format.
     16724 *
     16725 * return length on success else < 0 */
     16726int wc_EccKeyToPKCS8(ecc_key* key, byte* output,
     16727                     word32* outLen)
     16728{
     16729    return eccToPKCS8(key, output, outLen, 1);
    1576616730}
    1576716731#endif /* HAVE_PKCS8 */
     
    1618817152
    1618917153
    16190 static int DecodeSingleResponse(byte* source,
    16191                             word32* ioIndex, OcspResponse* resp, word32 size)
    16192 {
    16193     word32 idx = *ioIndex, prevIndex, oid, localIdx;
    16194     int length, wrapperSz;
    16195     CertStatus* cs = resp->status;
     17154static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size,
     17155                                int wrapperSz, OcspEntry* single)
     17156{
     17157    word32 idx = *ioIndex, prevIndex, oid, localIdx, certIdIdx;
     17158    int length;
    1619617159    int ret;
    1619717160    byte tag;
     
    1619917162    WOLFSSL_ENTER("DecodeSingleResponse");
    1620017163
    16201     /* Outer wrapper of the SEQUENCE OF Single Responses. */
    16202     if (GetSequence(source, &idx, &wrapperSz, size) < 0)
    16203         return ASN_PARSE_E;
    16204 
    1620517164    prevIndex = idx;
    16206 
    16207     /* When making a request, we only request one status on one certificate
    16208      * at a time. There should only be one SingleResponse */
    1620917165
    1621017166    /* Wrapper around the Single Response */
     
    1621317169
    1621417170    /* Wrapper around the CertID */
     17171    certIdIdx = idx;
    1621517172    if (GetSequence(source, &idx, &length, size) < 0)
    1621617173        return ASN_PARSE_E;
    16217     /* Skip the hash algorithm */
    16218     if (GetAlgoId(source, &idx, &oid, oidIgnoreType, size) < 0)
    16219         return ASN_PARSE_E;
     17174    single->rawCertId = source + certIdIdx;
     17175    /* Hash algorithm */
     17176    ret = GetAlgoId(source, &idx, &oid, oidIgnoreType, size);
     17177    if (ret < 0)
     17178        return ret;
     17179    single->hashAlgoOID = oid;
    1622017180    /* Save reference to the hash of CN */
    1622117181    ret = GetOctetString(source, &idx, &length, size);
    1622217182    if (ret < 0)
    1622317183        return ret;
    16224     resp->issuerHash = source + idx;
     17184    XMEMCPY(single->issuerHash, source + idx, length);
    1622517185    idx += length;
    1622617186    /* Save reference to the hash of the issuer public key */
     
    1622817188    if (ret < 0)
    1622917189        return ret;
    16230     resp->issuerKeyHash = source + idx;
     17190    XMEMCPY(single->issuerKeyHash, source + idx, length);
    1623117191    idx += length;
    1623217192
    1623317193    /* Get serial number */
    16234     if (GetSerialNumber(source, &idx, cs->serial, &cs->serialSz, size) < 0)
     17194    if (GetSerialNumber(source, &idx, single->status->serial, &single->status->serialSz, size) < 0)
    1623517195        return ASN_PARSE_E;
    16236 
    16237     if ( idx >= size )
     17196    single->rawCertIdSize = idx - certIdIdx;
     17197
     17198    if (idx >= size)
    1623817199        return BUFFER_E;
    1623917200
     
    1624217203    {
    1624317204        case (ASN_CONTEXT_SPECIFIC | CERT_GOOD):
    16244             cs->status = CERT_GOOD;
     17205            single->status->status = CERT_GOOD;
    1624517206            idx++;
    1624617207            break;
    1624717208        case (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CERT_REVOKED):
    16248             cs->status = CERT_REVOKED;
     17209            single->status->status = CERT_REVOKED;
    1624917210            if (GetLength(source, &idx, &length, size) < 0)
    1625017211                return ASN_PARSE_E;
     
    1625217213            break;
    1625317214        case (ASN_CONTEXT_SPECIFIC | CERT_UNKNOWN):
    16254             cs->status = CERT_UNKNOWN;
     17215            single->status->status = CERT_UNKNOWN;
    1625517216            idx++;
    1625617217            break;
     
    1626017221
    1626117222#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
    16262     cs->thisDateAsn = source + idx;
     17223    single->status->thisDateAsn = source + idx;
    1626317224    localIdx = 0;
    16264     if (GetDateInfo(cs->thisDateAsn, &localIdx, NULL,
    16265                     (byte*)&cs->thisDateParsed.type,
    16266                     &cs->thisDateParsed.length, size) < 0)
     17225    if (GetDateInfo(single->status->thisDateAsn, &localIdx, NULL,
     17226                    (byte*)&single->status->thisDateParsed.type,
     17227                    &single->status->thisDateParsed.length, size) < 0)
    1626717228        return ASN_PARSE_E;
    16268     XMEMCPY(cs->thisDateParsed.data,
    16269             cs->thisDateAsn + localIdx - cs->thisDateParsed.length,
    16270             cs->thisDateParsed.length);
    16271 #endif
    16272     if (GetBasicDate(source, &idx, cs->thisDate,
    16273                                                 &cs->thisDateFormat, size) < 0)
     17229    XMEMCPY(single->status->thisDateParsed.data,
     17230            single->status->thisDateAsn + localIdx - single->status->thisDateParsed.length,
     17231            single->status->thisDateParsed.length);
     17232#endif
     17233    if (GetBasicDate(source, &idx, single->status->thisDate,
     17234                                                &single->status->thisDateFormat, size) < 0)
    1627417235        return ASN_PARSE_E;
    1627517236
    1627617237#ifndef NO_ASN_TIME
    1627717238#ifndef WOLFSSL_NO_OCSP_DATE_CHECK
    16278     if (!XVALIDATE_DATE(cs->thisDate, cs->thisDateFormat, BEFORE))
     17239    if (!XVALIDATE_DATE(single->status->thisDate, single->status->thisDateFormat, BEFORE))
    1627917240        return ASN_BEFORE_DATE_E;
    1628017241#endif
     
    1628317244    /* The following items are optional. Only check for them if there is more
    1628417245     * unprocessed data in the singleResponse wrapper. */
    16285 
    1628617246    localIdx = idx;
    1628717247    if (((int)(idx - prevIndex) < wrapperSz) &&
     
    1629317253            return ASN_PARSE_E;
    1629417254#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
    16295         cs->nextDateAsn = source + idx;
     17255        single->status->nextDateAsn = source + idx;
    1629617256        localIdx = 0;
    16297         if (GetDateInfo(cs->nextDateAsn, &localIdx, NULL,
    16298                         (byte*)&cs->nextDateParsed.type,
    16299                         &cs->nextDateParsed.length, size) < 0)
     17257        if (GetDateInfo(single->status->nextDateAsn, &localIdx, NULL,
     17258                        (byte*)&single->status->nextDateParsed.type,
     17259                        &single->status->nextDateParsed.length, size) < 0)
    1630017260            return ASN_PARSE_E;
    16301         XMEMCPY(cs->nextDateParsed.data,
    16302                 cs->nextDateAsn + localIdx - cs->nextDateParsed.length,
    16303                 cs->nextDateParsed.length);
    16304 #endif
    16305         if (GetBasicDate(source, &idx, cs->nextDate,
    16306                                                 &cs->nextDateFormat, size) < 0)
     17261        XMEMCPY(single->status->nextDateParsed.data,
     17262                single->status->nextDateAsn + localIdx - single->status->nextDateParsed.length,
     17263                single->status->nextDateParsed.length);
     17264#endif
     17265        if (GetBasicDate(source, &idx, single->status->nextDate,
     17266                                                &single->status->nextDateFormat, size) < 0)
    1630717267            return ASN_PARSE_E;
    1630817268
    1630917269#ifndef NO_ASN_TIME
    1631017270#ifndef WOLFSSL_NO_OCSP_DATE_CHECK
    16311         if (!XVALIDATE_DATE(cs->nextDate, cs->nextDateFormat, AFTER))
     17271        if (!XVALIDATE_DATE(single->status->nextDate, single->status->nextDateFormat, AFTER))
    1631217272            return ASN_AFTER_DATE_E;
    1631317273#endif
     
    1631517275    }
    1631617276
     17277    /* Skip the optional extensions in singleResponse. */
    1631717278    localIdx = idx;
    1631817279    if (((int)(idx - prevIndex) < wrapperSz) &&
     
    1641817379    int ret;
    1641917380    byte tag;
     17381    int wrapperSz;
     17382    OcspEntry* single;
    1642017383
    1642117384    WOLFSSL_ENTER("DecodeResponseData");
     
    1645917422        return ASN_PARSE_E;
    1646017423
    16461     if ((ret = DecodeSingleResponse(source, &idx, resp, size)) < 0)
    16462         return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
     17424    /* Outer wrapper of the SEQUENCE OF Single Responses. */
     17425    if (GetSequence(source, &idx, &wrapperSz, size) < 0)
     17426        return ASN_PARSE_E;
     17427
     17428    localIdx = idx;
     17429    single = resp->single;
     17430
     17431    while (idx - localIdx < (word32)wrapperSz) {
     17432        ret = DecodeSingleResponse(source, &idx, size, wrapperSz, single);
     17433        if (ret < 0)
     17434            return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
     17435        if (idx - localIdx < (word32)wrapperSz) {
     17436            single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
     17437                DYNAMIC_TYPE_OCSP_ENTRY);
     17438            if (single->next == NULL) {
     17439                return MEMORY_E;
     17440            }
     17441            single = single->next;
     17442            XMEMSET(single, 0, sizeof(OcspEntry));
     17443            single->isDynamic = 1;
     17444        }
     17445    }
    1646317446
    1646417447    /*
     
    1657017553        if ((cert.extExtKeyUsage & EXTKEYUSE_OCSP_SIGN) == 0) {
    1657117554            if (XMEMCMP(cert.subjectHash,
    16572                         resp->issuerHash, KEYID_SIZE) == 0) {
     17555                        resp->single->issuerHash, OCSP_DIGEST_SIZE) == 0) {
    1657317556                WOLFSSL_MSG("\tOCSP Response signed by issuer");
    1657417557            }
     
    1660517588
    1660617589        #ifndef NO_SKID
    16607             ca = GetCA(cm, resp->issuerKeyHash);
     17590            ca = GetCA(cm, resp->single->issuerKeyHash);
    1660817591        #else
    16609             ca = GetCA(cm, resp->issuerHash);
     17592            ca = GetCA(cm, resp->single->issuerHash);
    1661017593        #endif
    1661117594
     
    1663217615
    1663317616
    16634 void InitOcspResponse(OcspResponse* resp, CertStatus* status,
    16635                                                     byte* source, word32 inSz)
     17617void InitOcspResponse(OcspResponse* resp, OcspEntry* single, CertStatus* status,
     17618                      byte* source, word32 inSz, void* heap)
    1663617619{
    1663717620    WOLFSSL_ENTER("InitOcspResponse");
    1663817621
    1663917622    XMEMSET(status, 0, sizeof(CertStatus));
     17623    XMEMSET(single,  0, sizeof(OcspEntry));
    1664017624    XMEMSET(resp,   0, sizeof(OcspResponse));
    1664117625
     17626    single->status       = status;
    1664217627    resp->responseStatus = -1;
    16643     resp->status         = status;
     17628    resp->single         = single;
    1664417629    resp->source         = source;
    1664517630    resp->maxIdx         = inSz;
     17631    resp->heap           = heap;
     17632}
     17633
     17634void FreeOcspResponse(OcspResponse* resp)
     17635{
     17636    OcspEntry *single, *next;
     17637    for (single = resp->single; single; single = next) {
     17638        next = single->next;
     17639        if (single->isDynamic)
     17640            XFREE(single, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
     17641    }
    1664617642}
    1664717643
     
    1691717913int CompareOcspReqResp(OcspRequest* req, OcspResponse* resp)
    1691817914{
    16919     int cmp;
     17915    int cmp = -1; /* default as not matching, cmp gets set on each check */
     17916    OcspEntry *single, *next, *prev = NULL, *top;
    1692017917
    1692117918    WOLFSSL_ENTER("CompareOcspReqResp");
    1692217919
    16923     if (req == NULL)
    16924     {
     17920    if (req == NULL) {
    1692517921        WOLFSSL_MSG("\tReq missing");
    1692617922        return -1;
    1692717923    }
    16928 
    16929     if (resp == NULL)
    16930     {
     17924    if (resp == NULL || resp->single == NULL) {
    1693117925        WOLFSSL_MSG("\tResp missing");
    1693217926        return 1;
     
    1693517929    /* Nonces are not critical. The responder may not necessarily add
    1693617930     * the nonce to the response. */
    16937     if (req->nonceSz
     17931    if (req->nonceSz && resp->nonce != NULL
    1693817932#ifndef WOLFSSL_FORCE_OCSP_NONCE_CHECK
    1693917933            && resp->nonceSz != 0
     
    1694117935    ) {
    1694217936        cmp = req->nonceSz - resp->nonceSz;
    16943         if (cmp != 0)
    16944         {
     17937        if (cmp != 0) {
    1694517938            WOLFSSL_MSG("\tnonceSz mismatch");
    1694617939            return cmp;
     
    1694817941
    1694917942        cmp = XMEMCMP(req->nonce, resp->nonce, req->nonceSz);
    16950         if (cmp != 0)
    16951         {
     17943        if (cmp != 0) {
    1695217944            WOLFSSL_MSG("\tnonce mismatch");
    1695317945            return cmp;
     
    1695517947    }
    1695617948
    16957     cmp = XMEMCMP(req->issuerHash, resp->issuerHash, KEYID_SIZE);
    16958     if (cmp != 0)
    16959     {
    16960         WOLFSSL_MSG("\tissuerHash mismatch");
    16961         return cmp;
    16962     }
    16963 
    16964     cmp = XMEMCMP(req->issuerKeyHash, resp->issuerKeyHash, KEYID_SIZE);
    16965     if (cmp != 0)
    16966     {
    16967         WOLFSSL_MSG("\tissuerKeyHash mismatch");
    16968         return cmp;
    16969     }
    16970 
    16971     cmp = req->serialSz - resp->status->serialSz;
    16972     if (cmp != 0)
    16973     {
    16974         WOLFSSL_MSG("\tserialSz mismatch");
    16975         return cmp;
    16976     }
    16977 
    16978     cmp = XMEMCMP(req->serial, resp->status->serial, req->serialSz);
    16979     if (cmp != 0)
    16980     {
    16981         WOLFSSL_MSG("\tserial mismatch");
     17949    /* match based on found status and return */
     17950    for (single = resp->single; single; single = next) {
     17951        cmp = req->serialSz - single->status->serialSz;
     17952        if (cmp == 0) {
     17953            if ((XMEMCMP(req->serial, single->status->serial, req->serialSz) == 0)
     17954             && (XMEMCMP(req->issuerHash, single->issuerHash, OCSP_DIGEST_SIZE) == 0)
     17955             && (XMEMCMP(req->issuerKeyHash, single->issuerKeyHash, OCSP_DIGEST_SIZE) == 0)) {
     17956                /* match found */
     17957                if (resp->single != single && prev) {
     17958                    /* move to top of list */
     17959                    top = resp->single;
     17960                    resp->single = single;
     17961                    prev->next = single->next;
     17962                    single->next = top;
     17963                }
     17964                break;
     17965            }
     17966        }
     17967        next = single->next;
     17968        prev = single;
     17969    }
     17970
     17971    if (cmp != 0) {
     17972        WOLFSSL_MSG("\trequest and response mismatch");
    1698217973        return cmp;
    1698317974    }
     
    1735218343
    1735318344
    17354 /* prase crl buffer into decoded state, 0 on success */
     18345/* parse crl buffer into decoded state, 0 on success */
    1735518346int ParseCRL(DecodedCRL* dcrl, const byte* buff, word32 sz, void* cm)
    1735618347{
     
    1738018371    dcrl->sigIndex = len + idx;
    1738118372
    17382     if (ParseCRL_CertList(dcrl, buff, &idx, idx + len) < 0)
     18373    if (ParseCRL_CertList(dcrl, buff, &idx, dcrl->sigIndex) < 0)
    1738318374        return ASN_PARSE_E;
    1738418375
    17385     if (ParseCRL_Extensions(dcrl, buff, &idx, idx + len) < 0)
     18376    if (ParseCRL_Extensions(dcrl, buff, &idx, dcrl->sigIndex) < 0)
    1738618377        return ASN_PARSE_E;
    1738718378
     
    1751618507
    1751718508
     18509
     18510#ifdef HAVE_SMIME
     18511
     18512/*****************************************************************************
     18513* wc_MIME_parse_headers - Reads the char array in and parses out MIME headers
     18514* and parameters into headers.  Will continue until in has no more content.
     18515*
     18516* RETURNS:
     18517* returns zero on success, non-zero on error.
     18518*/
     18519int wc_MIME_parse_headers(char* in, int inLen, MimeHdr** headers)
     18520{
     18521    MimeHdr* nextHdr = NULL;
     18522    MimeHdr* curHdr = NULL;
     18523    MimeParam* nextParam = NULL;
     18524    size_t start = 0;
     18525    size_t end = 0;
     18526    char* nameAttr = NULL;
     18527    char* bodyVal = NULL;
     18528    MimeTypes mimeType = MIME_HDR;
     18529    MimeStatus mimeStatus = MIME_NAMEATTR;
     18530    int ret = -1;
     18531    size_t pos = 0;
     18532    size_t lineLen = 0;
     18533    char* curLine = NULL;
     18534    char* ptr = NULL;
     18535
     18536    if (in == NULL || inLen <= 0 || in[inLen] != '\0' || headers == NULL) {
     18537        ret = BAD_FUNC_ARG;
     18538        goto error;
     18539    }
     18540    nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL, DYNAMIC_TYPE_PKCS7);
     18541    nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
     18542                                    DYNAMIC_TYPE_PKCS7);
     18543    if (nextHdr == NULL || nextParam == NULL) {
     18544        ret = MEMORY_E;
     18545        goto error;
     18546    }
     18547    XMEMSET(nextHdr, 0, (word32)sizeof(MimeHdr));
     18548    XMEMSET(nextParam, 0, (word32)sizeof(MimeParam));
     18549
     18550    curLine = XSTRTOK(in, "\r\n", &ptr);
     18551    if (curLine == NULL) {
     18552        ret = ASN_PARSE_E;
     18553        goto error;
     18554    }
     18555
     18556    while (curLine != NULL) {
     18557        /* Leftover from previous line, add params to previous header. */
     18558        if (curLine[0] == ' ' && curHdr) {
     18559            mimeType = MIME_PARAM;
     18560        }
     18561        else {
     18562            mimeType = MIME_HDR;
     18563        }
     18564        start = end = 0;
     18565        lineLen = XSTRLEN(curLine);
     18566
     18567        for (pos = 0; pos < lineLen; pos++) {
     18568            char cur = curLine[pos];
     18569
     18570            if (mimeStatus == MIME_NAMEATTR && ((cur == ':' &&
     18571                mimeType == MIME_HDR) || (cur == '=' &&
     18572                mimeType == MIME_PARAM))) {
     18573                mimeStatus = MIME_BODYVAL;
     18574                end = pos-1;
     18575                ret = wc_MIME_header_strip(curLine, &nameAttr, start, end);
     18576                if (ret) {
     18577                    goto error;
     18578                }
     18579                start = pos+1;
     18580            }
     18581            else if (mimeStatus == MIME_BODYVAL && cur == ';') {
     18582                end = pos-1;
     18583                ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
     18584                if (ret) {
     18585                    goto error;
     18586                }
     18587                if (mimeType == MIME_HDR) {
     18588                    nextHdr->name = nameAttr;
     18589                    nextHdr->body = bodyVal;
     18590                    nextHdr->next = curHdr;
     18591                    curHdr = nextHdr;
     18592                    nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
     18593                                                DYNAMIC_TYPE_PKCS7);
     18594                    if (nextHdr == NULL) {
     18595                        ret = MEMORY_E;
     18596                        goto error;
     18597                    }
     18598                    XMEMSET(nextHdr, 0, (word32)sizeof(MimeHdr));
     18599                }
     18600                else {
     18601                    nextParam->attribute = nameAttr;
     18602                    nextParam->value = bodyVal;
     18603                    nextParam->next = curHdr->params;
     18604                    curHdr->params = nextParam;
     18605                    nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
     18606                                                    DYNAMIC_TYPE_PKCS7);
     18607                    if (nextParam == NULL) {
     18608                        ret = MEMORY_E;
     18609                        goto error;
     18610                    }
     18611                    XMEMSET(nextParam, 0, (word32)sizeof(MimeParam));
     18612                }
     18613                mimeType = MIME_PARAM;
     18614                mimeStatus = MIME_NAMEATTR;
     18615                start = pos+1;
     18616            }
     18617        }
     18618
     18619        end = lineLen-1;
     18620        /* Omit newline characters. */
     18621        while ((curLine[end] == '\r' || curLine[end] == '\n') && end > 0) {
     18622            end--;
     18623        }
     18624        if (end >= start && mimeStatus == MIME_BODYVAL) {
     18625            ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
     18626            if (ret) {
     18627                goto error;
     18628            }
     18629            if (mimeType == MIME_HDR) {
     18630                nextHdr->name = nameAttr;
     18631                nextHdr->body = bodyVal;
     18632                nextHdr->next = curHdr;
     18633                curHdr = nextHdr;
     18634                nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
     18635                                            DYNAMIC_TYPE_PKCS7);
     18636                if (nextHdr == NULL) {
     18637                    ret = MEMORY_E;
     18638                    goto error;
     18639                }
     18640                XMEMSET(nextHdr, 0, (word32)sizeof(MimeHdr));
     18641            } else {
     18642                nextParam->attribute = nameAttr;
     18643                nextParam->value = bodyVal;
     18644                nextParam->next = curHdr->params;
     18645                curHdr->params = nextParam;
     18646                nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
     18647                                                DYNAMIC_TYPE_PKCS7);
     18648                if (nextParam == NULL) {
     18649                    ret = MEMORY_E;
     18650                    goto error;
     18651                }
     18652                XMEMSET(nextParam, 0, (word32)sizeof(MimeParam));
     18653            }
     18654        }
     18655
     18656        curLine = XSTRTOK(NULL, "\r\n", &ptr);
     18657        mimeStatus = MIME_NAMEATTR;
     18658    }
     18659
     18660    *headers = curHdr;
     18661    XFREE(nextHdr, NULL, DYNAMIC_TYPE_PKCS7);
     18662    XFREE(nextParam, NULL, DYNAMIC_TYPE_PKCS7);
     18663
     18664    return 0;
     18665
     18666error:
     18667    wc_MIME_free_hdrs(curHdr);
     18668    wc_MIME_free_hdrs(nextHdr);
     18669    XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
     18670    XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
     18671    XFREE(nextParam, NULL, DYNAMIC_TYPE_PKCS7);
     18672
     18673    return ret;
     18674}
     18675
     18676/*****************************************************************************
     18677* wc_MIME_header_strip - Reads the string in from indices start to end, strips
     18678* out disallowed/separator characters and places the rest into *out.
     18679*
     18680* RETURNS:
     18681* returns zero on success, non-zero on error.
     18682*/
     18683int wc_MIME_header_strip(char* in, char** out, size_t start, size_t end)
     18684{
     18685    size_t inPos = start;
     18686    size_t outPos = 0;
     18687    size_t inLen = 0;
     18688
     18689    if (end < start || in == NULL || out == NULL) {
     18690        return BAD_FUNC_ARG;
     18691    }
     18692
     18693    inLen = XSTRLEN(in);
     18694    if (start > inLen || end > inLen) {
     18695        return BAD_FUNC_ARG;
     18696    }
     18697
     18698    *out = (char*)XMALLOC(((end-start)+2)*sizeof(char), NULL,
     18699                          DYNAMIC_TYPE_PKCS7);
     18700    if (*out == NULL) {
     18701        return MEMORY_E;
     18702    }
     18703
     18704    while (inPos <= end) {
     18705        if (in[inPos] >= MIME_HEADER_ASCII_MIN && in[inPos] <=
     18706            MIME_HEADER_ASCII_MAX && in[inPos] != ';' && in[inPos] != '\"') {
     18707            (*out)[outPos] = in[inPos];
     18708            outPos++;
     18709        }
     18710        inPos++;
     18711    }
     18712    (*out)[outPos] = '\0';
     18713
     18714    return 0;
     18715}
     18716
     18717/*****************************************************************************
     18718* wc_MIME_find_header_name - Searches through all given headers until a header with
     18719* a name matching the provided name is found.
     18720*
     18721* RETURNS:
     18722* returns a pointer to the found header, if no match was found, returns NULL.
     18723*/
     18724MimeHdr* wc_MIME_find_header_name(const char* name, MimeHdr* header)
     18725{
     18726    size_t len = XSTRLEN(name);
     18727
     18728    while (header) {
     18729        if (!XSTRNCMP(name, header->name, len)) {
     18730            return header;
     18731        }
     18732        header = header->next;
     18733    }
     18734
     18735    return header;
     18736}
     18737
     18738/*****************************************************************************
     18739* wc_MIME_find_param_attr - Searches through all parameters until a parameter
     18740* with a attribute matching the provided attribute is found.
     18741*
     18742* RETURNS:
     18743* returns a pointer to the found parameter, if no match was found,
     18744* returns NULL.
     18745*/
     18746MimeParam* wc_MIME_find_param_attr(const char* attribute,
     18747                                    MimeParam* param)
     18748{
     18749    size_t len = XSTRLEN(attribute);
     18750
     18751    while (param) {
     18752        if (!XSTRNCMP(attribute, param->attribute, len)) {
     18753            return param;
     18754        }
     18755        param = param->next;
     18756    }
     18757
     18758    return param;
     18759}
     18760
     18761/*****************************************************************************
     18762* wc_MIME_free_hdrs - Frees all MIME headers, parameters and strings starting from
     18763* the provided header pointer.
     18764*
     18765* RETURNS:
     18766* returns zero on success, non-zero on error.
     18767*/
     18768int wc_MIME_free_hdrs(MimeHdr* head)
     18769{
     18770    MimeHdr* curHdr = NULL;
     18771    MimeParam* curParam = NULL;
     18772
     18773    while (head) {
     18774        while (head->params) {
     18775            curParam = head->params;
     18776            head->params = head->params->next;
     18777            XFREE(curParam->attribute, NULL, DYNAMIC_TYPE_PKCS7);
     18778            XFREE(curParam->value, NULL, DYNAMIC_TYPE_PKCS7);
     18779            XFREE(curParam, NULL, DYNAMIC_TYPE_PKCS7);
     18780        }
     18781        curHdr = head;
     18782        head = head->next;
     18783        XFREE(curHdr->name, NULL, DYNAMIC_TYPE_PKCS7);
     18784        XFREE(curHdr->body, NULL, DYNAMIC_TYPE_PKCS7);
     18785        XFREE(curHdr, NULL, DYNAMIC_TYPE_PKCS7);
     18786    }
     18787
     18788    return 0;
     18789}
     18790
     18791#endif /* HAVE_SMIME */
     18792
     18793
    1751818794#undef ERROR_OUT
    1751918795
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/blake2b.c

    r457 r464  
    4444#include <wolfssl/wolfcrypt/blake2.h>
    4545#include <wolfssl/wolfcrypt/blake2-impl.h>
     46#include <wolfssl/wolfcrypt/error-crypt.h>
    4647
    4748
     
    125126  blake2b_param P[1];
    126127
    127   if ( ( !outlen ) || ( outlen > BLAKE2B_OUTBYTES ) ) return -1;
     128  if ( ( !outlen ) || ( outlen > BLAKE2B_OUTBYTES ) ) return BAD_FUNC_ARG;
    128129
    129130#ifdef WOLFSSL_BLAKE2B_INIT_EACH_FIELD
     
    154155  blake2b_param P[1];
    155156
    156   if ( ( !outlen ) || ( outlen > BLAKE2B_OUTBYTES ) ) return -1;
    157 
    158   if ( !key || !keylen || keylen > BLAKE2B_KEYBYTES ) return -1;
     157  if ( ( !outlen ) || ( outlen > BLAKE2B_OUTBYTES ) ) return BAD_FUNC_ARG;
     158
     159  if ( !key || !keylen || keylen > BLAKE2B_KEYBYTES ) return BAD_FUNC_ARG;
    159160
    160161#ifdef WOLFSSL_BLAKE2B_INIT_EACH_FIELD
     
    178179#endif
    179180
    180   if( blake2b_init_param( S, P ) < 0 ) return -1;
     181  {
     182    int ret = blake2b_init_param( S, P );
     183    if ( ret < 0 ) return ret;
     184  }
    181185
    182186  {
     
    186190    block = (byte*)XMALLOC(BLAKE2B_BLOCKBYTES, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    187191
    188     if ( block == NULL ) return -1;
     192    if ( block == NULL ) return MEMORY_E;
    189193#else
    190194    byte block[BLAKE2B_BLOCKBYTES];
     
    204208}
    205209
    206 static int blake2b_compress( blake2b_state *S,
    207                              const byte block[BLAKE2B_BLOCKBYTES] )
     210static WC_INLINE int blake2b_compress(
     211    blake2b_state *S,
     212    const byte block[BLAKE2B_BLOCKBYTES],
     213    word64* m,
     214    word64* v)
    208215{
    209216  int i;
    210 
    211 #ifdef WOLFSSL_SMALL_STACK
    212   word64* m;
    213   word64* v;
    214 
    215   m = (word64*)XMALLOC(sizeof(word64) * 16, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    216 
    217   if ( m == NULL ) return -1;
    218 
    219   v = (word64*)XMALLOC(sizeof(word64) * 16, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    220 
    221   if ( v == NULL )
    222   {
    223     XFREE(m, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    224     return -1;
    225   }
    226 #else
    227   word64 m[16];
    228   word64 v[16];
    229 #endif
    230217
    231218  for( i = 0; i < 16; ++i )
     
    284271#undef ROUND
    285272
    286 #ifdef WOLFSSL_SMALL_STACK
    287   XFREE(m, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    288   XFREE(v, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    289 #endif
    290 
    291273  return 0;
    292274}
     
    295277int blake2b_update( blake2b_state *S, const byte *in, word64 inlen )
    296278{
     279  int ret = 0;
     280#ifdef WOLFSSL_SMALL_STACK
     281  word64* m;
     282  word64* v;
     283
     284  m = (word64*)XMALLOC(sizeof(word64) * 32, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     285
     286  if ( m == NULL ) return MEMORY_E;
     287
     288  v = &m[16];
     289#else
     290  word64 m[16];
     291  word64 v[16];
     292#endif
     293
    297294  while( inlen > 0 )
    298295  {
     
    306303      blake2b_increment_counter( S, BLAKE2B_BLOCKBYTES );
    307304
    308       if ( blake2b_compress( S, S->buf ) < 0 ) return -1; /* Compress */
     305      {
     306        ret = blake2b_compress( S, S->buf, m, v );
     307        if (ret < 0) break;
     308      }
    309309
    310310      XMEMCPY( S->buf, S->buf + BLAKE2B_BLOCKBYTES, BLAKE2B_BLOCKBYTES );
     
    322322  }
    323323
    324   return 0;
     324#ifdef WOLFSSL_SMALL_STACK
     325  XFREE(m, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     326#endif
     327
     328  return ret;
    325329}
    326330
     
    328332int blake2b_final( blake2b_state *S, byte *out, byte outlen )
    329333{
     334  int ret = 0;
    330335  byte buffer[BLAKE2B_OUTBYTES];
    331336  int     i;
     337#ifdef WOLFSSL_SMALL_STACK
     338  word64* m;
     339  word64* v;
     340
     341  m = (word64*)XMALLOC(sizeof(word64) * 32, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     342
     343  if ( m == NULL ) return MEMORY_E;
     344
     345  v = &m[16];
     346#else
     347  word64 m[16];
     348  word64 v[16];
     349#endif
    332350
    333351  if( S->buflen > BLAKE2B_BLOCKBYTES )
     
    335353    blake2b_increment_counter( S, BLAKE2B_BLOCKBYTES );
    336354
    337     if ( blake2b_compress( S, S->buf ) < 0 ) return -1;
     355    {
     356      ret = blake2b_compress( S, S->buf, m, v );
     357      if (ret < 0) goto out;
     358    }
    338359
    339360    S->buflen -= BLAKE2B_BLOCKBYTES;
     
    345366  XMEMSET( S->buf + S->buflen, 0, (wolfssl_word)(2 * BLAKE2B_BLOCKBYTES - S->buflen) );
    346367         /* Padding */
    347   if ( blake2b_compress( S, S->buf ) < 0 ) return -1;
     368  {
     369    ret = blake2b_compress( S, S->buf, m, v );
     370    if (ret < 0) goto out;
     371  }
    348372
    349373  for( i = 0; i < 8; ++i ) /* Output full hash to temp buffer */
     
    351375
    352376  XMEMCPY( out, buffer, outlen );
    353   return 0;
     377
     378 out:
     379
     380#ifdef WOLFSSL_SMALL_STACK
     381  XFREE(m, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     382#endif
     383
     384  return ret;
    354385}
    355386
     
    361392
    362393  /* Verify parameters */
    363   if ( NULL == in ) return -1;
    364 
    365   if ( NULL == out ) return -1;
     394  if ( NULL == in ) return BAD_FUNC_ARG;
     395
     396  if ( NULL == out ) return BAD_FUNC_ARG;
    366397
    367398  if( NULL == key ) keylen = 0;
     
    369400  if( keylen > 0 )
    370401  {
    371     if( blake2b_init_key( S, outlen, key, keylen ) < 0 ) return -1;
     402    int ret = blake2b_init_key( S, outlen, key, keylen );
     403    if (ret < 0) return ret;
    372404  }
    373405  else
    374406  {
    375     if( blake2b_init( S, outlen ) < 0 ) return -1;
    376   }
    377 
    378   if ( blake2b_update( S, ( byte * )in, inlen ) < 0) return -1;
     407    int ret = blake2b_init( S, outlen );
     408    if (ret < 0) return ret;
     409  }
     410
     411  {
     412    int ret = blake2b_update( S, ( byte * )in, inlen );
     413    if (ret < 0) return ret;
     414  }
    379415
    380416  return blake2b_final( S, out, outlen );
     
    423459{
    424460    if (b2b == NULL){
    425         return -1;
     461        return BAD_FUNC_ARG;
    426462    }
    427463    b2b->digestSz = digestSz;
     
    430466}
    431467
     468/* Init Blake2b digest with key, track size in case final doesn't want to "remember" */
     469int wc_InitBlake2b_WithKey(Blake2b* b2b, word32 digestSz, const byte *key, word32 keylen)
     470{
     471    if (b2b == NULL){
     472        return BAD_FUNC_ARG;
     473    }
     474    b2b->digestSz = digestSz;
     475
     476    if (keylen >= 256)
     477        return BAD_FUNC_ARG;
     478
     479    if (key)
     480        return blake2b_init_key(b2b->S, (byte)digestSz, key, (byte)keylen);
     481    else
     482        return blake2b_init(b2b->S, (byte)digestSz);
     483}
    432484
    433485/* Blake2b Update */
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/coding.c

    r457 r464  
    3232#include <wolfssl/wolfcrypt/error-crypt.h>
    3333#include <wolfssl/wolfcrypt/logging.h>
    34 
     34#ifndef NO_ASN
     35    #include <wolfssl/wolfcrypt/asn.h> /* For PEM_LINE_SZ */
     36#endif
     37#ifdef NO_INLINE
     38    #include <wolfssl/wolfcrypt/misc.h>
     39#else
     40    #define WOLFSSL_MISC_INCLUDED
     41    #include <wolfcrypt/src/misc.c>
     42#endif
    3543
    3644enum {
    3745    BAD         = 0xFF,  /* invalid encoding */
    3846    PAD         = '=',
    39     PEM_LINE_SZ = 64,
    4047    BASE64_MIN  = 0x2B,
    4148    BASE16_MIN  = 0x30,
     
    4350
    4451
     52#ifndef BASE64_LINE_SZ
     53    #ifdef NO_ASN
     54        #define BASE64_LINE_SZ 64
     55    #else
     56        #define BASE64_LINE_SZ PEM_LINE_SZ
     57    #endif
     58#endif
     59
    4560#ifdef WOLFSSL_BASE64_DECODE
    4661
     62#ifdef BASE64_NO_TABLE
     63static WC_INLINE byte Base64_Char2Val(byte c)
     64{
     65    word16 v = 0x0000;
     66
     67    v |= 0xff3E & ctMask16Eq(c, 0x2b);
     68    v |= 0xff3F & ctMask16Eq(c, 0x2f);
     69    v |= (c + 0xff04) & ctMask16GTE(c, 0x30) & ctMask16LTE(c, 0x39);
     70    v |= (0xff00 + c - 0x41) & ctMask16GTE(c, 0x41) & ctMask16LTE(c, 0x5a);
     71    v |= (0xff00 + c - 0x47) & ctMask16GTE(c, 0x61) & ctMask16LTE(c, 0x7a);
     72    v |= ~(v >> 8);
     73
     74    return (byte)v;
     75}
     76#else
    4777static
    48 const byte base64Decode[] = { 62, BAD, BAD, BAD, 63,   /* + starts at 0x2B */
    49                               52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
    50                               BAD, BAD, BAD, BAD, BAD, BAD, BAD,
    51                               0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
    52                               10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
    53                               20, 21, 22, 23, 24, 25,
    54                               BAD, BAD, BAD, BAD, BAD, BAD,
    55                               26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
    56                               36, 37, 38, 39, 40, 41, 42, 43, 44, 45,
    57                               46, 47, 48, 49, 50, 51
     78ALIGN64 const byte base64Decode[] = {          /* + starts at 0x2B */
     79/* 0x28:       + , - . / */                   62, BAD, BAD, BAD,  63,
     80/* 0x30: 0 1 2 3 4 5 6 7 */    52,  53,  54,  55,  56,  57,  58,  59,
     81/* 0x38: 8 9 : ; < = > ? */    60,  61, BAD, BAD, BAD, BAD, BAD, BAD,
     82/* 0x40: @ A B C D E F G */   BAD,   0,   1,   2,   3,   4,   5,   6,
     83/* 0x48: H I J K L M N O */     7,   8,   9,  10,  11,  12,  13,  14,
     84/* 0x50: P Q R S T U V W */    15,  16,  17,  18,  19,  20,  21,  22,
     85/* 0x58: X Y Z [ \ ] ^ _ */    23,  24,  25, BAD, BAD, BAD, BAD, BAD,
     86/* 0x60: ` a b c d e f g */   BAD,  26,  27,  28,  29,  30,  31,  32,
     87/* 0x68: h i j k l m n o */    33,  34,  35,  36,  37,  38,  39,  40,
     88/* 0x70: p q r s t u v w */    41,  42,  43,  44,  45,  46,  47,  48,
     89/* 0x78: x y z           */    49,  50,  51
    5890                            };
     91#define BASE64DECODE_SZ    (byte)(sizeof(base64Decode))
     92
     93static WC_INLINE byte Base64_Char2Val(byte c)
     94{
     95#ifndef WC_NO_CACHE_RESISTANT
     96    /* 80 characters in table.
     97     * 64 bytes in a cache line - first line has 64, second has 16
     98     */
     99    byte v;
     100    byte mask;
     101
     102    c -= BASE64_MIN;
     103    mask = (((byte)(0x3f - c)) >> 7) - 1;
     104    /* Load a value from the first cache line and use when mask set. */
     105    v  = base64Decode[ c & 0x3f        ] &   mask ;
     106    /* Load a value from the second cache line and use when mask not set. */
     107    v |= base64Decode[(c & 0x0f) | 0x40] & (~mask);
     108
     109    return v;
     110#else
     111    return base64Decode[c - BASE64_MIN];
     112#endif
     113}
     114#endif
    59115
    60116static WC_INLINE int Base64_SkipNewline(const byte* in, word32 *inLen, word32 *outJ)
     
    92148    word32 i = 0;
    93149    word32 j = 0;
    94     word32 plainSz = inLen - ((inLen + (PEM_LINE_SZ - 1)) / PEM_LINE_SZ );
     150    word32 plainSz = inLen - ((inLen + (BASE64_LINE_SZ - 1)) / BASE64_LINE_SZ );
    95151    int ret;
    96     const byte maxIdx = (byte)sizeof(base64Decode) + BASE64_MIN - 1;
     152#ifndef BASE64_NO_TABLE
     153    const byte maxIdx = BASE64DECODE_SZ + BASE64_MIN - 1;
     154#endif
    97155
    98156    plainSz = (plainSz * 3 + 3) / 4;
     
    102160        int pad3 = 0;
    103161        int pad4 = 0;
    104 
    105162        byte b1, b2, b3;
    106163        byte e1, e2, e3, e4;
     164
    107165        if ((ret = Base64_SkipNewline(in, &inLen, &j)) != 0) {
    108166            if (ret == BUFFER_E) {
     
    133191        inLen--;
    134192
    135         if (e1 == 0)            /* end file 0's */
    136             break;
    137193        if (e3 == PAD)
    138194            pad3 = 1;
     
    140196            pad4 = 1;
    141197
    142         if (e1 < BASE64_MIN || e2 < BASE64_MIN || e3 < BASE64_MIN || e4 < BASE64_MIN) {
     198        if (pad3 && !pad4)
     199            return ASN_INPUT_E;
     200
     201#ifndef BASE64_NO_TABLE
     202        if (e1 < BASE64_MIN || e2 < BASE64_MIN || e3 < BASE64_MIN ||
     203                                                              e4 < BASE64_MIN) {
    143204            WOLFSSL_MSG("Bad Base64 Decode data, too small");
    144205            return ASN_INPUT_E;
     
    149210            return ASN_INPUT_E;
    150211        }
     212#endif
    151213
    152214        if (i + 1 + !pad3 + !pad4 > *outLen) {
     
    155217        }
    156218
    157         e1 = base64Decode[e1 - BASE64_MIN];
    158         e2 = base64Decode[e2 - BASE64_MIN];
    159         e3 = (e3 == PAD) ? 0 : base64Decode[e3 - BASE64_MIN];
    160         e4 = (e4 == PAD) ? 0 : base64Decode[e4 - BASE64_MIN];
     219        e1 = Base64_Char2Val(e1);
     220        e2 = Base64_Char2Val(e2);
     221        e3 = (e3 == PAD) ? 0 : Base64_Char2Val(e3);
     222        e4 = (e4 == PAD) ? 0 : Base64_Char2Val(e4);
     223
     224        if (e1 == BAD || e2 == BAD || e3 == BAD || e4 == BAD) {
     225            WOLFSSL_MSG("Bad Base64 Decode bad character");
     226            return ASN_INPUT_E;
     227        }
    161228
    162229        b1 = (byte)((e1 << 2) | (e2 >> 4));
     
    199266/* make sure *i (idx) won't exceed max, store and possibly escape to out,
    200267 * raw means use e w/o decode,  0 on success */
    201 static int CEscape(int escaped, byte e, byte* out, word32* i, word32 max,
     268static int CEscape(int escaped, byte e, byte* out, word32* i, word32 maxSz,
    202269                  int raw, int getSzOnly)
    203270{
     
    241308
    242309    /* check size */
    243     if ( (idx+needed) > max && !getSzOnly) {
     310    if ( (idx+needed) > maxSz && !getSzOnly) {
    244311        WOLFSSL_MSG("Escape buffer max too small");
    245312        return BUFFER_E;
     
    292359
    293360    word32 outSz = (inLen + 3 - 1) / 3 * 4;
    294     word32 addSz = (outSz + PEM_LINE_SZ - 1) / PEM_LINE_SZ;  /* new lines */
     361    word32 addSz = (outSz + BASE64_LINE_SZ - 1) / BASE64_LINE_SZ;  /* new lines */
    295362
    296363    if (escaped == WC_ESC_NL_ENC)
     
    329396        inLen -= 3;
    330397
    331         /* Insert newline after PEM_LINE_SZ, unless no \n requested */
    332         if (escaped != WC_NO_NL_ENC && (++n % (PEM_LINE_SZ/4)) == 0 && inLen) {
     398        /* Insert newline after BASE64_LINE_SZ, unless no \n requested */
     399        if (escaped != WC_NO_NL_ENC && (++n % (BASE64_LINE_SZ/4)) == 0 && inLen) {
    333400            ret = CEscape(escaped, '\n', out, &i, *outLen, 1, getSzOnly);
    334401            if (ret != 0) break;
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/des3.c

    r457 r464  
    346346    }
    347347
    348     static void Des3Crypt(Des3* des, byte* out, const byte* in, word32 sz,
     348    static int Des3Crypt(Des3* des, byte* out, const byte* in, word32 sz,
    349349                   int dir)
    350350    {
     
    461461        }
    462462    #endif /* WOLFSSL_STM32_CUBEMX */
     463        return 0;
    463464    }
    464465
    465466    int wc_Des3_CbcEncrypt(Des3* des, byte* out, const byte* in, word32 sz)
    466467    {
    467         Des3Crypt(des, out, in, sz, DES_ENCRYPTION);
    468         return 0;
     468        return Des3Crypt(des, out, in, sz, DES_ENCRYPTION);
    469469    }
    470470
    471471    int wc_Des3_CbcDecrypt(Des3* des, byte* out, const byte* in, word32 sz)
    472472    {
    473         Des3Crypt(des, out, in, sz, DES_DECRYPTION);
    474         return 0;
     473        return Des3Crypt(des, out, in, sz, DES_DECRYPTION);
    475474    }
    476475
     
    11721171
    11731172    /* permuted choice table (key) */
    1174     static const byte pc1[] = {
     1173    static const FLASH_QUALIFIER byte pc1[] = {
    11751174           57, 49, 41, 33, 25, 17,  9,
    11761175            1, 58, 50, 42, 34, 26, 18,
     
    11851184
    11861185    /* number left rotations of pc1 */
    1187     static const byte totrot[] = {
     1186    static const FLASH_QUALIFIER byte totrot[] = {
    11881187           1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28
    11891188    };
    11901189
    11911190    /* permuted choice key (table) */
    1192     static const byte pc2[] = {
     1191    static const FLASH_QUALIFIER byte pc2[] = {
    11931192           14, 17, 11, 24,  1,  5,
    11941193            3, 28, 15,  6, 21, 10,
     
    12041203
    12051204    /* bit 0 is left-most in byte */
    1206     static const int bytebit[] = {
     1205    static const FLASH_QUALIFIER int bytebit[] = {
    12071206        0200,0100,040,020,010,04,02,01
    12081207    };
    12091208
    1210     static const word32 Spbox[8][64] = {
     1209    static const FLASH_QUALIFIER word32 Spbox[8][64] = {
    12111210    {   0x01010400,0x00000000,0x00010000,0x01010404,
    12121211        0x01010004,0x00010404,0x00000004,0x00010000,
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/dh.c

    r457 r464  
    931931    key->heap = heap; /* for XMALLOC/XFREE in future */
    932932
    933 #if !defined(WOLFSSL_QT) && !defined(OPENSSL_ALL)
     933#ifdef WOLFSSL_DH_EXTRA
     934    if (mp_init_multi(&key->p, &key->g, &key->q, &key->pub, &key->priv, NULL) != MP_OKAY)
     935#else
    934936    if (mp_init_multi(&key->p, &key->g, &key->q, NULL, NULL, NULL) != MP_OKAY)
    935 #else
    936     if (mp_init_multi(&key->p,&key->g,&key->q,&key->pub,&key->priv,NULL) != MP_OKAY)
    937937#endif
    938938        return MEMORY_E;
     
    961961        mp_clear(&key->g);
    962962        mp_clear(&key->q);
     963    #ifdef WOLFSSL_DH_EXTRA
     964        mp_clear(&key->pub);
     965        mp_forcezero(&key->priv);
     966    #endif
    963967
    964968    #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_DH)
     
    11491153
    11501154    mp_forcezero(tmpX);
    1151     mp_clear(tmpX);
    11521155    mp_clear(tmpQ);
    11531156#ifdef WOLFSSL_SMALL_STACK
     
    12071210        }
    12081211
    1209         ret = wc_RNG_GenerateBlock(rng, priv, sz);
     1212        if (sz > *privSz)
     1213            ret = WC_KEY_SIZE_E;
     1214
     1215        if (ret == 0)
     1216            ret = wc_RNG_GenerateBlock(rng, priv, sz);
    12101217
    12111218        if (ret == 0) {
     
    12311238    int ret = 0;
    12321239#ifndef WOLFSSL_SP_MATH
     1240    word32 binSz = 0;
    12331241#ifdef WOLFSSL_SMALL_STACK
    12341242    mp_int* x;
     
    12551263#endif
    12561264
    1257 #ifndef WOLFSSL_SP_MATH
     1265#if !defined(WOLFSSL_SP_MATH)
    12581266#ifdef WOLFSSL_SMALL_STACK
    12591267    x = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_DH);
     
    12801288        ret = MP_EXPTMOD_E;
    12811289
     1290    if (ret == 0) {
     1291        binSz = mp_unsigned_bin_size(y);
     1292        if (binSz > *pubSz) {
     1293            ret = WC_KEY_SIZE_E;
     1294        }
     1295    }
     1296
    12821297    if (ret == 0 && mp_to_unsigned_bin(y, pub) != MP_OKAY)
    12831298        ret = MP_TO_E;
    12841299
    12851300    if (ret == 0)
    1286         *pubSz = mp_unsigned_bin_size(y);
     1301        *pubSz = binSz;
    12871302
    12881303    mp_clear(y);
     
    14681483    }
    14691484
     1485    /* SP 800-56Ar3, section 5.6.2.3.1, process step 2 */
    14701486    if (ret == 0 && prime != NULL) {
    14711487#ifdef WOLFSSL_HAVE_SP_DH
     
    14861502        else
    14871503#endif
    1488 #ifdef WOLFSSL_SP_NO_4096
     1504#ifdef WOLFSSL_SP_4096
    14891505        if (mp_count_bits(&key->p) == 4096) {
    14901506            ret = sp_ModExp_4096(y, q, p, y);
     
    14971513
    14981514        {
    1499     /* SP 800-56Ar3, section 5.6.2.3.1, process step 2 */
    1500 #ifndef WOLFSSL_SP_MATH
     1515#if !defined(WOLFSSL_SP_MATH)
    15011516            /* calculate (y^q) mod(p), store back into y */
    15021517            if (mp_exptmod(y, q, p, y) != MP_OKAY)
     
    17831798#endif
    17841799        {
    1785 #ifndef WOLFSSL_SP_MATH
     1800#if !defined(WOLFSSL_SP_MATH)
    17861801            if (mp_exptmod(&key->g, privateKey, &key->p, checkKey) != MP_OKAY)
    17871802                ret = MP_EXPTMOD_E;
     
    17991814
    18001815    mp_forcezero(privateKey);
    1801     mp_clear(privateKey);
    18021816    mp_clear(publicKey);
    18031817    mp_clear(checkKey);
     
    18351849}
    18361850
    1837 
    18381851static int wc_DhAgree_Sync(DhKey* key, byte* agree, word32* agreeSz,
    18391852    const byte* priv, word32 privSz, const byte* otherPub, word32 pubSz)
     
    18411854    int ret = 0;
    18421855#ifdef WOLFSSL_SMALL_STACK
    1843     mp_int* y;
    1844 #ifndef WOLFSSL_SP_MATH
    1845     mp_int* x;
    1846     mp_int* z;
     1856    mp_int* y = NULL;
     1857#if !defined(WOLFSSL_SP_MATH)
     1858    mp_int* x = NULL;
     1859    mp_int* z = NULL;
    18471860#endif
    18481861#else
    18491862    mp_int y[1];
    1850 #ifndef WOLFSSL_SP_MATH
     1863#if !defined(WOLFSSL_SP_MATH)
    18511864    mp_int x[1];
    18521865    mp_int z[1];
     
    18701883    if (y == NULL)
    18711884        return MEMORY_E;
    1872 #ifndef WOLFSSL_SP_MATH
     1885#if !defined(WOLFSSL_SP_MATH)
    18731886    x = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_DH);
    18741887    if (x == NULL) {
     
    18991912        mp_clear(y);
    19001913    #ifdef WOLFSSL_SMALL_STACK
    1901     #ifndef WOLFSSL_SP_MATH
     1914    #if !defined(WOLFSSL_SP_MATH)
    19021915        XFREE(z, key->heap, DYNAMIC_TYPE_DH);
    19031916        XFREE(x, key->heap, DYNAMIC_TYPE_DH);
     
    19211934        mp_clear(y);
    19221935    #ifdef WOLFSSL_SMALL_STACK
    1923     #ifndef WOLFSSL_SP_MATH
     1936    #if !defined(WOLFSSL_SP_MATH)
    19241937        XFREE(z, key->heap, DYNAMIC_TYPE_DH);
    19251938        XFREE(x, key->heap, DYNAMIC_TYPE_DH);
     
    19431956        mp_clear(y);
    19441957    #ifdef WOLFSSL_SMALL_STACK
    1945     #ifndef WOLFSSL_SP_MATH
     1958    #if !defined(WOLFSSL_SP_MATH)
    19461959        XFREE(z, key->heap, DYNAMIC_TYPE_DH);
    19471960        XFREE(x, key->heap, DYNAMIC_TYPE_DH);
     
    19541967#endif
    19551968
    1956 #ifndef WOLFSSL_SP_MATH
     1969#if !defined(WOLFSSL_SP_MATH)
    19571970    if (mp_init_multi(x, y, z, 0, 0, 0) != MP_OKAY) {
    19581971    #ifdef WOLFSSL_SMALL_STACK
     
    19861999    mp_clear(y);
    19872000    mp_forcezero(x);
     2001#else
     2002    ret = WC_KEY_SIZE_E;
    19882003#endif
    19892004
    19902005#ifdef WOLFSSL_SMALL_STACK
    1991 #ifndef WOLFSSL_SP_MATH
     2006#if !defined(WOLFSSL_SP_MATH)
    19922007    XFREE(z, key->heap, DYNAMIC_TYPE_DH);
    19932008    XFREE(x, key->heap, DYNAMIC_TYPE_DH);
     
    20662081}
    20672082
    2068 #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL)
     2083#ifdef WOLFSSL_DH_EXTRA
     2084WOLFSSL_LOCAL int wc_DhKeyCopy(DhKey* src, DhKey* dst)
     2085{
     2086    int ret;
     2087
     2088    if (!src || !dst || src == dst) {
     2089        WOLFSSL_MSG("Parameters not provided or are the same");
     2090        return BAD_FUNC_ARG;
     2091    }
     2092
     2093    if ((ret = mp_copy(&src->p, &dst->p)) != MP_OKAY) {
     2094        WOLFSSL_MSG("mp_copy error");
     2095        return ret;
     2096    }
     2097
     2098    if ((ret = mp_copy(&src->g, &dst->g)) != MP_OKAY) {
     2099        WOLFSSL_MSG("mp_copy error");
     2100        return ret;
     2101    }
     2102
     2103    if ((ret = mp_copy(&src->q, &dst->q)) != MP_OKAY) {
     2104        WOLFSSL_MSG("mp_copy error");
     2105        return ret;
     2106    }
     2107
     2108    if ((ret = mp_copy(&src->pub, &dst->pub)) != MP_OKAY) {
     2109        WOLFSSL_MSG("mp_copy error");
     2110        return ret;
     2111    }
     2112
     2113    if ((ret = mp_copy(&src->priv, &dst->priv)) != MP_OKAY) {
     2114        WOLFSSL_MSG("mp_copy error");
     2115        return ret;
     2116    }
     2117
     2118    dst->heap = src->heap;
     2119
     2120    return MP_OKAY;
     2121}
     2122
    20692123/* Sets private and public key in DhKey if both are available, otherwise sets
    2070     either private or public key, depending on which is available.
    2071     Returns WOLFSSL_SUCCESS if at least one of the keys was set. */
    2072 WOLFSSL_LOCAL int wc_DhSetFullKeys(DhKey* key,const byte* priv_key,word32 privSz,
    2073                                    const byte* pub_key, word32 pubSz)
    2074 {
    2075     byte havePriv = 0;
    2076     byte havePub = 0;
    2077     mp_int* keyPriv = NULL;
    2078     mp_int* keyPub  = NULL;
     2124    either private or public key, depending on which is available. */
     2125int wc_DhImportKeyPair(DhKey* key, const byte* priv, word32 privSz,
     2126                       const byte* pub, word32 pubSz)
     2127{
     2128    byte havePriv, havePub;
     2129    mp_int *keyPriv = NULL, *keyPub  = NULL;
    20792130
    20802131    if (key == NULL) {
     
    20822133    }
    20832134
    2084     havePriv = ( (priv_key != NULL) && (privSz > 0) );
    2085     havePub  = ( (pub_key  != NULL) && (pubSz  > 0) );
     2135    havePriv = ( (priv != NULL) && (privSz > 0) );
     2136    havePub  = ( (pub  != NULL) && (pubSz  > 0) );
    20862137
    20872138    if (!havePub && !havePriv) {
     
    20892140        return BAD_FUNC_ARG;
    20902141    }
     2142
    20912143    /* Set Private Key */
    2092     if (havePriv == TRUE) {
     2144    if (havePriv) {
    20932145        /* may have leading 0 */
    2094         if (priv_key[0] == 0) {
    2095             privSz--; priv_key++;
     2146        if (priv[0] == 0) {
     2147            privSz--; priv++;
    20962148        }
    20972149        if (mp_init(&key->priv) != MP_OKAY)
    2098             havePriv = FALSE;
    2099     }
    2100 
    2101     if (havePriv == TRUE) {
    2102         if (mp_read_unsigned_bin(&key->priv, priv_key, privSz) != MP_OKAY) {
    2103             havePriv = FALSE;
     2150            havePriv = 0;
     2151    }
     2152    if (havePriv) {
     2153        if (mp_read_unsigned_bin(&key->priv, priv, privSz) != MP_OKAY) {
     2154            mp_clear(&key->priv);
     2155            havePriv = 0;
    21042156        } else {
    21052157            keyPriv = &key->priv;
    2106             WOLFSSL_MSG("DH Private Key Set.");
     2158            WOLFSSL_MSG("DH Private Key Set");
    21072159        }
    21082160    }
    21092161
    21102162    /* Set Public Key */
    2111     if (havePub == TRUE) {
     2163    if (havePub) {
    21122164        /* may have leading 0 */
    2113         if (pub_key[0] == 0) {
    2114             pubSz--; pub_key++;
     2165        if (pub[0] == 0) {
     2166            pubSz--; pub++;
    21152167        }
    21162168        if (mp_init(&key->pub) != MP_OKAY)
    2117             havePub = FALSE;
    2118     }
    2119 
    2120     if (havePub == TRUE) {
    2121         if (mp_read_unsigned_bin(&key->pub, pub_key, pubSz) != MP_OKAY) {
    2122             havePub = FALSE;
     2169            havePub = 0;
     2170    }
     2171    if (havePub) {
     2172        if (mp_read_unsigned_bin(&key->pub, pub, pubSz) != MP_OKAY) {
     2173            mp_clear(&key->pub);
     2174            havePub = 0;
    21232175        } else {
    21242176            keyPub = &key->pub;
    2125             WOLFSSL_MSG("DH Public Key Set.");
    2126         }
    2127     }
    2128     /* Free Memory if error occured */
    2129     if (havePriv == FALSE && keyPriv != NULL)
     2177            WOLFSSL_MSG("DH Public Key Set");
     2178        }
     2179    }
     2180    /* Free Memory if error occurred */
     2181    if (havePriv == 0 && keyPriv != NULL)
    21302182        mp_clear(keyPriv);
    2131     if (havePub == FALSE && keyPub != NULL)
     2183    if (havePub == 0 && keyPub != NULL)
    21322184        mp_clear(keyPub);
    21332185
    2134     /* WOLFSSL_SUCCESS if private or public was set else WOLFSSL_FAILURE */
    2135     return havePriv || havePub;
    2136 }
    2137 #endif
     2186    if (havePriv == 0 && havePub == 0) {
     2187        return MEMORY_E;
     2188    }
     2189
     2190    return 0;
     2191}
     2192
     2193/* Can be used with WOLFSSL_DH_EXTRA when key is loaded with
     2194    wc_DhKeyDecode or wc_DhImportKeyPair */
     2195int wc_DhExportKeyPair(DhKey* key, byte* priv, word32* pPrivSz,
     2196    byte* pub, word32* pPubSz)
     2197{
     2198    int ret = 0;
     2199    word32 pubSz, privSz;
     2200
     2201    if (key == NULL || (priv && pPrivSz == NULL) || (pub && pPubSz == NULL)) {
     2202        return BAD_FUNC_ARG;
     2203    }
     2204
     2205    if (priv) {
     2206        privSz = mp_unsigned_bin_size(&key->priv);
     2207        if (privSz > *pPrivSz) {
     2208            return BUFFER_E;
     2209        }
     2210        *pPrivSz = privSz;
     2211        ret |= mp_to_unsigned_bin(&key->priv, priv);
     2212    }
     2213
     2214    if (pub) {
     2215        pubSz = mp_unsigned_bin_size(&key->pub);
     2216        if (pubSz > *pPubSz) {
     2217            return BUFFER_E;
     2218        }
     2219        *pPubSz = pubSz;
     2220        ret |= mp_to_unsigned_bin(&key->pub,  pub);
     2221    }
     2222
     2223    if (ret != 0)
     2224        ret = ASN_DH_KEY_E;
     2225    return ret;
     2226}
     2227
     2228#endif /* WOLFSSL_DH_EXTRA */
    21382229
    21392230static int _DhSetKey(DhKey* key, const byte* p, word32 pSz, const byte* g,
     
    23682459    if (ret == 0) {
    23692460        /* at this point tmp generates a group of order q mod p */
     2461#ifndef USE_FAST_MATH
     2462        /* Exchanging is quick when the data pointer can be copied. */
    23702463        mp_exch(&tmp, &dh->g);
     2464#else
     2465        mp_copy(&tmp, &dh->g);
     2466#endif
    23712467    }
    23722468
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/dsa.c

    r457 r464  
    4141    #define WOLFSSL_MISC_INCLUDED
    4242    #include <wolfcrypt/src/misc.c>
     43#endif
     44
     45#ifdef _MSC_VER
     46    /* disable for while(0) cases (MSVC bug) */
     47    #pragma warning(disable:4127)
    4348#endif
    4449
     
    408413
    409414    /* at this point tmp generates a group of order q mod p */
     415#ifndef USE_FAST_MATH
     416    /* Exchanging is quick when the data pointer can be copied. */
    410417    mp_exch(&tmp, &dsa->g);
     418#else
     419    mp_copy(&tmp, &dsa->g);
     420#endif
    411421
    412422    mp_clear(&tmp);
     
    655665int wc_DsaSign(const byte* digest, byte* out, DsaKey* key, WC_RNG* rng)
    656666{
    657     mp_int  k, kInv, r, s, H;
     667#ifdef WOLFSSL_SMALL_STACK
     668    mp_int  *k = (mp_int *)XMALLOC(sizeof *k,
     669                                   key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     670    mp_int  *kInv = (mp_int *)XMALLOC(sizeof *kInv,
     671                                   key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     672    mp_int  *r = (mp_int *)XMALLOC(sizeof *r,
     673                                   key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     674    mp_int  *s = (mp_int *)XMALLOC(sizeof *s,
     675                                   key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     676    mp_int  *H = (mp_int *)XMALLOC(sizeof *H,
     677                                   key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    658678#ifndef WOLFSSL_MP_INVMOD_CONSTANT_TIME
    659     mp_int  b;
     679    mp_int  *b = (mp_int *)XMALLOC(sizeof *b,
     680                                   key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     681#endif
     682    byte    *buffer = (byte *)XMALLOC(DSA_HALF_SIZE, key->heap,
     683                                      DYNAMIC_TYPE_TMP_BUFFER);
     684#else
     685    mp_int  k[1], kInv[1], r[1], s[1], H[1];
     686#ifndef WOLFSSL_MP_INVMOD_CONSTANT_TIME
     687    mp_int  b[1];
     688#endif
     689    byte    buffer[DSA_HALF_SIZE];
    660690#endif
    661691    mp_int* qMinus1;
    662     int     ret = 0, sz;
    663     byte    buffer[DSA_HALF_SIZE];
     692    int     ret = 0, sz = 0;
    664693    byte*   tmp;  /* initial output pointer */
    665694
    666     if (digest == NULL || out == NULL || key == NULL || rng == NULL) {
    667         return BAD_FUNC_ARG;
    668     }
    669 
    670     tmp = out;
    671 
    672     sz = min((int)sizeof(buffer), mp_unsigned_bin_size(&key->q));
    673 
     695    do {
    674696#ifdef WOLFSSL_MP_INVMOD_CONSTANT_TIME
    675     if (mp_init_multi(&k, &kInv, &r, &s, &H, 0) != MP_OKAY)
     697        if (mp_init_multi(k, kInv, r, s, H, 0) != MP_OKAY)
    676698#else
    677     if (mp_init_multi(&k, &kInv, &r, &s, &H, &b) != MP_OKAY)
    678 #endif
    679     {
    680         return MP_INIT_E;
    681     }
    682     qMinus1 = &kInv;
    683 
    684     /* NIST FIPS 186-4: B.2.2
    685      * Per-Message Secret Number Generation by Testing Candidates
    686      * Generate k in range [1, q-1].
    687      *   Check that k is less than q-1: range [0, q-2].
    688      *   Add 1 to k: range [1, q-1].
    689      */
    690     if (mp_sub_d(&key->q, 1, qMinus1))
    691         ret = MP_SUB_E;
    692 
    693     if (ret == 0) {
     699            if (mp_init_multi(k, kInv, r, s, H, b) != MP_OKAY)
     700#endif
     701                {
     702                    ret = MP_INIT_E;
     703                    break;
     704                }
     705
     706#ifdef WOLFSSL_SMALL_STACK
     707        if ((k == NULL) ||
     708            (kInv == NULL) ||
     709            (r == NULL) ||
     710            (s == NULL) ||
     711            (H == NULL)
     712#ifndef WOLFSSL_MP_INVMOD_CONSTANT_TIME
     713            || (b == NULL)
     714#endif
     715            || (buffer == NULL)) {
     716            ret = MEMORY_E;
     717            break;
     718        }
     719#endif
     720
     721        if (digest == NULL || out == NULL || key == NULL || rng == NULL) {
     722            ret = BAD_FUNC_ARG;
     723            break;
     724        }
     725
     726        sz = min(DSA_HALF_SIZE, mp_unsigned_bin_size(&key->q));
     727        tmp = out;
     728        qMinus1 = kInv;
     729
     730        /* NIST FIPS 186-4: B.2.2
     731         * Per-Message Secret Number Generation by Testing Candidates
     732         * Generate k in range [1, q-1].
     733         *   Check that k is less than q-1: range [0, q-2].
     734         *   Add 1 to k: range [1, q-1].
     735         */
     736        if (mp_sub_d(&key->q, 1, qMinus1)) {
     737            ret = MP_SUB_E;
     738            break;
     739        }
     740
    694741        do {
    695742            /* Step 4: generate k */
    696             ret = wc_RNG_GenerateBlock(rng, buffer, sz);
     743            if ((ret = wc_RNG_GenerateBlock(rng, buffer, sz))) {
     744                break;
     745            }
    697746
    698747            /* Step 5 */
    699             if (ret == 0 && mp_read_unsigned_bin(&k, buffer, sz) != MP_OKAY)
     748            if (mp_read_unsigned_bin(k, buffer, sz) != MP_OKAY) {
    700749                ret = MP_READ_E;
     750                break;
     751            }
    701752
    702753            /* k is a random numnber and it should be less than q-1
    703754             * if k greater than repeat
    704755             */
    705         /* Step 6 */
    706         } while (ret == 0 && mp_cmp(&k, qMinus1) != MP_LT);
    707     }
    708     /* Step 7 */
    709     if (ret == 0 && mp_add_d(&k, 1, &k) != MP_OKAY)
    710         ret = MP_MOD_E;
     756            /* Step 6 */
     757        } while (mp_cmp(k, qMinus1) != MP_LT);
     758
     759        if (ret != 0)
     760            break;
     761
     762        /* Step 7 */
     763        if (mp_add_d(k, 1, k) != MP_OKAY) {
     764            ret = MP_MOD_E;
     765            break;
     766        }
    711767
    712768#ifdef WOLFSSL_MP_INVMOD_CONSTANT_TIME
    713     /* inverse k mod q */
    714     if (ret == 0 && mp_invmod(&k, &key->q, &kInv) != MP_OKAY)
    715         ret = MP_INVMOD_E;
    716 
    717     /* generate r, r = (g exp k mod p) mod q */
    718     if (ret == 0 && mp_exptmod_ex(&key->g, &k, key->q.used, &key->p,
    719                                                                &r) != MP_OKAY) {
    720         ret = MP_EXPTMOD_E;
    721     }
    722 
    723     if (ret == 0 && mp_mod(&r, &key->q, &r) != MP_OKAY)
    724         ret = MP_MOD_E;
    725 
    726     /* generate H from sha digest */
    727     if (ret == 0 && mp_read_unsigned_bin(&H, digest,WC_SHA_DIGEST_SIZE) != MP_OKAY)
    728         ret = MP_READ_E;
    729 
    730     /* generate s, s = (kInv * (H + x*r)) % q */
    731     if (ret == 0 && mp_mul(&key->x, &r, &s) != MP_OKAY)
    732         ret = MP_MUL_E;
    733 
    734     if (ret == 0 && mp_add(&s, &H, &s) != MP_OKAY)
    735         ret = MP_ADD_E;
    736 
    737     if (ret == 0 && mp_mulmod(&s, &kInv, &key->q, &s) != MP_OKAY)
    738         ret = MP_MULMOD_E;
     769        /* inverse k mod q */
     770        if (mp_invmod(k, &key->q, kInv) != MP_OKAY) {
     771            ret = MP_INVMOD_E;
     772            break;
     773        }
     774
     775        /* generate r, r = (g exp k mod p) mod q */
     776        if (mp_exptmod_ex(&key->g, k, key->q.used, &key->p, r) != MP_OKAY) {
     777            ret = MP_EXPTMOD_E;
     778            break;
     779        }
     780
     781        if (mp_mod(r, &key->q, r) != MP_OKAY) {
     782            ret = MP_MOD_E;
     783            break;
     784        }
     785
     786        /* generate H from sha digest */
     787        if (mp_read_unsigned_bin(H, digest,WC_SHA_DIGEST_SIZE) != MP_OKAY) {
     788            ret = MP_READ_E;
     789            break;
     790        }
     791
     792        /* generate s, s = (kInv * (H + x*r)) % q */
     793        if (mp_mul(&key->x, r, s) != MP_OKAY) {
     794            ret = MP_MUL_E;
     795            break;
     796        }
     797
     798        if (mp_add(s, H, s) != MP_OKAY) {
     799            ret = MP_ADD_E;
     800            break;
     801        }
     802
     803        if (mp_mulmod(s, kInv, &key->q, s) != MP_OKAY) {
     804            ret = MP_MULMOD_E;
     805            break;
     806        }
    739807#else
    740     /* Blinding value
    741      * Generate b in range [1, q-1].
    742      */
    743     if (ret == 0) {
     808        /* Blinding value
     809         * Generate b in range [1, q-1].
     810         */
    744811        do {
    745             ret = wc_RNG_GenerateBlock(rng, buffer, sz);
    746             if (ret == 0 && mp_read_unsigned_bin(&b, buffer, sz) != MP_OKAY)
     812            if ((ret = wc_RNG_GenerateBlock(rng, buffer, sz))) {
     813                break;
     814            }
     815            if (mp_read_unsigned_bin(b, buffer, sz) != MP_OKAY) {
    747816                ret = MP_READ_E;
    748         } while (ret == 0 && mp_cmp(&b, qMinus1) != MP_LT);
    749     }
    750     if (ret == 0 && mp_add_d(&b, 1, &b) != MP_OKAY)
    751         ret = MP_MOD_E;
    752 
    753     /* set H from sha digest */
    754     if (ret == 0 && mp_read_unsigned_bin(&H, digest,
    755                                                WC_SHA_DIGEST_SIZE) != MP_OKAY) {
    756         ret = MP_READ_E;
    757     }
    758 
    759     /* generate r, r = (g exp k mod p) mod q */
    760     if (ret == 0 && mp_exptmod_ex(&key->g, &k, key->q.used, &key->p,
    761                                                                &r) != MP_OKAY) {
    762         ret = MP_EXPTMOD_E;
    763     }
    764 
    765     /* calculate s = (H + xr)/k
    766                    = b.(H/k.b + x.r/k.b) */
    767 
    768     /* k = k.b */
    769     if (ret == 0 && mp_mulmod(&k, &b, &key->q, &k) != MP_OKAY)
    770         ret = MP_MULMOD_E;
    771 
    772     /* kInv = 1/k.b mod q */
    773     if (ret == 0 && mp_invmod(&k, &key->q, &kInv) != MP_OKAY)
    774         ret = MP_INVMOD_E;
    775 
    776     if (ret == 0 && mp_mod(&r, &key->q, &r) != MP_OKAY)
    777         ret = MP_MOD_E;
    778 
    779     /* s = x.r */
    780     if (ret == 0 && mp_mul(&key->x, &r, &s) != MP_OKAY)
    781         ret = MP_MUL_E;
    782 
    783     /* s = x.r/k.b */
    784     if (ret == 0 && mp_mulmod(&s, &kInv, &key->q, &s) != MP_OKAY)
    785         ret = MP_MULMOD_E;
    786 
    787     /* H = H/k.b */
    788     if (ret == 0 && mp_mulmod(&H, &kInv, &key->q, &H) != MP_OKAY)
    789         ret = MP_MULMOD_E;
    790 
    791     /* s = H/k.b + x.r/k.b
    792          = (H + x.r)/k.b */
    793     if (ret == 0 && mp_add(&s, &H, &s) != MP_OKAY)
    794         ret = MP_ADD_E;
    795 
    796     /* s = b.(e + x.r)/k.b
    797          = (e + x.r)/k */
    798     if (ret == 0 && mp_mulmod(&s, &b, &key->q, &s) != MP_OKAY)
    799         ret = MP_MULMOD_E;
    800 
    801     /* s = (e + x.r)/k */
    802     if (ret == 0 && mp_mod(&s, &key->q, &s) != MP_OKAY)
    803         ret = MP_MOD_E;
    804 #endif
    805 
    806     /* detect zero r or s */
    807     if (ret == 0 && (mp_iszero(&r) == MP_YES || mp_iszero(&s) == MP_YES))
    808         ret = MP_ZERO_E;
    809 
    810     /* write out */
    811     if (ret == 0)  {
    812         int rSz = mp_unsigned_bin_size(&r);
    813         int sSz = mp_unsigned_bin_size(&s);
    814 
    815         while (rSz++ < DSA_HALF_SIZE) {
    816             *out++ = 0x00;  /* pad front with zeros */
    817         }
    818 
    819         if (mp_to_unsigned_bin(&r, out) != MP_OKAY)
    820             ret = MP_TO_E;
    821         else {
    822             out = tmp + DSA_HALF_SIZE;  /* advance to s in output */
    823             while (sSz++ < DSA_HALF_SIZE) {
     817                break;
     818            }
     819        } while (mp_cmp(b, qMinus1) != MP_LT);
     820
     821        if (ret != 0)
     822            break;
     823
     824        if (mp_add_d(b, 1, b) != MP_OKAY) {
     825            ret = MP_MOD_E;
     826            break;
     827        }
     828
     829        /* set H from sha digest */
     830        if (mp_read_unsigned_bin(H, digest, WC_SHA_DIGEST_SIZE) != MP_OKAY) {
     831            ret = MP_READ_E;
     832            break;
     833        }
     834
     835        /* generate r, r = (g exp k mod p) mod q */
     836        if (mp_exptmod_ex(&key->g, k, key->q.used, &key->p, r) != MP_OKAY) {
     837            ret = MP_EXPTMOD_E;
     838            break;
     839        }
     840
     841        /* calculate s = (H + xr)/k = b.(H/k.b + x.r/k.b) */
     842
     843        /* k = k.b */
     844        if (mp_mulmod(k, b, &key->q, k) != MP_OKAY) {
     845            ret = MP_MULMOD_E;
     846            break;
     847        }
     848
     849        /* kInv = 1/k.b mod q */
     850        if (mp_invmod(k, &key->q, kInv) != MP_OKAY) {
     851            ret = MP_INVMOD_E;
     852            break;
     853        }
     854
     855        if (mp_mod(r, &key->q, r) != MP_OKAY) {
     856            ret = MP_MOD_E;
     857            break;
     858        }
     859
     860        /* s = x.r */
     861        if (mp_mul(&key->x, r, s) != MP_OKAY) {
     862            ret = MP_MUL_E;
     863            break;
     864        }
     865
     866        /* s = x.r/k.b */
     867        if (mp_mulmod(s, kInv, &key->q, s) != MP_OKAY) {
     868            ret = MP_MULMOD_E;
     869            break;
     870        }
     871
     872        /* H = H/k.b */
     873        if (mp_mulmod(H, kInv, &key->q, H) != MP_OKAY) {
     874            ret = MP_MULMOD_E;
     875            break;
     876        }
     877
     878        /* s = H/k.b + x.r/k.b = (H + x.r)/k.b */
     879        if (mp_add(s, H, s) != MP_OKAY) {
     880            ret = MP_ADD_E;
     881            break;
     882        }
     883
     884        /* s = b.(e + x.r)/k.b = (e + x.r)/k */
     885        if (mp_mulmod(s, b, &key->q, s) != MP_OKAY) {
     886            ret = MP_MULMOD_E;
     887            break;
     888        }
     889
     890        /* s = (e + x.r)/k */
     891        if (mp_mod(s, &key->q, s) != MP_OKAY) {
     892            ret = MP_MOD_E;
     893            break;
     894        }
     895#endif
     896
     897        /* detect zero r or s */
     898        if ((mp_iszero(r) == MP_YES) || (mp_iszero(s) == MP_YES)) {
     899            ret = MP_ZERO_E;
     900            break;
     901        }
     902
     903        /* write out */
     904        {
     905            int rSz = mp_unsigned_bin_size(r);
     906            int sSz = mp_unsigned_bin_size(s);
     907
     908            while (rSz++ < DSA_HALF_SIZE) {
    824909                *out++ = 0x00;  /* pad front with zeros */
    825910            }
    826             ret = mp_to_unsigned_bin(&s, out);
    827         }
    828     }
    829 
    830     ForceZero(buffer, sz);
    831     mp_forcezero(&kInv);
    832     mp_forcezero(&k);
     911
     912            if (mp_to_unsigned_bin(r, out) != MP_OKAY)
     913                ret = MP_TO_E;
     914            else {
     915                out = tmp + DSA_HALF_SIZE;  /* advance to s in output */
     916                while (sSz++ < DSA_HALF_SIZE) {
     917                    *out++ = 0x00;  /* pad front with zeros */
     918                }
     919                ret = mp_to_unsigned_bin(s, out);
     920            }
     921        }
     922    } while (0);
     923
     924#ifdef WOLFSSL_SMALL_STACK
     925    if (k) {
     926        if (ret != MP_INIT_E)
     927            mp_forcezero(k);
     928        XFREE(k, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     929    }
     930    if (kInv) {
     931        if (ret != MP_INIT_E)
     932            mp_forcezero(kInv);
     933        XFREE(kInv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     934    }
     935    if (r) {
     936        if (ret != MP_INIT_E)
     937            mp_clear(r);
     938        XFREE(r, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     939    }
     940    if (s) {
     941        if (ret != MP_INIT_E)
     942            mp_clear(s);
     943        XFREE(s, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     944    }
     945    if (H) {
     946        if (ret != MP_INIT_E)
     947            mp_clear(H);
     948        XFREE(H, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     949    }
    833950#ifndef WOLFSSL_MP_INVMOD_CONSTANT_TIME
    834     mp_forcezero(&b);
    835 
    836     mp_clear(&b);
    837 #endif
    838     mp_clear(&H);
    839     mp_clear(&s);
    840     mp_clear(&r);
    841     mp_clear(&kInv);
    842     mp_clear(&k);
     951    if (b) {
     952        if (ret != MP_INIT_E)
     953            mp_forcezero(b);
     954        XFREE(b, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     955    }
     956#endif
     957    if (buffer) {
     958        ForceZero(buffer, sz);
     959        XFREE(buffer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     960    }
     961#else /* !WOLFSSL_SMALL_STACK */
     962    if (ret != MP_INIT_E) {
     963        ForceZero(buffer, sz);
     964        mp_forcezero(kInv);
     965        mp_forcezero(k);
     966#ifndef WOLFSSL_MP_INVMOD_CONSTANT_TIME
     967        mp_forcezero(b);
     968#endif
     969        mp_clear(H);
     970        mp_clear(s);
     971        mp_clear(r);
     972    }
     973#endif
    843974
    844975    return ret;
     
    848979int wc_DsaVerify(const byte* digest, const byte* sig, DsaKey* key, int* answer)
    849980{
    850     mp_int w, u1, u2, v, r, s;
     981#ifdef WOLFSSL_SMALL_STACK
     982    mp_int *w = (mp_int *)XMALLOC(sizeof *w,
     983                                   key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     984    mp_int *u1 = (mp_int *)XMALLOC(sizeof *u1,
     985                                   key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     986    mp_int *u2 = (mp_int *)XMALLOC(sizeof *u2,
     987                                   key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     988    mp_int *v = (mp_int *)XMALLOC(sizeof *v,
     989                                   key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     990    mp_int *r = (mp_int *)XMALLOC(sizeof *r,
     991                                   key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     992    mp_int *s = (mp_int *)XMALLOC(sizeof *s,
     993                                   key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     994#else
     995    mp_int w[1], u1[1], u2[1], v[1], r[1], s[1];
     996#endif
    851997    int    ret = 0;
    852998
    853     if (digest == NULL || sig == NULL || key == NULL || answer == NULL) {
    854         return BAD_FUNC_ARG;
    855     }
    856 
    857     if (mp_init_multi(&w, &u1, &u2, &v, &r, &s) != MP_OKAY)
    858         return MP_INIT_E;
    859 
    860     /* set r and s from signature */
    861     if (mp_read_unsigned_bin(&r, sig, DSA_HALF_SIZE) != MP_OKAY ||
    862         mp_read_unsigned_bin(&s, sig + DSA_HALF_SIZE, DSA_HALF_SIZE) != MP_OKAY)
    863         ret = MP_READ_E;
    864 
    865     /* sanity checks */
    866     if (ret == 0) {
    867         if (mp_iszero(&r) == MP_YES || mp_iszero(&s) == MP_YES ||
    868                 mp_cmp(&r, &key->q) != MP_LT || mp_cmp(&s, &key->q) != MP_LT) {
     999    do {
     1000        if (mp_init_multi(w, u1, u2, v, r, s) != MP_OKAY) {
     1001            ret = MP_INIT_E;
     1002            break;
     1003        }
     1004
     1005        if (digest == NULL || sig == NULL || key == NULL || answer == NULL) {
     1006            ret = BAD_FUNC_ARG;
     1007            break;
     1008        }
     1009
     1010#ifdef WOLFSSL_SMALL_STACK
     1011        if ((w == NULL) ||
     1012            (u1 == NULL) ||
     1013            (u2 == NULL) ||
     1014            (v == NULL) ||
     1015            (r == NULL) ||
     1016            (s == NULL)) {
     1017            ret = MEMORY_E;
     1018            break;
     1019        }
     1020#endif
     1021
     1022        /* set r and s from signature */
     1023        if (mp_read_unsigned_bin(r, sig, DSA_HALF_SIZE) != MP_OKAY ||
     1024            mp_read_unsigned_bin(s, sig + DSA_HALF_SIZE, DSA_HALF_SIZE) != MP_OKAY) {
     1025            ret = MP_READ_E;
     1026            break;
     1027        }
     1028
     1029        /* sanity checks */
     1030        if (mp_iszero(r) == MP_YES || mp_iszero(s) == MP_YES ||
     1031            mp_cmp(r, &key->q) != MP_LT || mp_cmp(s, &key->q) != MP_LT) {
    8691032            ret = MP_ZERO_E;
    870         }
    871     }
    872 
    873     /* put H into u1 from sha digest */
    874     if (ret == 0 && mp_read_unsigned_bin(&u1,digest,WC_SHA_DIGEST_SIZE) != MP_OKAY)
    875         ret = MP_READ_E;
    876 
    877     /* w = s invmod q */
    878     if (ret == 0 && mp_invmod(&s, &key->q, &w) != MP_OKAY)
    879         ret = MP_INVMOD_E;
    880 
    881     /* u1 = (H * w) % q */
    882     if (ret == 0 && mp_mulmod(&u1, &w, &key->q, &u1) != MP_OKAY)
    883         ret = MP_MULMOD_E;
    884 
    885     /* u2 = (r * w) % q */
    886     if (ret == 0 && mp_mulmod(&r, &w, &key->q, &u2) != MP_OKAY)
    887         ret = MP_MULMOD_E;
    888 
    889     /* verify v = ((g^u1 * y^u2) mod p) mod q */
    890     if (ret == 0 && mp_exptmod(&key->g, &u1, &key->p, &u1) != MP_OKAY)
    891         ret = MP_EXPTMOD_E;
    892 
    893     if (ret == 0 && mp_exptmod(&key->y, &u2, &key->p, &u2) != MP_OKAY)
    894         ret = MP_EXPTMOD_E;
    895 
    896     if (ret == 0 && mp_mulmod(&u1, &u2, &key->p, &v) != MP_OKAY)
    897         ret = MP_MULMOD_E;
    898 
    899     if (ret == 0 && mp_mod(&v, &key->q, &v) != MP_OKAY)
    900         ret = MP_MULMOD_E;
    901 
    902     /* do they match */
    903     if (ret == 0 && mp_cmp(&r, &v) == MP_EQ)
    904         *answer = 1;
    905     else
    906         *answer = 0;
    907 
    908     mp_clear(&s);
    909     mp_clear(&r);
    910     mp_clear(&u1);
    911     mp_clear(&u2);
    912     mp_clear(&w);
    913     mp_clear(&v);
     1033            break;
     1034        }
     1035
     1036        /* put H into u1 from sha digest */
     1037        if (mp_read_unsigned_bin(u1,digest,WC_SHA_DIGEST_SIZE) != MP_OKAY) {
     1038            ret = MP_READ_E;
     1039            break;
     1040        }
     1041
     1042        /* w = s invmod q */
     1043        if (mp_invmod(s, &key->q, w) != MP_OKAY) {
     1044            ret = MP_INVMOD_E;
     1045            break;
     1046        }
     1047
     1048        /* u1 = (H * w) % q */
     1049        if (mp_mulmod(u1, w, &key->q, u1) != MP_OKAY) {
     1050            ret = MP_MULMOD_E;
     1051            break;
     1052        }
     1053
     1054        /* u2 = (r * w) % q */
     1055        if (mp_mulmod(r, w, &key->q, u2) != MP_OKAY) {
     1056            ret = MP_MULMOD_E;
     1057            break;
     1058        }
     1059
     1060        /* verify v = ((g^u1 * y^u2) mod p) mod q */
     1061        if (mp_exptmod(&key->g, u1, &key->p, u1) != MP_OKAY) {
     1062            ret = MP_EXPTMOD_E;
     1063            break;
     1064        }
     1065
     1066        if (mp_exptmod(&key->y, u2, &key->p, u2) != MP_OKAY) {
     1067            ret = MP_EXPTMOD_E;
     1068            break;
     1069        }
     1070
     1071        if (mp_mulmod(u1, u2, &key->p, v) != MP_OKAY) {
     1072            ret = MP_MULMOD_E;
     1073            break;
     1074        }
     1075
     1076        if (mp_mod(v, &key->q, v) != MP_OKAY) {
     1077            ret = MP_MULMOD_E;
     1078            break;
     1079        }
     1080
     1081        /* do they match */
     1082        if (mp_cmp(r, v) == MP_EQ)
     1083            *answer = 1;
     1084        else
     1085            *answer = 0;
     1086    } while (0);
     1087
     1088#ifdef WOLFSSL_SMALL_STACK
     1089    if (s) {
     1090        if (ret != MP_INIT_E)
     1091            mp_clear(s);
     1092        XFREE(s, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     1093    }
     1094    if (r) {
     1095        if (ret != MP_INIT_E)
     1096            mp_clear(r);
     1097        XFREE(r, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     1098    }
     1099    if (u1) {
     1100        if (ret != MP_INIT_E)
     1101            mp_clear(u1);
     1102        XFREE(u1, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     1103    }
     1104    if (u2) {
     1105        if (ret != MP_INIT_E)
     1106            mp_clear(u2);
     1107        XFREE(u2, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     1108    }
     1109    if (w) {
     1110        if (ret != MP_INIT_E)
     1111            mp_clear(w);
     1112        XFREE(w, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     1113    }
     1114    if (v) {
     1115        if (ret != MP_INIT_E)
     1116            mp_clear(v);
     1117        XFREE(v, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
     1118    }
     1119#else
     1120    if (ret != MP_INIT_E) {
     1121        mp_clear(s);
     1122        mp_clear(r);
     1123        mp_clear(u1);
     1124        mp_clear(u2);
     1125        mp_clear(w);
     1126        mp_clear(v);
     1127    }
     1128#endif
    9141129
    9151130    return ret;
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/ecc.c

    r457 r464  
    4949 *                        Includes the curve "a" variable in calculation
    5050 * ECC_DUMP_OID:        Enables dump of OID encoding and sum    default: off
    51  * ECC_CACHE_CURVE:     Enables cache of curve info to improve perofrmance
     51 * ECC_CACHE_CURVE:     Enables cache of curve info to improve performance
    5252                                                                default: off
    5353 * FP_ECC:              ECC Fixed Point Cache                   default: off
     
    5757                        For the ECC curve paramaters `ecc_set_type` use fixed
    5858                        array for hex string
     59 * WC_ECC_NONBLOCK:     Enable non-blocking support for sign/verify.
     60                        Requires SP with WOLFSSL_SP_NONBLOCK
     61 * WC_ECC_NONBLOCK_ONLY Enable the non-blocking function only, no fall-back to
     62                        normal blocking API's
     63 * WOLFSSL_ECDSA_SET_K: Enables the setting of the 'k' value to use during ECDSA
     64 *                      signing. If the value is invalid, a new random 'k' is
     65 *                      generated in the loop. (For testing)
     66 *                                                              default: off
     67 * WOLFSSL_ECDSA_SET_K_ONE_LOOP:
     68 *                      Enables the setting of the 'k' value to use during ECDSA
     69 *                      signing. If the value is invalid then an error is
     70 *                      returned rather than generating a new 'k'. (For testing)
     71 *                                                              default: off
    5972 */
    6073
     
    7285 * ECC_USER_CURVES: Allows custom combination of key sizes below
    7386 * HAVE_ALL_CURVES: Enable all key sizes (on unless ECC_USER_CURVES is defined)
     87 * ECC_MIN_KEY_SZ: Minimum supported ECC key size
    7488 * HAVE_ECC112: 112 bit key
    7589 * HAVE_ECC128: 128 bit key
     
    142156#endif
    143157
    144 #ifdef WOLFSSL_SP_MATH
     158#if defined(WOLFSSL_PSOC6_CRYPTO)
     159    #include <wolfssl/wolfcrypt/port/cypress/psoc6_crypto.h>
     160#endif
     161
     162#if defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_SP_MATH_ALL)
    145163    #define GEN_MEM_ERR MP_MEM
    146164#elif defined(USE_FAST_MATH)
     
    172190
    173191/* 256-bit curve on by default whether user curves or not */
    174 #if defined(HAVE_ECC112) || defined(HAVE_ALL_CURVES)
     192#if (defined(HAVE_ECC112) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 112
    175193    #define ECC112
    176194#endif
    177 #if defined(HAVE_ECC128) || defined(HAVE_ALL_CURVES)
     195#if (defined(HAVE_ECC128) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 128
    178196    #define ECC128
    179197#endif
    180 #if defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)
     198#if (defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 160
    181199    #define ECC160
    182200#endif
    183 #if defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)
     201#if (defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 192
    184202    #define ECC192
    185203#endif
    186 #if defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)
     204#if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224
    187205    #define ECC224
    188206#endif
    189 #if defined(HAVE_ECC239) || defined(HAVE_ALL_CURVES)
     207#if (defined(HAVE_ECC239) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 239
    190208    #define ECC239
    191209#endif
    192 #if !defined(NO_ECC256)  || defined(HAVE_ALL_CURVES)
     210#if (!defined(NO_ECC256)  || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 256
    193211    #define ECC256
    194212#endif
    195 #if defined(HAVE_ECC320) || defined(HAVE_ALL_CURVES)
     213#if (defined(HAVE_ECC320) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 320
    196214    #define ECC320
    197215#endif
    198 #if defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)
     216#if (defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 384
    199217    #define ECC384
    200218#endif
    201 #if defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)
     219#if (defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 512
    202220    #define ECC512
    203221#endif
    204 #if defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)
     222#if (defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 521
    205223    #define ECC521
    206224#endif
     
    9881006        "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296", /* Gx         */
    9891007        "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5", /* Gy         */
    990                 ecc_oid_secp256r1,                                                  /* oid/oidSz  */
     1008        ecc_oid_secp256r1,                                                  /* oid/oidSz  */
    9911009        ecc_oid_secp256r1_sz,
    9921010        ECC_SECP256R1_OID,                                                  /* oid sum    */
     
    11611179
    11621180#if (defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || !defined(WOLFSSL_SP_MATH)) && \
    1163     !defined(WOLFSSL_ATECC508A)
     1181    !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A)
    11641182static int ecc_check_pubkey_order(ecc_key* key, ecc_point* pubkey, mp_int* a,
    11651183        mp_int* prime, mp_int* order);
     
    12581276#endif /* ECC_CACHE_CURVE */
    12591277
    1260 static void _wc_ecc_curve_free(ecc_curve_spec* curve)
     1278static void wc_ecc_curve_cache_free_spec_item(ecc_curve_spec* curve, mp_int* item,
     1279    byte mask)
     1280{
     1281    if (item) {
     1282    #ifdef HAVE_WOLF_BIGINT
     1283        wc_bigint_free(&item->raw);
     1284    #endif
     1285        mp_clear(item);
     1286    }
     1287    curve->load_mask &= ~mask;
     1288}
     1289static void wc_ecc_curve_cache_free_spec(ecc_curve_spec* curve)
    12611290{
    12621291    if (curve == NULL) {
     
    12651294
    12661295    if (curve->load_mask & ECC_CURVE_FIELD_PRIME)
    1267         mp_clear(curve->prime);
     1296        wc_ecc_curve_cache_free_spec_item(curve, curve->prime, ECC_CURVE_FIELD_PRIME);
    12681297    if (curve->load_mask & ECC_CURVE_FIELD_AF)
    1269         mp_clear(curve->Af);
     1298        wc_ecc_curve_cache_free_spec_item(curve, curve->Af, ECC_CURVE_FIELD_AF);
    12701299#ifdef USE_ECC_B_PARAM
    12711300    if (curve->load_mask & ECC_CURVE_FIELD_BF)
    1272         mp_clear(curve->Bf);
     1301        wc_ecc_curve_cache_free_spec_item(curve, curve->Bf, ECC_CURVE_FIELD_BF);
    12731302#endif
    12741303    if (curve->load_mask & ECC_CURVE_FIELD_ORDER)
    1275         mp_clear(curve->order);
     1304        wc_ecc_curve_cache_free_spec_item(curve, curve->order, ECC_CURVE_FIELD_ORDER);
    12761305    if (curve->load_mask & ECC_CURVE_FIELD_GX)
    1277         mp_clear(curve->Gx);
     1306        wc_ecc_curve_cache_free_spec_item(curve, curve->Gx, ECC_CURVE_FIELD_GX);
    12781307    if (curve->load_mask & ECC_CURVE_FIELD_GY)
    1279         mp_clear(curve->Gy);
     1308        wc_ecc_curve_cache_free_spec_item(curve, curve->Gy, ECC_CURVE_FIELD_GY);
    12801309
    12811310    curve->load_mask = 0;
     
    12841313static void wc_ecc_curve_free(ecc_curve_spec* curve)
    12851314{
    1286     /* don't free cached curves */
    1287 #ifndef ECC_CACHE_CURVE
    1288     _wc_ecc_curve_free(curve);
    1289 #endif
    1290     (void)curve;
    1291 }
    1292 
    1293 static int wc_ecc_curve_load_item(const char* src, mp_int** dst,
    1294     ecc_curve_spec* curve, byte mask)
     1315    if (curve) {
     1316    #ifdef ECC_CACHE_CURVE
     1317        #ifdef WOLFSSL_CUSTOM_CURVES
     1318        /* only free custom curves (rest are globally cached) */
     1319        if (curve->dp && curve->dp->id == ECC_CURVE_CUSTOM) {
     1320            wc_ecc_curve_cache_free_spec(curve);
     1321            XFREE(curve, NULL, DYNAMIC_TYPE_ECC);
     1322        }
     1323        #endif
     1324    #else
     1325        wc_ecc_curve_cache_free_spec(curve);
     1326    #endif
     1327    }
     1328}
     1329
     1330static int wc_ecc_curve_cache_load_item(ecc_curve_spec* curve, const char* src,
     1331    mp_int** dst, byte mask)
    12951332{
    12961333    int err;
     
    13221359    byte load_mask)
    13231360{
    1324     int ret = 0, x;
     1361    int ret = 0;
    13251362    ecc_curve_spec* curve;
    13261363    byte load_items = 0; /* mask of items to load */
     1364#ifdef ECC_CACHE_CURVE
     1365    int x;
     1366#endif
    13271367
    13281368    if (dp == NULL || pCurve == NULL)
     
    13421382
    13431383    /* make sure cache has been allocated */
    1344     if (ecc_curve_spec_cache[x] == NULL) {
    1345         ecc_curve_spec_cache[x] = (ecc_curve_spec*)XMALLOC(
    1346             sizeof(ecc_curve_spec), NULL, DYNAMIC_TYPE_ECC);
    1347         if (ecc_curve_spec_cache[x] == NULL) {
     1384    if (ecc_curve_spec_cache[x] == NULL
     1385    #ifdef WOLFSSL_CUSTOM_CURVES
     1386        || dp->id == ECC_CURVE_CUSTOM
     1387    #endif
     1388    ) {
     1389        curve = (ecc_curve_spec*)XMALLOC(sizeof(ecc_curve_spec), NULL, DYNAMIC_TYPE_ECC);
     1390        if (curve == NULL) {
    13481391        #if defined(ECC_CACHE_CURVE) && !defined(SINGLE_THREADED)
    13491392            wc_UnLockMutex(&ecc_curve_cache_mutex);
     
    13511394            return MEMORY_E;
    13521395        }
    1353         XMEMSET(ecc_curve_spec_cache[x], 0, sizeof(ecc_curve_spec));
    1354     }
    1355 
    1356     /* set curve pointer to cache */
    1357     *pCurve = ecc_curve_spec_cache[x];
    1358 
     1396        XMEMSET(curve, 0, sizeof(ecc_curve_spec));
     1397
     1398        /* set curve pointer to cache */
     1399    #ifdef WOLFSSL_CUSTOM_CURVES
     1400        if (dp->id != ECC_CURVE_CUSTOM)
     1401    #endif
     1402        {
     1403            ecc_curve_spec_cache[x] = curve;
     1404        }
     1405    }
     1406    else {
     1407        curve = ecc_curve_spec_cache[x];
     1408    }
     1409    /* return new or cached curve */
     1410    *pCurve = curve;
     1411#else
     1412    curve = *pCurve;
    13591413#endif /* ECC_CACHE_CURVE */
    1360     curve = *pCurve;
    13611414
    13621415    /* make sure the curve is initialized */
     
    13821435
    13831436    /* load items */
    1384     x = 0;
    13851437    if (load_items & ECC_CURVE_FIELD_PRIME)
    1386         x += wc_ecc_curve_load_item(dp->prime, &curve->prime, curve,
     1438        ret += wc_ecc_curve_cache_load_item(curve, dp->prime, &curve->prime,
    13871439            ECC_CURVE_FIELD_PRIME);
    13881440    if (load_items & ECC_CURVE_FIELD_AF)
    1389         x += wc_ecc_curve_load_item(dp->Af, &curve->Af, curve,
     1441        ret += wc_ecc_curve_cache_load_item(curve, dp->Af, &curve->Af,
    13901442            ECC_CURVE_FIELD_AF);
    13911443#ifdef USE_ECC_B_PARAM
    13921444    if (load_items & ECC_CURVE_FIELD_BF)
    1393         x += wc_ecc_curve_load_item(dp->Bf, &curve->Bf, curve,
     1445        ret += wc_ecc_curve_cache_load_item(curve, dp->Bf, &curve->Bf,
    13941446            ECC_CURVE_FIELD_BF);
    13951447#endif
    13961448    if (load_items & ECC_CURVE_FIELD_ORDER)
    1397         x += wc_ecc_curve_load_item(dp->order, &curve->order, curve,
     1449        ret += wc_ecc_curve_cache_load_item(curve, dp->order, &curve->order,
    13981450            ECC_CURVE_FIELD_ORDER);
    13991451    if (load_items & ECC_CURVE_FIELD_GX)
    1400         x += wc_ecc_curve_load_item(dp->Gx, &curve->Gx, curve,
     1452        ret += wc_ecc_curve_cache_load_item(curve, dp->Gx, &curve->Gx,
    14011453            ECC_CURVE_FIELD_GX);
    14021454    if (load_items & ECC_CURVE_FIELD_GY)
    1403         x += wc_ecc_curve_load_item(dp->Gy, &curve->Gy, curve,
     1455        ret += wc_ecc_curve_cache_load_item(curve, dp->Gy, &curve->Gy,
    14041456            ECC_CURVE_FIELD_GY);
    14051457
    14061458    /* check for error */
    1407     if (x != 0) {
     1459    if (ret != 0) {
    14081460        wc_ecc_curve_free(curve);
    14091461        ret = MP_READ_E;
     
    14341486    for (x = 0; x < (int)ECC_SET_COUNT; x++) {
    14351487        if (ecc_curve_spec_cache[x]) {
    1436             _wc_ecc_curve_free(ecc_curve_spec_cache[x]);
     1488            wc_ecc_curve_cache_free_spec(ecc_curve_spec_cache[x]);
    14371489            XFREE(ecc_curve_spec_cache[x], NULL, DYNAMIC_TYPE_ECC);
    14381490            ecc_curve_spec_cache[x] = NULL;
     
    15101562
    15111563
    1512 #ifndef WOLFSSL_ATECC508A
     1564#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A)
    15131565
    15141566#if !defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_PUBLIC_ECC_ADD_DBL)
     
    15271579                             mp_int* a, mp_int* modulus, mp_digit mp)
    15281580{
    1529 #ifndef WOLFSSL_SP_MATH
     1581#if !defined(WOLFSSL_SP_MATH)
    15301582#ifdef WOLFSSL_SMALL_STACK
    15311583   mp_int* t1 = NULL;
     
    16121664
    16131665   /* should we dbl instead? */
    1614    if (err == MP_OKAY)
     1666   if (err == MP_OKAY) {
     1667#ifdef ECC_TIMING_RESISTANT
     1668       err = mp_submod_ct(modulus, Q->y, modulus, t1);
     1669#else
    16151670       err = mp_sub(modulus, Q->y, t1);
     1671#endif
     1672   }
    16161673   if (err == MP_OKAY) {
    16171674       if ( (mp_cmp(P->x, Q->x) == MP_EQ) &&
     
    17211778   /* Y = Y - T1 */
    17221779   if (err == MP_OKAY)
    1723        err = mp_sub(y, t1, y);
    1724    if (err == MP_OKAY) {
    1725        if (mp_isneg(y))
    1726            err = mp_add(y, modulus, y);
    1727    }
     1780       err = mp_submod_ct(y, t1, modulus, y);
    17281781   /* T1 = 2T1 */
    17291782   if (err == MP_OKAY)
    1730        err = mp_add(t1, t1, t1);
    1731    if (err == MP_OKAY) {
    1732        if (mp_cmp(t1, modulus) != MP_LT)
    1733            err = mp_sub(t1, modulus, t1);
    1734    }
     1783       err = mp_addmod_ct(t1, t1, modulus, t1);
    17351784   /* T1 = Y + T1 */
    17361785   if (err == MP_OKAY)
    1737        err = mp_add(t1, y, t1);
    1738    if (err == MP_OKAY) {
    1739        if (mp_cmp(t1, modulus) != MP_LT)
    1740            err = mp_sub(t1, modulus, t1);
    1741    }
     1786       err = mp_addmod_ct(t1, y, modulus, t1);
    17421787   /* X = X - T2 */
    17431788   if (err == MP_OKAY)
    1744        err = mp_sub(x, t2, x);
    1745    if (err == MP_OKAY) {
    1746        if (mp_isneg(x))
    1747            err = mp_add(x, modulus, x);
    1748    }
     1789       err = mp_submod_ct(x, t2, modulus, x);
    17491790   /* T2 = 2T2 */
    17501791   if (err == MP_OKAY)
    1751        err = mp_add(t2, t2, t2);
    1752    if (err == MP_OKAY) {
    1753        if (mp_cmp(t2, modulus) != MP_LT)
    1754            err = mp_sub(t2, modulus, t2);
    1755    }
     1792       err = mp_addmod_ct(t2, t2, modulus, t2);
    17561793   /* T2 = X + T2 */
    17571794   if (err == MP_OKAY)
    1758        err = mp_add(t2, x, t2);
    1759    if (err == MP_OKAY) {
    1760        if (mp_cmp(t2, modulus) != MP_LT)
    1761            err = mp_sub(t2, modulus, t2);
    1762    }
     1795       err = mp_addmod_ct(t2, x, modulus, t2);
    17631796
    17641797   if (err == MP_OKAY) {
     
    18091842   /* X = X - T2 */
    18101843   if (err == MP_OKAY)
    1811        err = mp_sub(x, t2, x);
    1812    if (err == MP_OKAY) {
    1813        if (mp_isneg(x))
    1814            err = mp_add(x, modulus, x);
    1815    }
     1844       err = mp_submod_ct(x, t2, modulus, x);
    18161845   /* T2 = T2 - X */
    18171846   if (err == MP_OKAY)
    1818        err = mp_sub(t2, x, t2);
    1819    if (err == MP_OKAY) {
    1820        if (mp_isneg(t2))
    1821            err = mp_add(t2, modulus, t2);
    1822    }
     1847       err = mp_submod_ct(t2, x, modulus, t2);
    18231848   /* T2 = T2 - X */
    18241849   if (err == MP_OKAY)
    1825        err = mp_sub(t2, x, t2);
    1826    if (err == MP_OKAY) {
    1827        if (mp_isneg(t2))
    1828            err = mp_add(t2, modulus, t2);
    1829    }
     1850       err = mp_submod_ct(t2, x, modulus, t2);
    18301851   /* T2 = T2 * Y */
    18311852   if (err == MP_OKAY)
     
    18361857   /* Y = T2 - T1 */
    18371858   if (err == MP_OKAY)
    1838        err = mp_sub(t2, t1, y);
    1839    if (err == MP_OKAY) {
    1840        if (mp_isneg(y))
    1841            err = mp_add(y, modulus, y);
    1842    }
     1859       err = mp_submod_ct(t2, t1, modulus, y);
    18431860   /* Y = Y/2 */
    1844    if (err == MP_OKAY) {
    1845        if (mp_isodd(y) == MP_YES)
    1846            err = mp_add(y, modulus, y);
    1847    }
    18481861   if (err == MP_OKAY)
    1849        err = mp_div_2(y, y);
     1862       err = mp_div_2_mod_ct(y, modulus, y);
    18501863
    18511864#ifdef ALT_ECC_SIZE
     
    19331946                                       mp_int* modulus, mp_digit mp)
    19341947{
    1935 #ifndef WOLFSSL_SP_MATH
     1948#if !defined(WOLFSSL_SP_MATH)
    19361949#ifdef WOLFSSL_SMALL_STACK
    19371950   mp_int* t1 = NULL;
     
    20642077   /* Z = 2Z */
    20652078   if (err == MP_OKAY)
    2066        err = mp_add(z, z, z);
    2067    if (err == MP_OKAY) {
    2068        if (mp_cmp(z, modulus) != MP_LT)
    2069            err = mp_sub(z, modulus, z);
    2070    }
     2079       err = mp_addmod_ct(z, z, modulus, z);
    20712080
    20722081   /* Determine if curve "a" should be used in calc */
     
    20762085      err = mp_submod(modulus, a, modulus, t2);
    20772086   }
    2078    if (err == MP_OKAY && mp_cmp_d(t2, 3) != MP_EQ) {
     2087   if (err == MP_OKAY && mp_iszero(t2)) {
     2088      /* T2 = X * X */
     2089      if (err == MP_OKAY)
     2090          err = mp_sqr(x, t2);
     2091      if (err == MP_OKAY)
     2092          err = mp_montgomery_reduce(t2, modulus, mp);
     2093      /* T1 = T2 + T1 */
     2094      if (err == MP_OKAY)
     2095          err = mp_addmod_ct(t2, t2, modulus, t1);
     2096      /* T1 = T2 + T1 */
     2097      if (err == MP_OKAY)
     2098          err = mp_addmod_ct(t1, t2, modulus, t1);
     2099   }
     2100   else if (err == MP_OKAY && mp_cmp_d(t2, 3) != MP_EQ) {
    20792101      /* use "a" in calc */
    20802102
     
    20942116      /* T1 = T2 + T1 */
    20952117      if (err == MP_OKAY)
    2096           err = mp_add(t1, t2, t1);
    2097       if (err == MP_OKAY) {
    2098          if (mp_cmp(t1, modulus) != MP_LT)
    2099             err = mp_sub(t1, modulus, t1);
    2100       }
     2118          err = mp_addmod_ct(t1, t2, modulus, t1);
    21012119      /* T1 = T2 + T1 */
    21022120      if (err == MP_OKAY)
    2103           err = mp_add(t1, t2, t1);
    2104       if (err == MP_OKAY) {
    2105           if (mp_cmp(t1, modulus) != MP_LT)
    2106               err = mp_sub(t1, modulus, t1);
    2107       }
     2121          err = mp_addmod_ct(t1, t2, modulus, t1);
    21082122      /* T1 = T2 + T1 */
    21092123      if (err == MP_OKAY)
    2110           err = mp_add(t1, t2, t1);
    2111       if (err == MP_OKAY) {
    2112          if (mp_cmp(t1, modulus) != MP_LT)
    2113             err = mp_sub(t1, modulus, t1);
    2114       }
     2124          err = mp_addmod_ct(t1, t2, modulus, t1);
    21152125   }
    21162126   else
     
    21222132      /* T2 = X - T1 */
    21232133      if (err == MP_OKAY)
    2124           err = mp_sub(x, t1, t2);
    2125       if (err == MP_OKAY) {
    2126           if (mp_isneg(t2))
    2127               err = mp_add(t2, modulus, t2);
    2128       }
     2134          err = mp_submod_ct(x, t1, modulus, t2);
    21292135      /* T1 = X + T1 */
    21302136      if (err == MP_OKAY)
    2131           err = mp_add(t1, x, t1);
    2132       if (err == MP_OKAY) {
    2133           if (mp_cmp(t1, modulus) != MP_LT)
    2134               err = mp_sub(t1, modulus, t1);
    2135       }
     2137          err = mp_addmod_ct(t1, x, modulus, t1);
    21362138      /* T2 = T1 * T2 */
    21372139      if (err == MP_OKAY)
     
    21422144      /* T1 = 2T2 */
    21432145      if (err == MP_OKAY)
    2144           err = mp_add(t2, t2, t1);
    2145       if (err == MP_OKAY) {
    2146           if (mp_cmp(t1, modulus) != MP_LT)
    2147               err = mp_sub(t1, modulus, t1);
    2148       }
     2146          err = mp_addmod_ct(t2, t2, modulus, t1);
    21492147      /* T1 = T1 + T2 */
    21502148      if (err == MP_OKAY)
    2151           err = mp_add(t1, t2, t1);
    2152       if (err == MP_OKAY) {
    2153           if (mp_cmp(t1, modulus) != MP_LT)
    2154               err = mp_sub(t1, modulus, t1);
    2155       }
     2149          err = mp_addmod_ct(t1, t2, modulus, t1);
    21562150   }
    21572151
    21582152   /* Y = 2Y */
    21592153   if (err == MP_OKAY)
    2160        err = mp_add(y, y, y);
    2161    if (err == MP_OKAY) {
    2162        if (mp_cmp(y, modulus) != MP_LT)
    2163            err = mp_sub(y, modulus, y);
    2164    }
     2154       err = mp_addmod_ct(y, y, modulus, y);
    21652155   /* Y = Y * Y */
    21662156   if (err == MP_OKAY)
     
    21762166
    21772167   /* T2 = T2/2 */
    2178    if (err == MP_OKAY) {
    2179        if (mp_isodd(t2) == MP_YES)
    2180            err = mp_add(t2, modulus, t2);
    2181    }
    21822168   if (err == MP_OKAY)
    2183        err = mp_div_2(t2, t2);
     2169       err = mp_div_2_mod_ct(t2, modulus, t2);
    21842170
    21852171   /* Y = Y * X */
     
    21972183   /* X = X - Y */
    21982184   if (err == MP_OKAY)
    2199        err = mp_sub(x, y, x);
    2200    if (err == MP_OKAY) {
    2201        if (mp_isneg(x))
    2202            err = mp_add(x, modulus, x);
    2203    }
     2185       err = mp_submod_ct(x, y, modulus, x);
    22042186   /* X = X - Y */
    22052187   if (err == MP_OKAY)
    2206        err = mp_sub(x, y, x);
    2207    if (err == MP_OKAY) {
    2208        if (mp_isneg(x))
    2209            err = mp_add(x, modulus, x);
    2210    }
     2188       err = mp_submod_ct(x, y, modulus, x);
    22112189
    22122190   /* Y = Y - X */
    22132191   if (err == MP_OKAY)
    2214        err = mp_sub(y, x, y);
    2215    if (err == MP_OKAY) {
    2216        if (mp_isneg(y))
    2217            err = mp_add(y, modulus, y);
    2218    }
     2192       err = mp_submod_ct(y, x, modulus, y);
    22192193   /* Y = Y * T1 */
    22202194   if (err == MP_OKAY)
     
    22252199   /* Y = Y - T2 */
    22262200   if (err == MP_OKAY)
    2227        err = mp_sub(y, t2, y);
    2228    if (err == MP_OKAY) {
    2229        if (mp_isneg(y))
    2230            err = mp_add(y, modulus, y);
    2231    }
     2201       err = mp_submod_ct(y, t2, modulus, y);
    22322202
    22332203#ifdef ALT_ECC_SIZE
     
    22922262int ecc_map_ex(ecc_point* P, mp_int* modulus, mp_digit mp, int ct)
    22932263{
    2294 #ifndef WOLFSSL_SP_MATH
     2264#if !defined(WOLFSSL_SP_MATH)
    22952265#ifdef WOLFSSL_SMALL_STACK
    22962266   mp_int* t1 = NULL;
     
    24092379   /* get 1/z */
    24102380   if (err == MP_OKAY) {
    2411 #if defined(ECC_TIMING_RESISTANT) && defined(USE_FAST_MATH)
     2381#if defined(ECC_TIMING_RESISTANT) && (defined(USE_FAST_MATH) || \
     2382                       defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_SP_MATH_ALL))
    24122383       if (ct) {
    24132384           err = mp_invmod_mont_ct(z, modulus, t1, mp);
     
    25082479#if !defined(FREESCALE_LTC_ECC) && !defined(WOLFSSL_STM32_PKA)
    25092480
    2510 #if !defined(FP_ECC) || !defined(WOLFSSL_SP_MATH)
     2481#if !defined(WOLFSSL_SP_MATH)
     2482
     2483#ifndef ECC_TIMING_RESISTANT
     2484
     2485/* size of sliding window, don't change this! */
     2486#define WINSIZE  4
     2487#define M_POINTS 8
     2488
     2489static int ecc_mulmod(mp_int* k, ecc_point* tG, ecc_point* R, ecc_point** M,
     2490    mp_int* a, mp_int* modulus, mp_digit mp, WC_RNG* rng)
     2491{
     2492   int      err = MP_OKAY;
     2493   int      i;
     2494   int      first = 1, bitbuf = 0, bitcpy = 0, j;
     2495   int      bitcnt = 0, mode = 0, digidx = 0;
     2496   mp_digit buf;
     2497   int      infinity;
     2498
     2499   (void)rng;
     2500
     2501   /* calc the M tab, which holds kG for k==8..15 */
     2502   /* M[0] == 8G */
     2503   if (err == MP_OKAY)
     2504       err = ecc_projective_dbl_point_safe(tG, M[0], a, modulus, mp);
     2505   if (err == MP_OKAY)
     2506       err = ecc_projective_dbl_point_safe(M[0], M[0], a, modulus, mp);
     2507   if (err == MP_OKAY)
     2508       err = ecc_projective_dbl_point_safe(M[0], M[0], a, modulus, mp);
     2509
     2510   /* now find (8+k)G for k=1..7 */
     2511   if (err == MP_OKAY)
     2512       for (j = 9; j < 16; j++) {
     2513           err = ecc_projective_add_point_safe(M[j-9], tG, M[j-M_POINTS], a,
     2514                                                        modulus, mp, &infinity);
     2515           if (err != MP_OKAY) break;
     2516       }
     2517
     2518   /* setup sliding window */
     2519   if (err == MP_OKAY) {
     2520       mode   = 0;
     2521       bitcnt = 1;
     2522       buf    = 0;
     2523       digidx = get_digit_count(k) - 1;
     2524       bitcpy = bitbuf = 0;
     2525       first  = 1;
     2526
     2527       /* perform ops */
     2528       for (;;) {
     2529           /* grab next digit as required */
     2530           if (--bitcnt == 0) {
     2531               if (digidx == -1) {
     2532                   break;
     2533               }
     2534               buf    = get_digit(k, digidx);
     2535               bitcnt = (int) DIGIT_BIT;
     2536               --digidx;
     2537           }
     2538
     2539           /* grab the next msb from the ltiplicand */
     2540           i = (int)(buf >> (DIGIT_BIT - 1)) & 1;
     2541           buf <<= 1;
     2542
     2543           /* skip leading zero bits */
     2544           if (mode == 0 && i == 0)
     2545               continue;
     2546
     2547           /* if the bit is zero and mode == 1 then we double */
     2548           if (mode == 1 && i == 0) {
     2549               err = ecc_projective_dbl_point_safe(R, R, a, modulus, mp);
     2550               if (err != MP_OKAY) break;
     2551               continue;
     2552           }
     2553
     2554           /* else we add it to the window */
     2555           bitbuf |= (i << (WINSIZE - ++bitcpy));
     2556           mode = 2;
     2557
     2558           if (bitcpy == WINSIZE) {
     2559               /* if this is the first window we do a simple copy */
     2560               if (first == 1) {
     2561                   /* R = kG [k = first window] */
     2562                   err = mp_copy(M[bitbuf-M_POINTS]->x, R->x);
     2563                   if (err != MP_OKAY) break;
     2564
     2565                   err = mp_copy(M[bitbuf-M_POINTS]->y, R->y);
     2566                   if (err != MP_OKAY) break;
     2567
     2568                   err = mp_copy(M[bitbuf-M_POINTS]->z, R->z);
     2569                   first = 0;
     2570               } else {
     2571                   /* normal window */
     2572                   /* ok window is filled so double as required and add  */
     2573                   /* double first */
     2574                   for (j = 0; j < WINSIZE; j++) {
     2575                       err = ecc_projective_dbl_point_safe(R, R, a, modulus,
     2576                                                                            mp);
     2577                       if (err != MP_OKAY) break;
     2578                   }
     2579                   if (err != MP_OKAY) break;  /* out of first for(;;) */
     2580
     2581                   /* now add, bitbuf will be 8..15 [8..2^WINSIZE] guaranteed */
     2582                   err = ecc_projective_add_point_safe(R, M[bitbuf-M_POINTS], R,
     2583                                                     a, modulus, mp, &infinity);
     2584               }
     2585               if (err != MP_OKAY) break;
     2586               /* empty window and reset */
     2587               bitcpy = bitbuf = 0;
     2588               mode = 1;
     2589           }
     2590       }
     2591   }
     2592
     2593   /* if bits remain then double/add */
     2594   if (err == MP_OKAY) {
     2595       if (mode == 2 && bitcpy > 0) {
     2596           /* double then add */
     2597           for (j = 0; j < bitcpy; j++) {
     2598               /* only double if we have had at least one add first */
     2599               if (first == 0) {
     2600                   err = ecc_projective_dbl_point_safe(R, R, a, modulus, mp);
     2601                   if (err != MP_OKAY) break;
     2602               }
     2603
     2604               bitbuf <<= 1;
     2605               if ((bitbuf & (1 << WINSIZE)) != 0) {
     2606                   if (first == 1) {
     2607                       /* first add, so copy */
     2608                       err = mp_copy(tG->x, R->x);
     2609                       if (err != MP_OKAY) break;
     2610
     2611                       err = mp_copy(tG->y, R->y);
     2612                       if (err != MP_OKAY) break;
     2613
     2614                       err = mp_copy(tG->z, R->z);
     2615                       if (err != MP_OKAY) break;
     2616                       first = 0;
     2617                   } else {
     2618                       /* then add */
     2619                       err = ecc_projective_add_point_safe(R, tG, R, a, modulus,
     2620                                                                 mp, &infinity);
     2621                       if (err != MP_OKAY) break;
     2622                   }
     2623               }
     2624           }
     2625       }
     2626   }
     2627
     2628   #undef WINSIZE
     2629
     2630   return err;
     2631}
     2632
     2633#else
     2634
     2635static int wc_ecc_gen_z(WC_RNG* rng, int size, ecc_point* p,
     2636        mp_int* modulus, mp_digit mp, mp_int* tx, mp_int* ty)
     2637{
     2638    int err = MP_OKAY;
     2639#ifdef WOLFSSL_SMALL_STACK
     2640    mp_int*       mu = NULL;
     2641#else
     2642    mp_int        mu[1];
     2643#endif
     2644
     2645#ifdef WOLFSSL_SMALL_STACK
     2646    mu = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
     2647    if (mu == NULL)
     2648        err = MEMORY_E;
     2649#endif
     2650
     2651    if (err == MP_OKAY)
     2652        err = mp_init(mu);
     2653    if (err == MP_OKAY)
     2654        err = mp_montgomery_calc_normalization(mu, modulus);
     2655    if (err == MP_OKAY)
     2656        err = wc_ecc_gen_k(rng, size, ty, modulus);
     2657    if (err == MP_OKAY)
     2658        err = mp_mulmod(ty, mu, modulus, ty);
     2659    if (err == MP_OKAY)
     2660        err = mp_mul(p->z, ty, p->z);
     2661    if (err == MP_OKAY)
     2662        err = mp_montgomery_reduce(p->z, modulus, mp);
     2663    if (err == MP_OKAY)
     2664        err = mp_sqr(ty, tx);
     2665    if (err == MP_OKAY)
     2666        err = mp_montgomery_reduce(tx, modulus, mp);
     2667    if (err == MP_OKAY)
     2668        err = mp_mul(ty, tx, ty);
     2669    if (err == MP_OKAY)
     2670        err = mp_montgomery_reduce(ty, modulus, mp);
     2671    if (err == MP_OKAY)
     2672        err = mp_mul(p->x, tx, p->x);
     2673    if (err == MP_OKAY)
     2674        err = mp_montgomery_reduce(p->x, modulus, mp);
     2675    if (err == MP_OKAY)
     2676        err = mp_mul(p->y, ty, p->y);
     2677    if (err == MP_OKAY)
     2678        err = mp_montgomery_reduce(p->y, modulus, mp);
     2679
     2680#ifdef WOLFSSL_SMALL_STACK
     2681    if (mu != NULL) {
     2682        mp_clear(mu);
     2683        XFREE(mu, NULL, DYNAMIC_TYPE_ECC);
     2684    }
     2685#else
     2686    mp_clear(mu);
     2687#endif
     2688
     2689    return err;
     2690}
     2691
     2692#define M_POINTS 3
     2693
     2694/* Joye double-add ladder.
     2695 * "Highly Regular Right-to-Left Algorithms for Scalar Multiplication"
     2696 * by Marc Joye (2007)
     2697 *
     2698 * Algorithm 1':
     2699 *   Input: P element of curve, k = (k[t-1],..., k[0]) base 2
     2700 *   Output: Q = kP
     2701 *   1: R[0] = P; R[1] = P
     2702 *   2: for j = 1 to t-1 do
     2703 *   3:   b = 1 - k[j]; R[b] = 2*R[b] + R[k[j]]
     2704 *   4: end for
     2705 *   5: b = k[0]; R[b] = R[b] - P
     2706 *   6: return R[0]
     2707 *
     2708 * Assumes: k < order.
     2709 */
     2710static int ecc_mulmod(mp_int* k, ecc_point* P, ecc_point* Q, ecc_point** R,
     2711    mp_int* a, mp_int* modulus, mp_digit mp, WC_RNG* rng)
     2712{
     2713    int      err = MP_OKAY;
     2714    int      bytes = (mp_count_bits(modulus) + 7) / 8;
     2715    int      i;
     2716    int      j = 1;
     2717    int      cnt = DIGIT_BIT;
     2718    int      t = 0;
     2719    mp_digit b;
     2720    mp_digit v = 0;
     2721#ifndef WC_NO_CACHE_RESISTANT
     2722    /* First bit always 1 (fix at end) and swap equals first bit */
     2723    int      swap = 1;
     2724#endif
     2725    int      infinity;
     2726
     2727    /* Step 1: R[0] = P; R[1] = P */
     2728    /* R[0] = P */
     2729    if (err == MP_OKAY)
     2730        err = mp_copy(P->x, R[0]->x);
     2731    if (err == MP_OKAY)
     2732        err = mp_copy(P->y, R[0]->y);
     2733    if (err == MP_OKAY)
     2734        err = mp_copy(P->z, R[0]->z);
     2735
     2736    /* R[1] = P */
     2737    if (err == MP_OKAY)
     2738        err = mp_copy(P->x, R[1]->x);
     2739    if (err == MP_OKAY)
     2740        err = mp_copy(P->y, R[1]->y);
     2741    if (err == MP_OKAY)
     2742        err = mp_copy(P->z, R[1]->z);
     2743
     2744    /* Randomize z ordinates to obfuscate timing. */
     2745    if ((err == MP_OKAY) && (rng != NULL))
     2746        err = wc_ecc_gen_z(rng, bytes, R[0], modulus, mp, R[2]->x, R[2]->y);
     2747    if ((err == MP_OKAY) && (rng != NULL))
     2748        err = wc_ecc_gen_z(rng, bytes, R[1], modulus, mp, R[2]->x, R[2]->y);
     2749
     2750    if (err == MP_OKAY) {
     2751        /* Order could be one greater than the size of the modulus. */
     2752        t = mp_count_bits(modulus) + 1;
     2753        v = k->dp[0] >> 1;
     2754        if (cnt > t) {
     2755            cnt = t;
     2756        }
     2757        err = mp_grow(k, modulus->used + 1);
     2758    }
     2759    /* Step 2: for j = 1 to t-1 do */
     2760    for (i = 1; (err == MP_OKAY) && (i < t); i++) {
     2761        if (--cnt == 0) {
     2762            v = k->dp[j++];
     2763            cnt = DIGIT_BIT;
     2764        }
     2765
     2766        /* Step 3: b = 1 - k[j]; R[b] = 2*R[b] + R[k[j]] */
     2767        b = v & 1;
     2768        v >>= 1;
     2769#ifdef WC_NO_CACHE_RESISTANT
     2770        err = ecc_projective_dbl_point_safe(R[b^1], R[b^1], a, modulus, mp);
     2771        if (err == MP_OKAY) {
     2772            err = ecc_projective_add_point_safe(R[b^1], R[b], R[b^1], a,
     2773                                                        modulus, mp, &infinity);
     2774        }
     2775#else
     2776        /* Swap R[0] and R[1] if other index is needed. */
     2777        swap ^= b;
     2778        if (err == MP_OKAY)
     2779            err = mp_cond_swap_ct(R[0]->x, R[1]->x, modulus->used, swap);
     2780        if (err == MP_OKAY)
     2781            err = mp_cond_swap_ct(R[0]->y, R[1]->y, modulus->used, swap);
     2782        if (err == MP_OKAY)
     2783            err = mp_cond_swap_ct(R[0]->z, R[1]->z, modulus->used, swap);
     2784        swap = (int)b;
     2785
     2786        if (err == MP_OKAY)
     2787            err = ecc_projective_dbl_point_safe(R[0], R[0], a, modulus, mp);
     2788        if (err == MP_OKAY) {
     2789            err = ecc_projective_add_point_safe(R[0], R[1], R[0], a, modulus,
     2790                                                                 mp, &infinity);
     2791        }
     2792#endif /* WC_NO_CACHE_RESISTANT */
     2793    }
     2794    /* Step 4: end for */
     2795#ifndef WC_NO_CACHE_RESISTANT
     2796    /* Swap back if last bit is 0. */
     2797    swap ^= 1;
     2798    if (err == MP_OKAY)
     2799        err = mp_cond_swap_ct(R[0]->x, R[1]->x, modulus->used, swap);
     2800    if (err == MP_OKAY)
     2801        err = mp_cond_swap_ct(R[0]->y, R[1]->y, modulus->used, swap);
     2802    if (err == MP_OKAY)
     2803        err = mp_cond_swap_ct(R[0]->z, R[1]->z, modulus->used, swap);
     2804#endif
     2805
     2806    /* Step 5: b = k[0]; R[b] = R[b] - P */
     2807    /* R[2] = -P */
     2808    if (err == MP_OKAY)
     2809        err = mp_copy(P->x, R[2]->x);
     2810    if (err == MP_OKAY)
     2811        err = mp_sub(modulus, P->y, R[2]->y);
     2812    if (err == MP_OKAY)
     2813        err = mp_copy(P->z, R[2]->z);
     2814    /* Subtract point by adding negative. */
     2815    if (err == MP_OKAY) {
     2816        b = k->dp[0] & 1;
     2817#ifdef WC_NO_CACHE_RESISTANT
     2818        err = ecc_projective_add_point_safe(R[b], R[2], R[b], a, modulus, mp,
     2819                                                                     &infinity);
     2820#else
     2821        /* Swap R[0] and R[1], if necessary, to operate on the one we want. */
     2822        err = mp_cond_swap_ct(R[0]->x, R[1]->x, modulus->used, (int)b);
     2823        if (err == MP_OKAY)
     2824            err = mp_cond_swap_ct(R[0]->y, R[1]->y, modulus->used, (int)b);
     2825        if (err == MP_OKAY)
     2826            err = mp_cond_swap_ct(R[0]->z, R[1]->z, modulus->used, (int)b);
     2827        if (err == MP_OKAY)
     2828            err = ecc_projective_add_point_safe(R[0], R[2], R[0], a, modulus,
     2829                                                                 mp, &infinity);
     2830        /* Swap back if necessary. */
     2831        if (err == MP_OKAY)
     2832            err = mp_cond_swap_ct(R[0]->x, R[1]->x, modulus->used, (int)b);
     2833        if (err == MP_OKAY)
     2834            err = mp_cond_swap_ct(R[0]->y, R[1]->y, modulus->used, (int)b);
     2835        if (err == MP_OKAY)
     2836            err = mp_cond_swap_ct(R[0]->z, R[1]->z, modulus->used, (int)b);
     2837#endif
     2838    }
     2839
     2840    /* Step 6: return R[0] */
     2841    if (err == MP_OKAY)
     2842        err = mp_copy(R[0]->x, Q->x);
     2843    if (err == MP_OKAY)
     2844        err = mp_copy(R[0]->y, Q->y);
     2845    if (err == MP_OKAY)
     2846        err = mp_copy(R[0]->z, Q->z);
     2847
     2848    return err;
     2849}
     2850
     2851#endif
     2852
     2853/* Convert the point to montogmery form.
     2854 *
     2855 * @param  [in]   p        Point to convert.
     2856 * @param  [out]  r        Point in montgomery form.
     2857 * @param  [in]   modulus  Modulus of ordinates.
     2858 * @return  0 on success.
     2859 * @return  -ve on failure.
     2860 */
     2861static int ecc_point_to_mont(ecc_point* p, ecc_point* r, mp_int* modulus,
     2862                             void* heap)
     2863{
     2864   int err = MP_OKAY;
     2865#ifdef WOLFSSL_SMALL_STACK
     2866   mp_int*       mu = NULL;
     2867#else
     2868   mp_int        mu[1];
     2869#endif
     2870
     2871   (void)heap;
     2872
     2873#ifdef WOLFSSL_SMALL_STACK
     2874   mu = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
     2875   if (mu == NULL)
     2876       err = MEMORY_E;
     2877#endif
     2878   if (err == MP_OKAY)
     2879       err = mp_init(mu);
     2880   if (err == MP_OKAY) {
     2881       err = mp_montgomery_calc_normalization(mu, modulus);
     2882
     2883       if (err == MP_OKAY) {
     2884           if (mp_cmp_d(mu, 1) == MP_EQ) {
     2885               err = mp_copy(p->x, r->x);
     2886               if (err == MP_OKAY)
     2887                   err = mp_copy(p->y, r->y);
     2888               if (err == MP_OKAY)
     2889                   err = mp_copy(p->z, r->z);
     2890           }
     2891           else {
     2892               err = mp_mulmod(p->x, mu, modulus, r->x);
     2893               if (err == MP_OKAY)
     2894                   err = mp_mulmod(p->y, mu, modulus, r->y);
     2895               if (err == MP_OKAY)
     2896                   err = mp_mulmod(p->z, mu, modulus, r->z);
     2897           }
     2898       }
     2899
     2900       mp_clear(mu);
     2901   }
     2902#ifdef WOLFSSL_SMALL_STACK
     2903   if (mu != NULL)
     2904      XFREE(mu, heap, DYNAMIC_TYPE_ECC);
     2905#endif
     2906   return err;
     2907}
     2908
     2909#ifdef WOLFSSL_SMALL_STACK_CACHE
     2910static int ecc_key_tmp_init(ecc_key* key, void* heap)
     2911{
     2912   int err = MP_OKAY;
     2913
     2914   XMEMSET(key, 0, sizeof(*key));
     2915
     2916   key->t1 = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
     2917   key->t2 = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
     2918#ifdef ALT_ECC_SIZE
     2919   key->x = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
     2920   key->y = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
     2921   key->z = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
     2922#endif
     2923   if (key->t1 == NULL || key->t2 == NULL
     2924#ifdef ALT_ECC_SIZE
     2925      || key->x == NULL || key->y == NULL || key->z == NULL
     2926#endif
     2927   ) {
     2928       err = MEMORY_E;
     2929   }
     2930
     2931   return err;
     2932}
     2933
     2934static void ecc_key_tmp_final(ecc_key* key, void* heap)
     2935{
     2936    (void)heap;
     2937#ifdef ALT_ECC_SIZE
     2938   if (key->z != NULL)
     2939      XFREE(key->z, heap, DYNAMIC_TYPE_ECC);
     2940   if (key->y != NULL)
     2941      XFREE(key->y, heap, DYNAMIC_TYPE_ECC);
     2942   if (key->x != NULL)
     2943      XFREE(key->x, heap, DYNAMIC_TYPE_ECC);
     2944#endif
     2945   if (key->t2 != NULL)
     2946      XFREE(key->t2, heap, DYNAMIC_TYPE_ECC);
     2947   if (key->t1 != NULL)
     2948      XFREE(key->t1, heap, DYNAMIC_TYPE_ECC);
     2949}
     2950#endif /* WOLFSSL_SMALL_STACK_CACHE */
     2951#endif /* !WOLFSSL_SP_MATH */
     2952
     2953#if !defined(WOLFSSL_SP_MATH) || !defined(FP_ECC)
    25112954/**
    25122955   Perform a point multiplication
     
    25212964*/
    25222965#ifdef FP_ECC
    2523 static int normal_ecc_mulmod(mp_int* k, ecc_point *G, ecc_point *R,
    2524                   mp_int* a, mp_int* modulus, int map,
    2525                   void* heap)
     2966static int normal_ecc_mulmod(mp_int* k, ecc_point *G, ecc_point *R, mp_int* a,
     2967                             mp_int* modulus, WC_RNG* rng, int map, void* heap)
    25262968#else
    2527 int wc_ecc_mulmod_ex(mp_int* k, ecc_point *G, ecc_point *R,
    2528                   mp_int* a, mp_int* modulus, int map,
    2529                   void* heap)
    2530 #endif
    2531 {
    2532 #ifndef WOLFSSL_SP_MATH
    2533 #ifndef ECC_TIMING_RESISTANT
    2534    /* size of sliding window, don't change this! */
    2535    #define WINSIZE  4
    2536    #define M_POINTS 8
    2537    int           first = 1, bitbuf = 0, bitcpy = 0, j;
    2538 #elif defined(WC_NO_CACHE_RESISTANT)
    2539    #define M_POINTS 4
     2969int wc_ecc_mulmod_ex(mp_int* k, ecc_point *G, ecc_point *R, mp_int* a,
     2970                     mp_int* modulus, int map, void* heap)
     2971#endif
     2972#if !defined(WOLFSSL_SP_MATH)
     2973{
     2974   ecc_point     *tG, *M[M_POINTS];
     2975   int           i, err;
     2976#ifdef WOLFSSL_SMALL_STACK_CACHE
     2977   ecc_key       *key = (ecc_key *)XMALLOC(sizeof *key, heap, DYNAMIC_TYPE_ECC);
     2978#endif
     2979   mp_digit      mp;
     2980
     2981   /* init variables */
     2982   tG = NULL;
     2983   XMEMSET(M, 0, sizeof(M));
     2984
     2985   if (k == NULL || G == NULL || R == NULL || modulus == NULL) {
     2986       err = ECC_BAD_ARG_E;
     2987       goto exit;
     2988   }
     2989
     2990#ifdef WOLFSSL_SMALL_STACK_CACHE
     2991   if (key == NULL) {
     2992       err = MP_MEM;
     2993       goto exit;
     2994   }
     2995   err = ecc_key_tmp_init(key, heap);
     2996   if (err != MP_OKAY)
     2997      goto exit;
     2998   R->key = key;
     2999#endif /* WOLFSSL_SMALL_STACK_CACHE */
     3000
     3001  /* alloc ram for window temps */
     3002  for (i = 0; i < M_POINTS; i++) {
     3003      M[i] = wc_ecc_new_point_h(heap);
     3004      if (M[i] == NULL) {
     3005         err = MEMORY_E;
     3006         goto exit;
     3007      }
     3008#ifdef WOLFSSL_SMALL_STACK_CACHE
     3009      M[i]->key = key;
     3010#endif
     3011  }
     3012
     3013   /* make a copy of G in case R==G */
     3014   tG = wc_ecc_new_point_h(heap);
     3015   if (tG == NULL) {
     3016       err = MEMORY_E;
     3017       goto exit;
     3018   }
     3019   if ((err = ecc_point_to_mont(G, tG, modulus, heap)) != MP_OKAY) {
     3020       goto exit;
     3021   }
     3022
     3023   /* init montgomery reduction */
     3024   if ((err = mp_montgomery_setup(modulus, &mp)) != MP_OKAY) {
     3025       goto exit;
     3026   }
     3027
     3028#ifdef FP_ECC
     3029   err = ecc_mulmod(k, tG, R, M, a, modulus, mp, rng);
    25403030#else
    2541    #define M_POINTS 5
    2542 #endif
    2543 
     3031   err = ecc_mulmod(k, tG, R, M, a, modulus, mp, NULL);
     3032#endif
     3033   /* map R back from projective space */
     3034   if (err == MP_OKAY && map)
     3035       err = ecc_map(R, modulus, mp);
     3036
     3037exit:
     3038
     3039   /* done */
     3040   wc_ecc_del_point_h(tG, heap);
     3041   for (i = 0; i < M_POINTS; i++) {
     3042       wc_ecc_del_point_h(M[i], heap);
     3043   }
     3044#ifdef WOLFSSL_SMALL_STACK_CACHE
     3045   if (key) {
     3046       if (R)
     3047           R->key = NULL;
     3048       if (err == MP_OKAY)
     3049           ecc_key_tmp_final(key, heap);
     3050       XFREE(key, heap, DYNAMIC_TYPE_ECC);
     3051   }
     3052#endif /* WOLFSSL_SMALL_STACK_CACHE */
     3053
     3054   return err;
     3055}
     3056#else
     3057{
     3058   if (k == NULL || G == NULL || R == NULL || modulus == NULL) {
     3059       return ECC_BAD_ARG_E;
     3060   }
     3061
     3062   (void)a;
     3063
     3064#ifdef WOLFSSL_HAVE_SP_ECC
     3065#ifndef WOLFSSL_SP_NO_256
     3066   if (mp_count_bits(modulus) == 256) {
     3067       return sp_ecc_mulmod_256(k, G, R, map, heap);
     3068   }
     3069#endif
     3070#ifdef WOLFSSL_SP_384
     3071   if (mp_count_bits(modulus) == 384) {
     3072       return sp_ecc_mulmod_384(k, G, R, map, heap);
     3073   }
     3074#endif
     3075#else
     3076   (void)map;
     3077   (void)map;
     3078   (void)heap;
     3079#endif
     3080   return ECC_BAD_ARG_E;
     3081}
     3082#endif
     3083#endif /* !WOLFSSL_SP_MATH || !FP_ECC */
     3084
     3085#ifndef FP_ECC
     3086/**
     3087   Perform a point multiplication
     3088   k    The scalar to multiply by
     3089   G    The base point
     3090   R    [out] Destination for kG
     3091   a    ECC curve parameter a
     3092   modulus  The modulus of the field the ECC curve is in
     3093   map      Boolean whether to map back to affine or not
     3094                (1==map, 0 == leave in projective)
     3095   return MP_OKAY on success
     3096*/
     3097int wc_ecc_mulmod_ex2(mp_int* k, ecc_point *G, ecc_point *R, mp_int* a,
     3098                      mp_int* modulus, mp_int* order, WC_RNG* rng, int map,
     3099                      void* heap)
     3100#if !defined(WOLFSSL_SP_MATH)
     3101{
    25443102   ecc_point     *tG, *M[M_POINTS];
    25453103   int           i, err;
     
    25473105   ecc_key       key;
    25483106#endif
    2549 #ifdef WOLFSSL_SMALL_STACK
    2550    mp_int*       mu = NULL;
    2551 #else
    2552    mp_int        mu[1];
    2553 #endif
    25543107   mp_digit      mp;
    2555    mp_digit      buf;
    2556    int           bitcnt = 0, mode = 0, digidx = 0;
     3108#ifdef ECC_TIMING_RESISTANT
     3109   mp_int t;
     3110#endif
    25573111
    25583112   if (k == NULL || G == NULL || R == NULL || modulus == NULL) {
    2559        return ECC_BAD_ARG_E;
     3113      return ECC_BAD_ARG_E;
    25603114   }
    25613115
     
    25633117   tG = NULL;
    25643118   XMEMSET(M, 0, sizeof(M));
    2565 #ifdef WOLFSSL_SMALL_STACK
    2566    mu = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
    2567    if (mu == NULL)
    2568        return MEMORY_E;
    2569 #endif
     3119
    25703120#ifdef WOLFSSL_SMALL_STACK_CACHE
    2571    key.t1 = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
    2572    key.t2 = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
    2573 #ifdef ALT_ECC_SIZE
    2574    key.x = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
    2575    key.y = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
    2576    key.z = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
    2577 #endif
    2578    if (key.t1 == NULL || key.t2 == NULL
    2579 #ifdef ALT_ECC_SIZE
    2580       || key.x == NULL || key.y == NULL || key.z == NULL
    2581 #endif
    2582    ) {
    2583 #ifdef ALT_ECC_SIZE
    2584        XFREE(key.z, heap, DYNAMIC_TYPE_ECC);
    2585        XFREE(key.y, heap, DYNAMIC_TYPE_ECC);
    2586        XFREE(key.x, heap, DYNAMIC_TYPE_ECC);
    2587 #endif
    2588        XFREE(key.t2, heap, DYNAMIC_TYPE_ECC);
    2589        XFREE(key.t1, heap, DYNAMIC_TYPE_ECC);
    2590        XFREE(mu, heap, DYNAMIC_TYPE_ECC);
    2591        return MEMORY_E;
    2592    }
     3121   err = ecc_key_tmp_init(&key, heap);
     3122   if (err != MP_OKAY)
     3123      goto exit;
     3124   R->key = &key;
    25933125#endif /* WOLFSSL_SMALL_STACK_CACHE */
    2594 
    2595    /* init montgomery reduction */
    2596    if ((err = mp_montgomery_setup(modulus, &mp)) != MP_OKAY) {
    2597 #ifdef WOLFSSL_SMALL_STACK_CACHE
    2598 #ifdef ALT_ECC_SIZE
    2599        XFREE(key.z, heap, DYNAMIC_TYPE_ECC);
    2600        XFREE(key.y, heap, DYNAMIC_TYPE_ECC);
    2601        XFREE(key.x, heap, DYNAMIC_TYPE_ECC);
    2602 #endif
    2603        XFREE(key.t2, heap, DYNAMIC_TYPE_ECC);
    2604        XFREE(key.t1, heap, DYNAMIC_TYPE_ECC);
    2605 #endif /* WOLFSSL_SMALL_STACK_CACHE */
    2606 #ifdef WOLFSSL_SMALL_STACK
    2607        XFREE(mu, heap, DYNAMIC_TYPE_ECC);
    2608 #endif
    2609        return err;
    2610    }
    2611 
    2612    if ((err = mp_init(mu)) != MP_OKAY) {
    2613 #ifdef WOLFSSL_SMALL_STACK_CACHE
    2614 #ifdef ALT_ECC_SIZE
    2615        XFREE(key.z, heap, DYNAMIC_TYPE_ECC);
    2616        XFREE(key.y, heap, DYNAMIC_TYPE_ECC);
    2617        XFREE(key.x, heap, DYNAMIC_TYPE_ECC);
    2618 #endif
    2619        XFREE(key.t2, heap, DYNAMIC_TYPE_ECC);
    2620        XFREE(key.t1, heap, DYNAMIC_TYPE_ECC);
    2621 #endif /* WOLFSSL_SMALL_STACK_CACHE */
    2622 #ifdef WOLFSSL_SMALL_STACK
    2623        XFREE(mu, heap, DYNAMIC_TYPE_ECC);
    2624 #endif
    2625        return err;
    2626    }
    2627    if ((err = mp_montgomery_calc_normalization(mu, modulus)) != MP_OKAY) {
    2628        mp_clear(mu);
    2629 #ifdef WOLFSSL_SMALL_STACK_CACHE
    2630 #ifdef ALT_ECC_SIZE
    2631        XFREE(key.z, heap, DYNAMIC_TYPE_ECC);
    2632        XFREE(key.y, heap, DYNAMIC_TYPE_ECC);
    2633        XFREE(key.x, heap, DYNAMIC_TYPE_ECC);
    2634 #endif
    2635        XFREE(key.t2, heap, DYNAMIC_TYPE_ECC);
    2636        XFREE(key.t1, heap, DYNAMIC_TYPE_ECC);
    2637 #endif /* WOLFSSL_SMALL_STACK_CACHE */
    2638 #ifdef WOLFSSL_SMALL_STACK
    2639        XFREE(mu, heap, DYNAMIC_TYPE_ECC);
    2640 #endif
    2641        return err;
    2642    }
    26433126
    26443127  /* alloc ram for window temps */
     
    26463129      M[i] = wc_ecc_new_point_h(heap);
    26473130      if (M[i] == NULL) {
    2648          mp_clear(mu);
    2649          err = MEMORY_E; goto exit;
     3131         err = MEMORY_E;
     3132         goto exit;
    26503133      }
    26513134#ifdef WOLFSSL_SMALL_STACK_CACHE
     
    26563139   /* make a copy of G in case R==G */
    26573140   tG = wc_ecc_new_point_h(heap);
    2658    if (tG == NULL)
     3141   if (tG == NULL) {
    26593142       err = MEMORY_E;
    2660 
    2661    /* tG = G  and convert to montgomery */
     3143       goto exit;
     3144   }
     3145   if ((err = ecc_point_to_mont(G, tG, modulus, heap)) != MP_OKAY) {
     3146       goto exit;
     3147   }
     3148
     3149   /* init montgomery reduction */
     3150   if ((err = mp_montgomery_setup(modulus, &mp)) != MP_OKAY) {
     3151      goto exit;
     3152   }
     3153
     3154   /* k can't have more bits than order */
     3155   if (mp_count_bits(k) > mp_count_bits(order)) {
     3156      err = ECC_OUT_OF_RANGE_E;
     3157      goto exit;
     3158   }
     3159
     3160
     3161#ifdef ECC_TIMING_RESISTANT
     3162   if ((err = mp_init(&t)) != MP_OKAY)
     3163      goto exit;
     3164
     3165   if (err == MP_OKAY)
     3166      err = ecc_mulmod(k, tG, R, M, a, modulus, mp, rng);
     3167
     3168    /* Check for k == order - 1. Result will be 0 point which is not correct
     3169     * Calculates order / 2 and adds order / 2 + 1 and gets infinity.
     3170     * (with constant time implementation)
     3171     */
     3172   if (err == MP_OKAY)
     3173      err = mp_sub_d(order, 1, &t);
    26623174   if (err == MP_OKAY) {
    2663        if (mp_cmp_d(mu, 1) == MP_EQ) {
    2664            err = mp_copy(G->x, tG->x);
    2665            if (err == MP_OKAY)
    2666                err = mp_copy(G->y, tG->y);
    2667            if (err == MP_OKAY)
    2668                err = mp_copy(G->z, tG->z);
    2669        } else {
    2670            err = mp_mulmod(G->x, mu, modulus, tG->x);
    2671            if (err == MP_OKAY)
    2672                err = mp_mulmod(G->y, mu, modulus, tG->y);
    2673            if (err == MP_OKAY)
    2674                err = mp_mulmod(G->z, mu, modulus, tG->z);
    2675        }
    2676    }
    2677 
    2678    /* done with mu */
    2679    mp_clear(mu);
    2680 
    2681 #ifdef WOLFSSL_SMALL_STACK_CACHE
    2682    R->key = &key;
    2683 #endif
    2684 #ifndef ECC_TIMING_RESISTANT
    2685 
    2686    /* calc the M tab, which holds kG for k==8..15 */
    2687    /* M[0] == 8G */
    2688    if (err == MP_OKAY)
    2689        err = ecc_projective_dbl_point(tG, M[0], a, modulus, mp);
    2690    if (err == MP_OKAY)
    2691        err = ecc_projective_dbl_point(M[0], M[0], a, modulus, mp);
    2692    if (err == MP_OKAY)
    2693        err = ecc_projective_dbl_point(M[0], M[0], a, modulus, mp);
    2694 
    2695    /* now find (8+k)G for k=1..7 */
    2696    if (err == MP_OKAY)
    2697        for (j = 9; j < 16; j++) {
    2698            err = ecc_projective_add_point(M[j-9], tG, M[j-M_POINTS], a, modulus,
    2699                                                                             mp);
    2700            if (err != MP_OKAY) break;
    2701        }
    2702 
    2703    /* setup sliding window */
    2704    if (err == MP_OKAY) {
    2705        mode   = 0;
    2706        bitcnt = 1;
    2707        buf    = 0;
    2708        digidx = get_digit_count(k) - 1;
    2709        bitcpy = bitbuf = 0;
    2710        first  = 1;
    2711 
    2712        /* perform ops */
    2713        for (;;) {
    2714            /* grab next digit as required */
    2715            if (--bitcnt == 0) {
    2716                if (digidx == -1) {
    2717                    break;
    2718                }
    2719                buf    = get_digit(k, digidx);
    2720                bitcnt = (int) DIGIT_BIT;
    2721                --digidx;
    2722            }
    2723 
    2724            /* grab the next msb from the ltiplicand */
    2725            i = (int)(buf >> (DIGIT_BIT - 1)) & 1;
    2726            buf <<= 1;
    2727 
    2728            /* skip leading zero bits */
    2729            if (mode == 0 && i == 0)
    2730                continue;
    2731 
    2732            /* if the bit is zero and mode == 1 then we double */
    2733            if (mode == 1 && i == 0) {
    2734                err = ecc_projective_dbl_point(R, R, a, modulus, mp);
    2735                if (err != MP_OKAY) break;
    2736                continue;
    2737            }
    2738 
    2739            /* else we add it to the window */
    2740            bitbuf |= (i << (WINSIZE - ++bitcpy));
    2741            mode = 2;
    2742 
    2743            if (bitcpy == WINSIZE) {
    2744                /* if this is the first window we do a simple copy */
    2745                if (first == 1) {
    2746                    /* R = kG [k = first window] */
    2747                    err = mp_copy(M[bitbuf-M_POINTS]->x, R->x);
    2748                    if (err != MP_OKAY) break;
    2749 
    2750                    err = mp_copy(M[bitbuf-M_POINTS]->y, R->y);
    2751                    if (err != MP_OKAY) break;
    2752 
    2753                    err = mp_copy(M[bitbuf-M_POINTS]->z, R->z);
    2754                    first = 0;
    2755                } else {
    2756                    /* normal window */
    2757                    /* ok window is filled so double as required and add  */
    2758                    /* double first */
    2759                    for (j = 0; j < WINSIZE; j++) {
    2760                        err = ecc_projective_dbl_point(R, R, a, modulus, mp);
    2761                        if (err != MP_OKAY) break;
    2762                    }
    2763                    if (err != MP_OKAY) break;  /* out of first for(;;) */
    2764 
    2765                    /* then add, bitbuf will be 8..15 [8..2^WINSIZE] guaranteed */
    2766                    err = ecc_projective_add_point(R, M[bitbuf-M_POINTS], R, a,
    2767                                                                    modulus, mp);
    2768                }
    2769                if (err != MP_OKAY) break;
    2770                /* empty window and reset */
    2771                bitcpy = bitbuf = 0;
    2772                mode = 1;
    2773            }
    2774        }
    2775    }
    2776 
    2777    /* if bits remain then double/add */
    2778    if (err == MP_OKAY) {
    2779        if (mode == 2 && bitcpy > 0) {
    2780            /* double then add */
    2781            for (j = 0; j < bitcpy; j++) {
    2782                /* only double if we have had at least one add first */
    2783                if (first == 0) {
    2784                    err = ecc_projective_dbl_point(R, R, a, modulus, mp);
    2785                    if (err != MP_OKAY) break;
    2786                }
    2787 
    2788                bitbuf <<= 1;
    2789                if ((bitbuf & (1 << WINSIZE)) != 0) {
    2790                    if (first == 1) {
    2791                        /* first add, so copy */
    2792                        err = mp_copy(tG->x, R->x);
    2793                        if (err != MP_OKAY) break;
    2794 
    2795                        err = mp_copy(tG->y, R->y);
    2796                        if (err != MP_OKAY) break;
    2797 
    2798                        err = mp_copy(tG->z, R->z);
    2799                        if (err != MP_OKAY) break;
    2800                        first = 0;
    2801                    } else {
    2802                        /* then add */
    2803                        err = ecc_projective_add_point(R, tG, R, a, modulus, mp);
    2804                        if (err != MP_OKAY) break;
    2805                    }
    2806                }
    2807            }
    2808        }
    2809    }
    2810 
    2811    #undef WINSIZE
    2812 
    2813 #else /* ECC_TIMING_RESISTANT */
    2814 
    2815    /* calc the M tab */
    2816    /* M[0] == G */
    2817    if (err == MP_OKAY)
    2818        err = mp_copy(tG->x, M[0]->x);
    2819    if (err == MP_OKAY)
    2820        err = mp_copy(tG->y, M[0]->y);
    2821    if (err == MP_OKAY)
    2822        err = mp_copy(tG->z, M[0]->z);
    2823 
    2824    /* M[1] == 2G */
    2825    if (err == MP_OKAY)
    2826        err = ecc_projective_dbl_point(tG, M[1], a, modulus, mp);
    2827 #ifdef WC_NO_CACHE_RESISTANT
    2828    if (err == MP_OKAY)
    2829        err = wc_ecc_copy_point(M[0], M[2]);
     3175      int kIsMinusOne = (mp_cmp(k, &t) == MP_EQ);
     3176      err = mp_cond_copy(tG->x, kIsMinusOne, R->x);
     3177      if (err == 0) {
     3178          err = mp_sub(modulus, tG->y, &t);
     3179      }
     3180      if (err == 0) {
     3181          err = mp_cond_copy(&t, kIsMinusOne, R->y);
     3182      }
     3183      if (err == 0) {
     3184          err = mp_cond_copy(tG->z, kIsMinusOne, R->z);
     3185      }
     3186   }
     3187
     3188   mp_free(&t);
    28303189#else
    2831    if (err == MP_OKAY)
    2832        err = wc_ecc_copy_point(M[0], M[3]);
    2833    if (err == MP_OKAY)
    2834        err = wc_ecc_copy_point(M[1], M[4]);
    2835 #endif
    2836 
    2837    /* setup sliding window */
    2838    mode   = 0;
    2839    bitcnt = 1;
    2840    buf    = 0;
    2841    digidx = get_digit_count(modulus) - 1;
    2842    /* The order MAY be 1 bit longer than the modulus. */
    2843    digidx += (modulus->dp[digidx] >> (DIGIT_BIT-1));
    2844 
    2845    /* perform ops */
    2846    if (err == MP_OKAY) {
    2847        for (;;) {
    2848            /* grab next digit as required */
    2849            if (--bitcnt == 0) {
    2850                if (digidx == -1) {
    2851                    break;
    2852                }
    2853                buf = get_digit(k, digidx);
    2854                bitcnt = (int)DIGIT_BIT;
    2855                --digidx;
    2856            }
    2857 
    2858            /* grab the next msb from the multiplicand */
    2859            i = (buf >> (DIGIT_BIT - 1)) & 1;
    2860            buf <<= 1;
    2861 
    2862 #ifdef WC_NO_CACHE_RESISTANT
    2863            if (mode == 0) {
    2864                /* timing resistant - dummy operations */
    2865                if (err == MP_OKAY)
    2866                    err = ecc_projective_add_point(M[1], M[2], M[2], a, modulus,
    2867                                                   mp);
    2868                if (err == MP_OKAY)
    2869                    err = ecc_projective_dbl_point(M[2], M[3], a, modulus, mp);
    2870            }
    2871            else {
    2872                if (err == MP_OKAY)
    2873                    err = ecc_projective_add_point(M[0], M[1], M[i^1], a,
    2874                                                   modulus, mp);
    2875                if (err == MP_OKAY)
    2876                    err = ecc_projective_dbl_point(M[i], M[i], a, modulus, mp);
    2877            }
    2878 #else
    2879            if (err == MP_OKAY)
    2880                err = ecc_projective_add_point(M[0], M[1], M[2], a, modulus, mp);
    2881            if (err == MP_OKAY)
    2882                err = mp_cond_copy(M[2]->x, i, M[0]->x);
    2883            if (err == MP_OKAY)
    2884                err = mp_cond_copy(M[2]->y, i, M[0]->y);
    2885            if (err == MP_OKAY)
    2886                err = mp_cond_copy(M[2]->z, i, M[0]->z);
    2887            if (err == MP_OKAY)
    2888                err = mp_cond_copy(M[2]->x, i ^ 1, M[1]->x);
    2889            if (err == MP_OKAY)
    2890                err = mp_cond_copy(M[2]->y, i ^ 1, M[1]->y);
    2891            if (err == MP_OKAY)
    2892                err = mp_cond_copy(M[2]->z, i ^ 1, M[1]->z);
    2893 
    2894            if (err == MP_OKAY)
    2895                err = mp_cond_copy(M[0]->x, i ^ 1, M[2]->x);
    2896            if (err == MP_OKAY)
    2897                err = mp_cond_copy(M[0]->y, i ^ 1, M[2]->y);
    2898            if (err == MP_OKAY)
    2899                err = mp_cond_copy(M[0]->z, i ^ 1, M[2]->z);
    2900            if (err == MP_OKAY)
    2901                err = mp_cond_copy(M[1]->x, i, M[2]->x);
    2902            if (err == MP_OKAY)
    2903                err = mp_cond_copy(M[1]->y, i, M[2]->y);
    2904            if (err == MP_OKAY)
    2905                err = mp_cond_copy(M[1]->z, i, M[2]->z);
    2906 
    2907            if (err == MP_OKAY)
    2908                err = ecc_projective_dbl_point(M[2], M[2], a, modulus, mp);
    2909            if (err == MP_OKAY)
    2910                err = mp_cond_copy(M[2]->x, i ^ 1, M[0]->x);
    2911            if (err == MP_OKAY)
    2912                err = mp_cond_copy(M[2]->y, i ^ 1, M[0]->y);
    2913            if (err == MP_OKAY)
    2914                err = mp_cond_copy(M[2]->z, i ^ 1, M[0]->z);
    2915            if (err == MP_OKAY)
    2916                err = mp_cond_copy(M[2]->x, i, M[1]->x);
    2917            if (err == MP_OKAY)
    2918                err = mp_cond_copy(M[2]->y, i, M[1]->y);
    2919            if (err == MP_OKAY)
    2920                err = mp_cond_copy(M[2]->z, i, M[1]->z);
    2921 
    2922            if (err == MP_OKAY)
    2923                err = mp_cond_copy(M[3]->x, (mode ^ 1) & i, M[0]->x);
    2924            if (err == MP_OKAY)
    2925                err = mp_cond_copy(M[3]->y, (mode ^ 1) & i, M[0]->y);
    2926            if (err == MP_OKAY)
    2927                err = mp_cond_copy(M[3]->z, (mode ^ 1) & i, M[0]->z);
    2928            if (err == MP_OKAY)
    2929                err = mp_cond_copy(M[4]->x, (mode ^ 1) & i, M[1]->x);
    2930            if (err == MP_OKAY)
    2931                err = mp_cond_copy(M[4]->y, (mode ^ 1) & i, M[1]->y);
    2932            if (err == MP_OKAY)
    2933                err = mp_cond_copy(M[4]->z, (mode ^ 1) & i, M[1]->z);
    2934 #endif /* WC_NO_CACHE_RESISTANT */
    2935 
    2936            if (err != MP_OKAY)
    2937                break;
    2938 
    2939            mode |= i;
    2940        } /* end for */
    2941    }
    2942 
    2943    /* copy result out */
    2944    if (err == MP_OKAY)
    2945        err = mp_copy(M[0]->x, R->x);
    2946    if (err == MP_OKAY)
    2947        err = mp_copy(M[0]->y, R->y);
    2948    if (err == MP_OKAY)
    2949        err = mp_copy(M[0]->z, R->z);
    2950 
    2951 #endif /* ECC_TIMING_RESISTANT */
    2952 
     3190   err = ecc_mulmod(k, tG, R, M, a, modulus, mp, rng);
     3191
     3192   (void)order;
     3193#endif
    29533194   /* map R back from projective space */
    29543195   if (err == MP_OKAY && map)
    2955        err = ecc_map(R, modulus, mp);
     3196      err = ecc_map(R, modulus, mp);
    29563197
    29573198exit:
     
    29603201   wc_ecc_del_point_h(tG, heap);
    29613202   for (i = 0; i < M_POINTS; i++) {
    2962        wc_ecc_del_point_h(M[i], heap);
     3203      wc_ecc_del_point_h(M[i], heap);
    29633204   }
    29643205#ifdef WOLFSSL_SMALL_STACK_CACHE
    29653206   R->key = NULL;
    2966 #ifdef ALT_ECC_SIZE
    2967    XFREE(key.z, heap, DYNAMIC_TYPE_ECC);
    2968    XFREE(key.y, heap, DYNAMIC_TYPE_ECC);
    2969    XFREE(key.x, heap, DYNAMIC_TYPE_ECC);
    2970 #endif
    2971    XFREE(key.t2, heap, DYNAMIC_TYPE_ECC);
    2972    XFREE(key.t1, heap, DYNAMIC_TYPE_ECC);
     3207   ecc_key_tmp_final(&key, heap);
    29733208#endif /* WOLFSSL_SMALL_STACK_CACHE */
    2974 #ifdef WOLFSSL_SMALL_STACK
    2975    XFREE(mu, heap, DYNAMIC_TYPE_ECC);
    2976 #endif
    29773209
    29783210   return err;
     3211}
    29793212#else
     3213{
    29803214   if (k == NULL || G == NULL || R == NULL || modulus == NULL) {
    29813215       return ECC_BAD_ARG_E;
     
    29833217
    29843218   (void)a;
    2985 
     3219   (void)order;
     3220   (void)rng;
     3221
     3222#ifdef WOLFSSL_HAVE_SP_ECC
    29863223#ifndef WOLFSSL_SP_NO_256
    29873224   if (mp_count_bits(modulus) == 256) {
     
    29943231   }
    29953232#endif
     3233#else
     3234   (void)map;
     3235   (void)heap;
     3236#endif
    29963237   return ECC_BAD_ARG_E;
    2997 #endif
    2998 }
    2999 
    3000 #endif /* !FP_ECC || !WOLFSSL_SP_MATH */
     3238}
     3239#endif /* !WOLFSSL_SP_MATH */
     3240#endif /* !FP_ECC */
    30013241
    30023242#endif /* !FREESCALE_LTC_ECC && !WOLFSSL_STM32_PKA */
     
    35353775{
    35363776   int err;
    3537 #if defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_ATECC508A)
     3777#if defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_ATECC508A) && \
     3778   !defined(WOLFSSL_ATECC608A)
    35383779   CRYS_ECDH_TempData_t tempBuff;
    35393780#endif
     
    35693810   }
    35703811
    3571 #ifdef WOLFSSL_ATECC508A
     3812#if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A)
    35723813   /* For SECP256R1 use hardware */
    35733814   if (private_key->dp->id == ECC_SECP256R1) {
     
    35913832        return err;
    35923833    }
    3593 
     3834#elif defined(WOLFSSL_SILABS_SE_ACCEL)
     3835    err = silabs_ecc_shared_secret(private_key, public_key, out, outlen);
    35943836#else
    35953837   err = wc_ecc_shared_secret_ex(private_key, &public_key->pubkey, out, outlen);
     
    36003842
    36013843
    3602 #if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
     3844#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A) && \
     3845    !defined(WOLFSSL_CRYPTOCELL)
    36033846
    36043847static int wc_ecc_shared_secret_gen_sync(ecc_key* private_key, ecc_point* point,
    36053848                               byte* out, word32* outlen, ecc_curve_spec* curve)
    36063849{
    3607     int err;
    3608 #ifndef WOLFSSL_SP_MATH
     3850    int err = MP_OKAY;
     3851#if !defined(WOLFSSL_SP_MATH)
    36093852    ecc_point* result = NULL;
    36103853    word32 x = 0;
     
    36143857    mp_int k_lcl;
    36153858
     3859    WOLFSSL_ENTER("wc_ecc_shared_secret_gen_sync");
    36163860    /* if cofactor flag has been set */
    36173861    if (private_key->flags & WC_ECC_FLAG_COFACTOR) {
     
    36303874        }
    36313875    }
     3876#else
     3877    WOLFSSL_ENTER("wc_ecc_shared_secret_gen_sync");
    36323878#endif
    36333879
     
    36473893    else
    36483894#endif
    3649 #endif
    3650 #ifdef WOLFSSL_SP_MATH
     3895#else
     3896    (void)point;
     3897    (void)out;
     3898    (void)outlen;
     3899    (void)k;
     3900#endif
     3901#if defined(WOLFSSL_SP_MATH)
    36513902    {
    36523903        err = WC_KEY_SIZE_E;
     
    36683919        }
    36693920
    3670         /* Map in a separate call as this should be constant time */
    3671         err = wc_ecc_mulmod_ex(k, point, result, curve->Af, curve->prime, 0,
    3672                                                              private_key->heap);
     3921#ifdef ECC_TIMING_RESISTANT
     3922        if (private_key->rng == NULL) {
     3923            err = MISSING_RNG_E;
     3924        }
     3925#endif
     3926
     3927        if (err == MP_OKAY) {
     3928            /* Map in a separate call as this should be constant time */
     3929#ifdef ECC_TIMING_RESISTANT
     3930            err = wc_ecc_mulmod_ex2(k, point, result, curve->Af, curve->prime,
     3931                                              curve->order, private_key->rng, 0,
     3932                                              private_key->heap);
     3933#else
     3934            err = wc_ecc_mulmod_ex2(k, point, result, curve->Af, curve->prime,
     3935                                      curve->order, NULL, 0, private_key->heap);
     3936#endif
     3937        }
    36733938        if (err == MP_OKAY) {
    36743939            err = mp_montgomery_setup(curve->prime, &mp);
     
    37003965#endif
    37013966
     3967    WOLFSSL_LEAVE("wc_ecc_shared_secret_gen_sync", err);
     3968
    37023969    return err;
    37033970}
     
    37113978
    37123979#if defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA)
    3713 #ifdef HAVE_CAVIUM_V
    3714     /* verify the curve is supported by hardware */
    3715     if (NitroxEccIsCurveSupported(private_key))
    3716 #endif
    3717     {
     3980    if (private_key->dp
     3981    #ifdef WOLFSSL_CUSTOM_CURVES
     3982        && private_key->dp->id != ECC_CURVE_CUSTOM
     3983    #endif
     3984    #ifdef HAVE_CAVIUM_V
     3985        /* verify the curve is supported by hardware */
     3986        && NitroxEccIsCurveSupported(private_key)
     3987    #endif
     3988    ) {
    37183989        word32 keySz = private_key->dp->size;
    37193990
     
    37704041{
    37714042    int err;
    3772     DECLARE_CURVE_SPECS(curve, 2);
     4043    DECLARE_CURVE_SPECS(curve, 3);
    37734044
    37744045    if (private_key == NULL || point == NULL || out == NULL ||
     
    37784049
    37794050    /* load curve info */
    3780     ALLOC_CURVE_SPECS(2);
     4051    ALLOC_CURVE_SPECS(3);
    37814052    err = wc_ecc_curve_load(private_key->dp, &curve,
    3782         (ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF));
     4053        (ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF | ECC_CURVE_FIELD_ORDER));
    37834054    if (err != MP_OKAY) {
    37844055        FREE_CURVE_SPECS();
     
    38264097    if (private_key->type != ECC_PRIVATEKEY &&
    38274098            private_key->type != ECC_PRIVATEKEY_ONLY) {
     4099        WOLFSSL_MSG("ECC_BAD_ARG_E");
    38284100        return ECC_BAD_ARG_E;
    38294101    }
    38304102
    38314103    /* Verify domain params supplied */
    3832     if (wc_ecc_is_valid_idx(private_key->idx) == 0)
     4104    if (wc_ecc_is_valid_idx(private_key->idx) == 0) {
     4105        WOLFSSL_MSG("wc_ecc_is_valid_idx failed");
    38334106        return ECC_BAD_ARG_E;
     4107    }
    38344108
    38354109    switch(private_key->state) {
     
    38654139    } /* switch */
    38664140
     4141    WOLFSSL_LEAVE("wc_ecc_shared_secret_ex", err);
     4142
    38674143    /* if async pending then return and skip done cleanup below */
    38684144    if (err == WC_PENDING_E) {
     
    38824158#endif /* HAVE_ECC_DHE */
    38834159
    3884 
    3885 #if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
     4160#ifdef USE_ECC_B_PARAM
     4161/* Checks if a point p lies on the curve with index curve_idx */
     4162int wc_ecc_point_is_on_curve(ecc_point *p, int curve_idx)
     4163{
     4164    int err;
     4165    DECLARE_CURVE_SPECS(curve, 3);
     4166
     4167    if (p == NULL)
     4168        return BAD_FUNC_ARG;
     4169
     4170    /* is the IDX valid ?  */
     4171    if (wc_ecc_is_valid_idx(curve_idx) != 1) {
     4172       return ECC_BAD_ARG_E;
     4173    }
     4174
     4175    ALLOC_CURVE_SPECS(3);
     4176    err = wc_ecc_curve_load(wc_ecc_get_curve_params(curve_idx), &curve,
     4177                                ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF |
     4178                                ECC_CURVE_FIELD_BF);
     4179    if (err == MP_OKAY) {
     4180        err = wc_ecc_is_point(p, curve->Af, curve->Bf, curve->prime);
     4181    }
     4182
     4183    wc_ecc_curve_free(curve);
     4184    FREE_CURVE_SPECS();
     4185
     4186    return err;
     4187}
     4188#endif /* USE_ECC_B_PARAM */
     4189
     4190#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A) && \
     4191    !defined(WOLFSSL_CRYPTOCELL)
    38864192/* return 1 if point is at infinity, 0 if not, < 0 on error */
    38874193int wc_ecc_point_is_at_infinity(ecc_point* p)
     
    38954201    return 0;
    38964202}
     4203#endif /* !WOLFSSL_ATECC508A && !WOLFSSL_CRYPTOCELL */
    38974204
    38984205/* generate random and ensure its greater than 0 and less than order */
     
    39384245#endif /* !WC_NO_RNG */
    39394246}
    3940 #endif /* !WOLFSSL_ATECC508A && !WOLFSSL_CRYPTOCELL */
    39414247
    39424248static WC_INLINE void wc_ecc_reset(ecc_key* key)
     
    39454251    key->state = ECC_STATE_NONE;
    39464252}
    3947 
    39484253
    39494254/* create the public ECC key from a private key
     
    39604265 * returns MP_OKAY on success
    39614266 */
    3962 static int wc_ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curveIn,
    3963         ecc_point* pubOut)
     4267static int ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curveIn,
     4268        ecc_point* pubOut, WC_RNG* rng)
    39644269{
    39654270    int err = MP_OKAY;
    3966 #ifndef WOLFSSL_ATECC508A
    3967 #ifndef WOLFSSL_SP_MATH
     4271#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A) \
     4272  && !defined(WOLFSSL_SILABS_SE_ACCEL)
     4273#if !defined(WOLFSSL_SP_MATH)
    39684274    ecc_point* base = NULL;
    39694275#endif
     
    39724278#endif /* !WOLFSSL_ATECC508A */
    39734279
     4280    (void)rng;
     4281
    39744282    if (key == NULL) {
    39754283        return BAD_FUNC_ARG;
    39764284    }
    39774285
    3978 #ifndef WOLFSSL_ATECC508A
     4286#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A) \
     4287  && !defined(WOLFSSL_SILABS_SE_ACCEL)
    39794288
    39804289    /* if ecc_point passed in then use it as output for public key point */
     
    39994308            err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL);
    40004309        }
     4310    }
     4311
     4312    if ((err == MP_OKAY) && (mp_iszero(&key->k) || mp_isneg(&key->k) ||
     4313                                      (mp_cmp(&key->k, curve->order) != MP_LT)))
     4314    {
     4315        err = ECC_PRIV_KEY_E;
    40014316    }
    40024317
     
    40144329    }
    40154330
    4016 
    40174331    if (err != MP_OKAY) {
    40184332    }
     
    40324346#endif
    40334347#endif
    4034 #ifdef WOLFSSL_SP_MATH
     4348#if defined(WOLFSSL_SP_MATH)
    40354349        err = WC_KEY_SIZE_E;
    40364350#else
    40374351    {
    4038         mp_digit mp;
     4352        mp_digit mp = 0;
    40394353
    40404354        base = wc_ecc_new_point_h(key->heap);
     
    40474361            err = mp_copy(curve->Gy, base->y);
    40484362        if (err == MP_OKAY)
     4363            err = mp_montgomery_setup(curve->prime, &mp);
     4364        if (err == MP_OKAY)
    40494365            err = mp_set(base->z, 1);
    40504366
     
    40524368        if (err == MP_OKAY) {
    40534369            /* Map in a separate call as this should be constant time */
    4054             err = wc_ecc_mulmod_ex(&key->k, base, pub, curve->Af, curve->prime,
    4055                                                                  0, key->heap);
     4370            err = wc_ecc_mulmod_ex2(&key->k, base, pub, curve->Af, curve->prime,
     4371                                               curve->order, rng, 0, key->heap);
    40564372            if (err == MP_MEM) {
    40574373               err = MEMORY_E;
    40584374            }
    4059         }
    4060         if (err == MP_OKAY) {
    4061             err = mp_montgomery_setup(curve->prime, &mp);
    40624375        }
    40634376        if (err == MP_OKAY) {
     
    40954408    (void)curveIn;
    40964409    err = NOT_COMPILED_IN;
    4097 #endif /* WOLFSSL_ATECC508A */
     4410#endif /* WOLFSSL_ATECC508A || WOLFSSL_SILABS_SE_ACCEL */
    40984411
    40994412    /* change key state if public part is cached */
     
    41194432    WOLFSSL_ENTER("wc_ecc_make_pub");
    41204433
    4121     return wc_ecc_make_pub_ex(key, NULL, pubOut);
    4122 }
    4123 
    4124 
    4125 WOLFSSL_ABI
    4126 int wc_ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, int curve_id)
    4127 {
     4434    return ecc_make_pub_ex(key, NULL, pubOut, NULL);
     4435}
     4436
     4437/* create the public ECC key from a private key - mask timing use random z
     4438 *
     4439 * key     an initialized private key to generate public part from
     4440 * pubOut  [out]ecc_point holding the public key, if NULL then public key part
     4441 *         is cached in key instead.
     4442 *
     4443 *
     4444 * returns MP_OKAY on success
     4445 */
     4446int wc_ecc_make_pub_ex(ecc_key* key, ecc_point* pubOut, WC_RNG* rng)
     4447{
     4448    WOLFSSL_ENTER("wc_ecc_make_pub");
     4449
     4450    return ecc_make_pub_ex(key, NULL, pubOut, rng);
     4451}
     4452
     4453
     4454int wc_ecc_make_key_ex2(WC_RNG* rng, int keysize, ecc_key* key, int curve_id,
     4455                        int flags)
     4456{
     4457
    41284458    int err;
    4129 #if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
    4130 #ifndef WOLFSSL_SP_MATH
     4459#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A) && \
     4460    !defined(WOLFSSL_CRYPTOCELL)
     4461#if !defined(WOLFSSL_SP_MATH)
    41314462    DECLARE_CURVE_SPECS(curve, ECC_CURVE_FIELD_COUNT);
    41324463#endif
    41334464#endif /* !WOLFSSL_ATECC508A */
    4134 #if defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_ATECC508A)
     4465#if defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_ATECC508A) && \
     4466    !defined(WOLFSSL_ATECC608A)
    41354467    const CRYS_ECPKI_Domain_t*  pDomain;
    41364468    CRYS_ECPKI_KG_TempData_t    tempBuff;
     
    41504482        return err;
    41514483    }
     4484
     4485    key->flags = flags;
    41524486
    41534487#ifdef WOLF_CRYPTO_CB
     
    41794513#endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_ECC */
    41804514
    4181 #ifdef WOLFSSL_ATECC508A
     4515#if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A)
    41824516   if (key->dp->id == ECC_SECP256R1) {
    41834517       key->type = ECC_PRIVATEKEY;
     
    42514585    }
    42524586
     4587#elif defined(WOLFSSL_SILABS_SE_ACCEL)
     4588    return silabs_ecc_make_key(key, keysize);
    42534589#else
    42544590
     
    42754611
    42764612   { /* software key gen */
    4277 #ifdef WOLFSSL_SP_MATH
     4613#if defined(WOLFSSL_SP_MATH)
    42784614        err = WC_KEY_SIZE_E;
    42794615#else
     
    42944630        /* generate public key from k */
    42954631        if (err == MP_OKAY)
    4296             err = wc_ecc_make_pub_ex(key, curve, NULL);
     4632            err = ecc_make_pub_ex(key, curve, NULL, rng);
    42974633
    42984634        if (err == MP_OKAY)
     
    43274663}
    43284664
     4665WOLFSSL_ABI
     4666int wc_ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, int curve_id)
     4667{
     4668    return wc_ecc_make_key_ex2(rng, keysize, key, curve_id, WC_ECC_FLAG_NONE);
     4669}
     4670
    43294671#ifdef ECC_DUMP_OID
    43304672/* Optional dump of encoded OID for adding new curves */
     
    44524794#endif
    44534795
    4454 #ifdef WOLFSSL_ATECC508A
     4796#if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A)
    44554797    key->slot = ATECC_INVALID_SLOT;
    44564798#else
     
    44984840}
    44994841
    4500 #ifdef HAVE_PKCS11
     4842#ifdef WOLF_CRYPTO_CB
    45014843int wc_ecc_init_id(ecc_key* key, unsigned char* id, int len, void* heap,
    45024844                   int devId)
     
    45114853    if (ret == 0)
    45124854        ret = wc_ecc_init_ex(key, heap, devId);
    4513 
    45144855    if (ret == 0 && id != NULL && len != 0) {
    45154856        XMEMCPY(key->id, id, len);
    45164857        key->idLen = len;
     4858    }
     4859
     4860    return ret;
     4861}
     4862
     4863int wc_ecc_init_label(ecc_key* key, const char* label, void* heap, int devId)
     4864{
     4865    int ret = 0;
     4866    int labelLen = 0;
     4867
     4868    if (key == NULL || label == NULL)
     4869        ret = BAD_FUNC_ARG;
     4870    if (ret == 0) {
     4871        labelLen = (int)XSTRLEN(label);
     4872        if (labelLen == 0 || labelLen > ECC_MAX_LABEL_LEN)
     4873            ret = BUFFER_E;
     4874    }
     4875
     4876    if (ret == 0)
     4877        ret = wc_ecc_init_ex(key, heap, devId);
     4878    if (ret == 0) {
     4879        XMEMCPY(key->label, label, labelLen);
     4880        key->labelLen = labelLen;
    45174881    }
    45184882
     
    45544918#ifndef NO_ASN
    45554919
    4556 #if defined(WOLFSSL_ATECC508A) || defined(PLUTON_CRYPTO_ECC) || \
    4557     defined(WOLFSSL_CRYPTOCELL)
     4920
     4921#if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A) ||  \
     4922    defined(PLUTON_CRYPTO_ECC) || defined(WOLFSSL_CRYPTOCELL) || \
     4923    defined(WOLFSSL_SILABS_SE_ACCEL)
    45584924static int wc_ecc_sign_hash_hw(const byte* in, word32 inlen,
    45594925    mp_int* r, mp_int* s, byte* out, word32 *outlen, WC_RNG* rng,
     
    45654931#endif
    45664932    {
    4567     #if defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_ATECC508A)
     4933    #if defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_ATECC508A) && \
     4934        !defined(WOLFSSL_ATECC608A)
    45684935        CRYS_ECDSA_SignUserContext_t sigCtxTemp;
    45694936        word32 raw_sig_size = *outlen;
     
    45724939    #endif
    45734940        word32 keysize = (word32)key->dp->size;
     4941    #ifdef PLUTON_CRYPTO_ECC
    45744942        word32 orderBits = wc_ecc_get_curve_order_bit_count(key->dp);
     4943    #endif
    45754944
    45764945        /* Check args */
     
    45794948        }
    45804949
    4581     #if defined(WOLFSSL_ATECC508A)
    4582         key->slot = atmel_ecc_alloc(ATMEL_SLOT_DEVICE);
    4583         if (key->slot == ATECC_INVALID_SLOT) {
    4584             return ECC_BAD_ARG_E;
    4585         }
    4586 
     4950    #if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A)
    45874951        /* Sign: Result is 32-bytes of R then 32-bytes of S */
    45884952        err = atmel_ecc_sign(key->slot, in, out);
     
    46044968            }
    46054969        }
     4970    #elif defined(WOLFSSL_SILABS_SE_ACCEL)
     4971        err = silabs_ecc_sign_hash(in, inlen, out, outlen, key);
     4972        if (err != 0) {
     4973               return WC_HW_E;
     4974        }
    46064975    #elif defined(WOLFSSL_CRYPTOCELL)
    4607 
     4976        /* truncate if hash is longer than key size */
     4977        if (msgLenInBytes > keysize) {
     4978            msgLenInBytes = keysize;
     4979        }
    46084980        hash_mode = cc310_hashModeECC(msgLenInBytes);
    46094981        if (hash_mode == CRYS_ECPKI_HASH_OpModeLast) {
    46104982            hash_mode = cc310_hashModeECC(keysize);
    46114983            hash_mode = CRYS_ECPKI_HASH_SHA256_mode;
    4612         }
    4613 
    4614         /* truncate if hash is longer than key size */
    4615         if (msgLenInBytes > keysize) {
    4616             msgLenInBytes = keysize;
     4984
    46174985        }
    46184986
     
    48005168
    48015169/* hardware crypto */
    4802 #if defined(WOLFSSL_ATECC508A) || defined(PLUTON_CRYPTO_ECC) || defined(WOLFSSL_CRYPTOCELL)
     5170#if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A) || \
     5171    defined(PLUTON_CRYPTO_ECC) || defined(WOLFSSL_CRYPTOCELL) || \
     5172  defined(WOLFSSL_SILABS_SE_ACCEL)
    48035173    err = wc_ecc_sign_hash_hw(in, inlen, r, s, out, outlen, rng, key);
    48045174#else
     
    48065176#endif
    48075177    if (err < 0) {
     5178        mp_clear(r);
     5179        mp_clear(s);
    48085180    #ifdef WOLFSSL_SMALL_STACK
    48095181        XFREE(s, key->heap, DYNAMIC_TYPE_ECC);
     
    48365208    return stm32_ecc_sign_hash_ex(in, inlen, rng, key, r, s);
    48375209}
    4838 #elif !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
     5210#elif !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A) && \
     5211      !defined(WOLFSSL_CRYPTOCELL)
    48395212/**
    48405213  Sign a message digest
     
    48505223{
    48515224   int    err = 0;
    4852 #ifndef WOLFSSL_SP_MATH
     5225#if !defined(WOLFSSL_SP_MATH)
    48535226   mp_int* e;
    48545227#if (!defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V)) && \
     
    48575230#endif
    48585231
    4859 #if defined(WOLFSSL_ECDSA_SET_K) || \
     5232#if defined(WOLFSSL_ECDSA_SET_K) || defined(WOLFSSL_ECDSA_SET_K_ONE_LOOP) || \
    48605233    (defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \
    48615234    (defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA)))
     
    48805253   }
    48815254
    4882 #ifdef WOLFSSL_SP_MATH
    4883 #ifndef WOLFSSL_SP_NO_256
    4884     if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) {
    4885     #ifndef WOLFSSL_ECDSA_SET_K
    4886         return sp_ecc_sign_256(in, inlen, rng, &key->k, r, s, NULL, key->heap);
     5255#if defined(WOLFSSL_SP_MATH)
     5256    if (key->idx == ECC_CUSTOM_IDX ||
     5257            (ecc_sets[key->idx].id != ECC_SECP256R1 &&
     5258             ecc_sets[key->idx].id != ECC_SECP384R1)) {
     5259        return WC_KEY_SIZE_E;
     5260    }
     5261#endif
     5262
     5263#if (defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_SP_MATH_ALL)) && \
     5264                                                    defined(WOLFSSL_HAVE_SP_ECC)
     5265    if (key->idx != ECC_CUSTOM_IDX
     5266    #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
     5267        && key->asyncDev.marker != WOLFSSL_ASYNC_MARKER_ECC
     5268    #endif
     5269    ) {
     5270    #if defined(WOLFSSL_ECDSA_SET_K) || defined(WOLFSSL_ECDSA_SET_K_ONE_LOOP)
     5271        mp_int* sign_k = key->sign_k;
    48875272    #else
    4888         return sp_ecc_sign_256(in, inlen, rng, &key->k, r, s, key->sign_k,
    4889                                                                      key->heap);
     5273        mp_int* sign_k = NULL;
    48905274    #endif
    4891     }
    4892 #endif
    4893 #ifdef WOLFSSL_SP_384
    4894     if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) {
    4895     #ifndef WOLFSSL_ECDSA_SET_K
    4896         return sp_ecc_sign_384(in, inlen, rng, &key->k, r, s, NULL, key->heap);
    4897     #else
    4898         return sp_ecc_sign_384(in, inlen, rng, &key->k, r, s, key->sign_k,
    4899                                                                      key->heap);
     5275    #if defined(WC_ECC_NONBLOCK) && defined(WC_ECC_NONBLOCK_ONLY)
     5276        /* perform blocking call to non-blocking function */
     5277        ecc_nb_ctx_t nb_ctx;
     5278        XMEMSET(&nb_ctx, 0, sizeof(nb_ctx));
    49005279    #endif
    4901     }
    4902 #endif
    4903     return WC_KEY_SIZE_E;
     5280    #ifndef WOLFSSL_SP_NO_256
     5281        if (ecc_sets[key->idx].id == ECC_SECP256R1) {
     5282        #ifdef WC_ECC_NONBLOCK
     5283            if (key->nb_ctx) {
     5284                return sp_ecc_sign_256_nb(&key->nb_ctx->sp_ctx, in, inlen, rng,
     5285                    &key->k, r, s, sign_k, key->heap);
     5286            }
     5287            #ifdef WC_ECC_NONBLOCK_ONLY
     5288            do { /* perform blocking call to non-blocking function */
     5289                err = sp_ecc_sign_256_nb(&nb_ctx.sp_ctx, in, inlen, rng,
     5290                    &key->k, r, s, sign_k, key->heap);
     5291            } while (err == FP_WOULDBLOCK);
     5292            return err;
     5293            #endif
     5294        #endif /* WC_ECC_NONBLOCK */
     5295        #if !defined(WC_ECC_NONBLOCK) || (defined(WC_ECC_NONBLOCK) && !defined(WC_ECC_NONBLOCK_ONLY))
     5296            return sp_ecc_sign_256(in, inlen, rng, &key->k, r, s, sign_k,
     5297                key->heap);
     5298        #endif
     5299        }
     5300    #endif
     5301    #ifdef WOLFSSL_SP_384
     5302        if (ecc_sets[key->idx].id == ECC_SECP384R1) {
     5303        #ifdef WC_ECC_NONBLOCK
     5304            if (key->nb_ctx) {
     5305                return sp_ecc_sign_384_nb(&key->nb_ctx->sp_ctx, in, inlen, rng,
     5306                    &key->k, r, s, sign_k, key->heap);
     5307            }
     5308            #ifdef WC_ECC_NONBLOCK_ONLY
     5309            do { /* perform blocking call to non-blocking function */
     5310                err = sp_ecc_sign_384_nb(&nb_ctx.sp_ctx, in, inlen, rng,
     5311                    &key->k, r, s, sign_k, key->heap);
     5312            } while (err == FP_WOULDBLOCK);
     5313            return err;
     5314            #endif
     5315        #endif /* WC_ECC_NONBLOCK */
     5316        #if !defined(WC_ECC_NONBLOCK) || (defined(WC_ECC_NONBLOCK) && !defined(WC_ECC_NONBLOCK_ONLY))
     5317            return sp_ecc_sign_384(in, inlen, rng, &key->k, r, s, sign_k,
     5318                key->heap);
     5319        #endif
     5320        }
     5321    #endif
     5322    }
    49045323#else
    4905 #ifdef WOLFSSL_HAVE_SP_ECC
    4906     #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
    4907     if (key->asyncDev.marker != WOLFSSL_ASYNC_MARKER_ECC)
    4908     #endif
    4909     {
    4910 #ifndef WOLFSSL_SP_NO_256
    4911         if (key->idx != ECC_CUSTOM_IDX &&
    4912                                        ecc_sets[key->idx].id == ECC_SECP256R1) {
    4913         #ifndef WOLFSSL_ECDSA_SET_K
    4914             return sp_ecc_sign_256(in, inlen, rng, &key->k, r, s, NULL,
    4915                                                                      key->heap);
    4916         #else
    4917             return sp_ecc_sign_256(in, inlen, rng, &key->k, r, s, key->sign_k,
    4918                                                                      key->heap);
    4919         #endif
    4920         }
    4921 #endif
    4922 #ifdef WOLFSSL_SP_384
    4923         if (key->idx != ECC_CUSTOM_IDX &&
    4924                                        ecc_sets[key->idx].id == ECC_SECP384R1) {
    4925         #ifndef WOLFSSL_ECDSA_SET_K
    4926             return sp_ecc_sign_384(in, inlen, rng, &key->k, r, s, NULL,
    4927                                                                      key->heap);
    4928         #else
    4929             return sp_ecc_sign_384(in, inlen, rng, &key->k, r, s, key->sign_k,
    4930                                                                      key->heap);
    4931         #endif
    4932         }
    4933 #endif
    4934     }
    4935 #endif /* WOLFSSL_HAVE_SP_ECC */
    4936 
     5324   (void)inlen;
     5325#endif
    49375326
    49385327#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \
     
    49525341#endif
    49535342
     5343
     5344#if !defined(WOLFSSL_SP_MATH)
     5345
    49545346#if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_CAVIUM_V)
    49555347   err = wc_ecc_alloc_mpint(key, &key->e);
     
    49775369
    49785370   /* load curve info */
    4979 #if defined(WOLFSSL_ECDSA_SET_K)
     5371#if defined(WOLFSSL_ECDSA_SET_K) || defined(WOLFSSL_ECDSA_SET_K_ONE_LOOP)
    49805372   ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT);
    49815373   err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL);
     
    51475539                    break;
    51485540               }
    5149        #ifdef WOLFSSL_ECDSA_SET_K
     5541       #if defined(WOLFSSL_ECDSA_SET_K) || defined(WOLFSSL_ECDSA_SET_K_ONE_LOOP)
    51505542               if (key->sign_k != NULL) {
    51515543                   if (loop_check > 1) {
     
    51545546                   }
    51555547
     5548                   /* use provided sign_k */
    51565549                   err = mp_copy(key->sign_k, &pubkey->k);
    51575550                   if (err != MP_OKAY) break;
    51585551
     5552                   /* free sign_k, so only used once */
    51595553                   mp_forcezero(key->sign_k);
    51605554                   mp_free(key->sign_k);
    51615555                   XFREE(key->sign_k, key->heap, DYNAMIC_TYPE_ECC);
    51625556                   key->sign_k = NULL;
    5163                    err = wc_ecc_make_pub_ex(pubkey, curve, NULL);
     5557           #ifdef WOLFSSL_ECDSA_SET_K_ONE_LOOP
     5558                   loop_check = 64;
     5559           #endif
     5560
     5561                   /* compute public key based on provided "k" */
     5562                   err = ecc_make_pub_ex(pubkey, curve, NULL, rng);
    51645563               }
    51655564               else
     
    51755574               if (err != MP_OKAY) break;
    51765575
    5177                if (mp_iszero(r) == MP_YES) {
    5178                 #ifndef ALT_ECC_SIZE
    5179                    mp_clear(pubkey->pubkey.x);
    5180                    mp_clear(pubkey->pubkey.y);
    5181                    mp_clear(pubkey->pubkey.z);
    5182                 #endif
    5183                    mp_forcezero(&pubkey->k);
    5184                }
    5185                else {
     5576               if (mp_iszero(r) == MP_NO) {
     5577                   mp_int* ep = &pubkey->k;
     5578                   mp_int* kp = &pubkey->k;
     5579                   mp_int* x  = &key->k;
     5580
    51865581                   /* find s = (e + xr)/k
    51875582                             = b.(e/k.b + x.r/k.b) */
    51885583
    5189                    /* k = k.b */
    5190                    err = mp_mulmod(&pubkey->k, b, curve->order, &pubkey->k);
     5584                   /* k' = k.b */
     5585                   err = mp_mulmod(&pubkey->k, b, curve->order, kp);
    51915586                   if (err != MP_OKAY) break;
    51925587
    5193                    /* k = 1/k.b */
    5194                    err = mp_invmod(&pubkey->k, curve->order, &pubkey->k);
     5588                   /* k' = 1/k.b
     5589                         = 1/k' */
     5590                   err = mp_invmod(kp, curve->order, kp);
    51955591                   if (err != MP_OKAY) break;
    51965592
    51975593                   /* s = x.r */
    5198                    err = mp_mulmod(&key->k, r, curve->order, s);
     5594                   err = mp_mulmod(x, r, curve->order, s);
    51995595                   if (err != MP_OKAY) break;
    52005596
    5201                    /* s = x.r/k.b */
    5202                    err = mp_mulmod(&pubkey->k, s, curve->order, s);
     5597                   /* s = x.r/k.b
     5598                        = k'.s */
     5599                   err = mp_mulmod(kp, s, curve->order, s);
    52035600                   if (err != MP_OKAY) break;
    52045601
    5205                    /* e = e/k.b */
    5206                    err = mp_mulmod(&pubkey->k, e, curve->order, e);
     5602                   /* e' = e/k.b
     5603                         = e.k' */
     5604                   err = mp_mulmod(kp, e, curve->order, ep);
    52075605                   if (err != MP_OKAY) break;
    52085606
    5209                    /* s = e/k.b + x.r/k.b
    5210                         = (e + x.r)/k.b */
    5211                    err = mp_add(e, s, s);
     5607                   /* s = e/k.b + x.r/k.b = (e + x.r)/k.b
     5608                        = e' + s */
     5609                   err = mp_addmod_ct(ep, s, curve->order, s);
    52125610                   if (err != MP_OKAY) break;
    52135611
    5214                    /* s = b.(e + x.r)/k.b
    5215                         = (e + x.r)/k */
     5612                   /* s = b.(e + x.r)/k.b = (e + x.r)/k
     5613                        = b.s */
    52165614                   err = mp_mulmod(s, b, curve->order, s);
    52175615                   if (err != MP_OKAY) break;
    52185616
    5219                    /* s = (e + xr)/k */
    5220                    err = mp_mod(s, curve->order, s);
    5221                    if (err != MP_OKAY) break;
    5222 
    5223                    if (mp_iszero(s) == MP_NO)
     5617                   if (mp_iszero(s) == MP_NO) {
     5618                       /* sign successful */
    52245619                       break;
     5620                   }
    52255621                }
     5622            #ifndef ALT_ECC_SIZE
     5623                mp_clear(pubkey->pubkey.x);
     5624                mp_clear(pubkey->pubkey.y);
     5625                mp_clear(pubkey->pubkey.z);
     5626            #endif
     5627                mp_forcezero(&pubkey->k);
    52265628           }
    52275629           mp_clear(b);
    5228            mp_free(b);
    52295630       #ifdef WOLFSSL_SMALL_STACK
    52305631           XFREE(b, key->heap, DYNAMIC_TYPE_ECC);
     
    52435644#endif
    52445645   FREE_CURVE_SPECS();
    5245 #endif /* WOLFSSL_SP_MATH */
     5646#endif /* !WOLFSSL_SP_MATH */
    52465647
    52475648   return err;
    52485649}
    52495650
    5250 #ifdef WOLFSSL_ECDSA_SET_K
     5651#if defined(WOLFSSL_ECDSA_SET_K) || defined(WOLFSSL_ECDSA_SET_K_ONE_LOOP)
    52515652int wc_ecc_sign_set_k(const byte* k, word32 klen, ecc_key* key)
    52525653{
    5253     int ret = 0;
     5654    int ret;
     5655    DECLARE_CURVE_SPECS(curve, 1);
    52545656
    52555657    if (k == NULL || klen == 0 || key == NULL) {
    5256         ret = BAD_FUNC_ARG;
    5257     }
    5258 
    5259     if (ret == 0) {
    5260         if (key->sign_k == NULL) {
    5261             key->sign_k = (mp_int*)XMALLOC(sizeof(mp_int), key->heap,
    5262                                                               DYNAMIC_TYPE_ECC);
    5263             if (key->sign_k == NULL) {
    5264                 ret = MEMORY_E;
    5265             }
    5266         }
    5267     }
    5268 
    5269     if (ret == 0) {
    5270         ret = mp_init(key->sign_k);
    5271     }
     5658        return BAD_FUNC_ARG;
     5659    }
     5660
     5661    ALLOC_CURVE_SPECS(1);
     5662    ret = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ORDER);
     5663    if (ret != 0) {
     5664        FREE_CURVE_SPECS();
     5665        return ret;
     5666    }
     5667
     5668    if (key->sign_k == NULL) {
     5669        key->sign_k = (mp_int*)XMALLOC(sizeof(mp_int), key->heap,
     5670                                                            DYNAMIC_TYPE_ECC);
     5671        if (key->sign_k) {
     5672            ret = mp_init(key->sign_k);
     5673        }
     5674        else {
     5675            ret = MEMORY_E;
     5676        }
     5677    }
     5678
    52725679    if (ret == 0) {
    52735680        ret = mp_read_unsigned_bin(key->sign_k, k, klen);
    52745681    }
    5275 
     5682    if (ret == 0 && mp_cmp(key->sign_k, curve->order) != MP_LT) {
     5683        ret = MP_VAL;
     5684    }
     5685
     5686    wc_ecc_curve_free(curve);
     5687    FREE_CURVE_SPECS();
    52765688    return ret;
    52775689}
    5278 #endif /* WOLFSSL_ECDSA_SET_K */
    5279 #endif /* WOLFSSL_ATECC508A && WOLFSSL_CRYPTOCELL*/
    5280 
    5281 #endif /* HAVE_ECC_SIGN */
     5690#endif /* WOLFSSL_ECDSA_SET_K || WOLFSSL_ECDSA_SET_K_ONE_LOOP */
     5691#endif /* WOLFSSL_ATECC508A && WOLFSSL_CRYPTOCELL */
     5692
     5693#endif /* !HAVE_ECC_SIGN */
    52825694
    52835695#ifdef WOLFSSL_CUSTOM_CURVES
     
    53165728    }
    53175729
    5318 #ifdef WOLFSSL_ECDSA_SET_K
     5730#if defined(WOLFSSL_ECDSA_SET_K) || defined(WOLFSSL_ECDSA_SET_K_ONE_LOOP)
    53195731    if (key->sign_k != NULL) {
    53205732        mp_forcezero(key->sign_k);
     
    53315743#endif
    53325744
    5333 #ifdef WOLFSSL_ATECC508A
     5745#if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A)
    53345746    atmel_ecc_free(key->slot);
    53355747    key->slot = ATECC_INVALID_SLOT;
     
    53505762}
    53515763
    5352 #if !defined(WOLFSSL_SP_MATH) && !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
     5764#ifndef WOLFSSL_SP_MATH
     5765/* Handles add failure cases:
     5766 *
     5767 * Before add:
     5768 *   Case 1: A is infinity
     5769 *        -> Copy B into result.
     5770 *   Case 2: B is infinity
     5771 *        -> Copy A into result.
     5772 *   Case 3: x and z are the same in A and B (same x value in affine)
     5773 *     Case 3a: y values the same - same point
     5774 *           -> Double instead of add.
     5775 *     Case 3b: y values different - negative of the other when points on curve
     5776 *           -> Need to set result to infinity.
     5777 *
     5778 * After add:
     5779 *   Case 1: A and B are the same point (maybe different z)
     5780 *           (Result was: x == y == z == 0)
     5781 *        -> Need to double instead.
     5782 *
     5783 *   Case 2: A + B = <infinity> = 0.
     5784 *           (Result was: z == 0, x and/or y not 0)
     5785 *        -> Need to set result to infinity.
     5786 */
     5787int ecc_projective_add_point_safe(ecc_point* A, ecc_point* B, ecc_point* R,
     5788    mp_int* a, mp_int* modulus, mp_digit mp, int* infinity)
     5789{
     5790    int err;
     5791
     5792    if (mp_iszero(A->x) && mp_iszero(A->y)) {
     5793        /* A is infinity. */
     5794        err = wc_ecc_copy_point(B, R);
     5795    }
     5796    else if (mp_iszero(B->x) && mp_iszero(B->y)) {
     5797        /* B is infinity. */
     5798        err = wc_ecc_copy_point(A, R);
     5799    }
     5800    else if ((mp_cmp(A->x, B->x) == MP_EQ) && (mp_cmp(A->z, B->z) == MP_EQ)) {
     5801        /* x ordinattes the same. */
     5802        if (mp_cmp(A->y, B->y) == MP_EQ) {
     5803            /* A = B */
     5804            err = ecc_projective_dbl_point(B, R, a, modulus, mp);
     5805        }
     5806        else {
     5807            /* A = -B */
     5808            err = mp_set(R->x, 0);
     5809            if (err == MP_OKAY)
     5810                err = mp_set(R->y, 0);
     5811            if (err == MP_OKAY)
     5812                err = mp_set(R->z, 1);
     5813            if ((err == MP_OKAY) && (infinity != NULL))
     5814                *infinity = 1;
     5815        }
     5816    }
     5817    else {
     5818        err = ecc_projective_add_point(A, B, R, a, modulus, mp);
     5819        if ((err == MP_OKAY) && mp_iszero(R->z)) {
     5820            /* When all zero then should have done a double */
     5821            if (mp_iszero(R->x) && mp_iszero(R->y)) {
     5822                err = ecc_projective_dbl_point(B, R, a, modulus, mp);
     5823            }
     5824            /* When only Z zero then result is infinity */
     5825            else {
     5826                err = mp_set(R->x, 0);
     5827                if (err == MP_OKAY)
     5828                    err = mp_set(R->y, 0);
     5829                if (err == MP_OKAY)
     5830                    err = mp_set(R->z, 1);
     5831                if ((err == MP_OKAY) && (infinity != NULL))
     5832                    *infinity = 1;
     5833            }
     5834        }
     5835    }
     5836
     5837    return err;
     5838}
     5839
     5840/* Handles when P is the infinity point.
     5841 *
     5842 * Double infinity -> infinity.
     5843 * Otherwise do normal double - which can't lead to infinity as odd order.
     5844 */
     5845int ecc_projective_dbl_point_safe(ecc_point *P, ecc_point *R, mp_int* a,
     5846                                  mp_int* modulus, mp_digit mp)
     5847{
     5848    int err;
     5849
     5850    if (mp_iszero(P->x) && mp_iszero(P->y)) {
     5851        /* P is infinity. */
     5852        err = wc_ecc_copy_point(P, R);
     5853    }
     5854    else {
     5855        err = ecc_projective_dbl_point(P, R, a, modulus, mp);
     5856    }
     5857
     5858    return err;
     5859}
     5860#endif
     5861
     5862#if !defined(WOLFSSL_SP_MATH) && !defined(WOLFSSL_ATECC508A) && \
     5863    !defined(WOLFSSL_ATECC608A) && !defined(WOLFSSL_CRYPTOCELL)
    53535864#ifdef ECC_SHAMIR
    53545865
     
    55316042  }
    55326043
    5533   if (err == MP_OKAY)
     6044  if (err == MP_OKAY) {
    55346045    /* precomp [i,0](A + B) table */
    5535     err = ecc_projective_dbl_point(precomp[1], precomp[2], a, modulus, mp);
    5536 
    5537   if (err == MP_OKAY)
    5538     err = ecc_projective_add_point(precomp[1], precomp[2], precomp[3],
    5539                                    a, modulus, mp);
    5540   if (err == MP_OKAY)
     6046    err = ecc_projective_dbl_point_safe(precomp[1], precomp[2], a, modulus, mp);
     6047  }
     6048  if (err == MP_OKAY) {
     6049    err = ecc_projective_add_point_safe(precomp[1], precomp[2], precomp[3],
     6050                                                          a, modulus, mp, NULL);
     6051  }
     6052
     6053  if (err == MP_OKAY) {
    55416054    /* precomp [0,i](A + B) table */
    5542     err = ecc_projective_dbl_point(precomp[1<<2], precomp[2<<2], a, modulus, mp);
    5543 
    5544   if (err == MP_OKAY)
    5545     err = ecc_projective_add_point(precomp[1<<2], precomp[2<<2], precomp[3<<2],
    5546                                    a, modulus, mp);
     6055    err = ecc_projective_dbl_point_safe(precomp[1<<2], precomp[2<<2], a,
     6056                                                                  modulus, mp);
     6057  }
     6058  if (err == MP_OKAY) {
     6059    err = ecc_projective_add_point_safe(precomp[1<<2], precomp[2<<2],
     6060                                           precomp[3<<2], a, modulus, mp, NULL);
     6061  }
    55476062
    55486063  if (err == MP_OKAY) {
     
    55516066      for (y = 1; y < 4; y++) {
    55526067        if (err == MP_OKAY) {
    5553           err = ecc_projective_add_point(precomp[x], precomp[(y<<2)],
    5554                                              precomp[x+(y<<2)], a, modulus, mp);
     6068          err = ecc_projective_add_point_safe(precomp[x], precomp[(y<<2)],
     6069                                                  precomp[x+(y<<2)], a, modulus,
     6070                                                  mp, NULL);
    55556071        }
    55566072      }
     
    55906106            /* double twice */
    55916107            if (err == MP_OKAY)
    5592                 err = ecc_projective_dbl_point(C, C, a, modulus, mp);
     6108                err = ecc_projective_dbl_point_safe(C, C, a, modulus, mp);
    55936109            if (err == MP_OKAY)
    5594                 err = ecc_projective_dbl_point(C, C, a, modulus, mp);
     6110                err = ecc_projective_dbl_point_safe(C, C, a, modulus, mp);
    55956111            else
    55966112                break;
     
    55996115        /* if not both zero */
    56006116        if ((nA != 0) || (nB != 0)) {
     6117            int i = nA + (nB<<2);
    56016118            if (first == 1) {
    56026119                /* if first, copy from table */
    56036120                first = 0;
    56046121                if (err == MP_OKAY)
    5605                     err = mp_copy(precomp[nA + (nB<<2)]->x, C->x);
     6122                    err = mp_copy(precomp[i]->x, C->x);
    56066123
    56076124                if (err == MP_OKAY)
    5608                     err = mp_copy(precomp[nA + (nB<<2)]->y, C->y);
     6125                    err = mp_copy(precomp[i]->y, C->y);
    56096126
    56106127                if (err == MP_OKAY)
    5611                     err = mp_copy(precomp[nA + (nB<<2)]->z, C->z);
     6128                    err = mp_copy(precomp[i]->z, C->z);
    56126129                else
    56136130                    break;
     
    56156132                /* if not first, add from table */
    56166133                if (err == MP_OKAY)
    5617                     err = ecc_projective_add_point(C, precomp[nA + (nB<<2)], C,
    5618                                                    a, modulus, mp);
     6134                    err = ecc_projective_add_point_safe(C, precomp[i],
     6135                                                        C, a, modulus, mp,
     6136                                                        &first);
    56196137                if (err != MP_OKAY)
    56206138                    break;
    5621                 if (mp_iszero(C->z)) {
    5622                     /* When all zero then should have done an add */
    5623                     if (mp_iszero(C->x) && mp_iszero(C->y)) {
    5624                         err = ecc_projective_dbl_point(precomp[nA + (nB<<2)], C,
    5625                                                        a, modulus, mp);
    5626                         if (err != MP_OKAY)
    5627                             break;
    5628                     }
    5629                     /* When only Z zero then result is infinity */
    5630                     else {
    5631                         err = mp_set(C->x, 0);
    5632                         if (err != MP_OKAY)
    5633                             break;
    5634                         err = mp_set(C->y, 0);
    5635                         if (err != MP_OKAY)
    5636                             break;
    5637                         err = mp_set(C->z, 1);
    5638                         if (err != MP_OKAY)
    5639                             break;
    5640                         first = 1;
    5641                     }
    5642                 }
    56436139            }
    56446140        }
     
    56776173
    56786174#endif /* ECC_SHAMIR */
    5679 #endif /* !WOLFSSL_SP_MATH && !WOLFSSL_ATECC508A && !WOLFSSL_CRYPTOCEL*/
     6175#endif /* (!WOLFSSL_SP_MATH && !WOLFSSL_ATECC508A && !WOLFSSL_ATECC608A &&
     6176        * !WOLFSSL_CRYPTOCEL */
    56806177
    56816178
     
    58216318#endif /* !NO_ASN */
    58226319
     6320static int wc_ecc_check_r_s_range(ecc_key* key, mp_int* r, mp_int* s)
     6321{
     6322    int err;
     6323    DECLARE_CURVE_SPECS(curve, 1);
     6324
     6325    ALLOC_CURVE_SPECS(1);
     6326    err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ORDER);
     6327    if (err != 0) {
     6328        FREE_CURVE_SPECS();
     6329        return err;
     6330    }
     6331
     6332    if (mp_iszero(r) || mp_iszero(s)) {
     6333        err = MP_ZERO_E;
     6334    }
     6335    if ((err == 0) && (mp_cmp(r, curve->order) != MP_LT)) {
     6336        err = MP_VAL;
     6337    }
     6338    if ((err == 0) && (mp_cmp(s, curve->order) != MP_LT)) {
     6339        err = MP_VAL;
     6340    }
     6341
     6342    wc_ecc_curve_free(curve);
     6343    FREE_CURVE_SPECS();
     6344    return err;
     6345}
    58236346
    58246347/**
     
    58396362    return stm32_ecc_verify_hash_ex(r, s, hash, hashlen, res, key);
    58406363}
     6364#elif defined(WOLFSSL_PSOC6_CRYPTO)
     6365{
     6366    return psoc6_ecc_verify_hash_ex(r, s, hash, hashlen, res, key);
     6367}
    58416368#else
    58426369{
    58436370   int           err;
    5844    word32        keySz;
    5845 #ifdef WOLFSSL_ATECC508A
     6371   word32        keySz = 0;
     6372#if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A)
    58466373   byte sigRS[ATECC_KEY_SIZE*2];
    58476374#elif defined(WOLFSSL_CRYPTOCELL)
     
    58506377   word32 msgLenInBytes = hashlen;
    58516378   CRYS_ECPKI_HASH_OpMode_t hash_mode;
     6379#elif defined(WOLFSSL_SILABS_SE_ACCEL)
     6380   byte sigRS[ECC_MAX_CRYPTO_HW_SIZE * 2];
    58526381#elif !defined(WOLFSSL_SP_MATH) || defined(FREESCALE_LTC_ECC)
    58536382   int          did_init = 0;
     
    58856414   }
    58866415
     6416   err = wc_ecc_check_r_s_range(key, r, s);
     6417   if (err != MP_OKAY) {
     6418      return err;
     6419   }
     6420
    58876421   keySz = key->dp->size;
    58886422
     
    59036437#endif
    59046438
    5905 #ifdef WOLFSSL_ATECC508A
     6439#if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A)
    59066440    /* Extract R and S */
    59076441    err = mp_to_unsigned_bin(r, &sigRS[0]);
     
    59326466   }
    59336467
     6468   /* truncate if hash is longer than key size */
     6469   if (msgLenInBytes > keySz) {
     6470       msgLenInBytes = keySz;
     6471   }
    59346472   hash_mode = cc310_hashModeECC(msgLenInBytes);
    59356473   if (hash_mode == CRYS_ECPKI_HASH_OpModeLast) {
    59366474       /* hash_mode = */ cc310_hashModeECC(keySz);
    59376475       hash_mode = CRYS_ECPKI_HASH_SHA256_mode;
    5938    }
    5939    /* truncate if hash is longer than key size */
    5940    if (msgLenInBytes > keySz) {
    5941        msgLenInBytes = keySz;
    59426476   }
    59436477
     
    59576491   /* valid signature if we get to this point */
    59586492   *res = 1;
     6493#elif defined(WOLFSSL_SILABS_SE_ACCEL)
     6494   /* Extract R and S */
     6495
     6496   err = mp_to_unsigned_bin(r, &sigRS[0]);
     6497   if (err != MP_OKAY) {
     6498       return err;
     6499   }
     6500   err = mp_to_unsigned_bin(s, &sigRS[keySz]);
     6501   if (err != MP_OKAY) {
     6502       return err;
     6503   }
     6504
     6505   err = silabs_ecc_verify_hash(&sigRS[0], keySz*2,
     6506                                hash, hashlen,
     6507                                res, key);
     6508
    59596509#else
    59606510  /* checking if private key with no public part */
    59616511  if (key->type == ECC_PRIVATEKEY_ONLY) {
    59626512      WOLFSSL_MSG("Verify called with private key, generating public part");
    5963       err = wc_ecc_make_pub_ex(key, NULL, NULL);
     6513      err = ecc_make_pub_ex(key, NULL, NULL, NULL);
    59646514      if (err != MP_OKAY) {
    59656515           WOLFSSL_MSG("Unable to extract public key");
     
    59706520#if defined(WOLFSSL_DSP) && !defined(FREESCALE_LTC_ECC)
    59716521  if (key->handle != -1) {
    5972       return sp_dsp_ecc_verify_256(key->handle, hash, hashlen, key->pubkey.x, key->pubkey.y,
    5973                                           key->pubkey.z, r, s, res, key->heap);
     6522      return sp_dsp_ecc_verify_256(key->handle, hash, hashlen, key->pubkey.x,
     6523        key->pubkey.y, key->pubkey.z, r, s, res, key->heap);
    59746524  }
    59756525  if (wolfSSL_GetHandleCbSet() == 1) {
    5976       return sp_dsp_ecc_verify_256(0, hash, hashlen, key->pubkey.x, key->pubkey.y,
    5977                                           key->pubkey.z, r, s, res, key->heap);
     6526      return sp_dsp_ecc_verify_256(0, hash, hashlen, key->pubkey.x,
     6527        key->pubkey.y, key->pubkey.z, r, s, res, key->heap);
    59786528  }
    59796529#endif
     6530
    59806531#if defined(WOLFSSL_SP_MATH) && !defined(FREESCALE_LTC_ECC)
    5981 #ifndef WOLFSSL_SP_NO_256
    5982   if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) {
    5983       return sp_ecc_verify_256(hash, hashlen, key->pubkey.x, key->pubkey.y,
    5984                                            key->pubkey.z, r, s, res, key->heap);
    5985   }
    5986 #endif
    5987 #ifdef WOLFSSL_SP_384
    5988   if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) {
    5989       return sp_ecc_verify_384(hash, hashlen, key->pubkey.x, key->pubkey.y,
    5990                                            key->pubkey.z, r, s, res, key->heap);
    5991   }
    5992 #endif
    5993   return WC_KEY_SIZE_E;
    5994 #else
    5995 #if defined WOLFSSL_HAVE_SP_ECC && !defined(FREESCALE_LTC_ECC)
     6532    if (key->idx == ECC_CUSTOM_IDX ||
     6533            (ecc_sets[key->idx].id != ECC_SECP256R1 &&
     6534             ecc_sets[key->idx].id != ECC_SECP384R1)) {
     6535        return WC_KEY_SIZE_E;
     6536    }
     6537#endif
     6538
     6539#if (defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_SP_MATH_ALL)) && \
     6540                                                    defined(WOLFSSL_HAVE_SP_ECC)
     6541    if (key->idx != ECC_CUSTOM_IDX
    59966542    #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
    5997     if (key->asyncDev.marker != WOLFSSL_ASYNC_MARKER_ECC)
     6543        && key->asyncDev.marker != WOLFSSL_ASYNC_MARKER_ECC
    59986544    #endif
    5999     {
    6000 #ifndef WOLFSSL_SP_NO_256
    6001         if (key->idx != ECC_CUSTOM_IDX &&
    6002                                        ecc_sets[key->idx].id == ECC_SECP256R1) {
    6003             return sp_ecc_verify_256(hash, hashlen, key->pubkey.x,
    6004                                          key->pubkey.y, key->pubkey.z,r, s, res,
    6005                                          key->heap);
    6006         }
    6007 #endif /* WOLFSSL_SP_NO_256 */
    6008 #ifdef WOLFSSL_SP_384
    6009         if (key->idx != ECC_CUSTOM_IDX &&
    6010                                        ecc_sets[key->idx].id == ECC_SECP384R1) {
    6011             return sp_ecc_verify_384(hash, hashlen, key->pubkey.x,
    6012                                          key->pubkey.y, key->pubkey.z,r, s, res,
    6013                                          key->heap);
    6014         }
    6015 #endif /* WOLFSSL_SP_384 */
    6016     }
    6017 #endif /* WOLFSSL_HAVE_SP_ECC */
    6018 
     6545    ) {
     6546    #if defined(WC_ECC_NONBLOCK) && defined(WC_ECC_NONBLOCK_ONLY)
     6547        /* perform blocking call to non-blocking function */
     6548        ecc_nb_ctx_t nb_ctx;
     6549        XMEMSET(&nb_ctx, 0, sizeof(nb_ctx));
     6550        err = NOT_COMPILED_IN; /* set default error */
     6551    #endif
     6552    #ifndef WOLFSSL_SP_NO_256
     6553        if (ecc_sets[key->idx].id == ECC_SECP256R1) {
     6554        #ifdef WC_ECC_NONBLOCK
     6555            if (key->nb_ctx) {
     6556                return sp_ecc_verify_256_nb(&key->nb_ctx->sp_ctx, hash, hashlen,
     6557                    key->pubkey.x, key->pubkey.y, key->pubkey.z, r, s, res,
     6558                    key->heap);
     6559            }
     6560            #ifdef WC_ECC_NONBLOCK_ONLY
     6561            do { /* perform blocking call to non-blocking function */
     6562                err = sp_ecc_verify_256_nb(&nb_ctx.sp_ctx, hash, hashlen,
     6563                    key->pubkey.x, key->pubkey.y, key->pubkey.z, r, s, res,
     6564                    key->heap);
     6565            } while (err == FP_WOULDBLOCK);
     6566            return err;
     6567            #endif
     6568        #endif /* WC_ECC_NONBLOCK */
     6569        #if !defined(WC_ECC_NONBLOCK) || (defined(WC_ECC_NONBLOCK) && !defined(WC_ECC_NONBLOCK_ONLY))
     6570            return sp_ecc_verify_256(hash, hashlen, key->pubkey.x,
     6571                key->pubkey.y, key->pubkey.z, r, s, res, key->heap);
     6572        #endif
     6573        }
     6574    #endif
     6575    #ifdef WOLFSSL_SP_384
     6576        if (ecc_sets[key->idx].id == ECC_SECP384R1) {
     6577        #ifdef WC_ECC_NONBLOCK
     6578            if (key->nb_ctx) {
     6579                return sp_ecc_verify_384_nb(&key->nb_ctx->sp_ctx, hash, hashlen,
     6580                    key->pubkey.x,  key->pubkey.y, key->pubkey.z, r, s, res,
     6581                    key->heap);
     6582            }
     6583            #ifdef WC_ECC_NONBLOCK_ONLY
     6584            do { /* perform blocking call to non-blocking function */
     6585                err = sp_ecc_verify_384_nb(&nb_ctx.sp_ctx, hash, hashlen,
     6586                    key->pubkey.x, key->pubkey.y, key->pubkey.z, r, s, res,
     6587                    key->heap);
     6588            } while (err == FP_WOULDBLOCK);
     6589            return err;
     6590            #endif
     6591        #endif /* WC_ECC_NONBLOCK */
     6592        #if !defined(WC_ECC_NONBLOCK) || (defined(WC_ECC_NONBLOCK) && !defined(WC_ECC_NONBLOCK_ONLY))
     6593            return sp_ecc_verify_384(hash, hashlen, key->pubkey.x,
     6594                key->pubkey.y, key->pubkey.z, r, s, res, key->heap);
     6595        #endif
     6596        }
     6597    #endif
     6598    }
     6599#endif
     6600
     6601#if !defined(WOLFSSL_SP_MATH) || defined(FREESCALE_LTC_ECC)
    60196602   ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT);
    60206603
     
    60436626   /* read in the specs for this curve */
    60446627   err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL);
    6045 
    6046    /* check for zero */
    6047    if (err == MP_OKAY) {
    6048        if (mp_iszero(r) == MP_YES || mp_iszero(s) == MP_YES ||
    6049            mp_cmp(r, curve->order) != MP_LT ||
    6050            mp_cmp(s, curve->order) != MP_LT) {
    6051            err = MP_ZERO_E;
    6052        }
    6053    }
    60546628
    60556629   /* read hash */
     
    61326706       if ((err = mp_init_multi(v, w, u1, u2, NULL, NULL)) != MP_OKAY) {
    61336707          err = MEMORY_E;
     6708       } else {
     6709           did_init = 1;
    61346710       }
    6135        did_init = 1;
    61366711   }
    61376712
     
    62006775            /* add them */
    62016776            if (err == MP_OKAY)
    6202                 err = ecc_projective_add_point(mQ, mG, mG, curve->Af,
    6203                                                               curve->prime, mp);
    6204             if (err == MP_OKAY && mp_iszero(mG->z)) {
    6205                 /* When all zero then should have done an add */
    6206                 if (mp_iszero(mG->x) && mp_iszero(mG->y)) {
    6207                     err = ecc_projective_dbl_point(mQ, mG, curve->Af,
    6208                                                               curve->prime, mp);
    6209                 }
    6210                 /* When only Z zero then result is infinity */
    6211                 else {
    6212                     err = mp_set(mG->x, 0);
    6213                     if (err == MP_OKAY)
    6214                         err = mp_set(mG->y, 0);
    6215                     if (err == MP_OKAY)
    6216                         err = mp_set(mG->z, 1);
    6217                 }
    6218             }
     6777                err = ecc_projective_add_point_safe(mQ, mG, mG, curve->Af,
     6778                                                        curve->prime, mp, NULL);
    62196779        }
    62206780        else {
     
    62736833   FREE_CURVE_SPECS();
    62746834
    6275 #endif /* WOLFSSL_SP_MATH */
     6835#endif /* !WOLFSSL_SP_MATH || FREESCALE_LTC_ECC */
    62766836#endif /* WOLFSSL_ATECC508A */
    62776837
     
    63576917#ifdef HAVE_COMP_KEY
    63586918    if (err == MP_OKAY && compressed == 1) {   /* build y */
    6359 #ifndef WOLFSSL_SP_MATH
    6360         int did_init = 0;
    6361         mp_int t1, t2;
    6362         DECLARE_CURVE_SPECS(curve, 3);
    6363 
    6364         ALLOC_CURVE_SPECS(3);
    6365 
    6366         if (mp_init_multi(&t1, &t2, NULL, NULL, NULL, NULL) != MP_OKAY)
    6367             err = MEMORY_E;
    6368         else
    6369             did_init = 1;
    6370 
    6371         /* load curve info */
    6372         if (err == MP_OKAY)
    6373             err = wc_ecc_curve_load(&ecc_sets[curve_idx], &curve,
    6374                 (ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF |
    6375                     ECC_CURVE_FIELD_BF));
    6376 
    6377         /* compute x^3 */
    6378         if (err == MP_OKAY)
    6379             err = mp_sqr(point->x, &t1);
    6380         if (err == MP_OKAY)
    6381             err = mp_mulmod(&t1, point->x, curve->prime, &t1);
    6382 
    6383         /* compute x^3 + a*x */
    6384         if (err == MP_OKAY)
    6385             err = mp_mulmod(curve->Af, point->x, curve->prime, &t2);
    6386         if (err == MP_OKAY)
    6387             err = mp_add(&t1, &t2, &t1);
    6388 
    6389         /* compute x^3 + a*x + b */
    6390         if (err == MP_OKAY)
    6391             err = mp_add(&t1, curve->Bf, &t1);
    6392 
    6393         /* compute sqrt(x^3 + a*x + b) */
    6394         if (err == MP_OKAY)
    6395             err = mp_sqrtmod_prime(&t1, curve->prime, &t2);
    6396 
    6397         /* adjust y */
    6398         if (err == MP_OKAY) {
    6399             if ((mp_isodd(&t2) == MP_YES && pointType == ECC_POINT_COMP_ODD) ||
    6400                 (mp_isodd(&t2) == MP_NO &&  pointType == ECC_POINT_COMP_EVEN)) {
    6401                 err = mp_mod(&t2, curve->prime, point->y);
    6402             }
    6403             else {
    6404                 err = mp_submod(curve->prime, &t2, curve->prime, point->y);
    6405             }
    6406         }
    6407 
    6408         if (did_init) {
    6409             mp_clear(&t2);
    6410             mp_clear(&t1);
    6411         }
    6412 
    6413         wc_ecc_curve_free(curve);
    6414         FREE_CURVE_SPECS();
    6415 #else
    6416     #ifndef WOLFSSL_SP_NO_256
     6919    #if defined(WOLFSSL_HAVE_SP_ECC)
     6920        #ifndef WOLFSSL_SP_NO_256
    64176921        if (curve_idx != ECC_CUSTOM_IDX &&
    64186922                                      ecc_sets[curve_idx].id == ECC_SECP256R1) {
     
    64206924        }
    64216925        else
    6422     #endif
    6423     #ifdef WOLFSSL_SP_384
     6926        #endif
     6927        #ifdef WOLFSSL_SP_384
    64246928        if (curve_idx != ECC_CUSTOM_IDX &&
    64256929                                      ecc_sets[curve_idx].id == ECC_SECP384R1) {
     
    64276931        }
    64286932        else
     6933        #endif
    64296934    #endif
     6935    #if !defined(WOLFSSL_SP_MATH)
     6936        {
     6937            int did_init = 0;
     6938            mp_int t1, t2;
     6939            DECLARE_CURVE_SPECS(curve, 3);
     6940
     6941            ALLOC_CURVE_SPECS(3);
     6942
     6943            if (mp_init_multi(&t1, &t2, NULL, NULL, NULL, NULL) != MP_OKAY)
     6944                err = MEMORY_E;
     6945            else
     6946                did_init = 1;
     6947
     6948            /* load curve info */
     6949            if (err == MP_OKAY)
     6950                err = wc_ecc_curve_load(&ecc_sets[curve_idx], &curve,
     6951                    (ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF |
     6952                        ECC_CURVE_FIELD_BF));
     6953
     6954        #if defined(WOLFSSL_CUSTOM_CURVES) && \
     6955            defined(WOLFSSL_VALIDATE_ECC_IMPORT)
     6956            /* validate prime is prime for custom curves */
     6957            if (err == MP_OKAY && curve_idx == ECC_CUSTOM_IDX) {
     6958                int isPrime = MP_NO;
     6959                err = mp_prime_is_prime(curve->prime, 8, &isPrime);
     6960                if (err == MP_OKAY && isPrime == MP_NO)
     6961                    err = MP_VAL;
     6962            }
     6963        #endif
     6964
     6965            /* compute x^3 */
     6966            if (err == MP_OKAY)
     6967                err = mp_sqr(point->x, &t1);
     6968            if (err == MP_OKAY)
     6969                err = mp_mulmod(&t1, point->x, curve->prime, &t1);
     6970
     6971            /* compute x^3 + a*x */
     6972            if (err == MP_OKAY)
     6973                err = mp_mulmod(curve->Af, point->x, curve->prime, &t2);
     6974            if (err == MP_OKAY)
     6975                err = mp_add(&t1, &t2, &t1);
     6976
     6977            /* compute x^3 + a*x + b */
     6978            if (err == MP_OKAY)
     6979                err = mp_add(&t1, curve->Bf, &t1);
     6980
     6981            /* compute sqrt(x^3 + a*x + b) */
     6982            if (err == MP_OKAY)
     6983                err = mp_sqrtmod_prime(&t1, curve->prime, &t2);
     6984
     6985            /* adjust y */
     6986            if (err == MP_OKAY) {
     6987                if ((mp_isodd(&t2) == MP_YES &&
     6988                                            pointType == ECC_POINT_COMP_ODD) ||
     6989                    (mp_isodd(&t2) == MP_NO &&
     6990                                            pointType == ECC_POINT_COMP_EVEN)) {
     6991                    err = mp_mod(&t2, curve->prime, point->y);
     6992                }
     6993                else {
     6994                    err = mp_submod(curve->prime, &t2, curve->prime, point->y);
     6995                }
     6996            }
     6997
     6998            if (did_init) {
     6999                mp_clear(&t2);
     7000                mp_clear(&t1);
     7001            }
     7002
     7003            wc_ecc_curve_free(curve);
     7004            FREE_CURVE_SPECS();
     7005        }
     7006    #else
    64307007        {
    64317008            err = WC_KEY_SIZE_E;
    64327009        }
    6433 #endif
     7010    #endif
    64347011    }
    64357012#endif
     
    66337210       return ECC_PRIVATEONLY_E;
    66347211
    6635    if (wc_ecc_is_valid_idx(key->idx) == 0 || key->dp == NULL) {
    6636       return ECC_BAD_ARG_E;
    6637    }
     7212   if (key->type == 0 ||
     7213       wc_ecc_is_valid_idx(key->idx) == 0 ||
     7214       key->dp == NULL) {
     7215       return ECC_BAD_ARG_E;
     7216   }
     7217
    66387218   numlen = key->dp->size;
    66397219
     
    67037283
    67047284
    6705 #if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
     7285#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A) && \
     7286    !defined(WOLFSSL_CRYPTOCELL)
    67067287
    67077288/* is ecc point on curve described by dp ? */
    67087289int wc_ecc_is_point(ecc_point* ecp, mp_int* a, mp_int* b, mp_int* prime)
    67097290{
    6710 #ifndef WOLFSSL_SP_MATH
     7291#if !defined(WOLFSSL_SP_MATH)
    67117292   int err;
    67127293#ifdef WOLFSSL_SMALL_STACK
     
    67507331   /* compute y^2 - x^3 */
    67517332   if (err == MP_OKAY)
    6752        err = mp_sub(t1, t2, t1);
     7333       err = mp_submod(t1, t2, prime, t1);
    67537334
    67547335   /* Determine if curve "a" should be used in calc */
     
    67957376   if (err == MP_OKAY) {
    67967377       if (mp_cmp(t1, b) != MP_EQ) {
    6797           err = MP_VAL;
     7378          err = IS_POINT_E;
    67987379       } else {
    67997380          err = MP_OKAY;
     
    68137394   (void)b;
    68147395
     7396#ifdef WOLFSSL_HAVE_SP_ECC
    68157397#ifndef WOLFSSL_SP_NO_256
    68167398   if (mp_count_bits(prime) == 256) {
     
    68237405   }
    68247406#endif
     7407#else
     7408   (void)ecp;
     7409   (void)prime;
     7410#endif
    68257411   return WC_KEY_SIZE_E;
    68267412#endif
    68277413}
    68287414
    6829 #ifndef WOLFSSL_SP_MATH
     7415#if !defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_VALIDATE_ECC_IMPORT)
    68307416/* validate privkey * generator == pubkey, 0 on success */
    68317417static int ecc_check_privkey_gen(ecc_key* key, mp_int* a, mp_int* prime)
     
    68347420    ecc_point* base = NULL;
    68357421    ecc_point* res  = NULL;
    6836     DECLARE_CURVE_SPECS(curve, 2);
     7422    DECLARE_CURVE_SPECS(curve, 3);
    68377423
    68387424    if (key == NULL)
    68397425        return BAD_FUNC_ARG;
    68407426
    6841     ALLOC_CURVE_SPECS(2);
     7427    ALLOC_CURVE_SPECS(3);
    68427428
    68437429    res = wc_ecc_new_point_h(key->heap);
     
    68707456        if (err == MP_OKAY) {
    68717457            /* load curve info */
    6872             err = wc_ecc_curve_load(key->dp, &curve,
    6873                                       (ECC_CURVE_FIELD_GX | ECC_CURVE_FIELD_GY));
     7458            err = wc_ecc_curve_load(key->dp, &curve, (ECC_CURVE_FIELD_GX |
     7459                                   ECC_CURVE_FIELD_GY | ECC_CURVE_FIELD_ORDER));
    68747460        }
    68757461
     
    68827468            err = mp_set(base->z, 1);
    68837469
     7470#ifdef ECC_TIMING_RESISTANT
    68847471        if (err == MP_OKAY)
    6885             err = wc_ecc_mulmod_ex(&key->k, base, res, a, prime, 1, key->heap);
     7472            err = wc_ecc_mulmod_ex2(&key->k, base, res, a, prime, curve->order,
     7473                                                        key->rng, 1, key->heap);
     7474#else
     7475        if (err == MP_OKAY)
     7476            err = wc_ecc_mulmod_ex2(&key->k, base, res, a, prime, curve->order,
     7477                                                            NULL, 1, key->heap);
     7478#endif
    68867479    }
    68877480
     
    69037496    return err;
    69047497}
    6905 #endif
     7498#endif /* !WOLFSSL_SP_MATH || WOLFSSL_VALIDATE_ECC_IMPORT */
    69067499
    69077500#ifdef WOLFSSL_VALIDATE_ECC_IMPORT
     
    69117504{
    69127505    int    err;
    6913 #ifndef WOLFSSL_ATECC508A
     7506#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A)
    69147507    DECLARE_CURVE_SPECS(curve, 2);
    69157508#endif
     
    69187511        return BAD_FUNC_ARG;
    69197512
    6920 #ifdef WOLFSSL_ATECC508A
     7513#if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A)
    69217514    /* Hardware based private key, so this operation is not supported */
    69227515    err = MP_OKAY; /* just report success */
    6923 
     7516#elif defined(WOLFSSL_SILABS_SE_ACCEL)
     7517    /* Hardware based private key, so this operation is not supported */
     7518    err = MP_OKAY; /* just report success */
    69247519#else
    69257520    ALLOC_CURVE_SPECS(2);
     
    69737568#endif
    69747569#endif
    6975 #ifndef WOLFSSL_SP_MATH
     7570#if !defined(WOLFSSL_SP_MATH)
    69767571            err = wc_ecc_mulmod_ex(order, pubkey, inf, a, prime, 1, key->heap);
    69777572        if (err == MP_OKAY && !wc_ecc_point_is_at_infinity(inf))
    69787573            err = ECC_INF_E;
    69797574#else
     7575        {
    69807576            (void)a;
    69817577            (void)prime;
    69827578
    69837579            err = WC_KEY_SIZE_E;
     7580        }
    69847581#endif
    69857582    }
     
    70227619int wc_ecc_check_key(ecc_key* key)
    70237620{
     7621#ifndef WOLFSSL_SP_MATH
    70247622    int    err;
    7025 #ifndef WOLFSSL_SP_MATH
    7026 #if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
     7623#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A) && \
     7624    !defined(WOLFSSL_CRYPTOCELL)
    70277625    mp_int* b = NULL;
    70287626#ifdef USE_ECC_B_PARAM
     
    70357633#endif /* USE_ECC_B_PARAM */
    70367634#endif /* WOLFSSL_ATECC508A */
     7635#endif /* !WOLFSSL_SP_MATH */
    70377636
    70387637    if (key == NULL)
    70397638        return BAD_FUNC_ARG;
    70407639
    7041 #if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_CRYPTOCELL)
    7042 
    7043     err = 0; /* consider key check success on ATECC508A */
     7640#ifdef WOLFSSL_HAVE_SP_ECC
     7641#ifndef WOLFSSL_SP_NO_256
     7642    if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) {
     7643        return sp_ecc_check_key_256(key->pubkey.x, key->pubkey.y,
     7644            key->type == ECC_PRIVATEKEY ? &key->k : NULL, key->heap);
     7645    }
     7646#endif
     7647#ifdef WOLFSSL_SP_384
     7648    if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) {
     7649        return sp_ecc_check_key_384(key->pubkey.x, key->pubkey.y,
     7650            key->type == ECC_PRIVATEKEY ? &key->k : NULL, key->heap);
     7651    }
     7652#endif
     7653#endif
     7654
     7655#ifndef WOLFSSL_SP_MATH
     7656#if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A) || \
     7657    defined(WOLFSSL_CRYPTOCELL) || defined(WOLFSSL_SILABS_SE_ACCEL)
     7658
     7659    err = 0; /* consider key check success on ATECC508/608A */
    70447660
    70457661#else
     
    71137729                curve->order);
    71147730
     7731    /* SP 800-56Ar3, section 5.6.2.1.2 */
     7732    /* private keys must be in the range [1, n-1] */
     7733    if ((err == MP_OKAY) && (key->type == ECC_PRIVATEKEY) &&
     7734                                    (mp_iszero(&key->k) || mp_isneg(&key->k) ||
     7735                                    (mp_cmp(&key->k, curve->order) != MP_LT))) {
     7736        err = ECC_PRIV_KEY_E;
     7737    }
     7738
    71157739    /* SP 800-56Ar3, section 5.6.2.1.4, method (b) for ECC */
    71167740    /* private * base generator must equal pubkey */
     
    71297753    FREE_CURVE_SPECS();
    71307754
     7755    return err;
    71317756#endif /* WOLFSSL_ATECC508A */
    71327757#else
    7133     if (key == NULL)
    7134         return BAD_FUNC_ARG;
    7135 
    7136     /* pubkey point cannot be at infinity */
    7137 #ifndef WOLFSSL_SP_NO_256
    7138     if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) {
    7139         err = sp_ecc_check_key_256(key->pubkey.x, key->pubkey.y, &key->k,
    7140                                                                      key->heap);
    7141     }
    7142     else
    7143 #endif
    7144 #ifdef WOLFSSL_SP_384
    7145     if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) {
    7146         err = sp_ecc_check_key_384(key->pubkey.x, key->pubkey.y, &key->k,
    7147                                                                      key->heap);
    7148     }
    7149     else
    7150 #endif
    7151     {
    7152         err = WC_KEY_SIZE_E;
    7153     }
    7154 #endif
    7155 
    7156     return err;
     7758    return WC_KEY_SIZE_E;
     7759#endif /* !WOLFSSL_SP_MATH */
    71577760}
    71587761
     
    72157818    in += 1;
    72167819
    7217 #ifdef WOLFSSL_ATECC508A
     7820#if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A)
    72187821    /* For SECP256R1 only save raw public key for hardware */
    72197822    if (curve_id == ECC_SECP256R1 && inLen <= sizeof(key->pubkey_raw)) {
     
    72447847#ifdef HAVE_COMP_KEY
    72457848    if (err == MP_OKAY && compressed == 1) {   /* build y */
    7246 #ifndef WOLFSSL_SP_MATH
     7849#if !defined(WOLFSSL_SP_MATH)
    72477850        mp_int t1, t2;
    72487851        int did_init = 0;
     
    72617864                (ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF |
    72627865                 ECC_CURVE_FIELD_BF));
     7866
     7867    #if defined(WOLFSSL_CUSTOM_CURVES) && \
     7868        defined(WOLFSSL_VALIDATE_ECC_IMPORT)
     7869        /* validate prime is prime for custom curves */
     7870        if (err == MP_OKAY && key->idx == ECC_CUSTOM_IDX) {
     7871            int isPrime = MP_NO;
     7872            err = mp_prime_is_prime(curve->prime, 8, &isPrime);
     7873            if (err == MP_OKAY && isPrime == MP_NO)
     7874                err = MP_VAL;
     7875        }
     7876    #endif
    72637877
    72647878        /* compute x^3 */
     
    73347948        err = mp_set(key->pubkey.z, 1);
    73357949
     7950#ifdef WOLFSSL_SILABS_SE_ACCEL
     7951    err = silabs_ecc_import(key, keysize);
     7952#endif
     7953
    73367954#ifdef WOLFSSL_VALIDATE_ECC_IMPORT
    73377955    if (err == MP_OKAY)
     
    73828000            return BAD_FUNC_ARG;
    73838001
    7384     #ifdef WOLFSSL_ATECC508A
     8002    #if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A)
    73858003        /* Hardware cannot export private portion */
    73868004        return NOT_COMPILED_IN;
     
    74608078{
    74618079    int ret;
    7462 #if defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_ATECC508A)
     8080#ifdef WOLFSSL_CRYPTOCELL
    74638081    const CRYS_ECPKI_Domain_t* pDomain;
    74648082    CRYS_ECPKI_BUILD_TempData_t tempBuff;
     
    74768094        key->type = ECC_PRIVATEKEY;
    74778095    #else
     8096        (void)pubSz;
    74788097        ret = NOT_COMPILED_IN;
    74798098    #endif
     
    74918110        return ret;
    74928111
    7493 #ifdef WOLFSSL_ATECC508A
    7494     /* Hardware does not support loading private keys */
    7495     return NOT_COMPILED_IN;
    7496 #elif defined(WOLFSSL_CRYPTOCELL)
     8112#ifdef WOLFSSL_CRYPTOCELL
    74978113    pDomain = CRYS_ECPKI_GetEcDomain(cc310_mapCurve(curve_id));
    74988114
     
    75268142        ret = mp_read_unsigned_bin(&key->k, priv, privSz);
    75278143    }
    7528 
     8144#elif defined(WOLFSSL_SILABS_SE_ACCEL)
     8145    if (ret == MP_OKAY)
     8146        ret = mp_read_unsigned_bin(&key->k, priv, privSz);
     8147
     8148    if (ret == MP_OKAY) {
     8149        if (pub) {
     8150            ret = silabs_ecc_import(key, key->dp->size);
     8151        } else
     8152        {
     8153            ret = silabs_ecc_import_private(key, key->dp->size);
     8154        }
     8155    }
    75298156#else
    75308157
     
    75388165#endif /* HAVE_WOLF_BIGINT */
    75398166
    7540 
    7541 #endif /* WOLFSSL_ATECC508A */
     8167#endif /* WOLFSSL_CRYPTOCELL */
    75428168
    75438169#ifdef WOLFSSL_VALIDATE_ECC_IMPORT
     
    76068232        err = mp_read_radix(stmp, s, MP_RADIX_HEX);
    76078233
     8234    if (err == MP_OKAY) {
     8235        if (mp_iszero(rtmp) == MP_YES || mp_iszero(stmp) == MP_YES)
     8236            err = MP_ZERO_E;
     8237    }
     8238
    76088239    /* convert mp_ints to ECDSA sig, initializes rtmp and stmp internally */
    76098240    if (err == MP_OKAY)
    76108241        err = StoreECC_DSA_Sig(out, outlen, rtmp, stmp);
    7611 
    7612     if (err == MP_OKAY) {
    7613         if (mp_iszero(rtmp) == MP_YES || mp_iszero(stmp) == MP_YES)
    7614             err = MP_ZERO_E;
    7615     }
    76168242
    76178243    mp_clear(rtmp);
     
    76388264    byte* out, word32* outlen)
    76398265{
    7640     int err;
    7641 #ifdef WOLFSSL_SMALL_STACK
    7642     mp_int* rtmp = NULL;
    7643     mp_int* stmp = NULL;
    7644 #else
    7645     mp_int  rtmp[1];
    7646     mp_int  stmp[1];
    7647 #endif
    7648 
    76498266    if (r == NULL || s == NULL || out == NULL || outlen == NULL)
    76508267        return ECC_BAD_ARG_E;
    76518268
    7652 #ifdef WOLFSSL_SMALL_STACK
    7653     rtmp = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
    7654     if (rtmp == NULL)
    7655         return MEMORY_E;
    7656     stmp = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
    7657     if (stmp == NULL) {
    7658         XFREE(rtmp, NULL, DYNAMIC_TYPE_ECC);
    7659         return MEMORY_E;
    7660     }
    7661 #endif
    7662 
    7663     err = mp_init_multi(rtmp, stmp, NULL, NULL, NULL, NULL);
    7664     if (err != MP_OKAY) {
    7665     #ifdef WOLFSSL_SMALL_STACK
    7666         XFREE(stmp, NULL, DYNAMIC_TYPE_ECC);
    7667         XFREE(rtmp, NULL, DYNAMIC_TYPE_ECC);
    7668     #endif
    7669         return err;
    7670     }
    7671 
    7672     err = mp_read_unsigned_bin(rtmp, r, rSz);
    7673     if (err == MP_OKAY)
    7674         err = mp_read_unsigned_bin(stmp, s, sSz);
    7675 
    76768269    /* convert mp_ints to ECDSA sig, initializes rtmp and stmp internally */
    7677     if (err == MP_OKAY)
    7678         err = StoreECC_DSA_Sig(out, outlen, rtmp, stmp);
    7679 
    7680     if (err == MP_OKAY) {
    7681         if (mp_iszero(rtmp) == MP_YES || mp_iszero(stmp) == MP_YES)
    7682             err = MP_ZERO_E;
    7683     }
    7684 
    7685     mp_clear(rtmp);
    7686     mp_clear(stmp);
    7687 #ifdef WOLFSSL_SMALL_STACK
    7688     XFREE(stmp, NULL, DYNAMIC_TYPE_ECC);
    7689     XFREE(rtmp, NULL, DYNAMIC_TYPE_ECC);
    7690 #endif
    7691 
    7692     return err;
     8270    return StoreECC_DSA_Sig_Bin(out, outlen, r, rSz, s, sSz);
    76938271}
    76948272
     
    77068284                     byte* s, word32* sLen)
    77078285{
    7708     int err;
    7709     int tmp_valid = 0;
    7710     word32 x = 0;
    7711 #ifdef WOLFSSL_SMALL_STACK
    7712     mp_int* rtmp = NULL;
    7713     mp_int* stmp = NULL;
    7714 #else
    7715     mp_int  rtmp[1];
    7716     mp_int  stmp[1];
    7717 #endif
    7718 
    77198286    if (sig == NULL || r == NULL || rLen == NULL || s == NULL || sLen == NULL)
    77208287        return ECC_BAD_ARG_E;
    77218288
    7722 #ifdef WOLFSSL_SMALL_STACK
    7723     rtmp = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
    7724     if (rtmp == NULL)
    7725         return MEMORY_E;
    7726     stmp = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
    7727     if (stmp == NULL) {
    7728         XFREE(rtmp, NULL, DYNAMIC_TYPE_ECC);
    7729         return MEMORY_E;
    7730     }
    7731 #endif
    7732 
    7733     err = DecodeECC_DSA_Sig(sig, sigLen, rtmp, stmp);
    7734 
    7735     /* rtmp and stmp are initialized */
    7736     if (err == MP_OKAY) {
    7737         tmp_valid = 1;
    7738 
    7739         /* extract r */
    7740         x = mp_unsigned_bin_size(rtmp);
    7741         if (*rLen < x)
    7742             err = BUFFER_E;
    7743     }
    7744     if (err == MP_OKAY) {
    7745         *rLen = x;
    7746         err = mp_to_unsigned_bin(rtmp, r);
    7747     }
    7748 
    7749     /* extract s */
    7750     if (err == MP_OKAY) {
    7751         x = mp_unsigned_bin_size(stmp);
    7752         if (*sLen < x)
    7753             err = BUFFER_E;
    7754 
    7755         if (err == MP_OKAY) {
    7756             *sLen = x;
    7757             err = mp_to_unsigned_bin(stmp, s);
    7758         }
    7759     }
    7760 
    7761     if (tmp_valid) {
    7762         mp_clear(rtmp);
    7763         mp_clear(stmp);
    7764     }
    7765 #ifdef WOLFSSL_SMALL_STACK
    7766     XFREE(stmp, NULL, DYNAMIC_TYPE_ECC);
    7767     XFREE(rtmp, NULL, DYNAMIC_TYPE_ECC);
    7768 #endif
    7769 
    7770     return err;
     8289    return DecodeECC_DSA_Sig_Bin(sig, sigLen, r, rLen, s, sLen);
    77718290}
    77728291#endif /* !NO_ASN */
     
    77778296{
    77788297    int err = MP_OKAY;
    7779 #if defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_ATECC508A)
     8298#if defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_ATECC508A) && \
     8299    !defined(WOLFSSL_ATECC608A)
    77808300    const CRYS_ECPKI_Domain_t* pDomain;
    77818301    CRYS_ECPKI_BUILD_TempData_t tempBuff;
    77828302    byte key_raw[ECC_MAX_CRYPTO_HW_SIZE*2 + 1];
     8303#endif
     8304
     8305#if (defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_ATECC508A) &&      \
     8306     !defined(WOLFSSL_ATECC608A))  ||                                   \
     8307  defined(WOLFSSL_SILABS_SE_ACCEL)
    77838308    word32 keySz = 0;
    77848309#endif
     8310
    77858311    /* if d is NULL, only import as public key using Qx,Qy */
    77868312    if (key == NULL || qx == NULL || qy == NULL) {
     
    78208346            err = mp_read_unsigned_bin(key->pubkey.x, (const byte*)qx,
    78218347                key->dp->size);
     8348
     8349        if (mp_iszero(key->pubkey.x)) {
     8350            WOLFSSL_MSG("Invalid Qx");
     8351            err = BAD_FUNC_ARG;
     8352        }
    78228353    }
    78238354
     
    78308361                key->dp->size);
    78318362
     8363        if (mp_iszero(key->pubkey.y)) {
     8364            WOLFSSL_MSG("Invalid Qy");
     8365            err = BAD_FUNC_ARG;
     8366        }
    78328367    }
    78338368
     
    78358370        err = mp_set(key->pubkey.z, 1);
    78368371
    7837 #ifdef WOLFSSL_ATECC508A
     8372#if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A)
    78388373    /* For SECP256R1 only save raw public key for hardware */
    78398374    if (err == MP_OKAY && curve_id == ECC_SECP256R1) {
    7840         word32 keySz = key->dp->size;
     8375        keySz = key->dp->size;
    78418376        err = wc_export_int(key->pubkey.x, key->pubkey_raw,
    78428377            &keySz, keySz, WC_TYPE_UNSIGNED_BIN);
     
    78448379            err = wc_export_int(key->pubkey.y, &key->pubkey_raw[keySz],
    78458380                &keySz, keySz, WC_TYPE_UNSIGNED_BIN);
     8381    }
     8382#elif defined(WOLFSSL_SILABS_SE_ACCEL)
     8383    keySz = key->dp->size;
     8384    if (err == MP_OKAY) {
     8385        err = silabs_ecc_sig_to_rs(key, keySz);
    78468386    }
    78478387#elif defined(WOLFSSL_CRYPTOCELL)
     
    78778417    /* import private key */
    78788418    if (err == MP_OKAY) {
    7879         if (d != NULL && d[0] != '\0') {
    7880         #ifdef WOLFSSL_ATECC508A
     8419        if (d != NULL) {
     8420        #if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A)
    78818421            /* Hardware doesn't support loading private key */
    78828422            err = NOT_COMPILED_IN;
    78838423
     8424        #elif defined(WOLFSSL_SILABS_SE_ACCEL)
     8425            err = silabs_ecc_import_private_raw(key, keySz, d, encType);
     8426
    78848427        #elif defined(WOLFSSL_CRYPTOCELL)
    7885 
    78868428            key->type = ECC_PRIVATEKEY;
    78878429
     
    79188460                    key->dp->size);
    79198461        #endif /* WOLFSSL_ATECC508A */
     8462            if (mp_iszero(&key->k)) {
     8463                WOLFSSL_MSG("Invalid private key");
     8464                return BAD_FUNC_ARG;
     8465            }
    79208466        } else {
    79218467            key->type = ECC_PUBLICKEY;
     
    80878633
    80888634
    8089 #ifndef WOLFSSL_SP_MATH
     8635#if !defined(WOLFSSL_SP_MATH)
    80908636
    80918637/** Our FP cache */
     
    80938639   ecc_point* g;               /* cached COPY of base point */
    80948640   ecc_point* LUT[1U<<FP_LUT]; /* fixed point lookup */
     8641   int        LUT_set;         /* flag to determine if the LUT has been computed */
    80958642   mp_int     mu;              /* copy of the montgomery constant */
    80968643   int        lru_count;       /* amount of times this entry has been used */
     
    86669213         fp_cache[z].LUT[x] = NULL;
    86679214      }
     9215      fp_cache[z].LUT_set = 0;
    86689216      fp_cache[z].lru_count = 0;
    86699217   }
     
    87239271   }
    87249272
     9273   fp_cache[idx].LUT_set   = 0;
    87259274   fp_cache[idx].lru_count = 0;
    87269275
     
    87299278#endif
    87309279
    8731 #ifndef WOLFSSL_SP_MATH
     9280#if !defined(WOLFSSL_SP_MATH)
    87329281/* build the LUT by spacing the bits of the input by #modulus/FP_LUT bits apart
    87339282 *
     
    87419290   unsigned x, y, bitlen, lut_gap;
    87429291   mp_int tmp;
     9292   int infinity;
    87439293
    87449294   if (mp_init(&tmp) != MP_OKAY)
     
    87919341         /* now double it bitlen/FP_LUT times */
    87929342         for (y = 0; y < lut_gap; y++) {
    8793              if ((err = ecc_projective_dbl_point(fp_cache[idx].LUT[1<<x],
     9343             if ((err = ecc_projective_dbl_point_safe(fp_cache[idx].LUT[1<<x],
    87949344                            fp_cache[idx].LUT[1<<x], a, modulus, mp)) != MP_OKAY) {
    87959345                 break;
     
    88079357
    88089358           /* perform the add */
    8809            if ((err = ecc_projective_add_point(
     9359           if ((err = ecc_projective_add_point_safe(
    88109360                           fp_cache[idx].LUT[lut_orders[y].terma],
    88119361                           fp_cache[idx].LUT[lut_orders[y].termb],
    8812                            fp_cache[idx].LUT[y], a, modulus, mp)) != MP_OKAY) {
     9362                           fp_cache[idx].LUT[y], a, modulus, mp,
     9363                           &infinity)) != MP_OKAY) {
    88139364              break;
    88149365           }
     
    88549405   mp_clear(&tmp);
    88559406
    8856    if (err == MP_OKAY)
    8857      return MP_OKAY;
     9407   if (err == MP_OKAY) {
     9408       fp_cache[idx].LUT_set = 1;
     9409       return MP_OKAY;
     9410   }
    88589411
    88599412   /* err cleanup */
     
    88649417   wc_ecc_del_point(fp_cache[idx].g);
    88659418   fp_cache[idx].g         = NULL;
     9419   fp_cache[idx].LUT_set   = 0;
    88669420   fp_cache[idx].lru_count = 0;
    88679421   mp_clear(&fp_cache[idx].mu);
     
    88789432#ifdef WOLFSSL_SMALL_STACK
    88799433   unsigned char* kb = NULL;
     9434   mp_int*        tk = NULL;
     9435   mp_int*        order = NULL;
    88809436#else
    88819437   unsigned char kb[KB_SIZE];
     9438   mp_int        tk[1];
     9439   mp_int        order[1];
    88829440#endif
    88839441   int      x, err;
    8884    unsigned y, z = 0, bitlen, bitpos, lut_gap, first;
    8885    mp_int   tk, order;
    8886 
    8887    if (mp_init_multi(&tk, &order, NULL, NULL, NULL, NULL) != MP_OKAY)
    8888        return MP_INIT_E;
     9442   unsigned y, z = 0, bitlen, bitpos, lut_gap;
     9443   int first;
     9444
     9445#ifdef WOLFSSL_SMALL_STACK
     9446   tk = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
     9447   if (tk == NULL) {
     9448      err = MEMORY_E; goto done;
     9449   }
     9450   order = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
     9451   if (order == NULL) {
     9452      err = MEMORY_E; goto done;
     9453   }
     9454#endif
     9455
     9456   if (mp_init_multi(tk, order, NULL, NULL, NULL, NULL) != MP_OKAY) {
     9457       err = MP_INIT_E; goto done;
     9458   }
    88899459
    88909460   /* if it's smaller than modulus we fine */
     
    88999469      if (y == 66) --x;
    89009470
    8901       if ((err = mp_read_radix(&order, ecc_sets[x].order,
     9471      if ((err = mp_read_radix(order, ecc_sets[x].order,
    89029472                                                MP_RADIX_HEX)) != MP_OKAY) {
    89039473         goto done;
     
    89059475
    89069476      /* k must be less than modulus */
    8907       if (mp_cmp(k, &order) != MP_LT) {
    8908          if ((err = mp_mod(k, &order, &tk)) != MP_OKAY) {
     9477      if (mp_cmp(k, order) != MP_LT) {
     9478         if ((err = mp_mod(k, order, tk)) != MP_OKAY) {
    89099479            goto done;
    89109480         }
    89119481      } else {
    8912          if ((err = mp_copy(k, &tk)) != MP_OKAY) {
     9482         if ((err = mp_copy(k, tk)) != MP_OKAY) {
    89139483            goto done;
    89149484         }
    89159485      }
    89169486   } else {
    8917       if ((err = mp_copy(k, &tk)) != MP_OKAY) {
     9487      if ((err = mp_copy(k, tk)) != MP_OKAY) {
    89189488         goto done;
    89199489      }
     
    89299499
    89309500   /* get the k value */
    8931    if (mp_unsigned_bin_size(&tk) > (int)(KB_SIZE - 2)) {
     9501   if (mp_unsigned_bin_size(tk) > (int)(KB_SIZE - 2)) {
    89329502      err = BUFFER_E; goto done;
    89339503   }
     
    89429512
    89439513   XMEMSET(kb, 0, KB_SIZE);
    8944    if ((err = mp_to_unsigned_bin(&tk, kb)) == MP_OKAY) {
     9514   if ((err = mp_to_unsigned_bin(tk, kb)) == MP_OKAY) {
    89459515      /* let's reverse kb so it's little endian */
    89469516      x = 0;
    8947       y = mp_unsigned_bin_size(&tk);
     9517      y = mp_unsigned_bin_size(tk);
    89489518      if (y > 0) {
    89499519          y -= 1;
     
    89699539          /* double if not first */
    89709540          if (!first) {
    8971              if ((err = ecc_projective_dbl_point(R, R, a, modulus,
     9541             if ((err = ecc_projective_dbl_point_safe(R, R, a, modulus,
    89729542                                                              mp)) != MP_OKAY) {
    89739543                break;
     
    89779547          /* add if not first, otherwise copy */
    89789548          if (!first && z) {
    8979              if ((err = ecc_projective_add_point(R, fp_cache[idx].LUT[z], R, a,
    8980                                                      modulus, mp)) != MP_OKAY) {
     9549             if ((err = ecc_projective_add_point_safe(R, fp_cache[idx].LUT[z],
     9550                                       R, a, modulus, mp, &first)) != MP_OKAY) {
    89819551                break;
    8982              }
    8983              if (mp_iszero(R->z)) {
    8984                  /* When all zero then should have done an add */
    8985                  if (mp_iszero(R->x) && mp_iszero(R->y)) {
    8986                      if ((err = ecc_projective_dbl_point(fp_cache[idx].LUT[z],
    8987                                                R, a, modulus, mp)) != MP_OKAY) {
    8988                          break;
    8989                      }
    8990                  }
    8991                  /* When only Z zero then result is infinity */
    8992                  else {
    8993                     err = mp_set(R->x, 0);
    8994                     if (err != MP_OKAY) {
    8995                        break;
    8996                     }
    8997                     err = mp_set(R->y, 0);
    8998                     if (err != MP_OKAY) {
    8999                        break;
    9000                     }
    9001                     err = mp_copy(&fp_cache[idx].mu, R->z);
    9002                     if (err != MP_OKAY) {
    9003                        break;
    9004                     }
    9005                     first = 1;
    9006                  }
    90079552             }
    90089553          } else if (z) {
     
    90329577done:
    90339578   /* cleanup */
    9034    mp_clear(&order);
    9035    mp_clear(&tk);
     9579   mp_clear(order);
     9580   mp_clear(tk);
    90369581
    90379582#ifdef WOLFSSL_SMALL_STACK
    90389583   XFREE(kb, NULL, DYNAMIC_TYPE_ECC_BUFFER);
     9584   XFREE(order, NULL, DYNAMIC_TYPE_ECC_BUFFER);
     9585   XFREE(tk, NULL, DYNAMIC_TYPE_ECC_BUFFER);
    90399586#endif
    90409587
     
    90469593
    90479594#ifdef ECC_SHAMIR
    9048 #ifndef WOLFSSL_SP_MATH
     9595#if !defined(WOLFSSL_SP_MATH)
    90499596/* perform a fixed point ECC mulmod */
    90509597static int accel_fp_mul2add(int idx1, int idx2,
     
    90579604#ifdef WOLFSSL_SMALL_STACK
    90589605   unsigned char* kb[2] = {NULL, NULL};
     9606   mp_int*        tka = NULL;
     9607   mp_int*        tkb = NULL;
     9608   mp_int*        order = NULL;
    90599609#else
    90609610   unsigned char kb[2][KB_SIZE];
     9611   mp_int        tka[1];
     9612   mp_int        tkb[1];
     9613   mp_int        order[1];
    90619614#endif
    90629615   int      x, err;
    9063    unsigned y, z, bitlen, bitpos, lut_gap, first, zA, zB;
    9064    mp_int tka, tkb, order;
    9065 
    9066    if (mp_init_multi(&tka, &tkb, &order, NULL, NULL, NULL) != MP_OKAY)
    9067        return MP_INIT_E;
     9616   unsigned y, z, bitlen, bitpos, lut_gap, zA, zB;
     9617   int first;
     9618
     9619#ifdef WOLFSSL_SMALL_STACK
     9620   tka = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
     9621   if (tka == NULL) {
     9622      err = MEMORY_E; goto done;
     9623   }
     9624   tkb = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
     9625   if (tkb == NULL) {
     9626      err = MEMORY_E; goto done;
     9627   }
     9628   order = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
     9629   if (order == NULL) {
     9630      err = MEMORY_E; goto done;
     9631   }
     9632#endif
     9633
     9634   if (mp_init_multi(tka, tkb, order, NULL, NULL, NULL) != MP_OKAY) {
     9635      err = MP_INIT_E; goto done;
     9636   }
    90689637
    90699638   /* if it's smaller than modulus we fine */
     
    90789647      if (y == 66) --x;
    90799648
    9080       if ((err = mp_read_radix(&order, ecc_sets[x].order,
     9649      if ((err = mp_read_radix(order, ecc_sets[x].order,
    90819650                                                MP_RADIX_HEX)) != MP_OKAY) {
    90829651         goto done;
     
    90849653
    90859654      /* kA must be less than modulus */
    9086       if (mp_cmp(kA, &order) != MP_LT) {
    9087          if ((err = mp_mod(kA, &order, &tka)) != MP_OKAY) {
     9655      if (mp_cmp(kA, order) != MP_LT) {
     9656         if ((err = mp_mod(kA, order, tka)) != MP_OKAY) {
    90889657            goto done;
    90899658         }
    90909659      } else {
    9091          if ((err = mp_copy(kA, &tka)) != MP_OKAY) {
     9660         if ((err = mp_copy(kA, tka)) != MP_OKAY) {
    90929661            goto done;
    90939662         }
    90949663      }
    90959664   } else {
    9096       if ((err = mp_copy(kA, &tka)) != MP_OKAY) {
     9665      if ((err = mp_copy(kA, tka)) != MP_OKAY) {
    90979666         goto done;
    90989667      }
     
    91109679      if (y == 66) --x;
    91119680
    9112       if ((err = mp_read_radix(&order, ecc_sets[x].order,
     9681      if ((err = mp_read_radix(order, ecc_sets[x].order,
    91139682                                                MP_RADIX_HEX)) != MP_OKAY) {
    91149683         goto done;
     
    91169685
    91179686      /* kB must be less than modulus */
    9118       if (mp_cmp(kB, &order) != MP_LT) {
    9119          if ((err = mp_mod(kB, &order, &tkb)) != MP_OKAY) {
     9687      if (mp_cmp(kB, order) != MP_LT) {
     9688         if ((err = mp_mod(kB, order, tkb)) != MP_OKAY) {
    91209689            goto done;
    91219690         }
    91229691      } else {
    9123          if ((err = mp_copy(kB, &tkb)) != MP_OKAY) {
     9692         if ((err = mp_copy(kB, tkb)) != MP_OKAY) {
    91249693            goto done;
    91259694         }
    91269695      }
    91279696   } else {
    9128       if ((err = mp_copy(kB, &tkb)) != MP_OKAY) {
     9697      if ((err = mp_copy(kB, tkb)) != MP_OKAY) {
    91299698         goto done;
    91309699      }
     
    91409709
    91419710   /* get the k value */
    9142    if ((mp_unsigned_bin_size(&tka) > (int)(KB_SIZE - 2)) ||
    9143        (mp_unsigned_bin_size(&tkb) > (int)(KB_SIZE - 2))  ) {
     9711   if ((mp_unsigned_bin_size(tka) > (int)(KB_SIZE - 2)) ||
     9712       (mp_unsigned_bin_size(tkb) > (int)(KB_SIZE - 2))  ) {
    91449713      err = BUFFER_E; goto done;
    91459714   }
     
    91549723
    91559724   XMEMSET(kb[0], 0, KB_SIZE);
    9156    if ((err = mp_to_unsigned_bin(&tka, kb[0])) != MP_OKAY) {
     9725   if ((err = mp_to_unsigned_bin(tka, kb[0])) != MP_OKAY) {
    91579726      goto done;
    91589727   }
     
    91609729   /* let's reverse kb so it's little endian */
    91619730   x = 0;
    9162    y = mp_unsigned_bin_size(&tka);
     9731   y = mp_unsigned_bin_size(tka);
    91639732   if (y > 0) {
    91649733       y -= 1;
    91659734   }
    9166    mp_clear(&tka);
     9735   mp_clear(tka);
    91679736   while ((unsigned)x < y) {
    91689737      z = kb[0][x]; kb[0][x] = kb[0][y]; kb[0][y] = (byte)z;
     
    91799748
    91809749   XMEMSET(kb[1], 0, KB_SIZE);
    9181    if ((err = mp_to_unsigned_bin(&tkb, kb[1])) == MP_OKAY) {
     9750   if ((err = mp_to_unsigned_bin(tkb, kb[1])) == MP_OKAY) {
    91829751      x = 0;
    9183       y = mp_unsigned_bin_size(&tkb);
     9752      y = mp_unsigned_bin_size(tkb);
    91849753      if (y > 0) {
    91859754          y -= 1;
     
    92069775          /* double if not first */
    92079776          if (!first) {
    9208              if ((err = ecc_projective_dbl_point(R, R, a, modulus,
     9777             if ((err = ecc_projective_dbl_point_safe(R, R, a, modulus,
    92099778                                                              mp)) != MP_OKAY) {
    92109779                break;
     
    92139782             /* add if not first, otherwise copy */
    92149783             if (zA) {
    9215                 if ((err = ecc_projective_add_point(R, fp_cache[idx1].LUT[zA],
    9216                                                R, a, modulus, mp)) != MP_OKAY) {
     9784                if ((err = ecc_projective_add_point_safe(R,
     9785                                             fp_cache[idx1].LUT[zA], R, a,
     9786                                             modulus, mp, &first)) != MP_OKAY) {
    92179787                   break;
    92189788                }
    9219                 if (mp_iszero(R->z)) {
    9220                     /* When all zero then should have done an add */
    9221                     if (mp_iszero(R->x) && mp_iszero(R->y)) {
    9222                         if ((err = ecc_projective_dbl_point(
    9223                                                   fp_cache[idx1].LUT[zA], R,
    9224                                                   a, modulus, mp)) != MP_OKAY) {
    9225                             break;
    9226                         }
    9227                     }
    9228                     /* When only Z zero then result is infinity */
    9229                     else {
    9230                        err = mp_set(R->x, 0);
    9231                        if (err != MP_OKAY) {
    9232                           break;
    9233                        }
    9234                        err = mp_set(R->y, 0);
    9235                        if (err != MP_OKAY) {
    9236                           break;
    9237                        }
    9238                        err = mp_copy(&fp_cache[idx1].mu, R->z);
    9239                        if (err != MP_OKAY) {
    9240                           break;
    9241                        }
    9242                        first = 1;
    9243                     }
    9244                 }
    92459789             }
    92469790
    92479791             if (zB) {
    9248                 if ((err = ecc_projective_add_point(R, fp_cache[idx2].LUT[zB],
    9249                                                R, a, modulus, mp)) != MP_OKAY) {
     9792                if ((err = ecc_projective_add_point_safe(R,
     9793                                             fp_cache[idx2].LUT[zB], R, a,
     9794                                             modulus, mp, &first)) != MP_OKAY) {
    92509795                   break;
    9251                 }
    9252                 if (mp_iszero(R->z)) {
    9253                     /* When all zero then should have done an add */
    9254                     if (mp_iszero(R->x) && mp_iszero(R->y)) {
    9255                         if ((err = ecc_projective_dbl_point(
    9256                                                   fp_cache[idx2].LUT[zB], R,
    9257                                                   a, modulus, mp)) != MP_OKAY) {
    9258                             break;
    9259                         }
    9260                     }
    9261                     /* When only Z zero then result is infinity */
    9262                     else {
    9263                        err = mp_set(R->x, 0);
    9264                        if (err != MP_OKAY) {
    9265                           break;
    9266                        }
    9267                        err = mp_set(R->y, 0);
    9268                        if (err != MP_OKAY) {
    9269                           break;
    9270                        }
    9271                        err = mp_copy(&fp_cache[idx2].mu, R->z);
    9272                        if (err != MP_OKAY) {
    9273                           break;
    9274                        }
    9275                        first = 1;
    9276                     }
    92779796                }
    92789797             }
     
    92899808             if (zB && first == 0) {
    92909809                if (zB) {
    9291                    if ((err = ecc_projective_add_point(R,
    9292                         fp_cache[idx2].LUT[zB], R, a, modulus, mp)) != MP_OKAY){
     9810                   if ((err = ecc_projective_add_point_safe(R,
     9811                                              fp_cache[idx2].LUT[zB], R, a,
     9812                                              modulus, mp, &first)) != MP_OKAY){
    92939813                      break;
    9294                    }
    9295                    if (mp_iszero(R->z)) {
    9296                        /* When all zero then should have done an add */
    9297                        if (mp_iszero(R->x) && mp_iszero(R->y)) {
    9298                            if ((err = ecc_projective_dbl_point(
    9299                                                   fp_cache[idx2].LUT[zB], R,
    9300                                                   a, modulus, mp)) != MP_OKAY) {
    9301                                break;
    9302                            }
    9303                        }
    9304                        /* When only Z zero then result is infinity */
    9305                        else {
    9306                           err = mp_set(R->x, 0);
    9307                           if (err != MP_OKAY) {
    9308                              break;
    9309                           }
    9310                           err = mp_set(R->y, 0);
    9311                           if (err != MP_OKAY) {
    9312                              break;
    9313                           }
    9314                           err = mp_copy(&fp_cache[idx2].mu, R->z);
    9315                           if (err != MP_OKAY) {
    9316                              break;
    9317                           }
    9318                           first = 1;
    9319                        }
    93209814                   }
    93219815                }
     
    93359829done:
    93369830   /* cleanup */
    9337    mp_clear(&tkb);
    9338    mp_clear(&tka);
    9339    mp_clear(&order);
     9831   mp_clear(tkb);
     9832   mp_clear(tka);
     9833   mp_clear(order);
    93409834
    93419835#ifdef WOLFSSL_SMALL_STACK
     
    93499843
    93509844#ifdef WOLFSSL_SMALL_STACK
     9845   XFREE(kb[1], NULL, DYNAMIC_TYPE_ECC_BUFFER);
    93519846   XFREE(kb[0], NULL, DYNAMIC_TYPE_ECC_BUFFER);
    9352    XFREE(kb[1], NULL, DYNAMIC_TYPE_ECC_BUFFER);
     9847   XFREE(order, NULL, DYNAMIC_TYPE_ECC_BUFFER);
     9848   XFREE(tkb, NULL, DYNAMIC_TYPE_ECC_BUFFER);
     9849   XFREE(tka, NULL, DYNAMIC_TYPE_ECC_BUFFER);
    93539850#endif
    93549851
     
    93799876   int  idx1 = -1, idx2 = -1, err, mpInit = 0;
    93809877   mp_digit mp;
    9381    mp_int   mu;
    9382 
    9383    err = mp_init(&mu);
    9384    if (err != MP_OKAY)
     9878#ifdef WOLFSSL_SMALL_STACK
     9879   mp_int   *mu = (mp_int *)XMALLOC(sizeof *mu, NULL, DYNAMIC_TYPE_ECC_BUFFER);
     9880
     9881   if (mu == NULL)
     9882       return MP_MEM;
     9883#else
     9884   mp_int   mu[1];
     9885#endif
     9886
     9887   err = mp_init(mu);
     9888   if (err != MP_OKAY) {
     9889#ifdef WOLFSSL_SMALL_STACK
     9890       XFREE(mu, NULL, DYNAMIC_TYPE_ECC_BUFFER);
     9891#endif
    93859892       return err;
     9893   }
    93869894
    93879895#ifndef HAVE_THREAD_LS
    9388    if (initMutex == 0) {
     9896   if (initMutex == 0) { /* extra sanity check if wolfCrypt_Init not called */
    93899897        wc_InitMutex(&ecc_fp_lock);
    93909898        initMutex = 1;
    93919899   }
    9392    if (wc_LockMutex(&ecc_fp_lock) != 0)
     9900
     9901   if (wc_LockMutex(&ecc_fp_lock) != 0) {
     9902#ifdef WOLFSSL_SMALL_STACK
     9903       XFREE(mu, NULL, DYNAMIC_TYPE_ECC_BUFFER);
     9904#endif
    93939905      return BAD_MUTEX_E;
     9906   }
    93949907#endif /* HAVE_THREAD_LS */
    93959908
     
    94279940
    94289941      if (err == MP_OKAY) {
    9429         /* if it's 2 build the LUT, if it's higher just use the LUT */
    9430         if (idx1 >= 0 && fp_cache[idx1].lru_count == 2) {
     9942        /* if it's >= 2 AND the LUT is not set build the LUT */
     9943        if (idx1 >= 0 && fp_cache[idx1].lru_count >= 2 && !fp_cache[idx1].LUT_set) {
    94319944           /* compute mp */
    94329945           err = mp_montgomery_setup(modulus, &mp);
     
    94349947           if (err == MP_OKAY) {
    94359948             mpInit = 1;
    9436              err = mp_montgomery_calc_normalization(&mu, modulus);
     9949             err = mp_montgomery_calc_normalization(mu, modulus);
    94379950           }
    94389951
    94399952           if (err == MP_OKAY)
    94409953             /* build the LUT */
    9441                err = build_lut(idx1, a, modulus, mp, &mu);
     9954             err = build_lut(idx1, a, modulus, mp, mu);
    94429955        }
    94439956      }
    94449957
    94459958      if (err == MP_OKAY) {
    9446         /* if it's 2 build the LUT, if it's higher just use the LUT */
    9447         if (idx2 >= 0 && fp_cache[idx2].lru_count == 2) {
     9959        /* if it's >= 2 AND the LUT is not set build the LUT */
     9960        if (idx2 >= 0 && fp_cache[idx2].lru_count >= 2 && !fp_cache[idx2].LUT_set) {
    94489961           if (mpInit == 0) {
    94499962                /* compute mp */
     
    94519964                if (err == MP_OKAY) {
    94529965                    mpInit = 1;
    9453                     err = mp_montgomery_calc_normalization(&mu, modulus);
     9966                    err = mp_montgomery_calc_normalization(mu, modulus);
    94549967                }
    94559968            }
    94569969
    94579970            if (err == MP_OKAY)
    9458             /* build the LUT */
    9459               err = build_lut(idx2, a, modulus, mp, &mu);
     9971              /* build the LUT */
     9972              err = build_lut(idx2, a, modulus, mp, mu);
    94609973        }
    94619974      }
     
    94639976
    94649977      if (err == MP_OKAY) {
    9465         if (idx1 >=0 && idx2 >= 0 && fp_cache[idx1].lru_count >= 2 &&
    9466                                      fp_cache[idx2].lru_count >= 2) {
     9978        if (idx1 >=0 && idx2 >= 0 && fp_cache[idx1].LUT_set &&
     9979                                     fp_cache[idx2].LUT_set) {
    94679980           if (mpInit == 0) {
    94689981              /* compute mp */
     
    94799992    wc_UnLockMutex(&ecc_fp_lock);
    94809993#endif /* HAVE_THREAD_LS */
    9481     mp_clear(&mu);
     9994    mp_clear(mu);
     9995#ifdef WOLFSSL_SMALL_STACK
     9996    XFREE(mu, NULL, DYNAMIC_TYPE_ECC_BUFFER);
     9997#endif
    94829998
    94839999    return err;
     
    949910015    mp_int* modulus, int map, void* heap)
    950010016{
    9501 #ifndef WOLFSSL_SP_MATH
     10017#if !defined(WOLFSSL_SP_MATH)
    950210018   int   idx, err = MP_OKAY;
    950310019   mp_digit mp;
     
    951310029
    951410030#ifndef HAVE_THREAD_LS
    9515    if (initMutex == 0) {
     10031   if (initMutex == 0) { /* extra sanity check if wolfCrypt_Init not called */
    951610032        wc_InitMutex(&ecc_fp_lock);
    951710033        initMutex = 1;
     
    954110057      if (err == MP_OKAY) {
    954210058        /* if it's 2 build the LUT, if it's higher just use the LUT */
    9543         if (idx >= 0 && fp_cache[idx].lru_count == 2) {
     10059        if (idx >= 0 && fp_cache[idx].lru_count >= 2 && !fp_cache[idx].LUT_set) {
    954410060           /* compute mp */
    954510061           err = mp_montgomery_setup(modulus, &mp);
     
    955810074
    955910075      if (err == MP_OKAY) {
    9560         if (idx >= 0 && fp_cache[idx].lru_count >= 2) {
     10076        if (idx >= 0 && fp_cache[idx].LUT_set) {
    956110077           if (mpSetup == 0) {
    956210078              /* compute mp */
     
    956610082             err = accel_fp_mul(idx, k, R, a, modulus, mp, map);
    956710083        } else {
    9568            err = normal_ecc_mulmod(k, G, R, a, modulus, map, heap);
     10084           err = normal_ecc_mulmod(k, G, R, a, modulus, NULL, map, heap);
    956910085        }
    957010086     }
     
    959510111}
    959610112
    9597 #ifndef WOLFSSL_SP_MATH
     10113/** ECC Fixed Point mulmod global
     10114    k        The multiplicand
     10115    G        Base point to multiply
     10116    R        [out] Destination of product
     10117    a        ECC curve parameter a
     10118    modulus  The modulus for the curve
     10119    map      [boolean] If non-zero maps the point back to affine coordinates,
     10120             otherwise it's left in jacobian-montgomery form
     10121    return MP_OKAY if successful
     10122*/
     10123int wc_ecc_mulmod_ex2(mp_int* k, ecc_point *G, ecc_point *R, mp_int* a,
     10124    mp_int* modulus, mp_int* order, WC_RNG* rng, int map, void* heap)
     10125{
     10126#if !defined(WOLFSSL_SP_MATH)
     10127   int   idx, err = MP_OKAY;
     10128   mp_digit mp;
     10129   mp_int   mu;
     10130   int      mpSetup = 0;
     10131
     10132   if (k == NULL || G == NULL || R == NULL || a == NULL || modulus == NULL ||
     10133                                                                order == NULL) {
     10134       return ECC_BAD_ARG_E;
     10135   }
     10136
     10137   if (mp_init(&mu) != MP_OKAY)
     10138       return MP_INIT_E;
     10139
     10140   /* k can't have more bits than order */
     10141   if (mp_count_bits(k) > mp_count_bits(order)) {
     10142      return ECC_OUT_OF_RANGE_E;
     10143   }
     10144
     10145#ifndef HAVE_THREAD_LS
     10146   if (initMutex == 0) { /* extra sanity check if wolfCrypt_Init not called */
     10147        wc_InitMutex(&ecc_fp_lock);
     10148        initMutex = 1;
     10149   }
     10150
     10151   if (wc_LockMutex(&ecc_fp_lock) != 0)
     10152      return BAD_MUTEX_E;
     10153#endif /* HAVE_THREAD_LS */
     10154
     10155      /* find point */
     10156      idx = find_base(G);
     10157
     10158      /* no entry? */
     10159      if (idx == -1) {
     10160         /* find hole and add it */
     10161         idx = find_hole();
     10162
     10163         if (idx >= 0)
     10164            err = add_entry(idx, G);
     10165      }
     10166      if (err == MP_OKAY && idx >= 0) {
     10167         /* increment LRU */
     10168         ++(fp_cache[idx].lru_count);
     10169      }
     10170
     10171
     10172      if (err == MP_OKAY) {
     10173        /* if it's 2 build the LUT, if it's higher just use the LUT */
     10174        if (idx >= 0 && fp_cache[idx].lru_count >= 2 && !fp_cache[idx].LUT_set) {
     10175           /* compute mp */
     10176           err = mp_montgomery_setup(modulus, &mp);
     10177
     10178           if (err == MP_OKAY) {
     10179             /* compute mu */
     10180             mpSetup = 1;
     10181             err = mp_montgomery_calc_normalization(&mu, modulus);
     10182           }
     10183
     10184           if (err == MP_OKAY)
     10185             /* build the LUT */
     10186             err = build_lut(idx, a, modulus, mp, &mu);
     10187        }
     10188      }
     10189
     10190      if (err == MP_OKAY) {
     10191        if (idx >= 0 && fp_cache[idx].LUT_set) {
     10192           if (mpSetup == 0) {
     10193              /* compute mp */
     10194              err = mp_montgomery_setup(modulus, &mp);
     10195           }
     10196           if (err == MP_OKAY)
     10197             err = accel_fp_mul(idx, k, R, a, modulus, mp, map);
     10198        } else {
     10199          err = normal_ecc_mulmod(k, G, R, a, modulus, rng, map, heap);
     10200        }
     10201     }
     10202
     10203#ifndef HAVE_THREAD_LS
     10204    wc_UnLockMutex(&ecc_fp_lock);
     10205#endif /* HAVE_THREAD_LS */
     10206    mp_clear(&mu);
     10207
     10208    return err;
     10209#else
     10210    (void)rng;
     10211
     10212   if (k == NULL || G == NULL || R == NULL || a == NULL || modulus == NULL ||
     10213                                                                order == NULL) {
     10214        return ECC_BAD_ARG_E;
     10215    }
     10216
     10217#ifndef WOLFSSL_SP_NO_256
     10218    if (mp_count_bits(modulus) == 256) {
     10219        return sp_ecc_mulmod_256(k, G, R, map, heap);
     10220    }
     10221#endif
     10222#ifdef WOLFSSL_SP_384
     10223    if (mp_count_bits(modulus) == 384) {
     10224        return sp_ecc_mulmod_384(k, G, R, map, heap);
     10225    }
     10226#endif
     10227    return WC_KEY_SIZE_E;
     10228#endif
     10229}
     10230
     10231#if !defined(WOLFSSL_SP_MATH)
    959810232/* helper function for freeing the cache ...
    959910233   must be called with the cache mutex locked */
     
    961010244         fp_cache[x].g         = NULL;
    961110245         mp_clear(&fp_cache[x].mu);
     10246         fp_cache[x].LUT_set   = 0;
    961210247         fp_cache[x].lru_count = 0;
    961310248         fp_cache[x].lock = 0;
     
    961710252#endif
    961810253
    9619 /** Free the Fixed Point cache */
    9620 void wc_ecc_fp_free(void)
     10254
     10255/** Init the Fixed Point cache */
     10256void wc_ecc_fp_init(void)
    962110257{
    962210258#ifndef WOLFSSL_SP_MATH
     
    962610262        initMutex = 1;
    962710263   }
     10264#endif
     10265#endif
     10266}
     10267
     10268
     10269/** Free the Fixed Point cache */
     10270void wc_ecc_fp_free(void)
     10271{
     10272#if !defined(WOLFSSL_SP_MATH)
     10273#ifndef HAVE_THREAD_LS
     10274   if (initMutex == 0) { /* extra sanity check if wolfCrypt_Init not called */
     10275        wc_InitMutex(&ecc_fp_lock);
     10276        initMutex = 1;
     10277   }
    962810278
    962910279   if (wc_LockMutex(&ecc_fp_lock) == 0) {
     
    964310293
    964410294#endif /* FP_ECC */
     10295
     10296#ifdef ECC_TIMING_RESISTANT
     10297int wc_ecc_set_rng(ecc_key* key, WC_RNG* rng)
     10298{
     10299    int err = 0;
     10300
     10301    if (key == NULL) {
     10302        err = BAD_FUNC_ARG;
     10303    }
     10304    else {
     10305        key->rng = rng;
     10306    }
     10307
     10308    return err;
     10309}
     10310#endif
    964510311
    964610312#ifdef HAVE_ECC_ENCRYPT
     
    968210348    byte      cliSt;       /* protocol state, for sanity checks */
    968310349    byte      srvSt;       /* protocol state, for sanity checks */
     10350    WC_RNG*   rng;
    968410351};
    968510352
     
    977910446
    978010447
    9781 static int ecc_ctx_set_salt(ecEncCtx* ctx, int flags, WC_RNG* rng)
     10448static int ecc_ctx_set_salt(ecEncCtx* ctx, int flags)
    978210449{
    978310450    byte* saltBuffer = NULL;
    978410451
    9785     if (ctx == NULL || rng == NULL || flags == 0)
     10452    if (ctx == NULL || flags == 0)
    978610453        return BAD_FUNC_ARG;
    978710454
    978810455    saltBuffer = (flags == REQ_RESP_CLIENT) ? ctx->clientSalt : ctx->serverSalt;
    978910456
    9790     return wc_RNG_GenerateBlock(rng, saltBuffer, EXCHANGE_SALT_SZ);
    9791 }
    9792 
    9793 
    9794 static void ecc_ctx_init(ecEncCtx* ctx, int flags)
     10457    return wc_RNG_GenerateBlock(ctx->rng, saltBuffer, EXCHANGE_SALT_SZ);
     10458}
     10459
     10460
     10461static void ecc_ctx_init(ecEncCtx* ctx, int flags, WC_RNG* rng)
    979510462{
    979610463    if (ctx) {
     
    980110468        ctx->macAlgo  = ecHMAC_SHA256;
    980210469        ctx->protocol = (byte)flags;
     10470        ctx->rng      = rng;
    980310471
    980410472        if (flags == REQ_RESP_CLIENT)
     
    981610484        return BAD_FUNC_ARG;
    981710485
    9818     ecc_ctx_init(ctx, ctx->protocol);
    9819     return ecc_ctx_set_salt(ctx, ctx->protocol, rng);
     10486    ecc_ctx_init(ctx, ctx->protocol, rng);
     10487    return ecc_ctx_set_salt(ctx, ctx->protocol);
    982010488}
    982110489
     
    992110589
    992210590    if (ctx == NULL) {  /* use defaults */
    9923         ecc_ctx_init(&localCtx, 0);
     10591        ecc_ctx_init(&localCtx, 0, NULL);
    992410592        ctx = &localCtx;
    992510593    }
     
    995410622    if (*outSz < (msgSz + digestSz))
    995510623        return BUFFER_E;
     10624
     10625#ifdef ECC_TIMING_RESISTANT
     10626    if (ctx->rng != NULL && privKey->rng == NULL)
     10627        privKey->rng = ctx->rng;
     10628#endif
    995610629
    995710630#ifdef WOLFSSL_SMALL_STACK
     
    999710670           case ecAES_128_CBC:
    999810671               {
    9999                    Aes aes;
    10000                    ret = wc_AesInit(&aes, NULL, INVALID_DEVID);
     10672#ifdef WOLFSSL_SMALL_STACK
     10673                   Aes *aes = (Aes *)XMALLOC(sizeof *aes, NULL,
     10674                                             DYNAMIC_TYPE_AES);
     10675                   if (aes == NULL) {
     10676                       ret = MEMORY_E;
     10677                       break;
     10678                   }
     10679#else
     10680                   Aes aes[1];
     10681#endif
     10682                   ret = wc_AesInit(aes, NULL, INVALID_DEVID);
    1000110683                   if (ret == 0) {
    10002                        ret = wc_AesSetKey(&aes, encKey, KEY_SIZE_128, encIv,
     10684                       ret = wc_AesSetKey(aes, encKey, KEY_SIZE_128, encIv,
    1000310685                                                                AES_ENCRYPTION);
    1000410686                       if (ret == 0) {
    10005                            ret = wc_AesCbcEncrypt(&aes, out, msg, msgSz);
     10687                           ret = wc_AesCbcEncrypt(aes, out, msg, msgSz);
    1000610688                       #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_AES)
    10007                            ret = wc_AsyncWait(ret, &aes.asyncDev,
     10689                           ret = wc_AsyncWait(ret, &aes->asyncDev,
    1000810690                                              WC_ASYNC_FLAG_NONE);
    1000910691                       #endif
    1001010692                       }
    10011                        wc_AesFree(&aes);
     10693                       wc_AesFree(aes);
    1001210694                   }
     10695#ifdef WOLFSSL_SMALL_STACK
     10696                   XFREE(aes, NULL, DYNAMIC_TYPE_AES);
     10697#endif
    1001310698                   if (ret != 0)
    1001410699                      break;
     
    1002610711           case ecHMAC_SHA256:
    1002710712               {
    10028                    Hmac hmac;
    10029                    ret = wc_HmacInit(&hmac, NULL, INVALID_DEVID);
     10713#ifdef WOLFSSL_SMALL_STACK
     10714                   Hmac *hmac = (Hmac *)XMALLOC(sizeof *hmac, NULL,
     10715                                                DYNAMIC_TYPE_HMAC);
     10716                   if (hmac == NULL) {
     10717                       ret = MEMORY_E;
     10718                       break;
     10719                   }
     10720#else
     10721                   Hmac hmac[1];
     10722#endif
     10723                   ret = wc_HmacInit(hmac, NULL, INVALID_DEVID);
    1003010724                   if (ret == 0) {
    10031                        ret = wc_HmacSetKey(&hmac, WC_SHA256, macKey, WC_SHA256_DIGEST_SIZE);
     10725                       ret = wc_HmacSetKey(hmac, WC_SHA256, macKey, WC_SHA256_DIGEST_SIZE);
    1003210726                       if (ret == 0)
    10033                            ret = wc_HmacUpdate(&hmac, out, msgSz);
     10727                           ret = wc_HmacUpdate(hmac, out, msgSz);
    1003410728                       if (ret == 0)
    10035                            ret = wc_HmacUpdate(&hmac, ctx->macSalt, ctx->macSaltSz);
     10729                           ret = wc_HmacUpdate(hmac, ctx->macSalt, ctx->macSaltSz);
    1003610730                       if (ret == 0)
    10037                            ret = wc_HmacFinal(&hmac, out+msgSz);
    10038                        wc_HmacFree(&hmac);
     10731                           ret = wc_HmacFinal(hmac, out+msgSz);
     10732                       wc_HmacFree(hmac);
    1003910733                   }
     10734#ifdef WOLFSSL_SMALL_STACK
     10735                   XFREE(hmac, NULL, DYNAMIC_TYPE_HMAC);
     10736#endif
    1004010737               }
    1004110738               break;
     
    1009010787
    1009110788    if (ctx == NULL) {  /* use defaults */
    10092         ecc_ctx_init(&localCtx, 0);
     10789        ecc_ctx_init(&localCtx, 0, NULL);
    1009310790        ctx = &localCtx;
    1009410791    }
     
    1012310820    if (*outSz < (msgSz - digestSz))
    1012410821        return BUFFER_E;
     10822
     10823#ifdef ECC_TIMING_RESISTANT
     10824    if (ctx->rng != NULL && privKey->rng == NULL)
     10825        privKey->rng = ctx->rng;
     10826#endif
    1012510827
    1012610828#ifdef WOLFSSL_SMALL_STACK
     
    1016710869           {
    1016810870               byte verify[WC_SHA256_DIGEST_SIZE];
    10169                Hmac hmac;
    10170 
    10171                ret = wc_HmacInit(&hmac, NULL, INVALID_DEVID);
     10871#ifdef WOLFSSL_SMALL_STACK
     10872               Hmac *hmac = (Hmac *)XMALLOC(sizeof *hmac, NULL, DYNAMIC_TYPE_HMAC);
     10873               if (hmac == NULL) {
     10874                   ret = MEMORY_E;
     10875                   break;
     10876               }
     10877#else
     10878               Hmac hmac[1];
     10879#endif
     10880               ret = wc_HmacInit(hmac, NULL, INVALID_DEVID);
    1017210881               if (ret == 0) {
    10173                    ret = wc_HmacSetKey(&hmac, WC_SHA256, macKey, WC_SHA256_DIGEST_SIZE);
     10882                   ret = wc_HmacSetKey(hmac, WC_SHA256, macKey, WC_SHA256_DIGEST_SIZE);
    1017410883                   if (ret == 0)
    10175                        ret = wc_HmacUpdate(&hmac, msg, msgSz-digestSz);
     10884                       ret = wc_HmacUpdate(hmac, msg, msgSz-digestSz);
    1017610885                   if (ret == 0)
    10177                        ret = wc_HmacUpdate(&hmac, ctx->macSalt, ctx->macSaltSz);
     10886                       ret = wc_HmacUpdate(hmac, ctx->macSalt, ctx->macSaltSz);
    1017810887                   if (ret == 0)
    10179                        ret = wc_HmacFinal(&hmac, verify);
     10888                       ret = wc_HmacFinal(hmac, verify);
    1018010889                   if (ret == 0) {
    1018110890                      if (XMEMCMP(verify, msg + msgSz - digestSz, digestSz) != 0)
     
    1018310892                   }
    1018410893
    10185                    wc_HmacFree(&hmac);
     10894                   wc_HmacFree(hmac);
    1018610895               }
     10896#ifdef WOLFSSL_SMALL_STACK
     10897               XFREE(hmac, NULL, DYNAMIC_TYPE_HMAC);
     10898#endif
    1018710899               break;
    1018810900           }
     
    1019910911           case ecAES_128_CBC:
    1020010912               {
    10201                    Aes aes;
    10202                    ret = wc_AesSetKey(&aes, encKey, KEY_SIZE_128, encIv,
     10913#ifdef WOLFSSL_SMALL_STACK
     10914                   Aes *aes = (Aes *)XMALLOC(sizeof *aes, NULL,
     10915                                             DYNAMIC_TYPE_AES);
     10916                   if (aes == NULL) {
     10917                       ret = MEMORY_E;
     10918                       break;
     10919                   }
     10920#else
     10921                   Aes aes[1];
     10922#endif
     10923                   ret = wc_AesInit(aes, NULL, INVALID_DEVID);
     10924                   if (ret == 0) {
     10925                       ret = wc_AesSetKey(aes, encKey, KEY_SIZE_128, encIv,
    1020310926                                                                AES_DECRYPTION);
     10927                       if (ret == 0) {
     10928                           ret = wc_AesCbcDecrypt(aes, out, msg,
     10929                                                                msgSz-digestSz);
     10930                       #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_AES)
     10931                           ret = wc_AsyncWait(ret, &aes->asyncDev,
     10932                                                            WC_ASYNC_FLAG_NONE);
     10933                       #endif
     10934                       }
     10935                       wc_AesFree(aes);
     10936                   }
     10937#ifdef WOLFSSL_SMALL_STACK
     10938                   XFREE(aes, NULL, DYNAMIC_TYPE_AES);
     10939#endif
    1020410940                   if (ret != 0)
    10205                        break;
    10206                    ret = wc_AesCbcDecrypt(&aes, out, msg, msgSz-digestSz);
    10207                 #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_AES)
    10208                    ret = wc_AsyncWait(ret, &aes.asyncDev, WC_ASYNC_FLAG_NONE);
    10209                 #endif
     10941                      break;
    1021010942               }
    1021110943               break;
     
    1023310965
    1023410966#ifdef HAVE_COMP_KEY
    10235 #if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
     10967#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A) && \
     10968    !defined(WOLFSSL_CRYPTOCELL)
    1023610969
    1023710970#ifndef WOLFSSL_SP_MATH
    10238 int do_mp_jacobi(mp_int* a, mp_int* n, int* c);
    10239 
    10240 int do_mp_jacobi(mp_int* a, mp_int* n, int* c)
    10241 {
    10242   int      k, s, res;
    10243   int      r = 0; /* initialize to help static analysis out */
    10244   mp_digit residue;
    10245 
    10246   /* if a < 0 return MP_VAL */
    10247   if (mp_isneg(a) == MP_YES) {
    10248      return MP_VAL;
    10249   }
    10250 
    10251   /* if n <= 0 return MP_VAL */
    10252   if (mp_cmp_d(n, 0) != MP_GT) {
    10253      return MP_VAL;
    10254   }
    10255 
    10256   /* step 1. handle case of a == 0 */
    10257   if (mp_iszero (a) == MP_YES) {
    10258      /* special case of a == 0 and n == 1 */
    10259      if (mp_cmp_d (n, 1) == MP_EQ) {
    10260        *c = 1;
    10261      } else {
    10262        *c = 0;
    10263      }
    10264      return MP_OKAY;
    10265   }
    10266 
    10267   /* step 2.  if a == 1, return 1 */
    10268   if (mp_cmp_d (a, 1) == MP_EQ) {
    10269     *c = 1;
    10270     return MP_OKAY;
    10271   }
    10272 
    10273   /* default */
    10274   s = 0;
    10275 
    10276   /* divide out larger power of two */
    10277   k = mp_cnt_lsb(a);
    10278   res = mp_div_2d(a, k, a, NULL);
    10279 
    10280   if (res == MP_OKAY) {
    10281     /* step 4.  if e is even set s=1 */
    10282     if ((k & 1) == 0) {
    10283       s = 1;
    10284     } else {
    10285       /* else set s=1 if p = 1/7 (mod 8) or s=-1 if p = 3/5 (mod 8) */
    10286       residue = n->dp[0] & 7;
    10287 
    10288       if (residue == 1 || residue == 7) {
    10289         s = 1;
    10290       } else if (residue == 3 || residue == 5) {
    10291         s = -1;
    10292       }
    10293     }
    10294 
    10295     /* step 5.  if p == 3 (mod 4) *and* a == 3 (mod 4) then s = -s */
    10296     if ( ((n->dp[0] & 3) == 3) && ((a->dp[0] & 3) == 3)) {
    10297       s = -s;
    10298     }
    10299   }
    10300 
    10301   if (res == MP_OKAY) {
    10302     /* if a == 1 we're done */
    10303     if (mp_cmp_d(a, 1) == MP_EQ) {
    10304       *c = s;
    10305     } else {
    10306       /* n1 = n mod a */
    10307       res = mp_mod (n, a, n);
    10308       if (res == MP_OKAY)
    10309         res = do_mp_jacobi(n, a, &r);
    10310 
    10311       if (res == MP_OKAY)
    10312         *c = s * r;
    10313     }
    10314   }
    10315 
    10316   return res;
    10317 }
    10318 
    10319 
    1032010971/* computes the jacobi c = (a | n) (or Legendre if n is prime)
    10321  * HAC pp. 73 Algorithm 2.149
    10322  * HAC is wrong here, as the special case of (0 | 1) is not
    10323  * handled correctly.
    1032410972 */
    1032510973int mp_jacobi(mp_int* a, mp_int* n, int* c)
     
    1032710975    mp_int   a1, n1;
    1032810976    int      res;
    10329 
    10330     /* step 3.  write a = a1 * 2**k  */
     10977    int      s = 1;
     10978    int      k;
     10979    mp_int*  t[2];
     10980    mp_int*  ts;
     10981    mp_digit residue;
     10982
     10983    if (mp_isneg(a) == MP_YES) {
     10984        return MP_VAL;
     10985    }
     10986    if (mp_isneg(n) == MP_YES) {
     10987        return MP_VAL;
     10988    }
     10989    if (mp_iseven(n) == MP_YES) {
     10990        return MP_VAL;
     10991    }
     10992
    1033110993    if ((res = mp_init_multi(&a1, &n1, NULL, NULL, NULL, NULL)) != MP_OKAY) {
    1033210994        return res;
    1033310995    }
    1033410996
    10335     if ((res = mp_copy(a, &a1)) != MP_OKAY) {
     10997    if ((res = mp_mod(a, n, &a1)) != MP_OKAY) {
    1033610998        goto done;
    1033710999    }
     
    1034111003    }
    1034211004
    10343     res = do_mp_jacobi(&a1, &n1, c);
     11005    t[0] = &a1;
     11006    t[1] = &n1;
     11007
     11008    /* Keep reducing until first number is 0. */
     11009    while (!mp_iszero(t[0])) {
     11010        /* Divide by 2 until odd. */
     11011        k = mp_cnt_lsb(t[0]);
     11012        if (k > 0) {
     11013            mp_rshb(t[0], k);
     11014
     11015            /* Negate s each time we divide by 2 if t[1] mod 8 == 3 or 5.
     11016             * Odd number of divides results in a negate.
     11017             */
     11018            residue = t[1]->dp[0] & 7;
     11019            if ((k & 1) && ((residue == 3) || (residue == 5))) {
     11020                s = -s;
     11021            }
     11022        }
     11023
     11024        /* Swap t[0] and t[1]. */
     11025        ts   = t[0];
     11026        t[0] = t[1];
     11027        t[1] = ts;
     11028
     11029        /* Negate s if both numbers == 3 mod 4. */
     11030        if (((t[0]->dp[0] & 3) == 3) && ((t[1]->dp[0] & 3) == 3)) {
     11031             s = -s;
     11032        }
     11033
     11034        /* Reduce first number modulo second. */
     11035        if ((k == 0) && (mp_count_bits(t[0]) == mp_count_bits(t[1]))) {
     11036            res = mp_sub(t[0], t[1], t[0]);
     11037        }
     11038        else {
     11039            res = mp_mod(t[0], t[1], t[0]);
     11040        }
     11041        if (res != MP_OKAY) {
     11042            goto done;
     11043        }
     11044    }
     11045
     11046    /* When the two numbers have divisors in common. */
     11047    if (!mp_isone(t[1])) {
     11048        s = 0;
     11049    }
     11050    *c = s;
    1034411051
    1034511052done:
     
    1037711084#else
    1037811085  int res, legendre, done = 0;
    10379   mp_int t1, C, Q, S, Z, M, T, R, two;
    1038011086  mp_digit i;
     11087#ifdef WOLFSSL_SMALL_STACK
     11088  mp_int *t1 = (mp_int *)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC_BUFFER);
     11089  mp_int *C = (mp_int *)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC_BUFFER);
     11090  mp_int *Q = (mp_int *)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC_BUFFER);
     11091  mp_int *S = (mp_int *)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC_BUFFER);
     11092  mp_int *Z = (mp_int *)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC_BUFFER);
     11093  mp_int *M = (mp_int *)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC_BUFFER);
     11094  mp_int *T = (mp_int *)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC_BUFFER);
     11095  mp_int *R = (mp_int *)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC_BUFFER);
     11096  mp_int *two = (mp_int *)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC_BUFFER);
     11097#else
     11098  mp_int t1[1], C[1], Q[1], S[1], Z[1], M[1], T[1], R[1], two[1];
     11099#endif
     11100
     11101  if ((mp_init_multi(t1, C, Q, S, Z, M) != MP_OKAY) ||
     11102      (mp_init_multi(T, R, two, NULL, NULL, NULL) != MP_OKAY)) {
     11103    res = MP_INIT_E;
     11104    goto out;
     11105  }
     11106
     11107#ifdef WOLFSSL_SMALL_STACK
     11108  if ((t1 == NULL) ||
     11109      (C == NULL) ||
     11110      (Q == NULL) ||
     11111      (S == NULL) ||
     11112      (Z == NULL) ||
     11113      (M == NULL) ||
     11114      (T == NULL) ||
     11115      (R == NULL) ||
     11116      (two == NULL)) {
     11117    res = MP_MEM;
     11118    goto out;
     11119  }
     11120#endif
    1038111121
    1038211122  /* first handle the simple cases n = 0 or n = 1 */
    1038311123  if (mp_cmp_d(n, 0) == MP_EQ) {
    1038411124    mp_zero(ret);
    10385     return MP_OKAY;
     11125    res = MP_OKAY;
     11126    goto out;
    1038611127  }
    1038711128  if (mp_cmp_d(n, 1) == MP_EQ) {
    10388     return mp_set(ret, 1);
     11129    res = mp_set(ret, 1);
     11130    goto out;
    1038911131  }
    1039011132
    1039111133  /* prime must be odd */
    1039211134  if (mp_cmp_d(prime, 2) == MP_EQ) {
    10393     return MP_VAL;
     11135    res = MP_VAL;
     11136    goto out;
    1039411137  }
    1039511138
    1039611139  /* is quadratic non-residue mod prime */
    1039711140  if ((res = mp_jacobi(n, prime, &legendre)) != MP_OKAY) {
    10398     return res;
     11141    goto out;
    1039911142  }
    1040011143  if (legendre == -1) {
    10401     return MP_VAL;
    10402   }
    10403 
    10404   if ((res = mp_init_multi(&t1, &C, &Q, &S, &Z, &M)) != MP_OKAY)
    10405     return res;
    10406 
    10407   if ((res = mp_init_multi(&T, &R, &two, NULL, NULL, NULL))
    10408                           != MP_OKAY) {
    10409     mp_clear(&t1); mp_clear(&C); mp_clear(&Q); mp_clear(&S); mp_clear(&Z);
    10410     mp_clear(&M);
    10411     return res;
     11144    res = MP_VAL;
     11145    goto out;
    1041211146  }
    1041311147
     
    1041811152  res = mp_mod_d(prime, 4, &i);
    1041911153  if (res == MP_OKAY && i == 3) {
    10420     res = mp_add_d(prime, 1, &t1);
     11154    res = mp_add_d(prime, 1, t1);
    1042111155
    1042211156    if (res == MP_OKAY)
    10423       res = mp_div_2(&t1, &t1);
     11157      res = mp_div_2(t1, t1);
    1042411158    if (res == MP_OKAY)
    10425       res = mp_div_2(&t1, &t1);
     11159      res = mp_div_2(t1, t1);
    1042611160    if (res == MP_OKAY)
    10427       res = mp_exptmod(n, &t1, prime, ret);
     11161      res = mp_exptmod(n, t1, prime, ret);
    1042811162
    1042911163    done = 1;
     
    1043611170    *                                      as: prime-1 = Q*2^S */
    1043711171    /* Q = prime - 1 */
    10438     res = mp_copy(prime, &Q);
     11172    res = mp_copy(prime, Q);
    1043911173    if (res == MP_OKAY)
    10440       res = mp_sub_d(&Q, 1, &Q);
     11174      res = mp_sub_d(Q, 1, Q);
    1044111175
    1044211176    /* S = 0 */
    1044311177    if (res == MP_OKAY)
    10444       mp_zero(&S);
    10445 
    10446     while (res == MP_OKAY && mp_iseven(&Q) == MP_YES) {
     11178      mp_zero(S);
     11179
     11180    while (res == MP_OKAY && mp_iseven(Q) == MP_YES) {
    1044711181      /* Q = Q / 2 */
    10448       res = mp_div_2(&Q, &Q);
     11182      res = mp_div_2(Q, Q);
    1044911183
    1045011184      /* S = S + 1 */
    1045111185      if (res == MP_OKAY)
    10452         res = mp_add_d(&S, 1, &S);
     11186        res = mp_add_d(S, 1, S);
    1045311187    }
    1045411188
     
    1045611190    /* Z = 2 */
    1045711191    if (res == MP_OKAY)
    10458       res = mp_set_int(&Z, 2);
     11192      res = mp_set_int(Z, 2);
    1045911193
    1046011194    while (res == MP_OKAY) {
    10461       res = mp_jacobi(&Z, prime, &legendre);
     11195      res = mp_jacobi(Z, prime, &legendre);
    1046211196      if (res == MP_OKAY && legendre == -1)
    1046311197        break;
     
    1046511199      /* Z = Z + 1 */
    1046611200      if (res == MP_OKAY)
    10467         res = mp_add_d(&Z, 1, &Z);
     11201        res = mp_add_d(Z, 1, Z);
    1046811202    }
    1046911203
    1047011204    /* C = Z ^ Q mod prime */
    1047111205    if (res == MP_OKAY)
    10472       res = mp_exptmod(&Z, &Q, prime, &C);
     11206      res = mp_exptmod(Z, Q, prime, C);
    1047311207
    1047411208    /* t1 = (Q + 1) / 2 */
    1047511209    if (res == MP_OKAY)
    10476       res = mp_add_d(&Q, 1, &t1);
     11210      res = mp_add_d(Q, 1, t1);
    1047711211    if (res == MP_OKAY)
    10478       res = mp_div_2(&t1, &t1);
     11212      res = mp_div_2(t1, t1);
    1047911213
    1048011214    /* R = n ^ ((Q + 1) / 2) mod prime */
    1048111215    if (res == MP_OKAY)
    10482       res = mp_exptmod(n, &t1, prime, &R);
     11216      res = mp_exptmod(n, t1, prime, R);
    1048311217
    1048411218    /* T = n ^ Q mod prime */
    1048511219    if (res == MP_OKAY)
    10486       res = mp_exptmod(n, &Q, prime, &T);
     11220      res = mp_exptmod(n, Q, prime, T);
    1048711221
    1048811222    /* M = S */
    1048911223    if (res == MP_OKAY)
    10490       res = mp_copy(&S, &M);
     11224      res = mp_copy(S, M);
    1049111225
    1049211226    if (res == MP_OKAY)
    10493       res = mp_set_int(&two, 2);
     11227      res = mp_set_int(two, 2);
    1049411228
    1049511229    while (res == MP_OKAY && done == 0) {
    10496       res = mp_copy(&T, &t1);
     11230      res = mp_copy(T, t1);
    1049711231
    1049811232      /* reduce to 1 and count */
    1049911233      i = 0;
    1050011234      while (res == MP_OKAY) {
    10501         if (mp_cmp_d(&t1, 1) == MP_EQ)
     11235        if (mp_cmp_d(t1, 1) == MP_EQ)
    1050211236            break;
    10503         res = mp_exptmod(&t1, &two, prime, &t1);
     11237        res = mp_exptmod(t1, two, prime, t1);
    1050411238        if (res == MP_OKAY)
    1050511239          i++;
    1050611240      }
    1050711241      if (res == MP_OKAY && i == 0) {
    10508         res = mp_copy(&R, ret);
     11242        res = mp_copy(R, ret);
    1050911243        done = 1;
    1051011244      }
     
    1051311247        /* t1 = 2 ^ (M - i - 1) */
    1051411248        if (res == MP_OKAY)
    10515           res = mp_sub_d(&M, i, &t1);
     11249          res = mp_sub_d(M, i, t1);
    1051611250        if (res == MP_OKAY)
    10517           res = mp_sub_d(&t1, 1, &t1);
     11251          res = mp_sub_d(t1, 1, t1);
    1051811252        if (res == MP_OKAY)
    10519           res = mp_exptmod(&two, &t1, prime, &t1);
     11253          res = mp_exptmod(two, t1, prime, t1);
    1052011254
    1052111255        /* t1 = C ^ (2 ^ (M - i - 1)) mod prime */
    1052211256        if (res == MP_OKAY)
    10523           res = mp_exptmod(&C, &t1, prime, &t1);
     11257          res = mp_exptmod(C, t1, prime, t1);
    1052411258
    1052511259        /* C = (t1 * t1) mod prime */
    1052611260        if (res == MP_OKAY)
    10527           res = mp_sqrmod(&t1, prime, &C);
     11261          res = mp_sqrmod(t1, prime, C);
    1052811262
    1052911263        /* R = (R * t1) mod prime */
    1053011264        if (res == MP_OKAY)
    10531           res = mp_mulmod(&R, &t1, prime, &R);
     11265          res = mp_mulmod(R, t1, prime, R);
    1053211266
    1053311267        /* T = (T * C) mod prime */
    1053411268        if (res == MP_OKAY)
    10535           res = mp_mulmod(&T, &C, prime, &T);
     11269          res = mp_mulmod(T, C, prime, T);
    1053611270
    1053711271        /* M = i */
    1053811272        if (res == MP_OKAY)
    10539           res = mp_set(&M, i);
     11273          res = mp_set(M, i);
    1054011274      }
    1054111275    }
    1054211276  }
    1054311277
    10544   /* done */
    10545   mp_clear(&t1);
    10546   mp_clear(&C);
    10547   mp_clear(&Q);
    10548   mp_clear(&S);
    10549   mp_clear(&Z);
    10550   mp_clear(&M);
    10551   mp_clear(&T);
    10552   mp_clear(&R);
    10553   mp_clear(&two);
     11278  out:
     11279
     11280#ifdef WOLFSSL_SMALL_STACK
     11281  if (t1) {
     11282    if (res != MP_INIT_E)
     11283      mp_clear(t1);
     11284    XFREE(t1, NULL, DYNAMIC_TYPE_ECC_BUFFER);
     11285  }
     11286  if (C) {
     11287    if (res != MP_INIT_E)
     11288      mp_clear(C);
     11289    XFREE(C, NULL, DYNAMIC_TYPE_ECC_BUFFER);
     11290  }
     11291  if (Q) {
     11292    if (res != MP_INIT_E)
     11293      mp_clear(Q);
     11294    XFREE(Q, NULL, DYNAMIC_TYPE_ECC_BUFFER);
     11295  }
     11296  if (S) {
     11297    if (res != MP_INIT_E)
     11298      mp_clear(S);
     11299    XFREE(S, NULL, DYNAMIC_TYPE_ECC_BUFFER);
     11300  }
     11301  if (Z) {
     11302    if (res != MP_INIT_E)
     11303      mp_clear(Z);
     11304    XFREE(Z, NULL, DYNAMIC_TYPE_ECC_BUFFER);
     11305  }
     11306  if (M) {
     11307    if (res != MP_INIT_E)
     11308      mp_clear(M);
     11309    XFREE(M, NULL, DYNAMIC_TYPE_ECC_BUFFER);
     11310  }
     11311  if (T) {
     11312    if (res != MP_INIT_E)
     11313      mp_clear(T);
     11314    XFREE(T, NULL, DYNAMIC_TYPE_ECC_BUFFER);
     11315  }
     11316  if (R) {
     11317    if (res != MP_INIT_E)
     11318      mp_clear(R);
     11319    XFREE(R, NULL, DYNAMIC_TYPE_ECC_BUFFER);
     11320  }
     11321  if (two) {
     11322    if (res != MP_INIT_E)
     11323      mp_clear(two);
     11324    XFREE(two, NULL, DYNAMIC_TYPE_ECC_BUFFER);
     11325  }
     11326#else
     11327  if (res != MP_INIT_E) {
     11328    mp_clear(t1);
     11329    mp_clear(C);
     11330    mp_clear(Q);
     11331    mp_clear(S);
     11332    mp_clear(Z);
     11333    mp_clear(M);
     11334    mp_clear(T);
     11335    mp_clear(R);
     11336    mp_clear(two);
     11337  }
     11338#endif
    1055411339
    1055511340  return res;
     
    1056911354       return BAD_FUNC_ARG;
    1057011355
    10571    if (wc_ecc_is_valid_idx(key->idx) == 0) {
    10572       return ECC_BAD_ARG_E;
    10573    }
     11356   if (key->type == ECC_PRIVATEKEY_ONLY)
     11357       return ECC_PRIVATEONLY_E;
     11358
     11359   if (key->type == 0 ||
     11360       wc_ecc_is_valid_idx(key->idx) == 0 ||
     11361       key->dp == NULL) {
     11362       return ECC_BAD_ARG_E;
     11363   }
     11364
    1057411365   numlen = key->dp->size;
    1057511366
     
    1075911550#endif /* HAVE_X963_KDF */
    1076011551
     11552#ifdef WC_ECC_NONBLOCK
     11553/* Enable ECC support for non-blocking operations */
     11554int wc_ecc_set_nonblock(ecc_key *key, ecc_nb_ctx_t* ctx)
     11555{
     11556    if (key) {
     11557        if (ctx) {
     11558            XMEMSET(ctx, 0, sizeof(ecc_nb_ctx_t));
     11559        }
     11560        key->nb_ctx = ctx;
     11561    }
     11562    return 0;
     11563}
     11564#endif /* WC_ECC_NONBLOCK */
     11565
    1076111566#endif /* HAVE_ECC */
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/error.c

    r457 r464  
    513513        return "PSS - Salt length unable to be recovered";
    514514
     515    case CHACHA_POLY_OVERFLOW:
     516        return "wolfcrypt - ChaCha20_Poly1305 limit overflow 4GB";
     517
    515518    case ASN_SELF_SIGNED_E:
    516519        return "ASN self-signed certificate error";
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/evp.c

    r457 r464  
    2020 */
    2121
     22
     23#ifdef HAVE_CONFIG_H
     24    #include <config.h>
     25#endif
     26
     27#include <wolfssl/wolfcrypt/settings.h>
     28
    2229#if !defined(WOLFSSL_EVP_INCLUDED)
    2330    #ifndef WOLFSSL_IGNORE_FILE_WARN
     
    2734#else
    2835
    29 #ifdef HAVE_CONFIG_H
    30     #include <config.h>
    31 #endif
    32 
    33 #include <wolfssl/wolfcrypt/settings.h>
     36#if defined(OPENSSL_EXTRA)
     37
     38#if !defined(HAVE_PKCS7) && \
     39      ((defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
     40       (HAVE_FIPS_VERSION == 2)) || defined(HAVE_SELFTEST))
     41    #include <wolfssl/wolfcrypt/aes.h>
     42#endif
     43
    3444
    3545#include <wolfssl/openssl/ecdsa.h>
    3646#include <wolfssl/openssl/evp.h>
    37 
    38 #if defined(OPENSSL_EXTRA)
    3947
    4048#ifndef NO_AES
    4149    #ifdef HAVE_AES_CBC
    4250    #ifdef WOLFSSL_AES_128
    43         static char *EVP_AES_128_CBC = NULL;
     51        static const char EVP_AES_128_CBC[] = "AES-128-CBC";
    4452    #endif
    4553    #ifdef WOLFSSL_AES_192
    46         static char *EVP_AES_192_CBC = NULL;
     54        static const char EVP_AES_192_CBC[] = "AES-192-CBC";
    4755    #endif
    4856    #ifdef WOLFSSL_AES_256
    49         static char *EVP_AES_256_CBC = NULL;
     57        static const char EVP_AES_256_CBC[] = "AES-256-CBC";
    5058    #endif
    5159    #endif /* HAVE_AES_CBC */
     
    5361    #ifdef WOLFSSL_AES_OFB
    5462    #ifdef WOLFSSL_AES_128
    55         static char *EVP_AES_128_OFB = NULL;
     63        static const char EVP_AES_128_OFB[] = "AES-128-OFB";
    5664    #endif
    5765    #ifdef WOLFSSL_AES_192
    58         static char *EVP_AES_192_OFB = NULL;
     66        static const char EVP_AES_192_OFB[] = "AES-192-OFB";
    5967    #endif
    6068    #ifdef WOLFSSL_AES_256
    61         static char *EVP_AES_256_OFB = NULL;
     69        static const char EVP_AES_256_OFB[] = "AES-256-OFB";
    6270    #endif
    6371    #endif /* WOLFSSL_AES_OFB */
     
    6573    #ifdef WOLFSSL_AES_XTS
    6674    #ifdef WOLFSSL_AES_128
    67         static char *EVP_AES_128_XTS = NULL;
     75        static const char EVP_AES_128_XTS[] = "AES-128-XTS";
    6876    #endif
    6977    #ifdef WOLFSSL_AES_256
    70         static char *EVP_AES_256_XTS = NULL;
     78        static const char EVP_AES_256_XTS[] = "AES-256-XTS";
    7179    #endif
    7280    #endif /* WOLFSSL_AES_XTS */
     
    7482    #ifdef WOLFSSL_AES_CFB
    7583    #ifdef WOLFSSL_AES_128
    76         static char *EVP_AES_128_CFB1 = NULL;
     84        static const char EVP_AES_128_CFB1[] = "AES-128-CFB1";
    7785    #endif
    7886    #ifdef WOLFSSL_AES_192
    79         static char *EVP_AES_192_CFB1 = NULL;
     87        static const char EVP_AES_192_CFB1[] = "AES-192-CFB1";
    8088    #endif
    8189    #ifdef WOLFSSL_AES_256
    82         static char *EVP_AES_256_CFB1 = NULL;
     90        static const char EVP_AES_256_CFB1[] = "AES-256-CFB1";
    8391    #endif
    8492
    8593    #ifdef WOLFSSL_AES_128
    86         static char *EVP_AES_128_CFB8 = NULL;
     94        static const char EVP_AES_128_CFB8[] = "AES-128-CFB8";
    8795    #endif
    8896    #ifdef WOLFSSL_AES_192
    89         static char *EVP_AES_192_CFB8 = NULL;
     97        static const char EVP_AES_192_CFB8[] = "AES-192-CFB8";
    9098    #endif
    9199    #ifdef WOLFSSL_AES_256
    92         static char *EVP_AES_256_CFB8 = NULL;
     100        static const char EVP_AES_256_CFB8[] = "AES-256-CFB8";
    93101    #endif
    94102
    95103    #ifdef WOLFSSL_AES_128
    96         static char *EVP_AES_128_CFB128 = NULL;
     104        static const char EVP_AES_128_CFB128[] = "AES-128-CFB128";
    97105    #endif
    98106    #ifdef WOLFSSL_AES_192
    99         static char *EVP_AES_192_CFB128 = NULL;
     107        static const char EVP_AES_192_CFB128[] = "AES-192-CFB128";
    100108    #endif
    101109    #ifdef WOLFSSL_AES_256
    102         static char *EVP_AES_256_CFB128 = NULL;
     110        static const char EVP_AES_256_CFB128[] = "AES-256-CFB128";
    103111    #endif
    104112    #endif /* WOLFSSL_AES_CFB */
     
    106114    #ifdef HAVE_AESGCM
    107115        #ifdef WOLFSSL_AES_128
    108             static char *EVP_AES_128_GCM = NULL;
     116            static const char EVP_AES_128_GCM[] = "AES-128-GCM";
    109117        #endif
    110118        #ifdef WOLFSSL_AES_192
    111             static char *EVP_AES_192_GCM = NULL;
     119            static const char EVP_AES_192_GCM[] = "AES-192-GCM";
    112120        #endif
    113121        #ifdef WOLFSSL_AES_256
    114             static char *EVP_AES_256_GCM = NULL;
     122            static const char EVP_AES_256_GCM[] = "AES-256-GCM";
    115123        #endif
    116124    #endif /* HAVE_AESGCM */
     125
     126    #ifdef WOLFSSL_AES_COUNTER
    117127    #ifdef WOLFSSL_AES_128
    118         static char *EVP_AES_128_CTR = NULL;
     128        static const char EVP_AES_128_CTR[] = "AES-128-CTR";
    119129    #endif
    120130    #ifdef WOLFSSL_AES_192
    121         static char *EVP_AES_192_CTR = NULL;
     131        static const char EVP_AES_192_CTR[] = "AES-192-CTR";
    122132    #endif
    123133    #ifdef WOLFSSL_AES_256
    124         static char *EVP_AES_256_CTR = NULL;
    125     #endif
    126 
     134        static const char EVP_AES_256_CTR[] = "AES-256-CTR";
     135    #endif
     136    #endif
     137
     138    #ifdef HAVE_AES_ECB
    127139    #ifdef WOLFSSL_AES_128
    128         static char *EVP_AES_128_ECB = NULL;
     140        static const char EVP_AES_128_ECB[] = "AES-128-ECB";
    129141    #endif
    130142    #ifdef WOLFSSL_AES_192
    131         static char *EVP_AES_192_ECB = NULL;
     143        static const char EVP_AES_192_ECB[] = "AES-192-ECB";
    132144    #endif
    133145    #ifdef WOLFSSL_AES_256
    134         static char *EVP_AES_256_ECB = NULL;
     146        static const char EVP_AES_256_ECB[] = "AES-256-ECB";
     147    #endif
    135148    #endif
    136149        #define      EVP_AES_SIZE 11
     
    141154
    142155#ifndef NO_DES3
    143     static char *EVP_DES_CBC = NULL;
    144     static char *EVP_DES_ECB = NULL;
    145 
    146     static char *EVP_DES_EDE3_CBC = NULL;
    147     static char *EVP_DES_EDE3_ECB = NULL;
     156    static const char EVP_DES_CBC[] = "DES-CBC";
     157    static const char EVP_DES_ECB[] = "DES-ECB";
     158
     159    static const char EVP_DES_EDE3_CBC[] = "DES-EDE3-CBC";
     160    static const char EVP_DES_EDE3_ECB[] = "DES-EDE3-ECB";
    148161
    149162    #define EVP_DES_SIZE 7
     
    152165
    153166#ifdef HAVE_IDEA
    154     static char *EVP_IDEA_CBC;
     167    static const char EVP_IDEA_CBC[] = "IDEA-CBC";
    155168    #define EVP_IDEA_SIZE 8
    156169#endif
     170
     171#ifndef NO_RC4
     172    static const char EVP_ARC4[] = "ARC4";
     173    #define EVP_ARC4_SIZE 4
     174#endif
     175
     176static const char EVP_NULL[] = "NULL";
     177#define EVP_NULL_SIZE 4
     178
    157179
    158180static unsigned int cipherType(const WOLFSSL_EVP_CIPHER *cipher);
     
    200222  #endif
    201223  #if defined(WOLFSSL_AES_XTS)
    202       case AES_128_XTS_TYPE: return 16;
    203       case AES_256_XTS_TYPE: return 32;
     224      /* Two keys for XTS. */
     225      case AES_128_XTS_TYPE: return 16 * 2;
     226      case AES_256_XTS_TYPE: return 32 * 2;
    204227  #endif
    205228  #if defined(HAVE_AESGCM)
     
    418441            break;
    419442    #endif
    420     #if defined(HAVE_AESGCM)
    421         case AES_128_GCM_TYPE:
    422         case AES_192_GCM_TYPE:
    423         case AES_256_GCM_TYPE:
    424             if (ctx->enc) {
    425                 if (out){
    426                     /* encrypt confidential data*/
    427                     ret = wc_AesGcmEncrypt(&ctx->cipher.aes, out, in, inl,
    428                               ctx->iv, ctx->ivSz, ctx->authTag, ctx->authTagSz,
    429                               NULL, 0);
    430                 }
    431                 else {
    432                     /* authenticated, non-confidential data */
    433                     ret = wc_AesGcmEncrypt(&ctx->cipher.aes, NULL, NULL, 0,
    434                               ctx->iv, ctx->ivSz, ctx->authTag, ctx->authTagSz,
    435                               in, inl);
    436                     /* Reset partial authTag error for AAD*/
    437                     if (ret == AES_GCM_AUTH_E)
    438                         ret = 0;
    439                 }
    440             }
    441             else {
    442                 if (out){
    443                     /* decrypt confidential data*/
    444                     ret = wc_AesGcmDecrypt(&ctx->cipher.aes, out, in, inl,
    445                               ctx->iv, ctx->ivSz, ctx->authTag, ctx->authTagSz,
    446                               NULL, 0);
    447                 }
    448                 else {
    449                     /* authenticated, non-confidential data*/
    450                     ret = wc_AesGcmDecrypt(&ctx->cipher.aes, NULL, NULL, 0,
    451                               ctx->iv, ctx->ivSz,
    452                               ctx->authTag, ctx->authTagSz,
    453                               in, inl);
    454                     /* Reset partial authTag error for AAD*/
    455                     if (ret == AES_GCM_AUTH_E)
    456                         ret = 0;
    457                 }
    458             }
    459             break;
    460     #endif
    461443    #if defined(WOLFSSL_AES_COUNTER)
    462444        case AES_128_CTR_TYPE:
     
    572554
    573555#if defined(HAVE_AESGCM)
     556static int wolfSSL_EVP_CipherUpdate_GCM_AAD(WOLFSSL_EVP_CIPHER_CTX *ctx,
     557        const unsigned char *in, int inl) {
     558    if (in && inl > 0) {
     559        byte* tmp = (byte*)XREALLOC(ctx->gcmAuthIn,
     560                ctx->gcmAuthInSz + inl, NULL, DYNAMIC_TYPE_OPENSSL);
     561        if (tmp) {
     562            ctx->gcmAuthIn = tmp;
     563            XMEMCPY(ctx->gcmAuthIn + ctx->gcmAuthInSz, in, inl);
     564            ctx->gcmAuthInSz += inl;
     565        }
     566        else {
     567            WOLFSSL_MSG("realloc error");
     568            return MEMORY_E;
     569        }
     570    }
     571    return 0;
     572}
     573
    574574static int wolfSSL_EVP_CipherUpdate_GCM(WOLFSSL_EVP_CIPHER_CTX *ctx,
    575575                                   unsigned char *out, int *outl,
    576576                                   const unsigned char *in, int inl)
    577577{
    578     /* process blocks */
    579     if (evpCipherBlock(ctx, out, in, inl) == 0)
     578    int ret = 0;
     579
     580    *outl = inl;
     581    if (out) {
     582        /* Buffer input for one-shot API */
     583        if (inl > 0) {
     584            byte* tmp;
     585            tmp = (byte*)XREALLOC(ctx->gcmBuffer,
     586                    ctx->gcmBufferLen + inl, NULL,
     587                    DYNAMIC_TYPE_OPENSSL);
     588            if (tmp) {
     589                XMEMCPY(tmp + ctx->gcmBufferLen, in, inl);
     590                ctx->gcmBufferLen += inl;
     591                ctx->gcmBuffer = tmp;
     592                *outl = 0;
     593            }
     594            else {
     595                ret = MEMORY_E;
     596            }
     597        }
     598    }
     599    else {
     600        ret = wolfSSL_EVP_CipherUpdate_GCM_AAD(ctx, in, inl);
     601    }
     602
     603    if (ret != 0) {
     604        *outl = 0;
    580605        return WOLFSSL_FAILURE;
    581     *outl = inl;
     606    }
     607
    582608    return WOLFSSL_SUCCESS;
    583609}
     
    599625
    600626    *outl = 0;
    601     if (inl == 0) {
    602         return WOLFSSL_SUCCESS;
    603     }
    604627
    605628#if !defined(NO_AES) && defined(HAVE_AESGCM)
     
    620643    }
    621644
    622 
     645    /* if(inl == 0)wolfSSL_EVP_CipherUpdate_GCM to get tag */
     646    if (inl == 0) {
     647        return WOLFSSL_SUCCESS;
     648    }
    623649    if (ctx->bufUsed > 0) { /* concatenate them if there is anything */
    624650        fill = fillBuff(ctx, in, inl);
     
    740766
    741767    WOLFSSL_ENTER("wolfSSL_EVP_CipherFinal");
    742 
     768    switch (ctx->cipherType) {
    743769#if !defined(NO_AES) && defined(HAVE_AESGCM)
    744         switch (ctx->cipherType) {
    745             case AES_128_GCM_TYPE:
    746             case AES_192_GCM_TYPE:
    747             case AES_256_GCM_TYPE:
     770        case AES_128_GCM_TYPE:
     771        case AES_192_GCM_TYPE:
     772        case AES_256_GCM_TYPE:
     773            if ((ctx->gcmBuffer && ctx->gcmBufferLen > 0)
     774             || (ctx->gcmBufferLen == 0)) {
     775                if (ctx->enc)
     776                    ret = wc_AesGcmEncrypt(&ctx->cipher.aes, out,
     777                            ctx->gcmBuffer, ctx->gcmBufferLen,
     778                            ctx->iv, ctx->ivSz, ctx->authTag, ctx->authTagSz,
     779                            ctx->gcmAuthIn, ctx->gcmAuthInSz);
     780                else
     781                    ret = wc_AesGcmDecrypt(&ctx->cipher.aes, out,
     782                            ctx->gcmBuffer, ctx->gcmBufferLen,
     783                            ctx->iv, ctx->ivSz, ctx->authTag, ctx->authTagSz,
     784                            ctx->gcmAuthIn, ctx->gcmAuthInSz);
     785
     786                if (ret == 0) {
     787                    ret = WOLFSSL_SUCCESS;
     788                    *outl = ctx->gcmBufferLen;
     789                }
     790                else {
     791                    ret = WOLFSSL_FAILURE;
     792                    *outl = 0;
     793                }
     794
     795                XFREE(ctx->gcmBuffer, NULL, DYNAMIC_TYPE_OPENSSL);
     796                ctx->gcmBuffer = NULL;
     797                ctx->gcmBufferLen = 0;
     798            }
     799            else {
    748800                *outl = 0;
    749                 /* Clear IV, since IV reuse is not recommended for AES GCM. */
    750                 XMEMSET(ctx->iv, 0, AES_BLOCK_SIZE);
    751                 return WOLFSSL_SUCCESS;
    752             default:
    753                 /* fall-through */
    754                 break;
    755         }
     801            }
     802            /* Clear IV, since IV reuse is not recommended for AES GCM. */
     803            XMEMSET(ctx->iv, 0, AES_BLOCK_SIZE);
     804            break;
    756805#endif /* !NO_AES && HAVE_AESGCM */
    757 
    758     if (!out)
    759         return WOLFSSL_FAILURE;
    760 
    761     if (ctx->flags & WOLFSSL_EVP_CIPH_NO_PADDING) {
    762         if (ctx->bufUsed != 0) return WOLFSSL_FAILURE;
    763         *outl = 0;
    764     }
    765     else if (ctx->enc) {
    766         if (ctx->block_size == 1) {
    767             *outl = 0;
    768         }
    769         else if ((ctx->bufUsed >= 0) && (ctx->block_size != 1)) {
    770             padBlock(ctx);
    771             PRINT_BUF(ctx->buf, ctx->block_size);
    772             if (evpCipherBlock(ctx, out, ctx->buf, ctx->block_size) == 0) {
    773                 WOLFSSL_MSG("Final Cipher Block failed");
    774                 ret = WOLFSSL_FAILURE;
     806        default:
     807            if (!out)
     808                return WOLFSSL_FAILURE;
     809
     810            if (ctx->flags & WOLFSSL_EVP_CIPH_NO_PADDING) {
     811                if (ctx->bufUsed != 0) return WOLFSSL_FAILURE;
     812                *outl = 0;
     813            }
     814            else if (ctx->enc) {
     815                if (ctx->block_size == 1) {
     816                    *outl = 0;
     817                }
     818                else if ((ctx->bufUsed >= 0) && (ctx->block_size != 1)) {
     819                    padBlock(ctx);
     820                    PRINT_BUF(ctx->buf, ctx->block_size);
     821                    if (evpCipherBlock(ctx, out, ctx->buf, ctx->block_size) == 0) {
     822                        WOLFSSL_MSG("Final Cipher Block failed");
     823                        ret = WOLFSSL_FAILURE;
     824                    }
     825                    else {
     826                        PRINT_BUF(out, ctx->block_size);
     827                        *outl = ctx->block_size;
     828                    }
     829                }
    775830            }
    776831            else {
    777                 PRINT_BUF(out, ctx->block_size);
    778                 *outl = ctx->block_size;
    779             }
    780         }
    781     }
    782     else {
    783         if (ctx->block_size == 1) {
    784             *outl = 0;
    785         }
    786         else if ((ctx->bufUsed % ctx->block_size) != 0) {
    787             *outl = 0;
    788             /* not enough padding for decrypt */
    789             WOLFSSL_MSG("Final Cipher Block not enough padding");
    790             ret = WOLFSSL_FAILURE;
    791         }
    792         else if (ctx->lastUsed) {
    793             PRINT_BUF(ctx->lastBlock, ctx->block_size);
    794             if ((fl = checkPad(ctx, ctx->lastBlock)) >= 0) {
    795                 XMEMCPY(out, ctx->lastBlock, fl);
    796                 *outl = fl;
    797                 if (ctx->lastUsed == 0 && ctx->bufUsed == 0) {
    798                     /* return error in cases where the block length is incorrect */
    799                     WOLFSSL_MSG("Final Cipher Block bad length");
     832                if (ctx->block_size == 1) {
     833                    *outl = 0;
     834                }
     835                else if ((ctx->bufUsed % ctx->block_size) != 0) {
     836                    *outl = 0;
     837                    /* not enough padding for decrypt */
     838                    WOLFSSL_MSG("Final Cipher Block not enough padding");
    800839                    ret = WOLFSSL_FAILURE;
    801840                }
    802             }
    803             else {
    804                 ret = WOLFSSL_FAILURE;
    805             }
    806         }
    807         else if (ctx->lastUsed == 0 && ctx->bufUsed == 0) {
    808             /* return error in cases where the block length is incorrect */
    809             ret = WOLFSSL_FAILURE;
    810         }
    811     }
     841                else if (ctx->lastUsed) {
     842                    PRINT_BUF(ctx->lastBlock, ctx->block_size);
     843                    if ((fl = checkPad(ctx, ctx->lastBlock)) >= 0) {
     844                        XMEMCPY(out, ctx->lastBlock, fl);
     845                        *outl = fl;
     846                        if (ctx->lastUsed == 0 && ctx->bufUsed == 0) {
     847                            /* return error in cases where the block length is
     848                             * incorrect */
     849                            WOLFSSL_MSG("Final Cipher Block bad length");
     850                            ret = WOLFSSL_FAILURE;
     851                        }
     852                    }
     853                    else {
     854                        ret = WOLFSSL_FAILURE;
     855                    }
     856                }
     857                else if (ctx->lastUsed == 0 && ctx->bufUsed == 0) {
     858                    /* return error in cases where the block length is
     859                     * incorrect */
     860                    ret = WOLFSSL_FAILURE;
     861                }
     862            }
     863            break;
     864    }
     865
    812866    if (ret == WOLFSSL_SUCCESS) {
    813867        /* reset cipher state after final */
    814         wolfSSL_EVP_CipherInit(ctx, NULL, NULL, NULL, -1);
     868        ret = wolfSSL_EVP_CipherInit(ctx, NULL, NULL, NULL, -1);
    815869    }
    816870    return ret;
     
    867921#endif
    868922
    869 
    870923int wolfSSL_EVP_CIPHER_CTX_block_size(const WOLFSSL_EVP_CIPHER_CTX *ctx)
    871924{
     
    931984    if (cipher == NULL) return 0; /* dummy for #ifdef */
    932985#ifndef NO_DES3
    933     else if (EVP_DES_CBC && XSTRNCMP(cipher, EVP_DES_CBC, EVP_DES_SIZE) == 0)
     986    else if (XSTRNCMP(cipher, EVP_DES_CBC, EVP_DES_SIZE) == 0)
    934987        return DES_CBC_TYPE;
    935     else if (EVP_DES_EDE3_CBC && XSTRNCMP(cipher, EVP_DES_EDE3_CBC, EVP_DES_EDE3_SIZE) == 0)
     988    else if (XSTRNCMP(cipher, EVP_DES_EDE3_CBC, EVP_DES_EDE3_SIZE) == 0)
    936989        return DES_EDE3_CBC_TYPE;
    937990#if !defined(NO_DES3)
    938     else if (EVP_DES_ECB && XSTRNCMP(cipher, EVP_DES_ECB, EVP_DES_SIZE) == 0)
     991    else if (XSTRNCMP(cipher, EVP_DES_ECB, EVP_DES_SIZE) == 0)
    939992        return DES_ECB_TYPE;
    940     else if (EVP_DES_EDE3_ECB && XSTRNCMP(cipher, EVP_DES_EDE3_ECB, EVP_DES_EDE3_SIZE) == 0)
     993    else if (XSTRNCMP(cipher, EVP_DES_EDE3_ECB, EVP_DES_EDE3_SIZE) == 0)
    941994        return DES_EDE3_ECB_TYPE;
    942995#endif /* NO_DES3 && HAVE_AES_ECB */
     
    945998#if defined(HAVE_AES_CBC)
    946999    #ifdef WOLFSSL_AES_128
    947     else if (EVP_AES_128_CBC && XSTRNCMP(cipher, EVP_AES_128_CBC, EVP_AES_SIZE) == 0)
     1000    else if (XSTRNCMP(cipher, EVP_AES_128_CBC, EVP_AES_SIZE) == 0)
    9481001        return AES_128_CBC_TYPE;
    9491002    #endif
    9501003    #ifdef WOLFSSL_AES_192
    951     else if (EVP_AES_192_CBC && XSTRNCMP(cipher, EVP_AES_192_CBC, EVP_AES_SIZE) == 0)
     1004    else if (XSTRNCMP(cipher, EVP_AES_192_CBC, EVP_AES_SIZE) == 0)
    9521005        return AES_192_CBC_TYPE;
    9531006    #endif
    9541007    #ifdef WOLFSSL_AES_256
    955     else if (EVP_AES_256_CBC && XSTRNCMP(cipher, EVP_AES_256_CBC, EVP_AES_SIZE) == 0)
     1008    else if (XSTRNCMP(cipher, EVP_AES_256_CBC, EVP_AES_SIZE) == 0)
    9561009        return AES_256_CBC_TYPE;
    9571010    #endif
     
    9591012#if defined(HAVE_AESGCM)
    9601013    #ifdef WOLFSSL_AES_128
    961     else if (EVP_AES_128_GCM && XSTRNCMP(cipher, EVP_AES_128_GCM, EVP_AES_SIZE) == 0)
     1014    else if (XSTRNCMP(cipher, EVP_AES_128_GCM, EVP_AES_SIZE) == 0)
    9621015        return AES_128_GCM_TYPE;
    9631016    #endif
    9641017    #ifdef WOLFSSL_AES_192
    965     else if (EVP_AES_192_GCM && XSTRNCMP(cipher, EVP_AES_192_GCM, EVP_AES_SIZE) == 0)
     1018    else if (XSTRNCMP(cipher, EVP_AES_192_GCM, EVP_AES_SIZE) == 0)
    9661019        return AES_192_GCM_TYPE;
    9671020    #endif
    9681021    #ifdef WOLFSSL_AES_256
    969     else if (EVP_AES_256_GCM && XSTRNCMP(cipher, EVP_AES_256_GCM, EVP_AES_SIZE) == 0)
     1022    else if (XSTRNCMP(cipher, EVP_AES_256_GCM, EVP_AES_SIZE) == 0)
    9701023        return AES_256_GCM_TYPE;
    9711024    #endif
     
    9731026#if defined(WOLFSSL_AES_COUNTER)
    9741027    #ifdef WOLFSSL_AES_128
    975     else if (EVP_AES_128_CTR && XSTRNCMP(cipher, EVP_AES_128_CTR, EVP_AES_SIZE) == 0)
     1028    else if (XSTRNCMP(cipher, EVP_AES_128_CTR, EVP_AES_SIZE) == 0)
    9761029        return AES_128_CTR_TYPE;
    9771030    #endif
    9781031    #ifdef WOLFSSL_AES_192
    979     else if (EVP_AES_192_CTR && XSTRNCMP(cipher, EVP_AES_192_CTR, EVP_AES_SIZE) == 0)
     1032    else if (XSTRNCMP(cipher, EVP_AES_192_CTR, EVP_AES_SIZE) == 0)
    9801033        return AES_192_CTR_TYPE;
    9811034    #endif
    9821035    #ifdef WOLFSSL_AES_256
    983     else if (EVP_AES_256_CTR && XSTRNCMP(cipher, EVP_AES_256_CTR, EVP_AES_SIZE) == 0)
     1036    else if (XSTRNCMP(cipher, EVP_AES_256_CTR, EVP_AES_SIZE) == 0)
    9841037        return AES_256_CTR_TYPE;
    9851038    #endif
     
    9871040#if defined(HAVE_AES_ECB)
    9881041    #ifdef WOLFSSL_AES_128
    989     else if (EVP_AES_128_ECB && XSTRNCMP(cipher, EVP_AES_128_ECB, EVP_AES_SIZE) == 0)
     1042    else if (XSTRNCMP(cipher, EVP_AES_128_ECB, EVP_AES_SIZE) == 0)
    9901043        return AES_128_ECB_TYPE;
    9911044    #endif
    9921045    #ifdef WOLFSSL_AES_192
    993     else if (EVP_AES_192_ECB && XSTRNCMP(cipher, EVP_AES_192_ECB, EVP_AES_SIZE) == 0)
     1046    else if (XSTRNCMP(cipher, EVP_AES_192_ECB, EVP_AES_SIZE) == 0)
    9941047        return AES_192_ECB_TYPE;
    9951048    #endif
    9961049    #ifdef WOLFSSL_AES_256
    997     else if (EVP_AES_256_ECB && XSTRNCMP(cipher, EVP_AES_256_ECB, EVP_AES_SIZE) == 0)
     1050    else if (XSTRNCMP(cipher, EVP_AES_256_ECB, EVP_AES_SIZE) == 0)
    9981051        return AES_256_ECB_TYPE;
    9991052    #endif
     
    10011054#if defined(WOLFSSL_AES_XTS)
    10021055    #ifdef WOLFSSL_AES_128
    1003     else if (EVP_AES_128_XTS && XSTRNCMP(cipher, EVP_AES_128_XTS, EVP_AES_SIZE) == 0)
     1056    else if (XSTRNCMP(cipher, EVP_AES_128_XTS, EVP_AES_SIZE) == 0)
    10041057        return AES_128_XTS_TYPE;
    10051058    #endif
    10061059    #ifdef WOLFSSL_AES_256
    1007     else if (EVP_AES_256_XTS && XSTRNCMP(cipher, EVP_AES_256_XTS, EVP_AES_SIZE) == 0)
     1060    else if (XSTRNCMP(cipher, EVP_AES_256_XTS, EVP_AES_SIZE) == 0)
    10081061        return AES_256_XTS_TYPE;
    10091062    #endif
     
    10111064#if defined(WOLFSSL_AES_CFB)
    10121065    #ifdef WOLFSSL_AES_128
    1013     else if (EVP_AES_128_CFB1 && XSTRNCMP(cipher, EVP_AES_128_CFB1, EVP_AESCFB_SIZE) == 0)
     1066    else if (XSTRNCMP(cipher, EVP_AES_128_CFB1, EVP_AESCFB_SIZE) == 0)
    10141067        return AES_128_CFB1_TYPE;
    10151068    #endif
    10161069    #ifdef WOLFSSL_AES_192
    1017     else if (EVP_AES_192_CFB1 && XSTRNCMP(cipher, EVP_AES_192_CFB1, EVP_AESCFB_SIZE) == 0)
     1070    else if (XSTRNCMP(cipher, EVP_AES_192_CFB1, EVP_AESCFB_SIZE) == 0)
    10181071        return AES_192_CFB1_TYPE;
    10191072    #endif
    10201073    #ifdef WOLFSSL_AES_256
    1021     else if (EVP_AES_256_CFB1 && XSTRNCMP(cipher, EVP_AES_256_CFB1, EVP_AESCFB_SIZE) == 0)
     1074    else if (XSTRNCMP(cipher, EVP_AES_256_CFB1, EVP_AESCFB_SIZE) == 0)
    10221075        return AES_256_CFB1_TYPE;
    10231076    #endif
    10241077    #ifdef WOLFSSL_AES_128
    1025     else if (EVP_AES_128_CFB8 && XSTRNCMP(cipher, EVP_AES_128_CFB8, EVP_AESCFB_SIZE) == 0)
     1078    else if (XSTRNCMP(cipher, EVP_AES_128_CFB8, EVP_AESCFB_SIZE) == 0)
    10261079        return AES_128_CFB8_TYPE;
    10271080    #endif
    10281081    #ifdef WOLFSSL_AES_192
    1029     else if (EVP_AES_192_CFB8 && XSTRNCMP(cipher, EVP_AES_192_CFB8, EVP_AESCFB_SIZE) == 0)
     1082    else if (XSTRNCMP(cipher, EVP_AES_192_CFB8, EVP_AESCFB_SIZE) == 0)
    10301083        return AES_192_CFB8_TYPE;
    10311084    #endif
    10321085    #ifdef WOLFSSL_AES_256
    1033     else if (EVP_AES_256_CFB8 && XSTRNCMP(cipher, EVP_AES_256_CFB8, EVP_AESCFB_SIZE) == 0)
     1086    else if (XSTRNCMP(cipher, EVP_AES_256_CFB8, EVP_AESCFB_SIZE) == 0)
    10341087        return AES_256_CFB8_TYPE;
    10351088    #endif
    10361089    #ifdef WOLFSSL_AES_128
    1037     else if (EVP_AES_128_CFB128 && XSTRNCMP(cipher, EVP_AES_128_CFB128, EVP_AESCFB_SIZE) == 0)
     1090    else if (XSTRNCMP(cipher, EVP_AES_128_CFB128, EVP_AESCFB_SIZE) == 0)
    10381091        return AES_128_CFB128_TYPE;
    10391092    #endif
    10401093    #ifdef WOLFSSL_AES_192
    1041     else if (EVP_AES_192_CFB128 && XSTRNCMP(cipher, EVP_AES_192_CFB128, EVP_AESCFB_SIZE) == 0)
     1094    else if (XSTRNCMP(cipher, EVP_AES_192_CFB128, EVP_AESCFB_SIZE) == 0)
    10421095        return AES_192_CFB128_TYPE;
    10431096    #endif
    10441097    #ifdef WOLFSSL_AES_256
    1045     else if (EVP_AES_256_CFB128 && XSTRNCMP(cipher, EVP_AES_256_CFB128, EVP_AESCFB_SIZE) == 0)
     1098    else if (XSTRNCMP(cipher, EVP_AES_256_CFB128, EVP_AESCFB_SIZE) == 0)
    10461099        return AES_256_CFB128_TYPE;
    10471100    #endif
    10481101#endif /*HAVE_AES_CBC */
     1102#if defined(WOLFSSL_AES_OFB)
     1103    #ifdef WOLFSSL_AES_128
     1104    else if (XSTRNCMP(cipher, EVP_AES_128_OFB, EVP_AES_SIZE) == 0)
     1105      return AES_128_OFB_TYPE;
     1106    #endif
     1107    #ifdef WOLFSSL_AES_192
     1108    else if (XSTRNCMP(cipher, EVP_AES_192_OFB, EVP_AES_SIZE) == 0)
     1109      return AES_192_OFB_TYPE;
     1110    #endif
     1111    #ifdef WOLFSSL_AES_256
     1112    else if (XSTRNCMP(cipher, EVP_AES_256_OFB, EVP_AES_SIZE) == 0)
     1113      return AES_256_OFB_TYPE;
     1114    #endif
     1115#endif
    10491116#endif /* !NO_AES */
     1117
     1118#ifndef NO_RC4
     1119    else if (XSTRNCMP(cipher, EVP_ARC4, EVP_ARC4_SIZE) == 0)
     1120      return ARC4_TYPE;
     1121#endif
    10501122      else return 0;
    10511123}
     
    10661138      case AES_192_GCM_TYPE:
    10671139      case AES_256_GCM_TYPE:
    1068           return AES_BLOCK_SIZE;
     1140          return 1;
    10691141  #endif
    10701142  #if defined(WOLFSSL_AES_COUNTER)
     
    10721144      case AES_192_CTR_TYPE:
    10731145      case AES_256_CTR_TYPE:
    1074           return AES_BLOCK_SIZE;
     1146          return 1;
    10751147  #endif
    10761148  #if defined(HAVE_AES_ECB)
     
    10801152          return AES_BLOCK_SIZE;
    10811153  #endif
     1154  #if defined(WOLFSSL_AES_CFB)
     1155      case AES_128_CFB1_TYPE:
     1156      case AES_192_CFB1_TYPE:
     1157      case AES_256_CFB1_TYPE:
     1158      case AES_128_CFB8_TYPE:
     1159      case AES_192_CFB8_TYPE:
     1160      case AES_256_CFB8_TYPE:
     1161      case AES_128_CFB128_TYPE:
     1162      case AES_192_CFB128_TYPE:
     1163      case AES_256_CFB128_TYPE:
     1164          return 1;
     1165  #endif
     1166  #if defined(WOLFSSL_AES_OFB)
     1167      case AES_128_OFB_TYPE:
     1168      case AES_192_OFB_TYPE:
     1169      case AES_256_OFB_TYPE:
     1170          return 1;
     1171  #endif
     1172  #if defined(WOLFSSL_AES_XTS)
     1173      case AES_128_XTS_TYPE:
     1174      case AES_256_XTS_TYPE:
     1175          return 1;
     1176  #endif
    10821177#endif /* NO_AES */
    1083   #ifndef NO_DES3
     1178
     1179#ifndef NO_RC4
     1180      case ARC4_TYPE:
     1181          return 1;
     1182#endif
     1183
     1184#ifndef NO_DES3
    10841185      case DES_CBC_TYPE: return 8;
    10851186      case DES_EDE3_CBC_TYPE: return 8;
    10861187      case DES_ECB_TYPE: return 8;
    10871188      case DES_EDE3_ECB_TYPE: return 8;
    1088   #endif
     1189#endif
    10891190      default:
    10901191          return 0;
     
    11061207        case AES_192_GCM_TYPE:
    11071208        case AES_256_GCM_TYPE:
    1108             return WOLFSSL_EVP_CIPH_GCM_MODE;
     1209            return WOLFSSL_EVP_CIPH_GCM_MODE &
     1210                    WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER;
    11091211    #endif
    11101212    #if defined(WOLFSSL_AES_COUNTER)
     
    11141216            return WOLFSSL_EVP_CIPH_CTR_MODE;
    11151217    #endif
     1218    #if defined(WOLFSSL_AES_CFB)
     1219        case AES_128_CFB1_TYPE:
     1220        case AES_192_CFB1_TYPE:
     1221        case AES_256_CFB1_TYPE:
     1222        case AES_128_CFB8_TYPE:
     1223        case AES_192_CFB8_TYPE:
     1224        case AES_256_CFB8_TYPE:
     1225        case AES_128_CFB128_TYPE:
     1226        case AES_192_CFB128_TYPE:
     1227        case AES_256_CFB128_TYPE:
     1228            return WOLFSSL_EVP_CIPH_CFB_MODE;
     1229    #endif
     1230    #if defined(WOLFSSL_AES_OFB)
     1231        case AES_128_OFB_TYPE:
     1232        case AES_192_OFB_TYPE:
     1233        case AES_256_OFB_TYPE:
     1234            return WOLFSSL_EVP_CIPH_OFB_MODE;
     1235    #endif
     1236    #if defined(WOLFSSL_AES_XTS)
     1237        case AES_128_XTS_TYPE:
     1238        case AES_256_XTS_TYPE:
     1239            return WOLFSSL_EVP_CIPH_XTS_MODE;
     1240    #endif
    11161241        case AES_128_ECB_TYPE:
    11171242        case AES_192_ECB_TYPE:
    11181243        case AES_256_ECB_TYPE:
    11191244            return WOLFSSL_EVP_CIPH_ECB_MODE;
    1120 #endif /* NO_ASE */
     1245#endif /* NO_AES */
    11211246    #ifndef NO_DES3
    11221247        case DES_CBC_TYPE:
     
    12091334{
    12101335    WOLFSSL_EVP_PKEY_CTX* ctx;
    1211     int type = NID_undef;
    12121336
    12131337    if (pkey == NULL) return 0;
     
    12231347    ctx->padding = RSA_PKCS1_PADDING;
    12241348#endif
    1225     type = wolfSSL_EVP_PKEY_type(pkey->type);
    1226 
    1227     if (type != NID_undef) {
    1228         if (wc_LockMutex(&pkey->refMutex) != 0) {
    1229             WOLFSSL_MSG("Couldn't lock pkey mutex");
    1230         }
    1231         pkey->references++;
    1232 
    1233         wc_UnLockMutex(&pkey->refMutex);
     1349    if (wolfSSL_EVP_PKEY_up_ref(pkey) != WOLFSSL_SUCCESS) {
     1350        WOLFSSL_MSG("Couldn't increase key reference count");
    12341351    }
    12351352    return ctx;
     
    12641381        pkey->type = id;
    12651382        ctx = wolfSSL_EVP_PKEY_CTX_new(pkey, e);
    1266         if (ctx == NULL) {
    1267             wolfSSL_EVP_PKEY_free(pkey);
    1268         }
     1383        /* wolfSSL_EVP_PKEY_CTX_new calls wolfSSL_EVP_PKEY_up_ref so we need
     1384         * to always call wolfSSL_EVP_PKEY_free (either to free it if an
     1385         * error occured in the previous function or to decrease the reference
     1386         * count so that pkey is actually free'd when wolfSSL_EVP_PKEY_CTX_free
     1387         * is called) */
     1388        wolfSSL_EVP_PKEY_free(pkey);
    12691389    }
    12701390    return ctx;
     
    13111431}
    13121432
     1433#ifndef NO_WOLFSSL_STUB
     1434int wolfSSL_EVP_PKEY_CTX_ctrl_str(WOLFSSL_EVP_PKEY_CTX *ctx,
     1435                          const char *name, const char *value)
     1436{
     1437    WOLFSSL_STUB("wolfSSL_EVP_PKEY_CTX_ctrl_str");
     1438    (void)ctx;
     1439    (void)name;
     1440    (void)value;
     1441    return WOLFSSL_FAILURE;
     1442}
     1443#endif /* NO_WOLFSSL_STUB */
     1444
    13131445#if !defined(NO_DH) && defined(HAVE_ECC)
     1446#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION!=2))
    13141447int wolfSSL_EVP_PKEY_derive(WOLFSSL_EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen)
    13151448{
     
    13361469                return WOLFSSL_FAILURE;
    13371470            }
     1471            /* computed DH agreement can be less than DH size if leading zeros */
    13381472            if (wolfSSL_DH_compute_key(key, ctx->peerKey->dh->pub_key,
    1339                                        ctx->pkey->dh) != len) {
     1473                                       ctx->pkey->dh) <= 0) {
    13401474                return WOLFSSL_FAILURE;
    13411475            }
     
    13681502        if (key) {
    13691503            word32 len32 = (word32)len;
     1504#if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) \
     1505    && (!defined(HAVE_FIPS) || \
     1506         (defined(HAVE_FIPS_VERSION) && HAVE_FIPS_VERSION > 2))
     1507
     1508            WC_RNG rng;
     1509            if (wc_InitRng(&rng) != MP_OKAY) {
     1510                WOLFSSL_MSG("Init RNG failed");
     1511                return WOLFSSL_FAILURE;
     1512            }
     1513            ((ecc_key*)ctx->pkey->ecc->internal)->rng = &rng;
     1514#endif
    13701515            if (*keylen < len32) {
    13711516                WOLFSSL_MSG("buffer too short");
     1517#if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) \
     1518    && (!defined(HAVE_FIPS) || \
     1519         (defined(HAVE_FIPS_VERSION) && HAVE_FIPS_VERSION > 2))
     1520                ((ecc_key*)ctx->pkey->ecc->internal)->rng = NULL;
     1521                wc_FreeRng(&rng);
     1522#endif
    13721523                return WOLFSSL_FAILURE;
    13731524            }
     
    13761527                                         key, &len32) != MP_OKAY) {
    13771528                WOLFSSL_MSG("wc_ecc_shared_secret failed");
     1529#if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) \
     1530    && (!defined(HAVE_FIPS) || \
     1531         (defined(HAVE_FIPS_VERSION) && HAVE_FIPS_VERSION > 2))
     1532                ((ecc_key*)ctx->pkey->ecc->internal)->rng = NULL;
     1533                wc_FreeRng(&rng);
     1534#endif
    13781535                return WOLFSSL_FAILURE;
    13791536            }
     1537#if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) \
     1538    && (!defined(HAVE_FIPS) || \
     1539         (defined(HAVE_FIPS_VERSION) && HAVE_FIPS_VERSION > 2))
     1540            ((ecc_key*)ctx->pkey->ecc->internal)->rng = NULL;
     1541            wc_FreeRng(&rng);
     1542#endif
    13801543            len = (int)len32;
    13811544        }
     
    13891552    return WOLFSSL_SUCCESS;
    13901553}
    1391 #endif
     1554#endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
     1555#endif /* !NO_DH || HAVE_ECC */
    13921556
    13931557/* Uses the WOLFSSL_EVP_PKEY_CTX to decrypt a buffer.
     
    17201884}
    17211885
     1886
     1887int wolfSSL_EVP_PKEY_copy_parameters(WOLFSSL_EVP_PKEY *to,
     1888        const WOLFSSL_EVP_PKEY *from)
     1889{
     1890    WOLFSSL_ENTER("wolfSSL_EVP_PKEY_copy_parameters");
     1891
     1892    if (!to || !from) {
     1893        WOLFSSL_MSG("Bad parameter");
     1894        return WOLFSSL_FAILURE;
     1895    }
     1896
     1897    if (to->type == EVP_PKEY_NONE) {
     1898        to->type = from->type;
     1899    }
     1900    else if (to->type != from->type) {
     1901        WOLFSSL_MSG("Different key types");
     1902        return WOLFSSL_FAILURE;
     1903    }
     1904
     1905    switch(from->type) {
     1906#ifdef HAVE_ECC
     1907    case EVP_PKEY_EC:
     1908        if (from->ecc) {
     1909            if (!to->ecc && !(to->ecc = wolfSSL_EC_KEY_new())) {
     1910                WOLFSSL_MSG("wolfSSL_EC_KEY_new error");
     1911                return WOLFSSL_FAILURE;
     1912            }
     1913            to->ownEcc = 1;
     1914            to->ecc->group->curve_idx = from->ecc->group->curve_idx;
     1915            to->ecc->group->curve_nid = from->ecc->group->curve_nid;
     1916            to->ecc->group->curve_oid = from->ecc->group->curve_oid;
     1917        }
     1918        else {
     1919            WOLFSSL_MSG("Missing ECC struct");
     1920            return WOLFSSL_FAILURE;
     1921        }
     1922        break;
     1923#endif
     1924#ifndef NO_DSA
     1925    case EVP_PKEY_DSA:
     1926        if (from->dsa) {
     1927            WOLFSSL_BIGNUM* cpy;
     1928            if (!to->dsa && !(to->dsa = wolfSSL_DSA_new())) {
     1929                WOLFSSL_MSG("wolfSSL_DSA_new error");
     1930                return WOLFSSL_FAILURE;
     1931            }
     1932            if (!(cpy = wolfSSL_BN_dup(from->dsa->p))) {
     1933                WOLFSSL_MSG("wolfSSL_BN_dup error");
     1934                return WOLFSSL_FAILURE;
     1935            }
     1936            to->dsa->p = cpy;
     1937            if (!(cpy = wolfSSL_BN_dup(from->dsa->q))) {
     1938                WOLFSSL_MSG("wolfSSL_BN_dup error");
     1939                return WOLFSSL_FAILURE;
     1940            }
     1941            to->dsa->q = cpy;
     1942            if (!(cpy = wolfSSL_BN_dup(from->dsa->g))) {
     1943                WOLFSSL_MSG("wolfSSL_BN_dup error");
     1944                return WOLFSSL_FAILURE;
     1945            }
     1946            to->dsa->g = cpy;
     1947        }
     1948        else {
     1949            WOLFSSL_MSG("Missing DSA struct");
     1950            return WOLFSSL_FAILURE;
     1951        }
     1952        break;
     1953#endif
     1954#ifndef NO_RSA
     1955    case EVP_PKEY_RSA:
     1956#endif
     1957#ifndef NO_DH
     1958    case EVP_PKEY_DH:
     1959#endif
     1960    default:
     1961        WOLFSSL_MSG("Copy parameters not available for this key type");
     1962        return WOLFSSL_FAILURE;
     1963    }
     1964#if defined(HAVE_ECC) || !defined(NO_DSA)
     1965    return WOLFSSL_SUCCESS;
     1966#endif
     1967}
     1968
    17221969#ifndef NO_WOLFSSL_STUB
    17231970WOLFSSL_API int wolfSSL_EVP_PKEY_missing_parameters(WOLFSSL_EVP_PKEY *pkey)
     
    17602007#endif /* HAVE_ECC */
    17612008    default:
    1762         break;
     2009        return ret;
    17632010    } /* switch (a->type) */
    17642011
     
    18242071
    18252072static const struct s_ent {
    1826     const int macType;
     2073    const enum wc_HashType macType;
    18272074    const int nid;
    18282075    const char *name;
     
    18372084
    18382085#ifndef NO_SHA
    1839     {WC_HASH_TYPE_SHA, NID_sha1, "SHA"},
     2086    {WC_HASH_TYPE_SHA, NID_sha1, "SHA1"},
     2087    {WC_HASH_TYPE_SHA, NID_sha1, "SHA"}, /* Leave for backwards compatibility */
    18402088#endif /* NO_SHA */
    18412089
     
    18592107    {WC_HASH_TYPE_SHA3_256, NID_sha3_256, "SHA3_256"},
    18602108#endif
     2109#ifndef WOLFSSL_NOSHA3_384
    18612110    {WC_HASH_TYPE_SHA3_384, NID_sha3_384, "SHA3_384"},
     2111#endif
    18622112#ifndef WOLFSSL_NOSHA3_512
    18632113    {WC_HASH_TYPE_SHA3_512, NID_sha3_512, "SHA3_512"},
    18642114#endif
    1865     {0, 0, NULL}
     2115    {WC_HASH_TYPE_NONE, 0, NULL}
    18662116};
    18672117
    1868 static int wolfSSL_EVP_md2macType(const WOLFSSL_EVP_MD *md)
     2118static enum wc_HashType wolfSSL_EVP_md2macType(const WOLFSSL_EVP_MD *md)
    18692119{
    18702120    const struct s_ent *ent ;
     
    20472297}
    20482298
    2049 
    20502299/* Initialize an EVP_DigestSign/Verify operation.
    20512300 * Initialize a digest for RSA and ECC keys, or HMAC for HMAC key.
     
    20572306                                      WOLFSSL_EVP_PKEY *pkey)
    20582307{
     2308    if (!type) {
     2309        int default_digest;
     2310        if (wolfSSL_EVP_PKEY_get_default_digest_nid(pkey, &default_digest)
     2311                != WOLFSSL_SUCCESS) {
     2312            WOLFSSL_MSG("Could not get default digest");
     2313            return WOLFSSL_FAILURE;
     2314        }
     2315        type = wolfSSL_EVP_get_digestbynid(default_digest);
     2316        if (!type) {
     2317            return BAD_FUNC_ARG;
     2318        }
     2319    }
     2320
    20592321    if (pkey->type == EVP_PKEY_HMAC) {
    20602322        int                  hashType;
    20612323        const unsigned char* key;
    2062         size_t               keySz;
    20632324
    20642325        if (XSTRNCMP(type, "SHA256", 6) == 0) {
     
    20802341        }
    20812342    #endif
     2343#ifdef WOLFSSL_SHA3
     2344    #ifndef WOLFSSL_NOSHA3_224
     2345        else if (XSTRNCMP(type, "SHA3_224", 8) == 0) {
     2346            hashType = WC_SHA3_224;
     2347        }
     2348    #endif
     2349    #ifndef WOLFSSL_NOSHA3_256
     2350        else if (XSTRNCMP(type, "SHA3_256", 8) == 0) {
     2351            hashType = WC_SHA3_256;
     2352        }
     2353    #endif
     2354        else if (XSTRNCMP(type, "SHA3_384", 8) == 0) {
     2355            hashType = WC_SHA3_384;
     2356        }
     2357    #ifndef WOLFSSL_NOSHA3_512
     2358        else if (XSTRNCMP(type, "SHA3_512", 8) == 0) {
     2359            hashType = WC_SHA3_512;
     2360        }
     2361    #endif
     2362#endif
    20822363    #ifndef NO_MD5
    20832364        else if (XSTRNCMP(type, "MD5", 3) == 0) {
     
    20882369        /* has to be last since would pick or 224, 256, 384, or 512 too */
    20892370        else if (XSTRNCMP(type, "SHA", 3) == 0) {
    2090              hashType = WC_SHA;
     2371            hashType = WC_SHA;
    20912372        }
    20922373    #endif /* NO_SHA */
     
    20942375             return BAD_FUNC_ARG;
    20952376
    2096         key = wolfSSL_EVP_PKEY_get0_hmac(pkey, &keySz);
    2097 
    2098         if (wc_HmacInit(&ctx->hash.hmac, NULL, INVALID_DEVID) != 0)
     2377        {
     2378            size_t keySz = 0;
     2379
     2380            key = wolfSSL_EVP_PKEY_get0_hmac(pkey, &keySz);
     2381
     2382            if (wc_HmacInit(&ctx->hash.hmac, NULL, INVALID_DEVID) != 0)
     2383                return WOLFSSL_FAILURE;
     2384
     2385            if (wc_HmacSetKey(&ctx->hash.hmac, hashType, key, (word32)keySz) != 0)
     2386                return WOLFSSL_FAILURE;
     2387        }
     2388
     2389        ctx->isHMAC = 1;
     2390    }
     2391    else if (wolfSSL_EVP_DigestInit(ctx, type) != 1)
    20992392            return WOLFSSL_FAILURE;
    21002393
    2101         if (wc_HmacSetKey(&ctx->hash.hmac, hashType, key, (word32)keySz) != 0)
     2394    if (ctx->pctx == NULL) {
     2395        ctx->pctx = wolfSSL_EVP_PKEY_CTX_new(pkey, e);
     2396        if (ctx->pctx == NULL)
    21022397            return WOLFSSL_FAILURE;
    2103 
    2104         ctx->macType = NID_hmac;
    2105     }
    2106     else {
    2107         int ret;
    2108 
    2109         if (ctx->pctx == NULL) {
    2110             ctx->pctx = wolfSSL_EVP_PKEY_CTX_new(pkey, e);
    2111             if (ctx->pctx == NULL)
    2112                 return WOLFSSL_FAILURE;
    2113         }
    2114 
    2115         ret = wolfSSL_EVP_DigestInit(ctx, type);
    2116         if (ret == WOLFSSL_SUCCESS && pctx != NULL)
    2117             *pctx = ctx->pctx;
    2118         return ret;
    2119     }
    2120 
     2398    }
     2399    if (pctx != NULL)
     2400        *pctx = ctx->pctx;
    21212401    return WOLFSSL_SUCCESS;
    21222402}
     
    21282408                                        const void *d, unsigned int cnt)
    21292409{
    2130     if (ctx->pctx == NULL) {
    2131         if (ctx->macType != NID_hmac)
    2132             return WOLFSSL_FAILURE;
    2133 
     2410    if (ctx->isHMAC) {
    21342411        if (wc_HmacUpdate(&ctx->hash.hmac, (const byte *)d, cnt) != 0)
    21352412            return WOLFSSL_FAILURE;
     
    21502427    int  ret;
    21512428
    2152     if (ctx->pctx == NULL) {
     2429    if (ctx->isHMAC) {
    21532430        Hmac hmacCopy;
    2154 
    2155         if (ctx->macType != NID_hmac)
    2156             return WOLFSSL_FAILURE;
    21572431
    21582432        if (wolfSSL_HmacCopy(&hmacCopy, &ctx->hash.hmac) != WOLFSSL_SUCCESS)
     
    22212495    #endif /* HAVE_BLAKE2 */
    22222496
     2497    #ifdef WOLFSSL_SHA3
     2498        #ifndef WOLFSSL_NOSHA3_224
     2499        case WC_SHA3_224:
     2500            hashLen = WC_SHA3_224_DIGEST_SIZE;
     2501            break;
     2502        #endif
     2503        #ifndef WOLFSSL_NOSHA3_256
     2504        case WC_SHA3_256:
     2505            hashLen = WC_SHA3_256_DIGEST_SIZE;
     2506            break;
     2507        #endif
     2508        #ifndef WOLFSSL_NOSHA3_384
     2509        case WC_SHA3_384:
     2510            hashLen = WC_SHA3_384_DIGEST_SIZE;
     2511            break;
     2512        #endif
     2513        #ifndef WOLFSSL_NOSHA3_512
     2514        case WC_SHA3_512:
     2515            hashLen = WC_SHA3_512_DIGEST_SIZE;
     2516            break;
     2517        #endif
     2518    #endif
     2519
    22232520        default:
    22242521            hashLen = 0;
     
    22362533    WOLFSSL_ENTER("EVP_DigestSignInit");
    22372534
    2238     if (ctx == NULL || type == NULL || pkey == NULL)
     2535    if (ctx == NULL || pkey == NULL)
    22392536        return BAD_FUNC_ARG;
    22402537
     
    22672564
    22682565    /* Return the maximum size of the signaure when sig is NULL. */
    2269     if (ctx->pctx == NULL) {
    2270         if (ctx->macType != NID_hmac)
    2271             return WOLFSSL_FAILURE;
    2272 
     2566    if (ctx->isHMAC) {
    22732567        hashLen = wolfssl_mac_len(ctx->hash.hmac.macType);
    22742568
     
    23002594        return WOLFSSL_FAILURE;
    23012595
    2302     if (ctx->pctx == NULL) {
     2596    if (ctx->isHMAC) {
    23032597        /* Copy the HMAC result as signature. */
    23042598        if ((unsigned int)(*siglen) > hashLen)
     
    23182612            if (nid < 0)
    23192613                break;
    2320             ret = wolfSSL_RSA_sign(nid, digest, hashLen, sig, &sigSz,
    2321                                    ctx->pctx->pkey->rsa);
     2614            ret = wolfSSL_RSA_sign_generic_padding(nid, digest, hashLen,
     2615                    sig, &sigSz, ctx->pctx->pkey->rsa, 1, ctx->pctx->padding);
    23222616            if (ret >= 0)
    23232617                *siglen = sigSz;
     
    23852679        return WOLFSSL_FAILURE;
    23862680
    2387     if (ctx->pctx == NULL) {
    2388         if (ctx->macType != NID_hmac)
    2389             return WOLFSSL_FAILURE;
     2681    if (ctx->isHMAC) {
    23902682
    23912683        hashLen = wolfssl_mac_len(ctx->hash.hmac.macType);
     
    23992691        return WOLFSSL_FAILURE;
    24002692
    2401     if (ctx->pctx == NULL) {
     2693    if (ctx->isHMAC) {
    24022694        /* Check HMAC result matches the signature. */
    24032695        if (XMEMCMP(sig, digest, siglen) == 0)
     
    24132705            if (nid < 0)
    24142706                return WOLFSSL_FAILURE;
    2415             return wolfSSL_RSA_verify(nid, digest, hashLen, sig,
     2707            return wolfSSL_RSA_verify_ex(nid, digest, hashLen, sig,
    24162708                                      (unsigned int)siglen,
    2417                                       ctx->pctx->pkey->rsa);
     2709                                      ctx->pctx->pkey->rsa, ctx->pctx->padding);
    24182710        }
    24192711    #endif /* NO_RSA */
     
    25742866
    25752867#ifndef NO_AES
     2868    #ifdef HAVE_AES_CBC
    25762869    #ifdef WOLFSSL_AES_128
    2577     {AES_128_CBC_TYPE, "AES-128-CBC", NID_aes_128_cbc},
     2870    {AES_128_CBC_TYPE, EVP_AES_128_CBC, NID_aes_128_cbc},
    25782871    #endif
    25792872    #ifdef WOLFSSL_AES_192
    2580     {AES_192_CBC_TYPE, "AES-192-CBC", NID_aes_192_cbc},
     2873    {AES_192_CBC_TYPE, EVP_AES_192_CBC, NID_aes_192_cbc},
    25812874    #endif
    25822875    #ifdef WOLFSSL_AES_256
    2583     {AES_256_CBC_TYPE, "AES-256-CBC", NID_aes_256_cbc},
    2584     #endif
    2585 
     2876    {AES_256_CBC_TYPE, EVP_AES_256_CBC, NID_aes_256_cbc},
     2877    #endif
     2878    #endif
     2879
     2880    #ifdef WOLFSSL_AES_CFB
    25862881    #ifdef WOLFSSL_AES_128
    2587     {AES_128_CFB1_TYPE, "AES-128-CFB1", NID_aes_128_cfb1},
     2882    {AES_128_CFB1_TYPE, EVP_AES_128_CFB1, NID_aes_128_cfb1},
    25882883    #endif
    25892884    #ifdef WOLFSSL_AES_192
    2590     {AES_192_CFB1_TYPE, "AES-192-CFB1", NID_aes_192_cfb1},
     2885    {AES_192_CFB1_TYPE, EVP_AES_192_CFB1, NID_aes_192_cfb1},
    25912886    #endif
    25922887    #ifdef WOLFSSL_AES_256
    2593     {AES_256_CFB1_TYPE, "AES-256-CFB1", NID_aes_256_cfb1},
     2888    {AES_256_CFB1_TYPE, EVP_AES_256_CFB1, NID_aes_256_cfb1},
    25942889    #endif
    25952890
    25962891    #ifdef WOLFSSL_AES_128
    2597     {AES_128_CFB8_TYPE, "AES-128-CFB8", NID_aes_128_cfb8},
     2892    {AES_128_CFB8_TYPE, EVP_AES_128_CFB8, NID_aes_128_cfb8},
    25982893    #endif
    25992894    #ifdef WOLFSSL_AES_192
    2600     {AES_192_CFB8_TYPE, "AES-192-CFB8", NID_aes_192_cfb8},
     2895    {AES_192_CFB8_TYPE, EVP_AES_192_CFB8, NID_aes_192_cfb8},
    26012896    #endif
    26022897    #ifdef WOLFSSL_AES_256
    2603     {AES_256_CFB8_TYPE, "AES-256-CFB8", NID_aes_256_cfb8},
     2898    {AES_256_CFB8_TYPE, EVP_AES_256_CFB8, NID_aes_256_cfb8},
    26042899    #endif
    26052900
    26062901    #ifdef WOLFSSL_AES_128
    2607     {AES_128_CFB128_TYPE, "AES-128-CFB128", NID_aes_128_cfb128},
     2902    {AES_128_CFB128_TYPE, EVP_AES_128_CFB128, NID_aes_128_cfb128},
    26082903    #endif
    26092904    #ifdef WOLFSSL_AES_192
    2610     {AES_192_CFB128_TYPE, "AES-192-CFB128", NID_aes_192_cfb128},
     2905    {AES_192_CFB128_TYPE, EVP_AES_192_CFB128, NID_aes_192_cfb128},
    26112906    #endif
    26122907    #ifdef WOLFSSL_AES_256
    2613     {AES_256_CFB128_TYPE, "AES-256-CFB128", NID_aes_256_cfb128},
    2614     #endif
    2615 
     2908    {AES_256_CFB128_TYPE, EVP_AES_256_CFB128, NID_aes_256_cfb128},
     2909    #endif
     2910    #endif
     2911
     2912    #ifdef HAVE_AES_OFB
    26162913    #ifdef WOLFSSL_AES_128
    2617     {AES_128_OFB_TYPE, "AES-128-OFB", NID_aes_128_ofb},
     2914    {AES_128_OFB_TYPE, EVP_AES_128_OFB, NID_aes_128_ofb},
    26182915    #endif
    26192916    #ifdef WOLFSSL_AES_192
    2620     {AES_192_OFB_TYPE, "AES-192-OFB", NID_aes_192_ofb},
     2917    {AES_192_OFB_TYPE, EVP_AES_192_OFB, NID_aes_192_ofb},
    26212918    #endif
    26222919    #ifdef WOLFSSL_AES_256
    2623     {AES_256_OFB_TYPE, "AES-256-OFB", NID_aes_256_ofb},
    2624     #endif
    2625 
     2920    {AES_256_OFB_TYPE, EVP_AES_256_OFB, NID_aes_256_ofb},
     2921    #endif
     2922    #endif
     2923
     2924    #ifdef HAVE_AES_XTS
    26262925    #ifdef WOLFSSL_AES_128
    2627     {AES_128_XTS_TYPE, "AES-128-XTS", NID_aes_128_xts},
     2926    {AES_128_XTS_TYPE, EVP_AES_128_XTS, NID_aes_128_xts},
    26282927    #endif
    26292928    #ifdef WOLFSSL_AES_256
    2630     {AES_256_XTS_TYPE, "AES-256-XTS", NID_aes_256_xts},
    2631     #endif
    2632 
     2929    {AES_256_XTS_TYPE, EVP_AES_256_XTS, NID_aes_256_xts},
     2930    #endif
     2931    #endif
     2932
     2933    #ifdef HAVE_AESGCM
    26332934    #ifdef WOLFSSL_AES_128
    2634     {AES_128_GCM_TYPE, "AES-128-GCM", NID_aes_128_gcm},
     2935    {AES_128_GCM_TYPE, EVP_AES_128_GCM, NID_aes_128_gcm},
    26352936    #endif
    26362937    #ifdef WOLFSSL_AES_192
    2637     {AES_192_GCM_TYPE, "AES-192-GCM", NID_aes_192_gcm},
     2938    {AES_192_GCM_TYPE, EVP_AES_192_GCM, NID_aes_192_gcm},
    26382939    #endif
    26392940    #ifdef WOLFSSL_AES_256
    2640     {AES_256_GCM_TYPE, "AES-256-GCM", NID_aes_256_gcm},
    2641     #endif
     2941    {AES_256_GCM_TYPE, EVP_AES_256_GCM, NID_aes_256_gcm},
     2942    #endif
     2943    #endif
     2944
     2945    #ifdef WOLFSSL_AES_COUNTER
    26422946    #ifdef WOLFSSL_AES_128
    2643         {AES_128_CTR_TYPE, "AES-128-CTR", NID_aes_128_ctr},
     2947        {AES_128_CTR_TYPE, EVP_AES_128_CTR, NID_aes_128_ctr},
    26442948    #endif
    26452949    #ifdef WOLFSSL_AES_192
    2646         {AES_192_CTR_TYPE, "AES-192-CTR", NID_aes_192_ctr},
     2950        {AES_192_CTR_TYPE, EVP_AES_192_CTR, NID_aes_192_ctr},
    26472951    #endif
    26482952    #ifdef WOLFSSL_AES_256
    2649         {AES_256_CTR_TYPE, "AES-256-CTR", NID_aes_256_ctr},
    2650     #endif
    2651 
     2953        {AES_256_CTR_TYPE, EVP_AES_256_CTR, NID_aes_256_ctr},
     2954    #endif
     2955    #endif
     2956
     2957    #ifdef HAVE_AES_ECB
    26522958    #ifdef WOLFSSL_AES_128
    2653         {AES_128_ECB_TYPE, "AES-128-ECB", NID_aes_128_ecb},
     2959        {AES_128_ECB_TYPE, EVP_AES_128_ECB, NID_aes_128_ecb},
    26542960    #endif
    26552961    #ifdef WOLFSSL_AES_192
    2656         {AES_192_ECB_TYPE, "AES-192-ECB", NID_aes_192_ecb},
     2962        {AES_192_ECB_TYPE, EVP_AES_192_ECB, NID_aes_192_ecb},
    26572963    #endif
    26582964    #ifdef WOLFSSL_AES_256
    2659         {AES_256_ECB_TYPE, "AES-256-ECB", NID_aes_256_ecb},
    2660     #endif
    2661 
     2965        {AES_256_ECB_TYPE, EVP_AES_256_ECB, NID_aes_256_ecb},
     2966    #endif
     2967    #endif
    26622968#endif
    26632969
    26642970#ifndef NO_DES3
    2665     {DES_CBC_TYPE, "DES-CBC", NID_des_cbc},
    2666     {DES_ECB_TYPE, "DES-ECB", NID_des_ecb},
    2667 
    2668     {DES_EDE3_CBC_TYPE, "DES-EDE3-CBC", NID_des_ede3_cbc},
    2669     {DES_EDE3_ECB_TYPE, "DES-EDE3-ECB", NID_des_ede3_ecb},
     2971    {DES_CBC_TYPE, EVP_DES_CBC, NID_des_cbc},
     2972    {DES_ECB_TYPE, EVP_DES_ECB, NID_des_ecb},
     2973
     2974    {DES_EDE3_CBC_TYPE, EVP_DES_EDE3_CBC, NID_des_ede3_cbc},
     2975    {DES_EDE3_ECB_TYPE, EVP_DES_EDE3_ECB, NID_des_ede3_ecb},
    26702976#endif
    26712977
    26722978#ifndef NO_RC4
    2673     {ARC4_TYPE, "ARC4", NID_undef},
     2979    {ARC4_TYPE, EVP_ARC4, NID_undef},
    26742980#endif
    26752981
    26762982#ifdef HAVE_IDEA
    2677     {IDEA_CBC_TYPE, "IDEA-CBC", NID_idea_cbc},
     2983    {IDEA_CBC_TYPE, EVP_IDEA_CBC, NID_idea_cbc},
    26782984#endif
    26792985    { 0, NULL, 0}
     
    27193025{
    27203026
    2721     static const struct alias {
     3027    const struct alias {
    27223028        const char *name;
    27233029        const char *alias;
     
    27253031    {
    27263032#ifndef NO_DES3
    2727         {"DES-CBC", "DES"},
    2728         {"DES-CBC", "des"},
    2729         {"DES-ECB", "DES-ECB"},
    2730         {"DES-ECB", "des-ecb"},
    2731         {"DES-EDE3-CBC", "DES3"},
    2732         {"DES-EDE3-CBC", "des3"},
    2733         {"DES-EDE3-ECB", "DES-EDE3"},
    2734         {"DES-EDE3-ECB", "des-ede3"},
    2735         {"DES-EDE3-ECB", "des-ede3-ecb"},
     3033        {EVP_DES_CBC, "DES"},
     3034        {EVP_DES_CBC, "des"},
     3035        {EVP_DES_ECB, "DES-ECB"},
     3036        {EVP_DES_ECB, "des-ecb"},
     3037        {EVP_DES_EDE3_CBC, "DES3"},
     3038        {EVP_DES_EDE3_CBC, "des3"},
     3039        {EVP_DES_EDE3_ECB, "DES-EDE3"},
     3040        {EVP_DES_EDE3_ECB, "des-ede3"},
     3041        {EVP_DES_EDE3_ECB, "des-ede3-ecb"},
    27363042#endif
    27373043#ifdef HAVE_IDEA
    2738         {"IDEA-CBC", "IDEA"},
    2739         {"IDEA-CBC", "idea"},
     3044        {EVP_IDEA_CBC, "IDEA"},
     3045        {EVP_IDEA_CBC, "idea"},
    27403046#endif
    27413047#ifndef NO_AES
    27423048    #ifdef HAVE_AES_CBC
    27433049        #ifdef WOLFSSL_AES_128
    2744         {"AES-128-CBC", "AES128-CBC"},
    2745         {"AES-128-CBC", "aes128-cbc"},
     3050            {EVP_AES_128_CBC, "AES128-CBC"},
     3051            {EVP_AES_128_CBC, "aes128-cbc"},
    27463052        #endif
    27473053        #ifdef WOLFSSL_AES_192
    2748         {"AES-192-CBC", "AES192-CBC"},
    2749         {"AES-192-CBC", "aes192-cbc"},
     3054            {EVP_AES_192_CBC, "AES192-CBC"},
     3055            {EVP_AES_192_CBC, "aes192-cbc"},
    27503056        #endif
    27513057        #ifdef WOLFSSL_AES_256
    2752         {"AES-256-CBC", "AES256-CBC"},
    2753         {"AES-256-CBC", "aes256-cbc"},
     3058            {EVP_AES_256_CBC, "AES256-CBC"},
     3059            {EVP_AES_256_CBC, "aes256-cbc"},
    27543060        #endif
    27553061    #endif
    2756     #ifdef WOLFSSL_AES_128
    2757         {"AES-128-ECB", "AES128-ECB"},
    2758         {"AES-128-ECB", "aes128-ecb"},
    2759     #endif
    2760     #ifdef WOLFSSL_AES_192
    2761         {"AES-192-ECB", "AES192-ECB"},
    2762         {"AES-192-ECB", "aes192-ecb"},
    2763     #endif
    2764     #ifdef WOLFSSL_AES_256
    2765         {"AES-256-ECB", "AES256-ECB"},
     3062    #ifdef HAVE_AES_ECB
     3063        #ifdef WOLFSSL_AES_128
     3064            {EVP_AES_128_ECB, "AES128-ECB"},
     3065            {EVP_AES_128_ECB, "aes128-ecb"},
     3066        #endif
     3067        #ifdef WOLFSSL_AES_192
     3068            {EVP_AES_192_ECB, "AES192-ECB"},
     3069            {EVP_AES_192_ECB, "aes192-ecb"},
     3070        #endif
     3071        #ifdef WOLFSSL_AES_256
     3072            {EVP_AES_256_ECB, "AES256-ECB"},
     3073        #endif
    27663074    #endif
    27673075    #ifdef HAVE_AESGCM
    27683076        #ifdef WOLFSSL_AES_128
    2769         {"AES-128-GCM", "aes-128-gcm"},
    2770         {"AES-128-GCM", "id-aes128-GCM"},
     3077            {EVP_AES_128_GCM, "aes-128-gcm"},
     3078            {EVP_AES_128_GCM, "id-aes128-GCM"},
    27713079        #endif
    27723080        #ifdef WOLFSSL_AES_192
    2773         {"AES-192-GCM", "aes-192-gcm"},
    2774         {"AES-192-GCM", "id-aes192-GCM"},
     3081            {EVP_AES_192_GCM, "aes-192-gcm"},
     3082            {EVP_AES_192_GCM, "id-aes192-GCM"},
    27753083        #endif
    27763084        #ifdef WOLFSSL_AES_256
    2777         {"AES-256-GCM", "aes-256-gcm"},
    2778         {"AES-256-GCM", "id-aes256-GCM"},
     3085            {EVP_AES_256_GCM, "aes-256-gcm"},
     3086            {EVP_AES_256_GCM, "id-aes256-GCM"},
    27793087        #endif
    27803088    #endif
    27813089#endif
    27823090#ifndef NO_RC4
    2783         {"ARC4", "RC4"},
     3091        {EVP_ARC4, "RC4"},
    27843092#endif
    27853093        { NULL, NULL}
     
    29063214void wolfSSL_EVP_init(void)
    29073215{
    2908 #ifndef NO_AES
    2909     #ifdef HAVE_AES_CBC
    2910         #ifdef WOLFSSL_AES_128
    2911         EVP_AES_128_CBC = (char *)EVP_get_cipherbyname("AES-128-CBC");
    2912         #endif
    2913         #ifdef WOLFSSL_AES_192
    2914         EVP_AES_192_CBC = (char *)EVP_get_cipherbyname("AES-192-CBC");
    2915         #endif
    2916         #ifdef WOLFSSL_AES_256
    2917         EVP_AES_256_CBC = (char *)EVP_get_cipherbyname("AES-256-CBC");
    2918         #endif
    2919     #endif /* HAVE_AES_CBC */
    2920 
    2921     #ifdef WOLFSSL_AES_CFB
    2922         #ifdef WOLFSSL_AES_128
    2923         EVP_AES_128_CFB1 = (char *)EVP_get_cipherbyname("AES-128-CFB1");
    2924         #endif
    2925 
    2926         #ifdef WOLFSSL_AES_192
    2927         EVP_AES_192_CFB1 = (char *)EVP_get_cipherbyname("AES-192-CFB1");
    2928         #endif
    2929 
    2930         #ifdef WOLFSSL_AES_256
    2931         EVP_AES_256_CFB1 = (char *)EVP_get_cipherbyname("AES-256-CFB1");
    2932         #endif
    2933 
    2934         #ifdef WOLFSSL_AES_128
    2935         EVP_AES_128_CFB8 = (char *)EVP_get_cipherbyname("AES-128-CFB8");
    2936         #endif
    2937 
    2938         #ifdef WOLFSSL_AES_192
    2939         EVP_AES_192_CFB8 = (char *)EVP_get_cipherbyname("AES-192-CFB8");
    2940         #endif
    2941 
    2942         #ifdef WOLFSSL_AES_256
    2943         EVP_AES_256_CFB8 = (char *)EVP_get_cipherbyname("AES-256-CFB8");
    2944         #endif
    2945 
    2946         #ifdef WOLFSSL_AES_128
    2947         EVP_AES_128_CFB128 = (char *)EVP_get_cipherbyname("AES-128-CFB128");
    2948         #endif
    2949 
    2950         #ifdef WOLFSSL_AES_192
    2951         EVP_AES_192_CFB128 = (char *)EVP_get_cipherbyname("AES-192-CFB128");
    2952         #endif
    2953 
    2954         #ifdef WOLFSSL_AES_256
    2955         EVP_AES_256_CFB128 = (char *)EVP_get_cipherbyname("AES-256-CFB128");
    2956         #endif
    2957     #endif /* WOLFSSL_AES_CFB */
    2958 
    2959     #ifdef WOLFSSL_AES_OFB
    2960         #ifdef WOLFSSL_AES_128
    2961         EVP_AES_128_OFB = (char *)EVP_get_cipherbyname("AES-128-OFB");
    2962         #endif
    2963 
    2964         #ifdef WOLFSSL_AES_192
    2965         EVP_AES_192_OFB = (char *)EVP_get_cipherbyname("AES-192-OFB");
    2966         #endif
    2967 
    2968         #ifdef WOLFSSL_AES_256
    2969         EVP_AES_256_OFB = (char *)EVP_get_cipherbyname("AES-256-OFB");
    2970         #endif
    2971     #endif /* WOLFSSL_AES_OFB */
    2972 
    2973     #ifdef WOLFSSL_AES_XTS
    2974         #ifdef WOLFSSL_AES_128
    2975         EVP_AES_128_XTS = (char *)EVP_get_cipherbyname("AES-128-XTS");
    2976         #endif
    2977 
    2978         #ifdef WOLFSSL_AES_256
    2979         EVP_AES_256_XTS = (char *)EVP_get_cipherbyname("AES-256-XTS");
    2980         #endif
    2981     #endif /* WOLFSSL_AES_XTS */
    2982 
    2983     #ifdef HAVE_AESGCM
    2984         #ifdef WOLFSSL_AES_128
    2985         EVP_AES_128_GCM = (char *)EVP_get_cipherbyname("AES-128-GCM");
    2986         #endif
    2987         #ifdef WOLFSSL_AES_192
    2988         EVP_AES_192_GCM = (char *)EVP_get_cipherbyname("AES-192-GCM");
    2989         #endif
    2990         #ifdef WOLFSSL_AES_256
    2991         EVP_AES_256_GCM = (char *)EVP_get_cipherbyname("AES-256-GCM");
    2992         #endif
    2993     #endif /* HAVE_AESGCM*/
    2994         #ifdef WOLFSSL_AES_128
    2995         EVP_AES_128_CTR = (char *)EVP_get_cipherbyname("AES-128-CTR");
    2996         #endif
    2997         #ifdef WOLFSSL_AES_192
    2998         EVP_AES_192_CTR = (char *)EVP_get_cipherbyname("AES-192-CTR");
    2999         #endif
    3000         #ifdef WOLFSSL_AES_256
    3001         EVP_AES_256_CTR = (char *)EVP_get_cipherbyname("AES-256-CTR");
    3002         #endif
    3003 
    3004         #ifdef WOLFSSL_AES_128
    3005         EVP_AES_128_ECB = (char *)EVP_get_cipherbyname("AES-128-ECB");
    3006         #endif
    3007         #ifdef WOLFSSL_AES_192
    3008         EVP_AES_192_ECB = (char *)EVP_get_cipherbyname("AES-192-ECB");
    3009         #endif
    3010         #ifdef WOLFSSL_AES_256
    3011         EVP_AES_256_ECB = (char *)EVP_get_cipherbyname("AES-256-ECB");
    3012         #endif
    3013 #endif /* ifndef NO_AES*/
    3014 
    3015 #ifndef NO_DES3
    3016     EVP_DES_CBC = (char *)EVP_get_cipherbyname("DES-CBC");
    3017     EVP_DES_ECB = (char *)EVP_get_cipherbyname("DES-ECB");
    3018 
    3019     EVP_DES_EDE3_CBC = (char *)EVP_get_cipherbyname("DES-EDE3-CBC");
    3020     EVP_DES_EDE3_ECB = (char *)EVP_get_cipherbyname("DES-EDE3-ECB");
    3021 #endif
    3022 
    3023 #ifdef HAVE_IDEA
    3024     EVP_IDEA_CBC = (char *)EVP_get_cipherbyname("IDEA-CBC");
    3025 #endif
     3216    /* Does nothing. */
    30263217}
    30273218
    30283219#if !defined(NO_PWDBASED)
    3029 int wolfSSL_EVP_get_hashinfo(const WOLFSSL_EVP_MD* evp,
    3030     int* pHash, int* pHashSz)
    3031 {
    3032     enum wc_HashType hash = WC_HASH_TYPE_NONE;
    3033     int hashSz;
    3034 
    3035     if (XSTRLEN(evp) < 3) {
    3036         /* do not try comparing strings if size is too small */
    3037         return WOLFSSL_FAILURE;
    3038     }
    3039 
    3040     if (XSTRNCMP("SHA", evp, 3) == 0) {
    3041         if (XSTRLEN(evp) > 3) {
    3042         #ifndef NO_SHA256
    3043             if (XSTRNCMP("SHA256", evp, 6) == 0) {
    3044                 hash = WC_HASH_TYPE_SHA256;
    3045             }
    3046             else
    3047         #endif
    3048         #ifdef WOLFSSL_SHA384
    3049             if (XSTRNCMP("SHA384", evp, 6) == 0) {
    3050                 hash = WC_HASH_TYPE_SHA384;
    3051             }
    3052             else
    3053         #endif
    3054         #ifdef WOLFSSL_SHA512
    3055             if (XSTRNCMP("SHA512", evp, 6) == 0) {
    3056                 hash = WC_HASH_TYPE_SHA512;
    3057             }
    3058             else
    3059         #endif
    3060             {
    3061                 WOLFSSL_MSG("Unknown SHA hash");
    3062             }
    3063         }
    3064         else {
    3065             hash = WC_HASH_TYPE_SHA;
    3066         }
    3067     }
    3068 #ifdef WOLFSSL_MD2
    3069     else if (XSTRNCMP("MD2", evp, 3) == 0) {
    3070         hash = WC_HASH_TYPE_MD2;
    3071     }
    3072 #endif
    3073 #ifndef NO_MD4
    3074     else if (XSTRNCMP("MD4", evp, 3) == 0) {
    3075         hash = WC_HASH_TYPE_MD4;
    3076     }
    3077 #endif
    3078 #ifndef NO_MD5
    3079     else if (XSTRNCMP("MD5", evp, 3) == 0) {
    3080         hash = WC_HASH_TYPE_MD5;
    3081     }
    3082 #endif
    3083 
    3084     if (pHash)
    3085         *pHash = hash;
    3086 
    3087     hashSz = wc_HashGetDigestSize(hash);
    3088     if (pHashSz)
    3089         *pHashSz = hashSz;
    3090 
    3091     if (hashSz < 0) {
    3092         return WOLFSSL_FAILURE;
    3093     }
    3094 
    3095     return WOLFSSL_SUCCESS;
    3096 }
    3097 
    30983220/* this function makes the assumption that out buffer is big enough for digest*/
    30993221int wolfSSL_EVP_Digest(const unsigned char* in, int inSz, unsigned char* out,
     
    31363258        {"MD4", "ssl3-md4"},
    31373259        {"MD5", "ssl3-md5"},
    3138         {"SHA", "ssl3-sha1"},
    3139         {"SHA", "SHA1"},
     3260        {"SHA1", "ssl3-sha1"},
     3261        {"SHA1", "SHA"},
    31403262        { NULL, NULL}
    31413263    };
     3264    char nameUpper[15]; /* 15 bytes should be enough for any name */
     3265    size_t i;
    31423266
    31433267    const struct alias  *al;
    31443268    const struct s_ent *ent;
    31453269
    3146 
     3270    for (i = 0; i < sizeof(nameUpper) && name[i] != '\0'; i++) {
     3271        nameUpper[i] = (char)XTOUPPER(name[i]);
     3272    }
     3273    if (i < sizeof(nameUpper))
     3274        nameUpper[i] = '\0';
     3275    else
     3276        return NULL;
     3277
     3278    name = nameUpper;
    31473279    for (al = alias_tbl; al->name != NULL; al++)
    31483280        if(XSTRNCMP(name, al->alias, XSTRLEN(al->alias)+1) == 0) {
     
    32053337    {
    32063338        WOLFSSL_ENTER("EVP_sha1");
    3207         return EVP_get_digestbyname("SHA");
     3339        return EVP_get_digestbyname("SHA1");
    32083340    }
    32093341#endif /* NO_SHA */
     
    32953427        if (ctx) {
    32963428            WOLFSSL_ENTER("EVP_MD_CTX_free");
    3297                 wolfSSL_EVP_MD_CTX_cleanup(ctx);
    3298                 XFREE(ctx, NULL, DYNAMIC_TYPE_OPENSSL);
    3299             }
     3429            wolfSSL_EVP_MD_CTX_cleanup(ctx);
     3430            XFREE(ctx, NULL, DYNAMIC_TYPE_OPENSSL);
     3431        }
    33003432    }
    33013433
    33023434    /* returns the NID of message digest used by the ctx */
    3303     int wolfSSL_EVP_MD_CTX_type(const WOLFSSL_EVP_MD_CTX *ctx) {
     3435    int wolfSSL_EVP_MD_CTX_type(const WOLFSSL_EVP_MD_CTX *ctx)
     3436    {
    33043437        const struct s_ent *ent;
    33053438
     
    33073440
    33083441        if (ctx) {
     3442            if (ctx->isHMAC) {
     3443                return NID_hmac;
     3444            }
     3445
    33093446            for(ent = md_tbl; ent->name != NULL; ent++) {
    33103447                if (ctx->macType == ent->macType) {
     
    33393476            const WOLFSSL_EVP_MD_CTX* src)
    33403477    {
    3341         if (src->macType == NID_hmac) {
    3342             wolfSSL_HmacCopy(&des->hash.hmac, (Hmac*)&src->hash.hmac);
     3478        int ret;
     3479        if (src->isHMAC) {
     3480            ret = wolfSSL_HmacCopy(&des->hash.hmac, (Hmac*)&src->hash.hmac);
    33433481        }
    33443482        else {
    33453483            switch (src->macType) {
     3484                case WC_HASH_TYPE_MD5:
    33463485            #ifndef NO_MD5
    3347                 case WC_HASH_TYPE_MD5:
    3348                     wc_Md5Copy((wc_Md5*)&src->hash.digest,
     3486                    ret = wc_Md5Copy((wc_Md5*)&src->hash.digest,
    33493487                            (wc_Md5*)&des->hash.digest);
     3488            #else
     3489                    ret = NOT_COMPILED_IN;
     3490            #endif /* !NO_MD5 */
    33503491                    break;
    3351             #endif /* !NO_MD5 */
    3352 
     3492                case WC_HASH_TYPE_SHA:
    33533493            #ifndef NO_SHA
    3354                 case WC_HASH_TYPE_SHA:
    3355                     wc_ShaCopy((wc_Sha*)&src->hash.digest,
     3494                    ret = wc_ShaCopy((wc_Sha*)&src->hash.digest,
    33563495                            (wc_Sha*)&des->hash.digest);
     3496            #else
     3497                    ret = NOT_COMPILED_IN;
     3498            #endif /* !NO_SHA */
    33573499                    break;
    3358             #endif /* !NO_SHA */
    3359 
     3500                case WC_HASH_TYPE_SHA224:
    33603501            #ifdef WOLFSSL_SHA224
    3361                 case WC_HASH_TYPE_SHA224:
    3362                     wc_Sha224Copy((wc_Sha224*)&src->hash.digest,
     3502                    ret = wc_Sha224Copy((wc_Sha224*)&src->hash.digest,
    33633503                            (wc_Sha224*)&des->hash.digest);
     3504            #else
     3505                    ret = NOT_COMPILED_IN;
     3506            #endif /* WOLFSSL_SHA224 */
    33643507                    break;
    3365             #endif /* WOLFSSL_SHA224 */
    3366 
     3508                case WC_HASH_TYPE_SHA256:
    33673509            #ifndef NO_SHA256
    3368                 case WC_HASH_TYPE_SHA256:
    3369                     wc_Sha256Copy((wc_Sha256*)&src->hash.digest,
     3510                    ret = wc_Sha256Copy((wc_Sha256*)&src->hash.digest,
    33703511                            (wc_Sha256*)&des->hash.digest);
     3512            #else
     3513                    ret = NOT_COMPILED_IN;
     3514            #endif /* !NO_SHA256 */
    33713515                    break;
    3372             #endif /* !NO_SHA256 */
    3373 
     3516                case WC_HASH_TYPE_SHA384:
    33743517            #ifdef WOLFSSL_SHA384
    3375                 case WC_HASH_TYPE_SHA384:
    3376                     wc_Sha384Copy((wc_Sha384*)&src->hash.digest,
     3518                    ret = wc_Sha384Copy((wc_Sha384*)&src->hash.digest,
    33773519                            (wc_Sha384*)&des->hash.digest);
     3520            #else
     3521                    ret = NOT_COMPILED_IN;
     3522            #endif /* WOLFSSL_SHA384 */
    33783523                    break;
    3379             #endif /* WOLFSSL_SHA384 */
     3524                case WC_HASH_TYPE_SHA512:
    33803525            #ifdef WOLFSSL_SHA512
    3381                 case WC_HASH_TYPE_SHA512:
    3382                     wc_Sha512Copy((wc_Sha512*)&src->hash.digest,
     3526                    ret = wc_Sha512Copy((wc_Sha512*)&src->hash.digest,
    33833527                        (wc_Sha512*)&des->hash.digest);
     3528            #else
     3529                    ret = NOT_COMPILED_IN;
     3530            #endif /* WOLFSSL_SHA512 */
    33843531                    break;
    3385             #endif /* WOLFSSL_SHA512 */
    3386         #ifdef WOLFSSL_SHA3
    3387             #ifndef WOLFSSL_NOSHA3_224
    33883532                case WC_HASH_TYPE_SHA3_224:
    3389                     wc_Sha3_224_Copy((wc_Sha3*)&src->hash.digest,
     3533            #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_224)
     3534                    ret = wc_Sha3_224_Copy((wc_Sha3*)&src->hash.digest,
    33903535                            (wc_Sha3*)&des->hash.digest);
     3536            #else
     3537                    ret = NOT_COMPILED_IN;
     3538            #endif
    33913539                    break;
     3540                case WC_HASH_TYPE_SHA3_256:
     3541            #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256)
     3542                    ret = wc_Sha3_256_Copy((wc_Sha3*)&src->hash.digest,
     3543                            (wc_Sha3*)&des->hash.digest);
     3544            #else
     3545                    ret = NOT_COMPILED_IN;
    33923546            #endif
    3393 
    3394             #ifndef WOLFSSL_NOSHA3_256
    3395                 case WC_HASH_TYPE_SHA3_256:
    3396                     wc_Sha3_256_Copy((wc_Sha3*)&src->hash.digest,
     3547                    break;
     3548                case WC_HASH_TYPE_SHA3_384:
     3549            #if defined(WOLFSSL_SHA3)
     3550                    ret = wc_Sha3_384_Copy((wc_Sha3*)&src->hash.digest,
    33973551                            (wc_Sha3*)&des->hash.digest);
     3552            #else
     3553                    ret = NOT_COMPILED_IN;
     3554            #endif
    33983555                    break;
     3556                case WC_HASH_TYPE_SHA3_512:
     3557            #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_512)
     3558                    ret = wc_Sha3_512_Copy((wc_Sha3*)&src->hash.digest,
     3559                        (wc_Sha3*)&des->hash.digest);
     3560            #else
     3561                    ret = NOT_COMPILED_IN;
    33993562            #endif
    3400 
    3401                 case WC_HASH_TYPE_SHA3_384:
    3402                     wc_Sha3_384_Copy((wc_Sha3*)&src->hash.digest,
    3403                             (wc_Sha3*)&des->hash.digest);
    34043563                    break;
    3405 
    3406             #ifndef WOLFSSL_NOSHA3_512
    3407                 case WC_HASH_TYPE_SHA3_512:
    3408                     wc_Sha3_512_Copy((wc_Sha3*)&src->hash.digest,
    3409                         (wc_Sha3*)&des->hash.digest);
     3564                case WC_HASH_TYPE_NONE:
     3565                case WC_HASH_TYPE_MD2:
     3566                case WC_HASH_TYPE_MD4:
     3567                case WC_HASH_TYPE_MD5_SHA:
     3568                case WC_HASH_TYPE_BLAKE2B:
     3569                case WC_HASH_TYPE_BLAKE2S:
     3570                default:
     3571                    ret = BAD_FUNC_ARG;
    34103572                    break;
    3411             #endif
    3412         #endif
    3413                 default:
    3414                     return WOLFSSL_FAILURE;
    3415             }
    3416         }
    3417         return WOLFSSL_SUCCESS;
     3573            }
     3574        }
     3575        return ret == 0 ? WOLFSSL_SUCCESS : WOLFSSL_FAILURE;
    34183576    }
    34193577
     
    34463604            return NULL;
    34473605        WOLFSSL_ENTER("EVP_MD_CTX_md");
     3606        if (ctx->isHMAC) {
     3607            return "HMAC";
     3608        }
    34483609        for(ent = md_tbl; ent->name != NULL; ent++) {
    34493610            if(ctx->macType == ent->macType) {
     
    34613622    {
    34623623        WOLFSSL_ENTER("wolfSSL_EVP_aes_128_cbc");
    3463         if (EVP_AES_128_CBC == NULL)
    3464             wolfSSL_EVP_init();
    34653624        return EVP_AES_128_CBC;
    34663625    }
     
    34723631    {
    34733632        WOLFSSL_ENTER("wolfSSL_EVP_aes_192_cbc");
    3474         if (EVP_AES_192_CBC == NULL)
    3475             wolfSSL_EVP_init();
    34763633        return EVP_AES_192_CBC;
    34773634    }
     
    34833640    {
    34843641        WOLFSSL_ENTER("wolfSSL_EVP_aes_256_cbc");
    3485         if (EVP_AES_256_CBC == NULL)
    3486             wolfSSL_EVP_init();
    34873642        return EVP_AES_256_CBC;
    34883643    }
     
    34963651    {
    34973652        WOLFSSL_ENTER("wolfSSL_EVP_aes_128_cfb1");
    3498         if (EVP_AES_128_CFB1 == NULL)
    3499             wolfSSL_EVP_init();
    35003653        return EVP_AES_128_CFB1;
    35013654    }
     
    35063659    {
    35073660        WOLFSSL_ENTER("wolfSSL_EVP_aes_192_cfb1");
    3508         if (EVP_AES_192_CFB1 == NULL)
    3509             wolfSSL_EVP_init();
    35103661        return EVP_AES_192_CFB1;
    35113662    }
     
    35163667    {
    35173668        WOLFSSL_ENTER("wolfSSL_EVP_aes_256_cfb1");
    3518         if (EVP_AES_256_CFB1 == NULL)
    3519             wolfSSL_EVP_init();
    35203669        return EVP_AES_256_CFB1;
    35213670    }
     
    35263675    {
    35273676        WOLFSSL_ENTER("wolfSSL_EVP_aes_128_cfb8");
    3528         if (EVP_AES_128_CFB8 == NULL)
    3529             wolfSSL_EVP_init();
    35303677        return EVP_AES_128_CFB8;
    35313678    }
     
    35363683    {
    35373684        WOLFSSL_ENTER("wolfSSL_EVP_aes_192_cfb8");
    3538         if (EVP_AES_192_CFB8 == NULL)
    3539             wolfSSL_EVP_init();
    35403685        return EVP_AES_192_CFB8;
    35413686    }
     
    35463691    {
    35473692        WOLFSSL_ENTER("wolfSSL_EVP_aes_256_cfb8");
    3548         if (EVP_AES_256_CFB8 == NULL)
    3549             wolfSSL_EVP_init();
    35503693        return EVP_AES_256_CFB8;
    35513694    }
     
    35573700    {
    35583701        WOLFSSL_ENTER("wolfSSL_EVP_aes_128_cfb128");
    3559         if (EVP_AES_128_CFB128 == NULL)
    3560             wolfSSL_EVP_init();
    35613702        return EVP_AES_128_CFB128;
    35623703    }
     
    35673708    {
    35683709        WOLFSSL_ENTER("wolfSSL_EVP_aes_192_cfb128");
    3569         if (EVP_AES_192_CFB128 == NULL)
    3570             wolfSSL_EVP_init();
    35713710        return EVP_AES_192_CFB128;
    35723711    }
     
    35773716    {
    35783717        WOLFSSL_ENTER("wolfSSL_EVP_aes_256_cfb128");
    3579         if (EVP_AES_256_CFB128 == NULL)
    3580             wolfSSL_EVP_init();
    35813718        return EVP_AES_256_CFB128;
    35823719    }
     
    35893726    {
    35903727        WOLFSSL_ENTER("wolfSSL_EVP_aes_128_ofb");
    3591         if (EVP_AES_128_OFB == NULL)
    3592             wolfSSL_EVP_init();
    35933728        return EVP_AES_128_OFB;
    35943729    }
     
    35993734    {
    36003735        WOLFSSL_ENTER("wolfSSL_EVP_aes_192_ofb");
    3601         if (EVP_AES_192_OFB == NULL)
    3602             wolfSSL_EVP_init();
    36033736        return EVP_AES_192_OFB;
    36043737    }
     
    36093742    {
    36103743        WOLFSSL_ENTER("wolfSSL_EVP_aes_256_ofb");
    3611         if (EVP_AES_256_OFB == NULL)
    3612             wolfSSL_EVP_init();
    36133744        return EVP_AES_256_OFB;
    36143745    }
     
    36213752    {
    36223753        WOLFSSL_ENTER("wolfSSL_EVP_aes_128_xts");
    3623         if (EVP_AES_128_XTS == NULL)
    3624             wolfSSL_EVP_init();
    36253754        return EVP_AES_128_XTS;
    36263755    }
     
    36313760    {
    36323761        WOLFSSL_ENTER("wolfSSL_EVP_aes_256_xts");
    3633         if (EVP_AES_256_XTS == NULL)
    3634             wolfSSL_EVP_init();
    36353762        return EVP_AES_256_XTS;
    36363763    }
     
    36433770    {
    36443771        WOLFSSL_ENTER("wolfSSL_EVP_aes_128_gcm");
    3645         if (EVP_AES_128_GCM == NULL)
    3646             wolfSSL_EVP_init();
    36473772        return EVP_AES_128_GCM;
    36483773    }
     
    36533778    {
    36543779        WOLFSSL_ENTER("wolfSSL_EVP_aes_192_gcm");
    3655         if (EVP_AES_192_GCM == NULL)
    3656             wolfSSL_EVP_init();
    36573780        return EVP_AES_192_GCM;
    36583781    }
     
    36633786    {
    36643787        WOLFSSL_ENTER("wolfSSL_EVP_aes_256_gcm");
    3665         if (EVP_AES_256_GCM == NULL)
    3666             wolfSSL_EVP_init();
    36673788        return EVP_AES_256_GCM;
    36683789    }
     
    36703791    #endif /* HAVE_AESGCM */
    36713792
     3793    #ifdef WOLFSSL_AES_COUNTER
    36723794    #ifdef WOLFSSL_AES_128
    36733795    const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_ctr(void)
    36743796    {
    36753797        WOLFSSL_ENTER("wolfSSL_EVP_aes_128_ctr");
    3676         if (EVP_AES_128_CTR == NULL)
    3677             wolfSSL_EVP_init();
    36783798        return EVP_AES_128_CTR;
    36793799    }
     
    36853805    {
    36863806        WOLFSSL_ENTER("wolfSSL_EVP_aes_192_ctr");
    3687         if (EVP_AES_192_CTR == NULL)
    3688             wolfSSL_EVP_init();
    36893807        return EVP_AES_192_CTR;
    36903808    }
     
    36963814    {
    36973815        WOLFSSL_ENTER("wolfSSL_EVP_aes_256_ctr");
    3698         if (EVP_AES_256_CTR == NULL)
    3699             wolfSSL_EVP_init();
    37003816        return EVP_AES_256_CTR;
    37013817    }
    37023818    #endif /* WOLFSSL_AES_256 */
    3703 
     3819    #endif /* WOLFSSL_AES_COUNTER */
     3820
     3821    #ifdef HAVE_AES_ECB
    37043822    #ifdef WOLFSSL_AES_128
    37053823    const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_aes_128_ecb(void)
    37063824    {
    37073825        WOLFSSL_ENTER("wolfSSL_EVP_aes_128_ecb");
    3708         if (EVP_AES_128_ECB == NULL)
    3709             wolfSSL_EVP_init();
    37103826        return EVP_AES_128_ECB;
    37113827    }
     
    37173833    {
    37183834        WOLFSSL_ENTER("wolfSSL_EVP_aes_192_ecb");
    3719         if (EVP_AES_192_ECB == NULL)
    3720             wolfSSL_EVP_init();
    37213835        return EVP_AES_192_ECB;
    37223836    }
     
    37283842    {
    37293843        WOLFSSL_ENTER("wolfSSL_EVP_aes_256_ecb");
    3730         if (EVP_AES_256_ECB == NULL)
    3731             wolfSSL_EVP_init();
    37323844        return EVP_AES_256_ECB;
    37333845    }
    37343846    #endif /* WOLFSSL_AES_256 */
     3847    #endif /* HAVE_AES_ECB */
    37353848    #endif /* NO_AES */
    37363849
     
    37393852    {
    37403853        WOLFSSL_ENTER("wolfSSL_EVP_des_cbc");
    3741         if (EVP_DES_CBC == NULL)
    3742             wolfSSL_EVP_init();
    37433854        return EVP_DES_CBC;
    37443855    }
     
    37473858    {
    37483859        WOLFSSL_ENTER("wolfSSL_EVP_des_ecb");
    3749         if (EVP_DES_ECB == NULL)
    3750             wolfSSL_EVP_init();
    37513860        return EVP_DES_ECB;
    37523861    }
     
    37553864    {
    37563865        WOLFSSL_ENTER("wolfSSL_EVP_des_ede3_cbc");
    3757         if (EVP_DES_EDE3_CBC == NULL)
    3758             wolfSSL_EVP_init();
    37593866        return EVP_DES_EDE3_CBC;
    37603867    }
     
    37633870    {
    37643871        WOLFSSL_ENTER("wolfSSL_EVP_des_ede3_ecb");
    3765         if (EVP_DES_EDE3_ECB == NULL)
    3766             wolfSSL_EVP_init();
    37673872        return EVP_DES_EDE3_ECB;
    37683873    }
     
    37733878    const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_rc4(void)
    37743879    {
    3775         static const char* type = "ARC4";
    37763880        WOLFSSL_ENTER("wolfSSL_EVP_rc4");
    3777         return type;
     3881        return EVP_ARC4;
    37783882    }
    37793883#endif
     
    37833887    {
    37843888        WOLFSSL_ENTER("wolfSSL_EVP_idea_cbc");
    3785         if (EVP_IDEA_CBC == NULL)
    3786             wolfSSL_EVP_init();
    37873889        return EVP_IDEA_CBC;
    37883890    }
     
    37903892    const WOLFSSL_EVP_CIPHER* wolfSSL_EVP_enc_null(void)
    37913893    {
    3792         static const char* type = "NULL";
    37933894        WOLFSSL_ENTER("wolfSSL_EVP_enc_null");
    3794         return type;
     3895        return EVP_NULL;
    37953896    }
    37963897
    37973898    int wolfSSL_EVP_MD_CTX_cleanup(WOLFSSL_EVP_MD_CTX* ctx)
    37983899    {
     3900        int ret = WOLFSSL_SUCCESS;
    37993901        WOLFSSL_ENTER("EVP_MD_CTX_cleanup");
    38003902        if (ctx->pctx != NULL)
    38013903            wolfSSL_EVP_PKEY_CTX_free(ctx->pctx);
    38023904
    3803         if (ctx->macType == NID_hmac) {
     3905        if (ctx->isHMAC) {
    38043906            wc_HmacFree(&ctx->hash.hmac);
    38053907        }
    38063908        else {
    38073909            switch (ctx->macType) {
     3910                case WC_HASH_TYPE_MD5:
    38083911            #ifndef NO_MD5
    3809                 case WC_HASH_TYPE_MD5:
    38103912                    wc_Md5Free((wc_Md5*)&ctx->hash.digest);
     3913            #endif /* !NO_MD5 */
    38113914                    break;
    3812             #endif /* !NO_MD5 */
    3813 
     3915                case WC_HASH_TYPE_SHA:
    38143916            #ifndef NO_SHA
    3815                 case WC_HASH_TYPE_SHA:
    38163917                    wc_ShaFree((wc_Sha*)&ctx->hash.digest);
     3918            #endif /* !NO_SHA */
    38173919                    break;
    3818             #endif /* !NO_SHA */
    3819 
     3920                case WC_HASH_TYPE_SHA224:
    38203921            #ifdef WOLFSSL_SHA224
    3821                 case WC_HASH_TYPE_SHA224:
    38223922                    wc_Sha224Free((wc_Sha224*)&ctx->hash.digest);
     3923            #endif /* WOLFSSL_SHA224 */
    38233924                    break;
    3824             #endif /* WOLFSSL_SHA224 */
    3825 
     3925                case WC_HASH_TYPE_SHA256:
    38263926            #ifndef NO_SHA256
    3827                 case WC_HASH_TYPE_SHA256:
    38283927                    wc_Sha256Free((wc_Sha256*)&ctx->hash.digest);
     3928            #endif /* !NO_SHA256 */
    38293929                    break;
    3830             #endif /* !NO_SHA256 */
    3831 
     3930                case WC_HASH_TYPE_SHA384:
    38323931            #ifdef WOLFSSL_SHA384
    3833                 case WC_HASH_TYPE_SHA384:
    38343932                    wc_Sha384Free((wc_Sha384*)&ctx->hash.digest);
     3933            #endif /* WOLFSSL_SHA384 */
    38353934                    break;
    3836             #endif /* WOLFSSL_SHA384 */
     3935                case WC_HASH_TYPE_SHA512:
    38373936            #ifdef WOLFSSL_SHA512
    3838                 case WC_HASH_TYPE_SHA512:
    38393937                    wc_Sha512Free((wc_Sha512*)&ctx->hash.digest);
     3938            #endif /* WOLFSSL_SHA512 */
    38403939                    break;
    3841             #endif /* WOLFSSL_SHA512 */
    3842         #ifdef WOLFSSL_SHA3
    3843             #ifndef WOLFSSL_NOSHA3_224
    38443940                case WC_HASH_TYPE_SHA3_224:
     3941            #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_224)
    38453942                    wc_Sha3_224_Free((wc_Sha3*)&ctx->hash.digest);
     3943            #endif
    38463944                    break;
     3945                case WC_HASH_TYPE_SHA3_256:
     3946            #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256)
     3947                    wc_Sha3_256_Free((wc_Sha3*)&ctx->hash.digest);
    38473948            #endif
    3848 
    3849             #ifndef WOLFSSL_NOSHA3_256
    3850                 case WC_HASH_TYPE_SHA3_256:
    3851                     wc_Sha3_256_Free((wc_Sha3*)&ctx->hash.digest);
    38523949                    break;
     3950                case WC_HASH_TYPE_SHA3_384:
     3951            #if defined(WOLFSSL_SHA3)
     3952                    wc_Sha3_384_Free((wc_Sha3*)&ctx->hash.digest);
    38533953            #endif
    3854 
    3855                 case WC_HASH_TYPE_SHA3_384:
    3856                     wc_Sha3_384_Free((wc_Sha3*)&ctx->hash.digest);
    38573954                    break;
    3858 
    3859             #ifndef WOLFSSL_NOSHA3_512
    38603955                case WC_HASH_TYPE_SHA3_512:
     3956            #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_512)
    38613957                    wc_Sha3_512_Free((wc_Sha3*)&ctx->hash.digest);
     3958            #endif
    38623959                    break;
    3863             #endif
    3864         #endif
     3960                case WC_HASH_TYPE_NONE:
     3961                case WC_HASH_TYPE_MD2:
     3962                case WC_HASH_TYPE_MD4:
     3963                case WC_HASH_TYPE_MD5_SHA:
     3964                case WC_HASH_TYPE_BLAKE2B:
     3965                case WC_HASH_TYPE_BLAKE2S:
    38653966                default:
    3866                     return WOLFSSL_FAILURE;
     3967                    ret = WOLFSSL_FAILURE;
     3968                    break;
    38673969            }
    38683970        }
    38693971        ForceZero(ctx, sizeof(*ctx));
    38703972        ctx->macType = WC_HASH_TYPE_NONE;
    3871         return 1;
     3973        return ret;
    38723974    }
    38733975
     
    40114113            ctx->cipherType = WOLFSSL_EVP_CIPH_TYPE_INIT;  /* not yet initialized  */
    40124114            ctx->keyLen     = 0;
     4115#ifdef HAVE_AESGCM
     4116            if (ctx->gcmBuffer) {
     4117                XFREE(ctx->gcmBuffer, NULL, DYNAMIC_TYPE_OPENSSL);
     4118                ctx->gcmBuffer = NULL;
     4119            }
     4120            ctx->gcmBufferLen = 0;
     4121            if (ctx->gcmAuthIn) {
     4122                XFREE(ctx->gcmAuthIn, NULL, DYNAMIC_TYPE_OPENSSL);
     4123                ctx->gcmAuthIn = NULL;
     4124            }
     4125            ctx->gcmAuthInSz = 0;
     4126#endif
    40134127        }
    40144128
     
    40814195#endif /* WOLFSSL_ENCRYPTED_KEYS && !NO_PWDBASED */
    40824196
     4197
    40834198#ifndef NO_AES
     4199#if defined(WOLFSSL_AES_128) || defined(WOLFSSL_AES_192) || \
     4200    defined(WOLFSSL_AES_256)
     4201    #define AES_SIZE_ANY
     4202#endif
     4203
     4204#if defined(HAVE_AES_CBC) || defined(WOLFSSL_AES_COUNTER) || \
     4205    defined(HAVE_AES_ECB) || defined(WOLFSSL_AES_CFB) || \
     4206    defined(WOLFSSSL_AES_OFB)
     4207    #define AES_SET_KEY
     4208#endif
     4209
     4210#if defined(AES_SIZE_ANY) && defined(AES_SET_KEY)
    40844211    static int   AesSetKey_ex(Aes* aes, const byte* key, word32 len,
    40854212                              const byte* iv, int dir, int direct)
     
    41044231        return ret;
    41054232    }
    4106 #endif
     4233#endif /* AES_ANY_SIZE && AES_SET_KEY */
     4234#endif /* NO_AES */
    41074235
    41084236    /* return WOLFSSL_SUCCESS on ok, 0 on failure to match API compatibility */
     
    41394267            iv = ctx->iv;
    41404268        }
     4269#endif
     4270#ifdef HAVE_AESGCM
     4271        if (ctx->gcmAuthIn) {
     4272            XFREE(ctx->gcmAuthIn, NULL, DYNAMIC_TYPE_OPENSSL);
     4273            ctx->gcmAuthIn = NULL;
     4274        }
     4275        ctx->gcmAuthInSz = 0;
    41414276#endif
    41424277
     
    42234358        #endif /* WOLFSSL_AES_256 */
    42244359    #endif /* HAVE_AES_CBC */
    4225 #if !defined(_WIN32) && !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
     4360#if (!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
     4361    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
    42264362    #ifdef HAVE_AESGCM
    42274363        #ifdef WOLFSSL_AES_128
     
    42314367            ctx->cipherType = AES_128_GCM_TYPE;
    42324368            ctx->flags     &= ~WOLFSSL_EVP_CIPH_MODE;
    4233             ctx->flags     |= WOLFSSL_EVP_CIPH_GCM_MODE;
     4369            ctx->flags     |= WOLFSSL_EVP_CIPH_GCM_MODE |
     4370                    WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER;
    42344371            ctx->keyLen     = 16;
    42354372            ctx->block_size = AES_BLOCK_SIZE;
     
    42374374            ctx->ivSz       = GCM_NONCE_MID_SZ;
    42384375
    4239             XMEMSET(ctx->authTag, 0, ctx->authTagSz);
    42404376            if (key && wc_AesGcmSetKey(&ctx->cipher.aes, key, ctx->keyLen)) {
    42414377                WOLFSSL_MSG("wc_AesGcmSetKey() failed");
     
    42564392            ctx->cipherType = AES_192_GCM_TYPE;
    42574393            ctx->flags     &= ~WOLFSSL_EVP_CIPH_MODE;
    4258             ctx->flags     |= WOLFSSL_EVP_CIPH_GCM_MODE;
     4394            ctx->flags     |= WOLFSSL_EVP_CIPH_GCM_MODE |
     4395                    WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER;
    42594396            ctx->keyLen     = 24;
    42604397            ctx->block_size = AES_BLOCK_SIZE;
     
    42624399            ctx->ivSz       = GCM_NONCE_MID_SZ;
    42634400
    4264             XMEMSET(ctx->authTag, 0, ctx->authTagSz);
    42654401            if (key && wc_AesGcmSetKey(&ctx->cipher.aes, key, ctx->keyLen)) {
    42664402                WOLFSSL_MSG("wc_AesGcmSetKey() failed");
     
    42814417            ctx->cipherType = AES_256_GCM_TYPE;
    42824418            ctx->flags     &= ~WOLFSSL_EVP_CIPH_MODE;
    4283             ctx->flags     |= WOLFSSL_EVP_CIPH_GCM_MODE;
     4419            ctx->flags     |= WOLFSSL_EVP_CIPH_GCM_MODE |
     4420                    WOLFSSL_EVP_CIPH_FLAG_AEAD_CIPHER;
    42844421            ctx->keyLen     = 32;
    42854422            ctx->block_size = AES_BLOCK_SIZE;
     
    42874424            ctx->ivSz       = GCM_NONCE_MID_SZ;
    42884425
    4289             XMEMSET(ctx->authTag, 0, ctx->authTagSz);
    42904426            if (key && wc_AesGcmSetKey(&ctx->cipher.aes, key, ctx->keyLen)) {
    42914427                WOLFSSL_MSG("wc_AesGcmSetKey() failed");
     
    43014437        #endif /* WOLFSSL_AES_256 */
    43024438    #endif /* HAVE_AESGCM */
    4303 #endif /* !defined(_WIN32) && !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST) */
     4439#endif /*!HAVE_FIPS && !HAVE_SELFTEST ||(HAVE_FIPS_VERSION && HAVE_FIPS_VERSION > 2)*/
    43044440#ifdef WOLFSSL_AES_COUNTER
    43054441        #ifdef WOLFSSL_AES_128
     
    43884524        #endif /* WOLFSSL_AES_256 */
    43894525#endif /* WOLFSSL_AES_COUNTER */
     4526    #ifdef HAVE_AES_ECB
    43904527        #ifdef WOLFSSL_AES_128
    43914528        if (ctx->cipherType == AES_128_ECB_TYPE ||
     
    44454582        }
    44464583        #endif /* WOLFSSL_AES_256 */
     4584    #endif /* HAVE_AES_ECB */
    44474585    #ifdef WOLFSSL_AES_CFB
    44484586        #ifdef WOLFSSL_AES_128
     
    46744812        }
    46754813        #endif /* WOLFSSL_AES_256 */
    4676     #endif /* HAVE_AES_CFB */
     4814    #endif /* WOLFSSL_AES_CFB */
    46774815    #ifdef WOLFSSL_AES_OFB
    46784816        #ifdef WOLFSSL_AES_128
     
    49045042#endif /* NO_DES3 */
    49055043#ifndef NO_RC4
    4906         if (ctx->cipherType == ARC4_TYPE || (type &&
    4907                                      XSTRNCMP(type, "ARC4", 4) == 0)) {
     5044        if (ctx->cipherType == ARC4_TYPE ||
     5045                (type && XSTRNCMP(type, EVP_ARC4, 4) == 0)) {
    49085046            WOLFSSL_MSG("ARC4");
    49095047            ctx->cipherType = ARC4_TYPE;
     
    49415079        }
    49425080#endif /* HAVE_IDEA */
    4943         if (ctx->cipherType == NULL_CIPHER_TYPE || (type &&
    4944                                      XSTRNCMP(type, "NULL", 4) == 0)) {
     5081        if (ctx->cipherType == NULL_CIPHER_TYPE ||
     5082                (type && XSTRNCMP(type, EVP_NULL, 4) == 0)) {
    49455083            WOLFSSL_MSG("NULL cipher");
    49465084            ctx->cipherType = NULL_CIPHER_TYPE;
     
    50175155#endif
    50185156
    5019     /* WOLFSSL_SUCCESS on ok */
     5157    /* Return length on ok */
    50205158    int wolfSSL_EVP_Cipher(WOLFSSL_EVP_CIPHER_CTX* ctx, byte* dst, byte* src,
    50215159                          word32 len)
     
    50305168             ctx->cipherType != AES_256_GCM_TYPE)) {
    50315169            WOLFSSL_MSG("Bad function argument");
    5032             return 0;  /* failure */
     5170            return WOLFSSL_FATAL_ERROR;
    50335171        }
    50345172
    50355173        if (ctx->cipherType == 0xff) {
    50365174            WOLFSSL_MSG("no init");
    5037             return 0;  /* failure */
     5175            return WOLFSSL_FATAL_ERROR;
    50385176        }
    50395177
     
    50505188                else
    50515189                    ret = wc_AesCbcDecrypt(&ctx->cipher.aes, dst, src, len);
     5190                if (ret == 0)
     5191                    ret = (len / AES_BLOCK_SIZE) * AES_BLOCK_SIZE;
    50525192                break;
    50535193#endif /* HAVE_AES_CBC */
     
    50635203                else
    50645204                    ret = wc_AesCfb1Decrypt(&ctx->cipher.aes, dst, src, len);
     5205                if (ret == 0)
     5206                    ret = len;
    50655207                break;
    50665208            case AES_128_CFB8_TYPE:
     
    50725214                else
    50735215                    ret = wc_AesCfb8Decrypt(&ctx->cipher.aes, dst, src, len);
     5216                if (ret == 0)
     5217                    ret = len;
    50745218                break;
    50755219#endif /* !HAVE_SELFTEST && !HAVE_FIPS */
     
    50825226                else
    50835227                    ret = wc_AesCfbDecrypt(&ctx->cipher.aes, dst, src, len);
     5228                if (ret == 0)
     5229                    ret = len;
    50845230                break;
    50855231#endif /* WOLFSSL_AES_CFB */
     
    50935239                else
    50945240                    ret = wc_AesOfbDecrypt(&ctx->cipher.aes, dst, src, len);
     5241                if (ret == 0)
     5242                    ret = len;
    50955243                break;
    50965244#endif /* WOLFSSL_AES_OFB */
     
    51055253                    ret = wc_AesXtsDecrypt(&ctx->cipher.xts, dst, src, len,
    51065254                            ctx->iv, ctx->ivSz);
     5255                if (ret == 0)
     5256                    ret = len;
    51075257                break;
    51085258#endif /* WOLFSSL_AES_XTS */
     
    51135263            case AES_256_GCM_TYPE :
    51145264                WOLFSSL_MSG("AES GCM");
    5115                 if (ctx->enc) {
    5116                     if (dst){
    5117                         /* encrypt confidential data*/
    5118                         ret = wc_AesGcmEncrypt(&ctx->cipher.aes, dst, src, len,
    5119                                   ctx->iv, ctx->ivSz, ctx->authTag, ctx->authTagSz,
    5120                                   NULL, 0);
    5121                     }
    5122                     else {
    5123                         /* authenticated, non-confidential data */
    5124                         ret = wc_AesGcmEncrypt(&ctx->cipher.aes, NULL, NULL, 0,
    5125                                   ctx->iv, ctx->ivSz, ctx->authTag, ctx->authTagSz,
    5126                                   src, len);
    5127                         /* Reset partial authTag error for AAD*/
    5128                         if (ret == AES_GCM_AUTH_E)
    5129                             ret = 0;
    5130                     }
     5265                if (!dst) {
     5266                    ret = wolfSSL_EVP_CipherUpdate_GCM_AAD(ctx, src, len);
    51315267                }
    51325268                else {
    5133                     if (dst){
    5134                         /* decrypt confidential data*/
    5135                         ret = wc_AesGcmDecrypt(&ctx->cipher.aes, dst, src, len,
    5136                                   ctx->iv, ctx->ivSz, ctx->authTag, ctx->authTagSz,
    5137                                   NULL, 0);
    5138                     }
    5139                     else {
    5140                         /* authenticated, non-confidential data*/
    5141                         ret = wc_AesGcmDecrypt(&ctx->cipher.aes, NULL, NULL, 0,
    5142                                   ctx->iv, ctx->ivSz,
    5143                                   ctx->authTag, ctx->authTagSz,
    5144                                   src, len);
    5145                         /* Reset partial authTag error for AAD*/
    5146                         if (ret == AES_GCM_AUTH_E)
    5147                             ret = 0;
    5148                     }
     5269                    if (ctx->enc)
     5270                        ret = wc_AesGcmEncrypt(&ctx->cipher.aes, dst, src,
     5271                                len, ctx->iv, ctx->ivSz, ctx->authTag,
     5272                                ctx->authTagSz, ctx->gcmAuthIn, ctx->gcmAuthInSz);
     5273                    else
     5274                        ret = wc_AesGcmDecrypt(&ctx->cipher.aes, dst, src,
     5275                                len, ctx->iv, ctx->ivSz, ctx->authTag,
     5276                                ctx->authTagSz, ctx->gcmAuthIn, ctx->gcmAuthInSz);
    51495277                }
     5278                if (ret == 0)
     5279                    ret = len;
    51505280                break;
    51515281#endif /* HAVE_AESGCM */
     
    51595289                else
    51605290                    ret = wc_AesEcbDecrypt(&ctx->cipher.aes, dst, src, len);
     5291                if (ret == 0)
     5292                    ret = (len / AES_BLOCK_SIZE) * AES_BLOCK_SIZE;
    51615293                break;
    51625294#endif
     
    51655297            case AES_192_CTR_TYPE :
    51665298            case AES_256_CTR_TYPE :
    5167                     WOLFSSL_MSG("AES CTR");
    5168                     ret = wc_AesCtrEncrypt(&ctx->cipher.aes, dst, src, len);
     5299                WOLFSSL_MSG("AES CTR");
     5300                ret = wc_AesCtrEncrypt(&ctx->cipher.aes, dst, src, len);
     5301                if (ret == 0)
     5302                    ret = len;
    51695303                break;
    51705304#endif /* WOLFSSL_AES_COUNTER */
     
    51785312                else
    51795313                    wc_Des_CbcDecrypt(&ctx->cipher.des, dst, src, len);
     5314                if (ret == 0)
     5315                    ret = (len / DES_BLOCK_SIZE) * DES_BLOCK_SIZE;
    51805316                break;
    51815317            case DES_EDE3_CBC_TYPE :
     
    51855321                else
    51865322                    ret = wc_Des3_CbcDecrypt(&ctx->cipher.des3, dst, src, len);
     5323                if (ret == 0)
     5324                    ret = (len / DES_BLOCK_SIZE) * DES_BLOCK_SIZE;
    51875325                break;
    51885326#ifdef WOLFSSL_DES_ECB
     
    51905328                WOLFSSL_MSG("DES ECB");
    51915329                ret = wc_Des_EcbEncrypt(&ctx->cipher.des, dst, src, len);
     5330                if (ret == 0)
     5331                    ret = (len / DES_BLOCK_SIZE) * DES_BLOCK_SIZE;
    51925332                break;
    51935333            case DES_EDE3_ECB_TYPE :
    51945334                WOLFSSL_MSG("DES3 ECB");
    51955335                ret = wc_Des3_EcbEncrypt(&ctx->cipher.des3, dst, src, len);
     5336                if (ret == 0)
     5337                    ret = (len / DES_BLOCK_SIZE) * DES_BLOCK_SIZE;
    51965338                break;
    51975339#endif
     
    52025344                WOLFSSL_MSG("ARC4");
    52035345                wc_Arc4Process(&ctx->cipher.arc4, dst, src, len);
     5346                if (ret == 0)
     5347                    ret = len;
    52045348                break;
    52055349#endif
     
    52125356                else
    52135357                    wc_IdeaCbcDecrypt(&ctx->cipher.idea, dst, src, len);
     5358                if (ret == 0)
     5359                    ret = (len / IDEA_BLOCK_SIZE) * IDEA_BLOCK_SIZE;
    52145360                break;
    52155361#endif
     
    52175363                WOLFSSL_MSG("NULL CIPHER");
    52185364                XMEMCPY(dst, src, len);
     5365                ret = len;
    52195366                break;
    52205367
    52215368            default: {
    52225369                WOLFSSL_MSG("bad type");
    5223                 return 0;  /* failure */
    5224             }
    5225         }
    5226 
    5227         if (ret != 0) {
     5370                return WOLFSSL_FATAL_ERROR;
     5371            }
     5372        }
     5373
     5374        if (ret < 0) {
    52285375            WOLFSSL_MSG("wolfSSL_EVP_Cipher failure");
    5229             return 0;  /* failure */
     5376            return WOLFSSL_FATAL_ERROR;
    52305377        }
    52315378
    52325379        if (wolfSSL_StoreExternalIV(ctx) != WOLFSSL_SUCCESS) {
    5233             return WOLFSSL_FAILURE;
     5380            return WOLFSSL_FATAL_ERROR;
    52345381        }
    52355382
    52365383        WOLFSSL_MSG("wolfSSL_EVP_Cipher success");
    5237         return WOLFSSL_SUCCESS;  /* success */
     5384        return ret;
    52385385    }
    52395386
     
    52465393        WOLFSSL_ENTER("EVP_DigestInit");
    52475394
    5248         if (ctx == NULL || md == NULL) {
     5395        if (ctx == NULL) {
    52495396            return BAD_FUNC_ARG;
    52505397        }
     
    52605407        /* Set to 0 if no match */
    52615408        ctx->macType = wolfSSL_EVP_md2macType(md);
    5262         if (XSTRNCMP(md, "SHA256", 6) == 0) {
     5409        if (md == NULL) {
     5410             XMEMSET(&ctx->hash.digest, 0, sizeof(WOLFSSL_Hasher));
     5411        }
     5412        else if (XSTRNCMP(md, "SHA256", 6) == 0) {
    52635413             ret = wolfSSL_SHA256_Init(&(ctx->hash.digest.sha256));
    52645414        }
     
    53265476                                size_t sz)
    53275477    {
    5328         int macType;
     5478        int ret = WOLFSSL_FAILURE;
     5479        enum wc_HashType macType;
    53295480
    53305481        WOLFSSL_ENTER("EVP_DigestUpdate");
     
    53325483        macType = wolfSSL_EVP_md2macType(EVP_MD_CTX_md(ctx));
    53335484        switch (macType) {
    5334 #ifndef NO_MD4
    53355485            case WC_HASH_TYPE_MD4:
     5486        #ifndef NO_MD4
    53365487                wolfSSL_MD4_Update((MD4_CTX*)&ctx->hash, data,
    53375488                                  (unsigned long)sz);
     5489                ret = WOLFSSL_SUCCESS;
     5490        #endif
    53385491                break;
    5339 #endif
    5340 #ifndef NO_MD5
    53415492            case WC_HASH_TYPE_MD5:
    5342                 wolfSSL_MD5_Update((MD5_CTX*)&ctx->hash, data,
     5493        #ifndef NO_MD5
     5494                ret = wolfSSL_MD5_Update((MD5_CTX*)&ctx->hash, data,
    53435495                                  (unsigned long)sz);
     5496        #endif
    53445497                break;
    5345 #endif
    5346 #ifndef NO_SHA
    53475498            case WC_HASH_TYPE_SHA:
    5348                 wolfSSL_SHA_Update((SHA_CTX*)&ctx->hash, data,
     5499        #ifndef NO_SHA
     5500                ret = wolfSSL_SHA_Update((SHA_CTX*)&ctx->hash, data,
    53495501                                  (unsigned long)sz);
     5502        #endif
    53505503                break;
    5351 #endif
    5352 #ifdef WOLFSSL_SHA224
    53535504            case WC_HASH_TYPE_SHA224:
    5354                 wolfSSL_SHA224_Update((SHA224_CTX*)&ctx->hash, data,
     5505        #ifdef WOLFSSL_SHA224
     5506                ret = wolfSSL_SHA224_Update((SHA224_CTX*)&ctx->hash, data,
    53555507                                     (unsigned long)sz);
     5508        #endif
    53565509                break;
    5357 #endif
    5358 #ifndef NO_SHA256
    53595510            case WC_HASH_TYPE_SHA256:
    5360                 wolfSSL_SHA256_Update((SHA256_CTX*)&ctx->hash, data,
     5511        #ifndef NO_SHA256
     5512                ret = wolfSSL_SHA256_Update((SHA256_CTX*)&ctx->hash, data,
    53615513                                     (unsigned long)sz);
     5514        #endif /* !NO_SHA256 */
    53625515                break;
    5363 #endif /* !NO_SHA256 */
    5364 #ifdef WOLFSSL_SHA384
    53655516            case WC_HASH_TYPE_SHA384:
    5366                 wolfSSL_SHA384_Update((SHA384_CTX*)&ctx->hash, data,
     5517        #ifdef WOLFSSL_SHA384
     5518                ret = wolfSSL_SHA384_Update((SHA384_CTX*)&ctx->hash, data,
    53675519                                     (unsigned long)sz);
     5520        #endif
    53685521                break;
    5369 #endif
    5370 #ifdef WOLFSSL_SHA512
    53715522            case WC_HASH_TYPE_SHA512:
    5372                 wolfSSL_SHA512_Update((SHA512_CTX*)&ctx->hash, data,
     5523        #ifdef WOLFSSL_SHA512
     5524                ret = wolfSSL_SHA512_Update((SHA512_CTX*)&ctx->hash, data,
    53735525                                     (unsigned long)sz);
     5526        #endif /* WOLFSSL_SHA512 */
    53745527                break;
    5375 #endif /* WOLFSSL_SHA512 */
    5376     #ifdef WOLFSSL_SHA3
    5377         #ifndef WOLFSSL_NOSHA3_224
    53785528            case WC_HASH_TYPE_SHA3_224:
    5379                 wolfSSL_SHA3_224_Update((SHA3_224_CTX*)&ctx->hash, data,
     5529        #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_224)
     5530                ret = wolfSSL_SHA3_224_Update((SHA3_224_CTX*)&ctx->hash, data,
    53805531                                     (unsigned long)sz);
     5532        #endif
    53815533                break;
     5534            case WC_HASH_TYPE_SHA3_256:
     5535        #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256)
     5536                ret = wolfSSL_SHA3_256_Update((SHA3_256_CTX*)&ctx->hash, data,
     5537                                     (unsigned long)sz);
    53825538        #endif
    5383         #ifndef WOLFSSL_NOSHA3_256
    5384             case WC_HASH_TYPE_SHA3_256:
    5385                 wolfSSL_SHA3_256_Update((SHA3_256_CTX*)&ctx->hash, data,
     5539                break;
     5540            case WC_HASH_TYPE_SHA3_384:
     5541        #if defined(WOLFSSL_SHA3)
     5542                ret = wolfSSL_SHA3_384_Update((SHA3_384_CTX*)&ctx->hash, data,
    53865543                                     (unsigned long)sz);
     5544        #endif
    53875545                break;
     5546            case WC_HASH_TYPE_SHA3_512:
     5547        #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_512)
     5548                ret = wolfSSL_SHA3_512_Update((SHA3_512_CTX*)&ctx->hash, data,
     5549                                     (unsigned long)sz);
    53885550        #endif
    5389             case WC_HASH_TYPE_SHA3_384:
    5390                 wolfSSL_SHA3_384_Update((SHA3_384_CTX*)&ctx->hash, data,
    5391                                      (unsigned long)sz);
    53925551                break;
    5393         #ifndef WOLFSSL_NOSHA3_512
    5394             case WC_HASH_TYPE_SHA3_512:
    5395                 wolfSSL_SHA3_512_Update((SHA3_512_CTX*)&ctx->hash, data,
    5396                                      (unsigned long)sz);
    5397                 break;
    5398         #endif
    5399     #endif
     5552            case WC_HASH_TYPE_NONE:
     5553            case WC_HASH_TYPE_MD2:
     5554            case WC_HASH_TYPE_MD5_SHA:
     5555            case WC_HASH_TYPE_BLAKE2B:
     5556            case WC_HASH_TYPE_BLAKE2S:
    54005557            default:
    54015558                return WOLFSSL_FAILURE;
    54025559        }
    54035560
    5404         return WOLFSSL_SUCCESS;
     5561        return ret;
    54055562    }
    54065563
     
    54095566                               unsigned int* s)
    54105567    {
    5411         int macType;
     5568        int ret = WOLFSSL_FAILURE;
     5569        enum wc_HashType macType;
    54125570
    54135571        WOLFSSL_ENTER("EVP_DigestFinal");
    54145572        macType = wolfSSL_EVP_md2macType(EVP_MD_CTX_md(ctx));
    54155573        switch (macType) {
    5416 #ifndef NO_MD4
    54175574            case WC_HASH_TYPE_MD4:
     5575        #ifndef NO_MD4
    54185576                wolfSSL_MD4_Final(md, (MD4_CTX*)&ctx->hash);
    54195577                if (s) *s = MD4_DIGEST_SIZE;
     5578                ret = WOLFSSL_SUCCESS;
     5579        #endif
    54205580                break;
    5421 #endif
    5422 #ifndef NO_MD5
    54235581            case WC_HASH_TYPE_MD5:
    5424                 wolfSSL_MD5_Final(md, (MD5_CTX*)&ctx->hash);
     5582        #ifndef NO_MD5
     5583                ret = wolfSSL_MD5_Final(md, (MD5_CTX*)&ctx->hash);
    54255584                if (s) *s = WC_MD5_DIGEST_SIZE;
     5585        #endif
    54265586                break;
    5427 #endif
    5428 #ifndef NO_SHA
    54295587            case WC_HASH_TYPE_SHA:
    5430                 wolfSSL_SHA_Final(md, (SHA_CTX*)&ctx->hash);
     5588        #ifndef NO_SHA
     5589                ret = wolfSSL_SHA_Final(md, (SHA_CTX*)&ctx->hash);
    54315590                if (s) *s = WC_SHA_DIGEST_SIZE;
     5591        #endif
    54325592                break;
    5433 #endif
    5434 #ifdef WOLFSSL_SHA224
    54355593            case WC_HASH_TYPE_SHA224:
    5436                 wolfSSL_SHA224_Final(md, (SHA224_CTX*)&ctx->hash);
     5594        #ifdef WOLFSSL_SHA224
     5595                ret = wolfSSL_SHA224_Final(md, (SHA224_CTX*)&ctx->hash);
    54375596                if (s) *s = WC_SHA224_DIGEST_SIZE;
     5597        #endif
    54385598                break;
    5439 #endif
    5440 #ifndef NO_SHA256
    54415599            case WC_HASH_TYPE_SHA256:
    5442                 wolfSSL_SHA256_Final(md, (SHA256_CTX*)&ctx->hash);
     5600        #ifndef NO_SHA256
     5601                ret = wolfSSL_SHA256_Final(md, (SHA256_CTX*)&ctx->hash);
    54435602                if (s) *s = WC_SHA256_DIGEST_SIZE;
     5603        #endif /* !NO_SHA256 */
    54445604                break;
    5445 #endif /* !NO_SHA256 */
    5446 #ifdef WOLFSSL_SHA384
    54475605            case WC_HASH_TYPE_SHA384:
    5448                 wolfSSL_SHA384_Final(md, (SHA384_CTX*)&ctx->hash);
     5606        #ifdef WOLFSSL_SHA384
     5607                ret = wolfSSL_SHA384_Final(md, (SHA384_CTX*)&ctx->hash);
    54495608                if (s) *s = WC_SHA384_DIGEST_SIZE;
     5609        #endif
    54505610                break;
    5451 #endif
    5452 #ifdef WOLFSSL_SHA512
    54535611            case WC_HASH_TYPE_SHA512:
    5454                 wolfSSL_SHA512_Final(md, (SHA512_CTX*)&ctx->hash);
     5612        #ifdef WOLFSSL_SHA512
     5613                ret = wolfSSL_SHA512_Final(md, (SHA512_CTX*)&ctx->hash);
    54555614                if (s) *s = WC_SHA512_DIGEST_SIZE;
     5615        #endif /* WOLFSSL_SHA512 */
    54565616                break;
    5457 #endif /* WOLFSSL_SHA512 */
    5458     #ifdef WOLFSSL_SHA3
    5459         #ifndef WOLFSSL_NOSHA3_224
    54605617            case WC_HASH_TYPE_SHA3_224:
    5461                 wolfSSL_SHA3_224_Final(md, (SHA3_224_CTX*)&ctx->hash);
     5618        #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_224)
     5619                ret = wolfSSL_SHA3_224_Final(md, (SHA3_224_CTX*)&ctx->hash);
    54625620                if (s) *s = WC_SHA3_224_DIGEST_SIZE;
     5621        #endif
    54635622                break;
     5623            case WC_HASH_TYPE_SHA3_256:
     5624        #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256)
     5625                ret = wolfSSL_SHA3_256_Final(md, (SHA3_256_CTX*)&ctx->hash);
     5626                if (s) *s = WC_SHA3_256_DIGEST_SIZE;
    54645627        #endif
    5465         #ifndef WOLFSSL_NOSHA3_256
    5466             case WC_HASH_TYPE_SHA3_256:
    5467                 wolfSSL_SHA3_256_Final(md, (SHA3_256_CTX*)&ctx->hash);
    5468                 if (s) *s = WC_SHA3_256_DIGEST_SIZE;
    54695628                break;
     5629            case WC_HASH_TYPE_SHA3_384:
     5630        #if defined(WOLFSSL_SHA3)
     5631                ret = wolfSSL_SHA3_384_Final(md, (SHA3_384_CTX*)&ctx->hash);
     5632                if (s) *s = WC_SHA3_384_DIGEST_SIZE;
    54705633        #endif
    5471             case WC_HASH_TYPE_SHA3_384:
    5472                 wolfSSL_SHA3_384_Final(md, (SHA3_384_CTX*)&ctx->hash);
    5473                 if (s) *s = WC_SHA3_384_DIGEST_SIZE;
    54745634                break;
    5475         #ifndef WOLFSSL_NOSHA3_512
    54765635            case WC_HASH_TYPE_SHA3_512:
    5477                 wolfSSL_SHA3_512_Final(md, (SHA3_512_CTX*)&ctx->hash);
     5636        #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_512)
     5637                ret = wolfSSL_SHA3_512_Final(md, (SHA3_512_CTX*)&ctx->hash);
    54785638                if (s) *s = WC_SHA3_512_DIGEST_SIZE;
     5639        #endif
    54795640                break;
    5480         #endif
    5481     #endif
     5641            case WC_HASH_TYPE_NONE:
     5642            case WC_HASH_TYPE_MD2:
     5643            case WC_HASH_TYPE_MD5_SHA:
     5644            case WC_HASH_TYPE_BLAKE2B:
     5645            case WC_HASH_TYPE_BLAKE2S:
    54825646            default:
    54835647                return WOLFSSL_FAILURE;
    54845648        }
    54855649
    5486         return WOLFSSL_SUCCESS;
     5650        return ret;
    54875651    }
    54885652
     
    55125676        case NID_sha1:
    55135677            return wolfSSL_EVP_sha1();
     5678#endif
     5679#ifndef NO_SHA256
     5680        case NID_sha256:
     5681            return wolfSSL_EVP_sha256();
    55145682#endif
    55155683        default:
     
    55815749        return WOLFSSL_FAILURE;
    55825750
     5751    if (wolfSSL_RSA_up_ref(key) != WOLFSSL_SUCCESS) {
     5752        WOLFSSL_MSG("wolfSSL_RSA_up_ref failed");
     5753        return WOLFSSL_FAILURE;
     5754    }
    55835755    if (pkey->rsa != NULL && pkey->ownRsa == 1) {
    55845756        wolfSSL_RSA_free(pkey->rsa);
    55855757    }
    55865758    pkey->rsa    = key;
    5587     pkey->ownRsa = 0; /* pkey does not own RSA */
     5759    pkey->ownRsa = 1; /* pkey does not own RSA but needs to call free on it */
    55885760    pkey->type   = EVP_PKEY_RSA;
    55895761    if (key->inSet == 0) {
     
    57185890
    57195891    return WOLFSSL_SUCCESS;
     5892}
     5893
     5894WOLFSSL_DSA* wolfSSL_EVP_PKEY_get0_DSA(struct WOLFSSL_EVP_PKEY *pkey)
     5895{
     5896    if (!pkey) {
     5897        return NULL;
     5898    }
     5899    return pkey->dsa;
    57205900}
    57215901
     
    58145994#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
    58155995#if !defined(NO_DH) && !defined(NO_FILESYSTEM)
     5996#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION>2))
    58165997/* with set1 functions the pkey struct does not own the DH structure
    58175998 * Build the following DH Key format from the passed in WOLFSSL_DH
     
    58926073    return WOLFSSL_SUCCESS;
    58936074}
     6075#endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
    58946076
    58956077WOLFSSL_DH* wolfSSL_EVP_PKEY_get0_DH(WOLFSSL_EVP_PKEY* key)
     
    59016083}
    59026084
     6085#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION>2))
    59036086WOLFSSL_DH* wolfSSL_EVP_PKEY_get1_DH(WOLFSSL_EVP_PKEY* key)
    59046087{
     
    59346117    return local;
    59356118}
     6119#endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
    59366120#endif /* NO_DH && NO_FILESYSTEM */
    59376121
     
    59596143            break;
    59606144    #endif
    5961     #ifdef NO_DH
     6145    #ifndef NO_DH
    59626146         case EVP_PKEY_DH:
    59636147            ret = wolfSSL_EVP_PKEY_assign_DH(pkey, (WOLFSSL_DH*)key);
     
    59756159#if defined(HAVE_ECC)
    59766160/* try and populate public pkey_sz and pkey.ptr */
    5977 static void ECC_populate_EVP_PKEY(EVP_PKEY* pkey, ecc_key* ecc)
    5978 {
    5979     int ret;
     6161static int ECC_populate_EVP_PKEY(EVP_PKEY* pkey, ecc_key* ecc)
     6162{
     6163    word32 derSz = 0;
    59806164    if (!pkey || !ecc)
    5981         return;
    5982     if ((ret = wc_EccPublicKeyDerSize(ecc, 1)) > 0) {
    5983         int derSz = ret;
    5984         char* derBuf = (char*)XMALLOC(derSz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     6165        return WOLFSSL_FAILURE;
     6166    if (wc_EccKeyToPKCS8(ecc, NULL, &derSz) == LENGTH_ONLY_E) {
     6167        byte* derBuf = (byte*)XMALLOC(derSz, NULL, DYNAMIC_TYPE_OPENSSL);
    59856168        if (derBuf) {
    5986             ret = wc_EccPublicKeyToDer(ecc, (byte*)derBuf, derSz, 1);
    5987             if (ret >= 0) {
     6169            if (wc_EccKeyToPKCS8(ecc, derBuf, &derSz) >= 0) {
    59886170                if (pkey->pkey.ptr) {
    59896171                    XFREE(pkey->pkey.ptr, NULL, DYNAMIC_TYPE_OPENSSL);
    59906172                }
    5991                 pkey->pkey_sz = ret;
    5992                 pkey->pkey.ptr = derBuf;
    5993             }
    5994             else { /* failure - okay to ignore */
    5995                 XFREE(derBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     6173                pkey->pkey_sz = (int)derSz;
     6174                pkey->pkey.ptr = (char*)derBuf;
     6175                return WOLFSSL_SUCCESS;
     6176            }
     6177            else {
     6178                XFREE(derBuf, NULL, DYNAMIC_TYPE_OPENSSL);
    59966179                derBuf = NULL;
    59976180            }
    59986181        }
    59996182    }
     6183    return WOLFSSL_FAILURE;
    60006184}
    60016185
     
    60296213    pkey->ownEcc = 0; /* pkey does not own EC key */
    60306214    pkey->type   = EVP_PKEY_EC;
    6031     ECC_populate_EVP_PKEY(pkey, (ecc_key*)key->internal);
    6032     return WOLFSSL_SUCCESS;
     6215    return ECC_populate_EVP_PKEY(pkey, (ecc_key*)key->internal);
    60336216#else
    60346217    (void)pkey;
     
    60666249
    60676250    /* try and populate public pkey_sz and pkey.ptr */
    6068     ECC_populate_EVP_PKEY(pkey, (ecc_key*)key->internal);
    6069 
    6070     return WOLFSSL_SUCCESS;
     6251    return ECC_populate_EVP_PKEY(pkey, (ecc_key*)key->internal);
    60716252}
    60726253#endif /* HAVE_ECC */
     
    61806361            return AES_BLOCK_SIZE;
    61816362#endif
     6363#if (!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
     6364    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
    61826365#ifdef HAVE_AESGCM
    61836366        case AES_128_GCM_TYPE :
     
    61876370            return GCM_NONCE_MID_SZ;
    61886371#endif
     6372#endif /* (HAVE_FIPS && !HAVE_SELFTEST) || HAVE_FIPS_VERSION > 2 */
    61896373#ifdef WOLFSSL_AES_COUNTER
    61906374        case AES_128_CTR_TYPE :
     
    62656449#ifdef HAVE_AES_CBC
    62666450    #ifdef WOLFSSL_AES_128
    6267     if (EVP_AES_128_CBC && XSTRNCMP(name, EVP_AES_128_CBC, XSTRLEN(EVP_AES_128_CBC)) == 0)
     6451    if (XSTRNCMP(name, EVP_AES_128_CBC, XSTRLEN(EVP_AES_128_CBC)) == 0)
    62686452        return AES_BLOCK_SIZE;
    62696453    #endif
    62706454    #ifdef WOLFSSL_AES_192
    6271     if (EVP_AES_192_CBC && XSTRNCMP(name, EVP_AES_192_CBC, XSTRLEN(EVP_AES_192_CBC)) == 0)
     6455    if (XSTRNCMP(name, EVP_AES_192_CBC, XSTRLEN(EVP_AES_192_CBC)) == 0)
    62726456        return AES_BLOCK_SIZE;
    62736457    #endif
    62746458    #ifdef WOLFSSL_AES_256
    6275     if (EVP_AES_256_CBC && XSTRNCMP(name, EVP_AES_256_CBC, XSTRLEN(EVP_AES_256_CBC)) == 0)
     6459    if (XSTRNCMP(name, EVP_AES_256_CBC, XSTRLEN(EVP_AES_256_CBC)) == 0)
    62766460        return AES_BLOCK_SIZE;
    62776461    #endif
    62786462#endif /* HAVE_AES_CBC */
     6463#if (!defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)) || \
     6464    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
    62796465#ifdef HAVE_AESGCM
    62806466    #ifdef WOLFSSL_AES_128
    6281     if (EVP_AES_128_GCM && XSTRNCMP(name, EVP_AES_128_GCM, XSTRLEN(EVP_AES_128_GCM)) == 0)
     6467    if (XSTRNCMP(name, EVP_AES_128_GCM, XSTRLEN(EVP_AES_128_GCM)) == 0)
    62826468        return GCM_NONCE_MID_SZ;
    62836469    #endif
    62846470    #ifdef WOLFSSL_AES_192
    6285     if (EVP_AES_192_GCM && XSTRNCMP(name, EVP_AES_192_GCM, XSTRLEN(EVP_AES_192_GCM)) == 0)
     6471    if (XSTRNCMP(name, EVP_AES_192_GCM, XSTRLEN(EVP_AES_192_GCM)) == 0)
    62866472        return GCM_NONCE_MID_SZ;
    62876473    #endif
    62886474    #ifdef WOLFSSL_AES_256
    6289     if (EVP_AES_256_GCM && XSTRNCMP(name, EVP_AES_256_GCM, XSTRLEN(EVP_AES_256_GCM)) == 0)
     6475    if (XSTRNCMP(name, EVP_AES_256_GCM, XSTRLEN(EVP_AES_256_GCM)) == 0)
    62906476        return GCM_NONCE_MID_SZ;
    62916477    #endif
    62926478#endif /* HAVE_AESGCM */
     6479#endif /* (HAVE_FIPS && !HAVE_SELFTEST) || HAVE_FIPS_VERSION > 2 */
    62936480#ifdef WOLFSSL_AES_COUNTER
    62946481    #ifdef WOLFSSL_AES_128
    6295     if (EVP_AES_128_CTR && XSTRNCMP(name, EVP_AES_128_CTR, XSTRLEN(EVP_AES_128_CTR)) == 0)
     6482    if (XSTRNCMP(name, EVP_AES_128_CTR, XSTRLEN(EVP_AES_128_CTR)) == 0)
    62966483        return AES_BLOCK_SIZE;
    62976484    #endif
    62986485    #ifdef WOLFSSL_AES_192
    6299     if (EVP_AES_192_CTR && XSTRNCMP(name, EVP_AES_192_CTR, XSTRLEN(EVP_AES_192_CTR)) == 0)
     6486    if (XSTRNCMP(name, EVP_AES_192_CTR, XSTRLEN(EVP_AES_192_CTR)) == 0)
    63006487        return AES_BLOCK_SIZE;
    63016488    #endif
    63026489    #ifdef WOLFSSL_AES_256
    6303     if (EVP_AES_256_CTR && XSTRNCMP(name, EVP_AES_256_CTR, XSTRLEN(EVP_AES_256_CTR)) == 0)
     6490    if (XSTRNCMP(name, EVP_AES_256_CTR, XSTRLEN(EVP_AES_256_CTR)) == 0)
    63046491        return AES_BLOCK_SIZE;
    63056492    #endif
     
    63076494#ifdef WOLFSSL_AES_XTS
    63086495    #ifdef WOLFSSL_AES_128
    6309     if (EVP_AES_128_XTS && XSTRNCMP(name, EVP_AES_128_XTS, XSTRLEN(EVP_AES_128_XTS)) == 0)
     6496    if (XSTRNCMP(name, EVP_AES_128_XTS, XSTRLEN(EVP_AES_128_XTS)) == 0)
    63106497        return AES_BLOCK_SIZE;
    63116498    #endif /* WOLFSSL_AES_128 */
    63126499
    63136500    #ifdef WOLFSSL_AES_256
    6314     if (EVP_AES_256_XTS && XSTRNCMP(name, EVP_AES_256_XTS, XSTRLEN(EVP_AES_256_XTS)) == 0)
     6501    if (XSTRNCMP(name, EVP_AES_256_XTS, XSTRLEN(EVP_AES_256_XTS)) == 0)
    63156502        return AES_BLOCK_SIZE;
    63166503    #endif /* WOLFSSL_AES_256 */
     
    63206507
    63216508#ifndef NO_DES3
    6322     if ((EVP_DES_CBC && XSTRNCMP(name, EVP_DES_CBC, XSTRLEN(EVP_DES_CBC)) == 0) ||
    6323            (EVP_DES_EDE3_CBC && XSTRNCMP(name, EVP_DES_EDE3_CBC, XSTRLEN(EVP_DES_EDE3_CBC)) == 0)) {
     6509    if ((XSTRNCMP(name, EVP_DES_CBC, XSTRLEN(EVP_DES_CBC)) == 0) ||
     6510           (XSTRNCMP(name, EVP_DES_EDE3_CBC, XSTRLEN(EVP_DES_EDE3_CBC)) == 0)) {
    63246511        return DES_BLOCK_SIZE;
    63256512    }
     
    63276514
    63286515#ifdef HAVE_IDEA
    6329     if (EVP_IDEA_CBC && XSTRNCMP(name, EVP_IDEA_CBC, XSTRLEN(EVP_IDEA_CBC)) == 0)
     6516    if (XSTRNCMP(name, EVP_IDEA_CBC, XSTRLEN(EVP_IDEA_CBC)) == 0)
    63306517        return IDEA_BLOCK_SIZE;
    63316518#endif
     
    63826569
    63836570
    6384 int wolfSSL_EVP_PKEY_id(const EVP_PKEY *pkey)
     6571int wolfSSL_EVP_PKEY_id(const WOLFSSL_EVP_PKEY *pkey)
    63856572{
    63866573    if (pkey != NULL)
     
    63906577
    63916578
    6392 int wolfSSL_EVP_PKEY_base_id(const EVP_PKEY *pkey)
     6579int wolfSSL_EVP_PKEY_base_id(const WOLFSSL_EVP_PKEY *pkey)
    63936580{
    63946581    if (pkey == NULL)
     
    63976584}
    63986585
     6586int wolfSSL_EVP_PKEY_get_default_digest_nid(WOLFSSL_EVP_PKEY *pkey, int *pnid)
     6587{
     6588    WOLFSSL_ENTER("wolfSSL_EVP_PKEY_get_default_digest_nid");
     6589
     6590    if (!pkey || !pnid) {
     6591        WOLFSSL_MSG("Bad parameter");
     6592        return WOLFSSL_FAILURE;
     6593    }
     6594
     6595    switch (pkey->type) {
     6596    case EVP_PKEY_HMAC:
     6597#ifndef NO_DSA
     6598    case EVP_PKEY_DSA:
     6599#endif
     6600#ifndef NO_RSA
     6601    case EVP_PKEY_RSA:
     6602#endif
     6603#ifdef HAVE_ECC
     6604    case EVP_PKEY_EC:
     6605#endif
     6606        *pnid = NID_sha256;
     6607        return WOLFSSL_SUCCESS;
     6608    default:
     6609        return WOLFSSL_FAILURE;
     6610    }
     6611}
    63996612
    64006613/* increments ref count of WOLFSSL_EVP_PKEY. Return 1 on success, 0 on error */
     
    64086621        wc_UnLockMutex(&pkey->refMutex);
    64096622
    6410         return 1;
    6411     }
    6412 
    6413     return 0;
     6623        return WOLFSSL_SUCCESS;
     6624    }
     6625
     6626    return WOLFSSL_FAILURE;
    64146627}
    64156628
     
    64796692#endif /* OPENSSL_EXTRA */
    64806693
    6481 #if defined(OPENSSL_EXTRA_X509_SMALL)
     6694#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    64826695/* Subset of OPENSSL_EXTRA for PKEY operations PKEY free is needed by the
    64836696 * subset of X509 API */
     
    65036716        ret = wc_InitRng(&pkey->rng);
    65046717#endif
     6718        pkey->references = 1;
     6719        wc_InitMutex(&pkey->refMutex); /* init of mutex needs to come before
     6720                                        * wolfSSL_EVP_PKEY_free */
    65056721        if (ret != 0){
    65066722            wolfSSL_EVP_PKEY_free(pkey);
     
    65086724            return NULL;
    65096725        }
    6510         pkey->references = 1;
    6511         wc_InitMutex(&pkey->refMutex);
    65126726    }
    65136727    else {
     
    65916805}
    65926806
    6593 #endif /* OPENSSL_EXTRA_X509_SMALL */
     6807#if !defined(NO_PWDBASED)
     6808int wolfSSL_EVP_get_hashinfo(const WOLFSSL_EVP_MD* evp,
     6809    int* pHash, int* pHashSz)
     6810{
     6811    enum wc_HashType hash = WC_HASH_TYPE_NONE;
     6812    int hashSz;
     6813
     6814    if (XSTRLEN(evp) < 3) {
     6815        /* do not try comparing strings if size is too small */
     6816        return WOLFSSL_FAILURE;
     6817    }
     6818
     6819    if (XSTRNCMP("SHA", evp, 3) == 0) {
     6820        if (XSTRLEN(evp) > 3) {
     6821        #ifndef NO_SHA256
     6822            if (XSTRNCMP("SHA256", evp, 6) == 0) {
     6823                hash = WC_HASH_TYPE_SHA256;
     6824            }
     6825            else
     6826        #endif
     6827        #ifdef WOLFSSL_SHA384
     6828            if (XSTRNCMP("SHA384", evp, 6) == 0) {
     6829                hash = WC_HASH_TYPE_SHA384;
     6830            }
     6831            else
     6832        #endif
     6833        #ifdef WOLFSSL_SHA512
     6834            if (XSTRNCMP("SHA512", evp, 6) == 0) {
     6835                hash = WC_HASH_TYPE_SHA512;
     6836            }
     6837            else
     6838        #endif
     6839            if (XSTRNCMP("SHA1", evp, 4) == 0) {
     6840                hash = WC_HASH_TYPE_SHA;
     6841            }
     6842            else {
     6843                WOLFSSL_MSG("Unknown SHA hash");
     6844            }
     6845        }
     6846        else {
     6847            hash = WC_HASH_TYPE_SHA;
     6848        }
     6849    }
     6850#ifdef WOLFSSL_MD2
     6851    else if (XSTRNCMP("MD2", evp, 3) == 0) {
     6852        hash = WC_HASH_TYPE_MD2;
     6853    }
     6854#endif
     6855#ifndef NO_MD4
     6856    else if (XSTRNCMP("MD4", evp, 3) == 0) {
     6857        hash = WC_HASH_TYPE_MD4;
     6858    }
     6859#endif
     6860#ifndef NO_MD5
     6861    else if (XSTRNCMP("MD5", evp, 3) == 0) {
     6862        hash = WC_HASH_TYPE_MD5;
     6863    }
     6864#endif
     6865
     6866    if (pHash)
     6867        *pHash = hash;
     6868
     6869    hashSz = wc_HashGetDigestSize(hash);
     6870    if (pHashSz)
     6871        *pHashSz = hashSz;
     6872
     6873    if (hashSz < 0) {
     6874        return WOLFSSL_FAILURE;
     6875    }
     6876
     6877    return WOLFSSL_SUCCESS;
     6878}
     6879#endif /* !defined(NO_PWDBASED) */
     6880
     6881#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
    65946882
    65956883#endif /* WOLFSSL_EVP_INCLUDED */
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/hash.c

    r457 r464  
    3434#include <wolfssl/wolfcrypt/hash.h>
    3535#include <wolfssl/wolfcrypt/hmac.h>
     36#include <wolfssl/wolfcrypt/cryptocb.h>
    3637
    3738#ifdef NO_INLINE
     
    625626    int ret = HASH_TYPE_E; /* Default to hash type error */
    626627
    627     if (hash == NULL || data == NULL)
     628    if (hash == NULL || (data == NULL && dataSz > 0))
    628629        return BAD_FUNC_ARG;
    629630
     
    10271028        wc_Sha sha[1];
    10281029    #endif
     1030        int devId = INVALID_DEVID;
    10291031
    10301032    #ifdef WOLFSSL_SMALL_STACK
     
    10341036    #endif
    10351037
    1036         if ((ret = wc_InitSha(sha)) != 0) {
     1038    #ifdef WOLF_CRYPTO_CB
     1039        /* only use devId if its not an empty hash */
     1040        if (data != NULL && len > 0)
     1041            devId = wc_CryptoCb_GetDevIdAtIndex(0);
     1042    #endif
     1043
     1044        if ((ret = wc_InitSha_ex(sha, NULL, devId)) != 0) {
    10371045            WOLFSSL_MSG("InitSha failed");
    10381046        }
     
    11021110        wc_Sha256 sha256[1];
    11031111    #endif
     1112        int devId = INVALID_DEVID;
    11041113
    11051114    #ifdef WOLFSSL_SMALL_STACK
     
    11101119    #endif
    11111120
    1112         if ((ret = wc_InitSha256(sha256)) != 0) {
     1121    #ifdef WOLF_CRYPTO_CB
     1122        /* only use devId if its not an empty hash */
     1123        if (data != NULL && len > 0)
     1124            devId = wc_CryptoCb_GetDevIdAtIndex(0);
     1125    #endif
     1126
     1127        if ((ret = wc_InitSha256_ex(sha256, NULL, devId)) != 0) {
    11131128            WOLFSSL_MSG("InitSha256 failed");
    11141129        }
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/hmac.c

    r457 r464  
    2525#endif
    2626
    27 #include <wolfssl/wolfcrypt/settings.h>
     27#include <wolfssl/wolfcrypt/wc_port.h>
    2828#include <wolfssl/wolfcrypt/error-crypt.h>
    2929
     
    10151015
    10161016    if (ret == 0)
    1017         ret  = wc_HmacInit(hmac, heap, devId);
     1017        ret = wc_HmacInit(hmac, heap, devId);
    10181018    if (ret == 0) {
    10191019        XMEMCPY(hmac->id, id, len);
    10201020        hmac->idLen = len;
     1021    }
     1022
     1023    return ret;
     1024}
     1025
     1026int wc_HmacInit_Label(Hmac* hmac, const char* label, void* heap, int devId)
     1027{
     1028    int ret = 0;
     1029    int labelLen = 0;
     1030
     1031    if (hmac == NULL || label == NULL)
     1032        ret = BAD_FUNC_ARG;
     1033    if (ret == 0) {
     1034        labelLen = (int)XSTRLEN(label);
     1035        if (labelLen == 0 || labelLen > HMAC_MAX_LABEL_LEN)
     1036            ret = BUFFER_E;
     1037    }
     1038
     1039    if (ret == 0)
     1040        ret  = wc_HmacInit(hmac, heap, devId);
     1041    if (ret == 0) {
     1042        XMEMCPY(hmac->label, label, labelLen);
     1043        hmac->labelLen = labelLen;
    10211044    }
    10221045
     
    12171240        byte   n = 0x1;
    12181241
     1242        /* RFC 5869 states that the length of output keying material in
     1243           octets must be L <= 255*HashLen or N = ceil(L/HashLen) */
     1244
     1245        if (out == NULL || ((outSz/hashSz) + ((outSz % hashSz) != 0)) > 255)
     1246            return BAD_FUNC_ARG;
     1247
    12191248        ret = wc_HmacInit(&myHmac, NULL, INVALID_DEVID);
    12201249        if (ret != 0)
    12211250            return ret;
     1251
    12221252
    12231253        while (outIdx < outSz) {
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/integer.c

    r457 r464  
    272272int mp_leading_bit (mp_int * a)
    273273{
    274     int bit = 0;
    275     mp_int t;
    276 
    277     if (mp_init_copy(&t, a) != MP_OKAY)
    278         return 0;
    279 
    280     while (mp_iszero(&t) == MP_NO) {
    281 #ifndef MP_8BIT
    282         bit = (t.dp[0] & 0x80) != 0;
    283 #else
    284         bit = ((t.dp[0] | ((t.dp[1] & 0x01) << 7)) & 0x80) != 0;
    285 #endif
    286         if (mp_div_2d (&t, 8, &t, NULL) != MP_OKAY)
    287             break;
    288     }
    289     mp_clear(&t);
    290     return bit;
     274    int c = mp_count_bits(a);
     275
     276    if (c == 0) return 0;
     277    return (c % 8) == 0;
    291278}
    292279
     
    335322    len = mp_unsigned_bin_size(a);
    336323
     324    if (len > c) {
     325      return MP_VAL;
     326    }
     327
    337328    /* pad front w/ zeros to match length */
    338     for (i = 0; i < c - len; i++)
    339         b[i] = 0x00;
     329    for (i = 0; i < c - len; i++) {
     330      b[i] = 0x00;
     331    }
    340332    return mp_to_unsigned_bin(a, b + i);
    341333}
     
    555547}
    556548
     549int mp_cond_swap_ct (mp_int * a, mp_int * b, int c, int m)
     550{
     551    (void)c;
     552    if (m == 1)
     553        mp_exch(a, b);
     554    return MP_OKAY;
     555}
     556
    557557
    558558/* shift right a certain number of bits */
     
    563563    mp_digit D = x;
    564564
     565    /* shifting by a negative number not supported, and shifting by
     566     * zero changes nothing.
     567     */
     568    if (x <= 0) return;
     569
     570    /* shift digits first if needed */
     571    if (x >= DIGIT_BIT) {
     572        mp_rshd(c, x / DIGIT_BIT);
     573        /* recalculate number of bits to shift */
     574        D = x % DIGIT_BIT;
     575        /* check if any more shifting needed */
     576        if (D == 0) return;
     577    }
     578
     579    /* zero shifted is always zero */
    565580    if (mp_iszero(c)) return;
    566581
     
    670685  }
    671686  /* clear the digit that is not completely outside/inside the modulus */
    672   c->dp[b / DIGIT_BIT] &= (mp_digit) ((((mp_digit) 1) <<
    673               (((mp_digit) b) % DIGIT_BIT)) - ((mp_digit) 1));
     687  x = DIGIT_BIT - (b % DIGIT_BIT);
     688  if (x != DIGIT_BIT) {
     689    c->dp[b / DIGIT_BIT] &= ~((mp_digit)0) >> (x + ((sizeof(mp_digit)*8) - DIGIT_BIT));
     690  }
    674691  mp_clamp (c);
    675692  return MP_OKAY;
     
    681698{
    682699  int     res;
    683 
    684   /* make sure there are at least two digits */
    685   if (a->alloc < 2) {
    686      if ((res = mp_grow(a, 2)) != MP_OKAY) {
     700  int     digits_needed;
     701
     702  while (c > 0 && b[0] == 0) {
     703      c--;
     704      b++;
     705  }
     706
     707  digits_needed = ((c * CHAR_BIT) + DIGIT_BIT - 1) / DIGIT_BIT;
     708
     709  /* make sure there are enough digits available */
     710  if (a->alloc < digits_needed) {
     711     if ((res = mp_grow(a, digits_needed)) != MP_OKAY) {
    687712        return res;
    688713     }
     
    700725#ifndef MP_8BIT
    701726      a->dp[0] |= *b++;
    702       a->used += 1;
     727      if (a->used == 0)
     728          a->used = 1;
    703729#else
    704730      a->dp[0] = (*b & MP_MASK);
    705731      a->dp[1] |= ((*b++ >> 7U) & 1);
    706       a->used += 2;
     732      if (a->used == 0)
     733          a->used = 2;
    707734#endif
    708735  }
     
    15781605  mp_clamp (b);
    15791606  return MP_OKAY;
     1607}
     1608
     1609/* c = a / 2 (mod b) - constant time (a < b and positive) */
     1610int mp_div_2_mod_ct(mp_int *a, mp_int *b, mp_int *c)
     1611{
     1612    int res;
     1613
     1614    if (mp_isodd(a)) {
     1615        res = mp_add(a, b, c);
     1616        if (res == MP_OKAY) {
     1617            res = mp_div_2(c, c);
     1618        }
     1619    }
     1620    else {
     1621        res = mp_div_2(a, c);
     1622    }
     1623
     1624    return res;
    15801625}
    15811626
     
    19912036#ifdef BN_FAST_MP_MONTGOMERY_REDUCE_C
    19922037     if (((P->used * 2 + 1) < (int)MP_WARRAY) &&
    1993           P->used < (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
     2038          P->used < (1L << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
    19942039        redux = fast_mp_montgomery_reduce;
    19952040     } else
     
    22372282#ifdef BN_FAST_MP_MONTGOMERY_REDUCE_C
    22382283  if (((P->used * 2 + 1) < (int)MP_WARRAY) &&
    2239        P->used < (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
     2284       P->used < (1L << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
    22402285     redux = fast_mp_montgomery_reduce;
    22412286  } else
    22422287#endif
     2288#ifdef BN_MP_MONTGOMERY_REDUCE_C
    22432289  {
    2244 #ifdef BN_MP_MONTGOMERY_REDUCE_C
    22452290     /* use slower baseline Montgomery method */
    22462291     redux = mp_montgomery_reduce;
    2247 #else
    2248      return MP_VAL;
    2249 #endif
     2292  }
     2293#endif
     2294
     2295  if (redux == NULL) {
     2296      return MP_VAL;
    22502297  }
    22512298
     
    24492496#endif
    24502497
     2498  XMEMSET(W, 0, (n->used * 2 + 1) * sizeof(mp_word));
     2499
    24512500  /* first we have to get the digits of the input into
    24522501   * an array of double precision words W[...]
     
    24652514    for (ix = 0; ix < x->used; ix++) {
    24662515      *_W++ = *tmpx++;
    2467     }
    2468 
    2469     /* zero the high words of W[a->used..m->used*2] */
    2470     for (; ix < n->used * 2 + 1; ix++) {
    2471       *_W++ = 0;
    24722516    }
    24732517  }
     
    25972641  if ((digs < (int)MP_WARRAY) &&
    25982642      n->used <
    2599       (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
     2643      (1L << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
    26002644    return fast_mp_montgomery_reduce (x, n, rho);
    26012645  }
     
    29973041}
    29983042
     3043/* d = a - b (mod c) - a < c and b < c and positive */
     3044int mp_submod_ct(mp_int* a, mp_int* b, mp_int* c, mp_int* d)
     3045{
     3046    int res;
     3047
     3048    res = mp_sub(a, b, d);
     3049    if (res == MP_OKAY && mp_isneg(d)) {
     3050        res = mp_add(d, c, d);
     3051    }
     3052
     3053    return res;
     3054}
     3055
     3056/* d = a + b (mod c) - a < c and b < c and positive */
     3057int mp_addmod_ct(mp_int* a, mp_int* b, mp_int* c, mp_int* d)
     3058{
     3059    int res;
     3060
     3061    res = mp_add(a, b, d);
     3062    if (res == MP_OKAY && mp_cmp(d, c) != MP_LT) {
     3063        res = mp_sub(d, c, d);
     3064    }
     3065
     3066    return res;
     3067}
     3068
    29993069/* computes b = a*a */
    30003070int mp_sqr (mp_int * a, mp_int * b)
     
    30443114    if ((digs < (int)MP_WARRAY) &&
    30453115        MIN(a->used, b->used) <=
    3046         (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
     3116        (1L << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
    30473117      res = fast_s_mp_mul_digs (a, b, c, digs);
    30483118    } else
     
    35073577  if ((digs < (int)MP_WARRAY) &&
    35083578      MIN (a->used, b->used) <
    3509           (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
     3579          (1L << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
    35103580    return fast_s_mp_mul_digs (a, b, c, digs);
    35113581  }
     
    40154085  if (((a->used + b->used + 1) < (int)MP_WARRAY)
    40164086      && MIN (a->used, b->used) <
    4017       (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
     4087      (1L << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
    40184088    return fast_s_mp_mul_high_digs (a, b, c, digs);
    40194089  }
     
    43254395  int       res, ix, oldused;
    43264396
     4397  if (b > MP_MASK) return MP_VAL;
     4398
    43274399  /* grow c as required */
    43284400  if (c->alloc < a->used + 1) {
     
    45124584
    45134585     if (w >= b) {
     4586#ifdef WOLFSSL_LINUXKM
     4587        t = (mp_digit)w;
     4588        /* Linux kernel macro for in-place 64 bit integer division. */
     4589        do_div(t, b);
     4590#else
    45144591        t = (mp_digit)(w / b);
     4592#endif
    45154593        w -= ((mp_word)t) * ((mp_word)b);
    45164594      } else {
     
    45444622#if defined(WOLFSSL_KEY_GEN) || !defined(NO_DH) || !defined(NO_DSA) || !defined(NO_RSA)
    45454623
    4546 const mp_digit ltm_prime_tab[PRIME_SIZE] = {
     4624const FLASH_QUALIFIER mp_digit ltm_prime_tab[PRIME_SIZE] = {
    45474625  0x0002, 0x0003, 0x0005, 0x0007, 0x000B, 0x000D, 0x0011, 0x0013,
    45484626  0x0017, 0x001D, 0x001F, 0x0025, 0x0029, 0x002B, 0x002F, 0x0035,
     
    46354713#if defined(WOLFSSL_HAVE_SP_RSA) || defined(WOLFSSL_HAVE_SP_DH)
    46364714#ifndef WOLFSSL_SP_NO_2048
    4637   if (mp_count_bits(a) == 1024)
     4715  if (mp_count_bits(a) == 1024 && mp_isodd(a))
    46384716      err = sp_ModExp_1024(b, &r, a, &y);
    4639   else if (mp_count_bits(a) == 2048)
     4717  else if (mp_count_bits(a) == 2048 && mp_isodd(a))
    46404718      err = sp_ModExp_2048(b, &r, a, &y);
    46414719  else
    46424720#endif
    46434721#ifndef WOLFSSL_SP_NO_3072
    4644   if (mp_count_bits(a) == 1536)
     4722  if (mp_count_bits(a) == 1536 && mp_isodd(a))
    46454723      err = sp_ModExp_1536(b, &r, a, &y);
    4646   else if (mp_count_bits(a) == 3072)
     4724  else if (mp_count_bits(a) == 3072 && mp_isodd(a))
    46474725      err = sp_ModExp_3072(b, &r, a, &y);
    46484726  else
    46494727#endif
    46504728#ifdef WOLFSSL_SP_4096
    4651   if (mp_count_bits(a) == 4096)
     4729  if (mp_count_bits(a) == 4096 && mp_isodd(a))
    46524730      err = sp_ModExp_4096(b, &r, a, &y);
    46534731  else
     
    50905168
    50915169/* chars used in radix conversions */
    5092 const char *mp_s_rmap = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\
    5093                          abcdefghijklmnopqrstuvwxyz+/";
     5170const char *mp_s_rmap = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
     5171                        "abcdefghijklmnopqrstuvwxyz+/";
    50945172#endif
    50955173
     
    51795257    /* special case for binary */
    51805258    if (radix == MP_RADIX_BIN) {
    5181         *size = mp_count_bits (a) + (a->sign == MP_NEG ? 1 : 0) + 1;
     5259        *size = mp_count_bits(a);
     5260        if (*size == 0)
     5261          *size = 1;
     5262        *size += (a->sign == MP_NEG ? 1 : 0) + 1; /* "-" sign + null term */
    51825263        return MP_OKAY;
    51835264    }
     
    51895270
    51905271    if (mp_iszero(a) == MP_YES) {
    5191         *size = 2;
     5272#ifndef WC_DISABLE_RADIX_ZERO_PAD
     5273        if (radix == 16)
     5274            *size = 3;
     5275        else
     5276#endif
     5277            *size = 2;
    51925278        return MP_OKAY;
    51935279    }
     
    51955281    /* digs is the digit count */
    51965282    digs = 0;
    5197 
    5198     /* if it's negative add one for the sign */
    5199     if (a->sign == MP_NEG) {
    5200         ++digs;
    5201     }
    52025283
    52035284    /* init a copy of the input */
     
    52195300    mp_clear (&t);
    52205301
     5302#ifndef WC_DISABLE_RADIX_ZERO_PAD
     5303    /* For hexadecimal output, add zero padding when number of digits is odd */
     5304    if ((digs & 1) && (radix == 16)) {
     5305        ++digs;
     5306    }
     5307#endif
     5308
     5309    /* if it's negative add one for the sign */
     5310    if (a->sign == MP_NEG) {
     5311        ++digs;
     5312    }
     5313
    52215314    /* return digs + 1, the 1 is for the NULL byte that would be required. */
    52225315    *size = digs + 1;
     
    52395332    /* quick out if its zero */
    52405333    if (mp_iszero(a) == MP_YES) {
     5334#ifndef WC_DISABLE_RADIX_ZERO_PAD
     5335        if (radix == 16) {
     5336            *str++ = '0';
     5337        }
     5338#endif
    52415339        *str++ = '0';
    52425340        *str = '\0';
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/logging.c

    r457 r464  
    112112#endif /* WOLFSSL_FUNC_TIME */
    113113
     114#ifdef HAVE_WC_INTROSPECTION
     115
     116const char *wolfSSL_configure_args(void) {
     117#ifdef LIBWOLFSSL_CONFIGURE_ARGS
     118  /* the spaces on either side are to make matching simple and efficient. */
     119  return " " LIBWOLFSSL_CONFIGURE_ARGS " ";
     120#else
     121  return NULL;
     122#endif
     123}
     124
     125const char *wolfSSL_global_cflags(void) {
     126#ifdef LIBWOLFSSL_GLOBAL_CFLAGS
     127  /* the spaces on either side are to make matching simple and efficient. */
     128  return " " LIBWOLFSSL_GLOBAL_CFLAGS " ";
     129#else
     130  return NULL;
     131#endif
     132}
     133
     134#endif /* HAVE_WC_INTROSPECTION */
     135
     136#ifdef HAVE_STACK_SIZE_VERBOSE
     137
     138THREAD_LS_T unsigned char *StackSizeCheck_myStack = NULL;
     139THREAD_LS_T size_t StackSizeCheck_stackSize = 0;
     140THREAD_LS_T size_t StackSizeCheck_stackSizeHWM = 0;
     141THREAD_LS_T size_t *StackSizeCheck_stackSizeHWM_ptr = 0;
     142THREAD_LS_T void *StackSizeCheck_stackOffsetPointer = 0;
     143
     144#endif /* HAVE_STACK_SIZE_VERBOSE */
     145
    114146#ifdef DEBUG_WOLFSSL
    115147
     
    231263#elif defined(WOLFSSL_ANDROID_DEBUG)
    232264    #include <android/log.h>
    233 #else
    234     #include <stdio.h>   /* for default printf stuff */
     265#elif defined(WOLFSSL_XILINX)
     266    #include "xil_printf.h"
     267#elif defined(WOLFSSL_LINUXKM)
     268    /* the requisite linux/kernel.h is included in wc_port.h, with incompatible warnings masked out. */
     269#elif defined(FUSION_RTOS)
     270    #include <fclstdio.h>
     271    #include <wolfssl/wolfcrypt/wc_port.h>
     272    #define fprintf FCL_FPRINTF
     273#else
     274    #include <stdio.h>  /* for default printf stuff */
    235275#endif
    236276
     
    264304#elif defined(MQX_USE_IO_OLD)
    265305        fprintf(_mqxio_stderr, "%s\n", logMessage);
    266 
    267306#elif defined(WOLFSSL_APACHE_MYNEWT)
    268307        LOG_DEBUG(&mynewt_log, LOG_MODULE_DEFAULT, "%s\n", logMessage);
     
    275314#elif defined(WOLFSSL_ANDROID_DEBUG)
    276315        __android_log_print(ANDROID_LOG_VERBOSE, "[wolfSSL]", "%s", logMessage);
     316#elif defined(WOLFSSL_XILINX)
     317        xil_printf("%s\r\n", logMessage);
     318#elif defined(WOLFSSL_LINUXKM)
     319        printk("%s\n", logMessage);
    277320#else
    278321        fprintf(stderr, "%s\n", logMessage);
     
    818861        {
    819862            next = current->next;
    820             cb(current->error, strlen(current->error), u);
     863            cb(current->error, XSTRLEN(current->error), u);
    821864            XFREE(current, current->heap, DYNAMIC_TYPE_LOG);
    822865            current = next;
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/md5.c

    r457 r464  
    128128        cau_md5_hash_n((byte*)data, 1, (unsigned char*)md5->digest);
    129129#else
    130         MMCAU_MD5_HashN((byte*)data, 1, (uint32_t*)md5->digest);
     130        MMCAU_MD5_HashN((byte*)data, 1, (word32*)md5->digest);
    131131#endif
    132132        wolfSSL_CryptHwMutexUnLock();
     
    149149                cau_md5_hash_n(local, 1, (unsigned char*)md5->digest);
    150150            #else
    151                 MMCAU_MD5_HashN(local, 1, (uint32_t*)md5->digest);
     151                MMCAU_MD5_HashN(local, 1, (word32*)md5->digest);
    152152            #endif
    153153                data += WC_MD5_BLOCK_SIZE;
     
    163163#else
    164164        MMCAU_MD5_HashN((byte*)data, len / WC_MD5_BLOCK_SIZE,
    165             (uint32_t*)md5->digest);
     165            (word32*)md5->digest);
    166166#endif
    167167        }
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/memory.c

    r457 r464  
    313313
    314314int wc_LoadStaticMemory(WOLFSSL_HEAP_HINT** pHint,
    315     unsigned char* buf, unsigned int sz, int flag, int max)
     315    unsigned char* buf, unsigned int sz, int flag, int maxSz)
    316316{
    317317    int ret;
     
    363363    /* determine what max applies too */
    364364    if ((flag & WOLFMEM_IO_POOL) || (flag & WOLFMEM_IO_POOL_FIXED)) {
    365         heap->maxIO = max;
     365        heap->maxIO = maxSz;
    366366    }
    367367    else { /* general memory used in handshakes */
    368         heap->maxHa = max;
     368        heap->maxHa = maxSz;
    369369    }
    370370
     
    372372    *pHint = hint;
    373373
    374     (void)max;
     374    (void)maxSz;
    375375
    376376    return 0;
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/misc.c

    r457 r464  
    1919 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
    2020 */
    21 
    22 
     21/*
     22
     23DESCRIPTION
     24This module implements the arithmetic-shift right, left, byte swapping, XOR,
     25masking and clearing memory logic.
     26
     27*/
    2328#ifdef HAVE_CONFIG_H
    2429    #include <config.h>
     
    7883
    7984#else /* generic */
     85/* This routine performs a left circular arithmetic shift of <x> by <y> value. */
    8086
    8187    WC_STATIC WC_INLINE word32 rotlFixed(word32 x, word32 y)
     
    8490    }
    8591
    86 
     92/* This routine performs a right circular arithmetic shift of <x> by <y> value. */
    8793    WC_STATIC WC_INLINE word32 rotrFixed(word32 x, word32 y)
    8894    {
     
    9298#endif
    9399
    94 
     100#ifdef WC_RC2
     101
     102/* This routine performs a left circular arithmetic shift of <x> by <y> value */
     103WC_STATIC WC_INLINE word16 rotlFixed16(word16 x, word16 y)
     104{
     105    return (x << y) | (x >> (sizeof(y) * 8 - y));
     106}
     107
     108
     109/* This routine performs a right circular arithmetic shift of <x> by <y> value */
     110WC_STATIC WC_INLINE word16 rotrFixed16(word16 x, word16 y)
     111{
     112    return (x >> y) | (x << (sizeof(y) * 8 - y));
     113}
     114
     115#endif /* WC_RC2 */
     116
     117/* This routine performs a byte swap of 32-bit word value. */
    95118WC_STATIC WC_INLINE word32 ByteReverseWord32(word32 value)
    96119{
     
    105128        defined(__GNUC_PREREQ) && __GNUC_PREREQ(4, 3)
    106129    return (word32)__builtin_bswap32(value);
     130#elif defined(WOLFSSL_BYTESWAP32_ASM) && defined(__GNUC__) && \
     131      defined(__aarch64__)
     132    __asm__ volatile (
     133        "REV32 %0, %0  \n"
     134        : "+r" (value)
     135        :
     136    );
     137    return value;
     138#elif defined(WOLFSSL_BYTESWAP32_ASM) && defined(__GNUC__) && \
     139      (defined(__thumb__) || defined(__arm__))
     140    __asm__ volatile (
     141        "REV %0, %0  \n"
     142        : "+r" (value)
     143        :
     144    );
     145    return value;
    107146#elif defined(FAST_ROTATE)
    108147    /* 5 instructions with rotate instruction, 9 without */
     
    115154#endif
    116155}
    117 
    118 
     156/* This routine performs a byte swap of words array of a given count. */
    119157WC_STATIC WC_INLINE void ByteReverseWords(word32* out, const word32* in,
    120158                                    word32 byteCount)
     
    126164
    127165}
    128 
    129166
    130167#if defined(WORD64_AVAILABLE) && !defined(WOLFSSL_NO_WORD64_OPS)
     
    173210
    174211#ifndef WOLFSSL_NO_XOR_OPS
     212/* This routine performs a bitwise XOR operation of <*r> and <*a> for <n> number
     213of wolfssl_words, placing the result in <*r>. */
     214WC_STATIC WC_INLINE void XorWordsOut(wolfssl_word* r, const wolfssl_word* a,
     215                                     const wolfssl_word* b, word32 n)
     216{
     217    word32 i;
     218
     219    for (i = 0; i < n; i++) r[i] = a[i] ^ b[i];
     220}
     221
     222/* This routine performs a bitwise XOR operation of <*buf> and <*mask> of n
     223counts, placing the result in <*buf>. */
     224
     225WC_STATIC WC_INLINE void xorbufout(void*out, const void* buf, const void* mask,
     226                                   word32 count)
     227{
     228    if (((wolfssl_word)out | (wolfssl_word)buf | (wolfssl_word)mask | count) % \
     229                                                         WOLFSSL_WORD_SIZE == 0)
     230        XorWordsOut( (wolfssl_word*)out, (wolfssl_word*)buf,
     231                     (const wolfssl_word*)mask, count / WOLFSSL_WORD_SIZE);
     232    else {
     233        word32 i;
     234        byte*       o = (byte*)out;
     235        byte*       b = (byte*)buf;
     236        const byte* m = (const byte*)mask;
     237
     238        for (i = 0; i < count; i++) o[i] = b[i] ^ m[i];
     239    }
     240}
     241
     242/* This routine performs a bitwise XOR operation of <*r> and <*a> for <n> number
     243of wolfssl_words, placing the result in <*r>. */
    175244WC_STATIC WC_INLINE void XorWords(wolfssl_word* r, const wolfssl_word* a, word32 n)
    176245{
     
    180249}
    181250
     251/* This routine performs a bitwise XOR operation of <*buf> and <*mask> of n
     252counts, placing the result in <*buf>. */
    182253
    183254WC_STATIC WC_INLINE void xorbuf(void* buf, const void* mask, word32 count)
     
    197268
    198269#ifndef WOLFSSL_NO_FORCE_ZERO
    199 /* Make sure compiler doesn't skip */
     270/* This routine fills the first len bytes of the memory area pointed by mem
     271   with zeros. It ensures compiler optimizations doesn't skip it  */
    200272WC_STATIC WC_INLINE void ForceZero(const void* mem, word32 len)
    201273{
    202274    volatile byte* z = (volatile byte*)mem;
    203275
    204 #if defined(WOLFSSL_X86_64_BUILD) && defined(WORD64_AVAILABLE)
     276#if (defined(WOLFSSL_X86_64_BUILD) || defined(WOLFSSL_AARCH64_BUILD)) \
     277            && defined(WORD64_AVAILABLE)
    205278    volatile word64* w;
    206279    #ifndef WOLFSSL_UNALIGNED_64BIT_ACCESS
     
    243316        #define min min
    244317    #endif
     318    /* returns the smaller of a and b */
    245319    WC_STATIC WC_INLINE word32 min(word32 a, word32 b)
    246320    {
     
    324398WC_STATIC WC_INLINE byte ctMaskGT(int a, int b)
    325399{
    326     return (((word32)a - b - 1) >> 31) - 1;
     400    return (byte)((((word32)a - b - 1) >> 31) - 1);
    327401}
    328402
     
    330404WC_STATIC WC_INLINE byte ctMaskGTE(int a, int b)
    331405{
    332     return (((word32)a - b    ) >> 31) - 1;
     406    return (byte)((((word32)a - b    ) >> 31) - 1);
    333407}
    334408
     
    336410WC_STATIC WC_INLINE int ctMaskIntGTE(int a, int b)
    337411{
    338     return (((word32)a - b    ) >> 31) - 1;
     412    return (int)((((word32)a - b    ) >> 31) - 1);
    339413}
    340414
     
    342416WC_STATIC WC_INLINE byte ctMaskLT(int a, int b)
    343417{
    344     return (((word32)b - a - 1) >> 31) - 1;
     418    return (byte)((((word32)b - a - 1) >> 31) - 1);
    345419}
    346420
     
    348422WC_STATIC WC_INLINE byte ctMaskLTE(int a, int b)
    349423{
    350     return (((word32)b - a    ) >> 31) - 1;
     424    return (byte)((((word32)b - a    ) >> 31) - 1);
    351425}
    352426
     
    354428WC_STATIC WC_INLINE byte ctMaskEq(int a, int b)
    355429{
    356     return (~ctMaskGT(a, b)) & (~ctMaskLT(a, b));
    357 }
    358 
     430    return (byte)(~ctMaskGT(a, b)) & (byte)(~ctMaskLT(a, b));
     431}
     432
     433/* Constant time - sets 16 bit integer mask when a > b */
    359434WC_STATIC WC_INLINE word16 ctMask16GT(int a, int b)
    360435{
    361     return (((word32)a - b - 1) >> 31) - 1;
    362 }
    363 
     436    return (word16)((((word32)a - b - 1) >> 31) - 1);
     437}
     438
     439/* Constant time - sets 16 bit integer mask when a >= b */
     440WC_STATIC WC_INLINE word16 ctMask16GTE(int a, int b)
     441{
     442    return (word16)((((word32)a - b    ) >> 31) - 1);
     443}
     444
     445/* Constant time - sets 16 bit integer mask when a < b. */
    364446WC_STATIC WC_INLINE word16 ctMask16LT(int a, int b)
    365447{
    366     return (((word32)a - b - 1) >> 31) - 1;
    367 }
    368 
     448    return (word16)((((word32)b - a - 1) >> 31) - 1);
     449}
     450
     451/* Constant time - sets 16 bit integer mask when a <= b. */
     452WC_STATIC WC_INLINE word16 ctMask16LTE(int a, int b)
     453{
     454    return (word16)((((word32)b - a    ) >> 31) - 1);
     455}
     456
     457/* Constant time - sets 16 bit integer mask when a == b. */
    369458WC_STATIC WC_INLINE word16 ctMask16Eq(int a, int b)
    370459{
    371     return (~ctMask16GT(a, b)) & (~ctMask16LT(a, b));
     460    return (word16)(~ctMask16GT(a, b)) & (word16)(~ctMask16LT(a, b));
    372461}
    373462
     
    375464WC_STATIC WC_INLINE byte ctMaskNotEq(int a, int b)
    376465{
    377     return ctMaskGT(a, b) | ctMaskLT(a, b);
     466    return (byte)ctMaskGT(a, b) | (byte)ctMaskLT(a, b);
    378467}
    379468
     
    381470WC_STATIC WC_INLINE byte ctMaskSel(byte m, byte a, byte b)
    382471{
    383     return (b & ((byte)~(word32)m)) | (a & m);
     472    return (byte)((b & ((byte)~(word32)m)) | (a & m));
    384473}
    385474
     
    394483WC_STATIC WC_INLINE byte ctSetLTE(int a, int b)
    395484{
    396     return ((word32)a - b - 1) >> 31;
     485    return (byte)(((word32)a - b - 1) >> 31);
    397486}
    398487#endif
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/pwdbased.c

    r457 r464  
    502502        }
    503503
     504        if (ret < 0) {
     505            mp_clear(&B1);
     506            break;
     507        }
     508
    504509        currentLen = min(kLen, (int)u);
    505510        XMEMCPY(output, Ai, currentLen);
     
    722727    blocksSz = bSz * parallel;
    723728    blocks = (byte*)XMALLOC(blocksSz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    724     if (blocks == NULL)
     729    if (blocks == NULL) {
     730        ret = MEMORY_E;
    725731        goto end;
     732    }
    726733    /* Temporary for scryptROMix. */
    727734    v = (byte*)XMALLOC((1 << cost) * bSz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    728     if (v == NULL)
     735    if (v == NULL) {
     736        ret = MEMORY_E;
    729737        goto end;
     738    }
    730739    /* Temporary for scryptBlockMix. */
    731740    y = (byte*)XMALLOC(blockSize * 128, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    732     if (y == NULL)
     741    if (y == NULL) {
     742        ret = MEMORY_E;
    733743        goto end;
     744    }
    734745
    735746    /* Step 1. */
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/random.c

    r457 r464  
    2020 */
    2121
    22 
     22/*
     23
     24DESCRIPTION
     25This library contains implementation for the random number generator.
     26
     27*/
    2328#ifdef HAVE_CONFIG_H
    2429    #include <config.h>
     
    165170#endif
    166171
     172#if defined(WOLFSSL_SILABS_SE_ACCEL)
     173#include <wolfssl/wolfcrypt/port/silabs/silabs_random.h>
     174#endif
     175
    167176
    168177#if defined(HAVE_INTEL_RDRAND) || defined(HAVE_INTEL_RDSEED)
     
    172181        intel_flags = cpuid_get_flags();
    173182    }
    174     #ifdef HAVE_INTEL_RDSEED
     183    #if defined(HAVE_INTEL_RDSEED) && !defined(WOLFSSL_LINUXKM)
    175184    static int wc_GenerateSeed_IntelRD(OS_Seed* os, byte* output, word32 sz);
    176185    #endif
     
    180189
    181190#ifdef USE_WINDOWS_API
     191    #define USE_INTEL_INTRINSICS
     192#elif !defined __GNUC__ || defined __clang__ || __GNUC__ > 4
     193    #define USE_INTEL_INTRINSICS
     194#else
     195    #undef USE_INTEL_INTRINSICS
     196#endif
     197
     198#ifdef USE_INTEL_INTRINSICS
    182199    #include <immintrin.h>
     200    /* Before clang 7 or GCC 9, immintrin.h did not define _rdseed64_step() */
     201    #ifndef HAVE_INTEL_RDSEED
     202    #elif defined __clang__ && __clang_major__ > 6
     203    #elif !defined __GNUC__
     204    #elif __GNUC__ > 8
     205    #else
     206        #ifndef __clang__
     207            #pragma GCC push_options
     208            #pragma GCC target("rdseed")
     209        #else
     210            #define __RDSEED__
     211        #endif
     212        #include <x86intrin.h>
     213        #ifndef __clang__
     214            #pragma GCC pop_options
     215        #endif
     216    #endif
    183217#endif /* USE_WINDOWS_API */
    184218#endif
     
    280314};
    281315
    282 /* NOTE: if DRBG struct is changed please update random.h drbg_data size */
    283 typedef struct DRBG {
    284     word32 reseedCtr;
    285     word32 lastBlock;
    286     byte V[DRBG_SEED_LEN];
    287     byte C[DRBG_SEED_LEN];
    288 #if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB)
    289     void* heap;
    290     int devId;
    291 #endif
    292     byte   matchCount;
    293 #ifdef WOLFSSL_SMALL_STACK_CACHE
    294     wc_Sha256 sha256;
    295 #endif
    296 } DRBG;
    297 
     316typedef struct DRBG_internal DRBG_internal;
    298317
    299318static int wc_RNG_HealthTestLocal(int reseed);
     
    301320/* Hash Derivation Function */
    302321/* Returns: DRBG_SUCCESS or DRBG_FAILURE */
    303 static int Hash_df(DRBG* drbg, byte* out, word32 outSz, byte type,
     322static int Hash_df(DRBG_internal* drbg, byte* out, word32 outSz, byte type,
    304323                                                  const byte* inA, word32 inASz,
    305324                                                  const byte* inB, word32 inBSz)
     
    390409
    391410/* Returns: DRBG_SUCCESS or DRBG_FAILURE */
    392 static int Hash_DRBG_Reseed(DRBG* drbg, const byte* seed, word32 seedSz)
     411static int Hash_DRBG_Reseed(DRBG_internal* drbg, const byte* seed, word32 seedSz)
    393412{
    394413    byte newV[DRBG_SEED_LEN];
     
    422441    }
    423442
    424     return Hash_DRBG_Reseed(rng->drbg, seed, seedSz);
     443    return Hash_DRBG_Reseed((DRBG_internal *)rng->drbg, seed, seedSz);
    425444}
    426445
     
    437456
    438457/* Returns: DRBG_SUCCESS or DRBG_FAILURE */
    439 static int Hash_gen(DRBG* drbg, byte* out, word32 outSz, const byte* V)
     458static int Hash_gen(DRBG_internal* drbg, byte* out, word32 outSz, const byte* V)
    440459{
    441460    int ret = DRBG_FAILURE;
     
    488507                }
    489508                else {
    490                     if (i == len) {
     509                    if (i == (len-1)) {
    491510                        len++;
    492511                    }
     
    512531            }
    513532        }
     533        else {
     534            /* wc_Sha256Update or wc_Sha256Final returned error */
     535            break;
     536        }
    514537    }
    515538    ForceZero(data, sizeof(data));
     
    529552        int sIdx, dIdx;
    530553
    531         for (sIdx = sLen - 1, dIdx = dLen - 1; sIdx >= 0; dIdx--, sIdx--)
    532         {
    533             carry += d[dIdx] + s[sIdx];
     554        for (sIdx = sLen - 1, dIdx = dLen - 1; sIdx >= 0; dIdx--, sIdx--) {
     555            carry += (word16)d[dIdx] + (word16)s[sIdx];
    534556            d[dIdx] = (byte)carry;
    535557            carry >>= 8;
     
    537559
    538560        for (; carry != 0 && dIdx >= 0; dIdx--) {
    539             carry += d[dIdx];
     561            carry += (word16)d[dIdx];
    540562            d[dIdx] = (byte)carry;
    541563            carry >>= 8;
     
    545567
    546568/* Returns: DRBG_SUCCESS, DRBG_NEED_RESEED, or DRBG_FAILURE */
    547 static int Hash_DRBG_Generate(DRBG* drbg, byte* out, word32 outSz)
     569static int Hash_DRBG_Generate(DRBG_internal* drbg, byte* out, word32 outSz)
    548570{
    549571    int ret;
     
    611633
    612634/* Returns: DRBG_SUCCESS or DRBG_FAILURE */
    613 static int Hash_DRBG_Instantiate(DRBG* drbg, const byte* seed, word32 seedSz,
     635static int Hash_DRBG_Instantiate(DRBG_internal* drbg, const byte* seed, word32 seedSz,
    614636                                             const byte* nonce, word32 nonceSz,
    615637                                             void* heap, int devId)
    616638{
    617     int ret;
    618 
    619     XMEMSET(drbg, 0, sizeof(DRBG));
     639    int ret = DRBG_FAILURE;
     640
     641    XMEMSET(drbg, 0, sizeof(DRBG_internal));
    620642#if defined(WOLFSSL_ASYNC_CRYPT) || defined(WOLF_CRYPTO_CB)
    621643    drbg->heap = heap;
     
    646668        ret = DRBG_SUCCESS;
    647669    }
    648     else {
    649         ret = DRBG_FAILURE;
    650     }
    651670
    652671    return ret;
     
    654673
    655674/* Returns: DRBG_SUCCESS or DRBG_FAILURE */
    656 static int Hash_DRBG_Uninstantiate(DRBG* drbg)
     675static int Hash_DRBG_Uninstantiate(DRBG_internal* drbg)
    657676{
    658677    word32 i;
     
    664683#endif
    665684
    666     ForceZero(drbg, sizeof(DRBG));
    667 
    668     for (i = 0; i < sizeof(DRBG); i++)
     685    ForceZero(drbg, sizeof(DRBG_internal));
     686
     687    for (i = 0; i < sizeof(DRBG_internal); i++)
    669688        compareSum |= compareDrbg[i] ^ 0;
    670689
     
    675694int wc_RNG_TestSeed(const byte* seed, word32 seedSz)
    676695{
    677     int ret = DRBG_SUCCESS;
     696    int ret = 0;
    678697
    679698    /* Check the seed for duplicate words. */
     
    701720                    void* heap, int devId)
    702721{
    703     int ret = RNG_FAILURE_E;
     722    int ret = 0;
    704723#ifdef HAVE_HASHDRBG
    705724    word32 seedSz = SEED_SZ + SEED_BLOCK_SZ;
     
    772791#if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
    773792        rng->drbg =
    774                 (struct DRBG*)XMALLOC(sizeof(DRBG), rng->heap,
     793                (struct DRBG*)XMALLOC(sizeof(DRBG_internal), rng->heap,
    775794                                                          DYNAMIC_TYPE_RNG);
    776 #else
    777         /* compile-time validation of drbg_data size */
    778         typedef char drbg_data_test[sizeof(rng->drbg_data) >=
    779                 sizeof(struct DRBG) ? 1 : -1];
    780         (void)sizeof(drbg_data_test);
    781         rng->drbg = (struct DRBG*)rng->drbg_data;
    782 #endif
    783 
    784795        if (rng->drbg == NULL) {
    785796            ret = MEMORY_E;
    786         }
    787         else {
     797            rng->status = DRBG_FAILED;
     798        }
     799#else
     800        rng->drbg = (struct DRBG*)&rng->drbg_data;
     801#endif
     802        if (ret == 0) {
    788803            ret = wc_GenerateSeed(&rng->seed, seed, seedSz);
    789             if (ret != 0)
     804            if (ret == 0)
     805                ret = wc_RNG_TestSeed(seed, seedSz);
     806            else {
    790807                ret = DRBG_FAILURE;
    791             else
    792                 ret = wc_RNG_TestSeed(seed, seedSz);
     808                rng->status = DRBG_FAILED;
     809            }
    793810
    794811            if (ret == DRBG_SUCCESS)
    795                  ret = Hash_DRBG_Instantiate(rng->drbg,
     812              ret = Hash_DRBG_Instantiate((DRBG_internal *)rng->drbg,
    796813                            seed + SEED_BLOCK_SZ, seedSz - SEED_BLOCK_SZ,
    797814                            nonce, nonceSz, rng->heap, devId);
     
    901918        return BAD_FUNC_ARG;
    902919
     920    if (sz == 0)
     921        return 0;
     922
    903923#ifdef WOLF_CRYPTO_CB
    904924    if (rng->devId != INVALID_DEVID) {
     
    913933    if (IS_INTEL_RDRAND(intel_flags))
    914934        return wc_GenerateRand_IntelRD(NULL, output, sz);
     935#endif
     936
     937#if defined(WOLFSSL_SILABS_SE_ACCEL) && defined(WOLFSSL_SILABS_TRNG)
     938    return silabs_GenerateRand(output, sz);
    915939#endif
    916940
     
    940964        return RNG_FAILURE_E;
    941965
    942     ret = Hash_DRBG_Generate(rng->drbg, output, sz);
     966    ret = Hash_DRBG_Generate((DRBG_internal *)rng->drbg, output, sz);
    943967    if (ret == DRBG_NEED_RESEED) {
    944968        if (wc_RNG_HealthTestLocal(1) == 0) {
     
    953977
    954978            if (ret == DRBG_SUCCESS)
    955                 ret = Hash_DRBG_Reseed(rng->drbg, newSeed + SEED_BLOCK_SZ,
     979              ret = Hash_DRBG_Reseed((DRBG_internal *)rng->drbg, newSeed + SEED_BLOCK_SZ,
    956980                                       SEED_SZ);
    957981            if (ret == DRBG_SUCCESS)
    958                 ret = Hash_DRBG_Generate(rng->drbg, output, sz);
     982              ret = Hash_DRBG_Generate((DRBG_internal *)rng->drbg, output, sz);
    959983
    960984            ForceZero(newSeed, sizeof(newSeed));
     
    10061030#ifdef HAVE_HASHDRBG
    10071031    if (rng->drbg != NULL) {
    1008         if (Hash_DRBG_Uninstantiate(rng->drbg) != DRBG_SUCCESS)
     1032      if (Hash_DRBG_Uninstantiate((DRBG_internal *)rng->drbg) != DRBG_SUCCESS)
    10091033            ret = RNG_FAILURE_E;
    10101034
     
    10401064{
    10411065    int ret = -1;
    1042     DRBG* drbg;
     1066    DRBG_internal* drbg;
    10431067#ifndef WOLFSSL_SMALL_STACK
    1044     DRBG  drbg_var;
     1068    DRBG_internal  drbg_var;
    10451069#endif
    10461070
     
    10581082
    10591083#ifdef WOLFSSL_SMALL_STACK
    1060     drbg = (DRBG*)XMALLOC(sizeof(DRBG), NULL, DYNAMIC_TYPE_RNG);
     1084    drbg = (DRBG_internal*)XMALLOC(sizeof(DRBG_internal), NULL, DYNAMIC_TYPE_RNG);
    10611085    if (drbg == NULL) {
    10621086        return MEMORY_E;
     
    11081132
    11091133
    1110 const byte seedA[] = {
     1134const FLASH_QUALIFIER byte seedA_data[] = {
    11111135    0x63, 0x36, 0x33, 0x77, 0xe4, 0x1e, 0x86, 0x46, 0x8d, 0xeb, 0x0a, 0xb4,
    11121136    0xa8, 0xed, 0x68, 0x3f, 0x6a, 0x13, 0x4e, 0x47, 0xe0, 0x14, 0xc7, 0x00,
     
    11151139};
    11161140
    1117 const byte reseedSeedA[] = {
     1141const FLASH_QUALIFIER byte reseedSeedA_data[] = {
    11181142    0xe6, 0x2b, 0x8a, 0x8e, 0xe8, 0xf1, 0x41, 0xb6, 0x98, 0x05, 0x66, 0xe3,
    11191143    0xbf, 0xe3, 0xc0, 0x49, 0x03, 0xda, 0xd4, 0xac, 0x2c, 0xdf, 0x9f, 0x22,
     
    11211145};
    11221146
    1123 const byte outputA[] = {
     1147const FLASH_QUALIFIER byte outputA_data[] = {
    11241148    0x04, 0xee, 0xc6, 0x3b, 0xb2, 0x31, 0xdf, 0x2c, 0x63, 0x0a, 0x1a, 0xfb,
    11251149    0xe7, 0x24, 0x94, 0x9d, 0x00, 0x5a, 0x58, 0x78, 0x51, 0xe1, 0xaa, 0x79,
     
    11351159};
    11361160
    1137 const byte seedB[] = {
     1161const FLASH_QUALIFIER byte seedB_data[] = {
    11381162    0xa6, 0x5a, 0xd0, 0xf3, 0x45, 0xdb, 0x4e, 0x0e, 0xff, 0xe8, 0x75, 0xc3,
    11391163    0xa2, 0xe7, 0x1f, 0x42, 0xc7, 0x12, 0x9d, 0x62, 0x0f, 0xf5, 0xc1, 0x19,
     
    11431167};
    11441168
    1145 const byte outputB[] = {
     1169const FLASH_QUALIFIER byte outputB_data[] = {
    11461170    0xd3, 0xe1, 0x60, 0xc3, 0x5b, 0x99, 0xf3, 0x40, 0xb2, 0x62, 0x82, 0x64,
    11471171    0xd1, 0x75, 0x10, 0x60, 0xe0, 0x04, 0x5d, 0xa3, 0x83, 0xff, 0x57, 0xa5,
     
    11761200
    11771201    if (reseed) {
    1178         ret = wc_RNG_HealthTest(1, seedA, sizeof(seedA),
    1179                                 reseedSeedA, sizeof(reseedSeedA),
     1202#ifdef WOLFSSL_USE_FLASHMEM
     1203        byte* seedA = (byte*)XMALLOC(sizeof(seedA_data), NULL,
     1204                             DYNAMIC_TYPE_TMP_BUFFER);
     1205        byte* reseedSeedA = (byte*)XMALLOC(sizeof(reseedSeedA_data), NULL,
     1206                             DYNAMIC_TYPE_TMP_BUFFER);
     1207        byte* outputA = (byte*)XMALLOC(sizeof(outputA_data), NULL,
     1208                             DYNAMIC_TYPE_TMP_BUFFER);
     1209
     1210        if (!seedA || !reseedSeedA || !outputA) {
     1211            XFREE(seedA, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     1212            XFREE(reseedSeedA, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     1213            XFREE(outputA, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     1214            ret = MEMORY_E;
     1215        }
     1216        else {
     1217            XMEMCPY_P(seedA, seedA_data, sizeof(seedA_data));
     1218            XMEMCPY_P(reseedSeedA, reseedSeedA_data, sizeof(reseedSeedA_data));
     1219            XMEMCPY_P(outputA, outputA_data, sizeof(outputA_data));
     1220#else
     1221        const byte* seedA = seedA_data;
     1222        const byte* reseedSeedA = reseedSeedA_data;
     1223        const byte* outputA = outputA_data;
     1224#endif
     1225        ret = wc_RNG_HealthTest(1, seedA, sizeof(seedA_data),
     1226                                reseedSeedA, sizeof(reseedSeedA_data),
    11801227                                check, RNG_HEALTH_TEST_CHECK_SIZE);
    11811228        if (ret == 0) {
     
    11841231                ret = -1;
    11851232        }
     1233
     1234#ifdef WOLFSSL_USE_FLASHMEM
     1235            XFREE(seedA, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     1236            XFREE(reseedSeedA, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     1237            XFREE(outputA, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     1238        }
     1239#endif
    11861240    }
    11871241    else {
    1188         ret = wc_RNG_HealthTest(0, seedB, sizeof(seedB),
     1242#ifdef WOLFSSL_USE_FLASHMEM
     1243        byte* seedB = (byte*)XMALLOC(sizeof(seedB_data), NULL,
     1244                             DYNAMIC_TYPE_TMP_BUFFER);
     1245        byte* outputB = (byte*)XMALLOC(sizeof(outputB_data), NULL,
     1246                               DYNAMIC_TYPE_TMP_BUFFER);
     1247
     1248        if (!seedB || !outputB) {
     1249            XFREE(seedB, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     1250            XFREE(outputB, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     1251            ret = MEMORY_E;
     1252        }
     1253        else {
     1254            XMEMCPY_P(seedB, seedB_data, sizeof(seedB_data));
     1255            XMEMCPY_P(outputB, outputB_data, sizeof(outputB_data));
     1256#else
     1257        const byte* seedB = seedB_data;
     1258        const byte* outputB = outputB_data;
     1259#endif
     1260        ret = wc_RNG_HealthTest(0, seedB, sizeof(seedB_data),
    11891261                                NULL, 0,
    11901262                                check, RNG_HEALTH_TEST_CHECK_SIZE);
     
    12011273        if (ret == 0) {
    12021274            ret = wc_RNG_HealthTest_ex(0,
    1203                                     seedB + 32, sizeof(seedB) - 32,
     1275                                    seedB + 32, sizeof(seedB_data) - 32,
    12041276                                    seedB, 32,
    12051277                                    NULL, 0,
     
    12071279                                    NULL, INVALID_DEVID);
    12081280            if (ret == 0) {
    1209                 if (ConstantCompare(check, outputB, sizeof(outputB)) != 0)
     1281                if (ConstantCompare(check, outputB, sizeof(outputB_data)) != 0)
    12101282                    ret = -1;
    12111283            }
    12121284        }
     1285
     1286#ifdef WOLFSSL_USE_FLASHMEM
     1287            XFREE(seedB, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     1288            XFREE(outputB, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     1289        }
     1290#endif
    12131291    }
    12141292
     
    13321410#ifdef HAVE_INTEL_RDSEED
    13331411
    1334 #ifndef USE_WINDOWS_API
     1412#ifndef USE_INTEL_INTRINSICS
    13351413
    13361414    /* return 0 on success */
     
    13431421    }
    13441422
    1345 #else /* USE_WINDOWS_API */
     1423#else /* USE_INTEL_INTRINSICS */
    13461424    /* The compiler Visual Studio uses does not allow inline assembly.
    13471425     * It does allow for Intel intrinsic functions. */
    13481426
    13491427    /* return 0 on success */
     1428# ifdef __GNUC__
     1429    __attribute__((target("rdseed")))
     1430# endif
    13501431    static WC_INLINE int IntelRDseed64(word64* seed)
    13511432    {
    13521433        int ok;
    13531434
    1354         ok = _rdseed64_step(seed);
     1435        ok = _rdseed64_step((unsigned long long*) seed);
    13551436        return (ok) ? 0 : -1;
    13561437    }
    13571438
    1358 #endif /* USE_WINDOWS_API */
     1439#endif /* USE_INTEL_INTRINSICS */
    13591440
    13601441/* return 0 on success */
     
    13691450}
    13701451
     1452#ifndef WOLFSSL_LINUXKM
    13711453/* return 0 on success */
    13721454static int wc_GenerateSeed_IntelRD(OS_Seed* os, byte* output, word32 sz)
     
    13991481    return 0;
    14001482}
     1483#endif
    14011484
    14021485#endif /* HAVE_INTEL_RDSEED */
     
    14041487#ifdef HAVE_INTEL_RDRAND
    14051488
    1406 #ifndef USE_WINDOWS_API
     1489#ifndef USE_INTEL_INTRINSICS
    14071490
    14081491/* return 0 on success */
     
    14161499}
    14171500
    1418 #else /* USE_WINDOWS_API */
     1501#else /* USE_INTEL_INTRINSICS */
    14191502    /* The compiler Visual Studio uses does not allow inline assembly.
    14201503     * It does allow for Intel intrinsic functions. */
    14211504
    14221505/* return 0 on success */
     1506# ifdef __GNUC__
     1507__attribute__((target("rdrnd")))
     1508# endif
    14231509static WC_INLINE int IntelRDrand64(word64 *rnd)
    14241510{
    14251511    int ok;
    14261512
    1427     ok = _rdrand64_step(rnd);
     1513    ok = _rdrand64_step((unsigned long long*) rnd);
    14281514
    14291515    return (ok) ? 0 : -1;
    14301516}
    14311517
    1432 #endif /* USE_WINDOWS_API */
     1518#endif /* USE_INTEL_INTRINSICS */
    14331519
    14341520/* return 0 on success */
     
    16081694}
    16091695
     1696#elif (defined(WOLFSSL_ATMEL) || defined(WOLFSSL_ATECC_RNG)) && \
     1697      !defined(WOLFSSL_PIC32MZ_RNG)
     1698    /* enable ATECC RNG unless using PIC32MZ one instead */
     1699    #include <wolfssl/wolfcrypt/port/atmel/atmel.h>
     1700
     1701    int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
     1702    {
     1703        int ret = 0;
     1704
     1705        (void)os;
     1706        if (output == NULL) {
     1707            return BUFFER_E;
     1708        }
     1709
     1710        ret = atmel_get_random_number(sz, output);
     1711
     1712        return ret;
     1713    }
    16101714
    16111715#elif defined(MICROCHIP_PIC32)
     
    18161920    #endif /* FREESCALE_K70_RNGA */
    18171921
     1922#elif defined(WOLFSSL_SILABS_SE_ACCEL)
     1923    int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
     1924    {
     1925        (void)os;
     1926        return silabs_GenerateRand(output, sz);
     1927    }
     1928
    18181929#elif defined(STM32_RNG)
    18191930     /* Generate a RNG seed using the hardware random number generator
     
    18471958            ) {
    18481959                /* Single byte at a time */
    1849                 uint32_t tmpRng = 0;
     1960                word32 tmpRng = 0;
    18501961                if (HAL_RNG_GenerateRandomNumber(&hrng, &tmpRng) != HAL_OK) {
    18511962                    wolfSSL_CryptHwMutexUnLock();
     
    18561967            else {
    18571968                /* Use native 32 instruction */
    1858                 if (HAL_RNG_GenerateRandomNumber(&hrng, (uint32_t*)&output[i]) != HAL_OK) {
     1969                if (HAL_RNG_GenerateRandomNumber(&hrng, (word32*)&output[i]) != HAL_OK) {
    18591970                    wolfSSL_CryptHwMutexUnLock();
    18601971                    return RAN_BLOCK_E;
     
    20532164    }
    20542165
    2055 #elif defined(WOLFSSL_NRF51)
     2166#elif defined(WOLFSSL_NRF51) || defined(WOLFSSL_NRF5x)
    20562167    #include "app_error.h"
    20572168    #include "nrf_drv_rng.h"
     
    20592170    {
    20602171        int remaining = sz, length, pos = 0;
    2061         uint8_t available;
    2062         uint32_t err_code;
     2172        word32 err_code;
     2173        byte available;
     2174        static byte initialized = 0;
    20632175
    20642176        (void)os;
    20652177
    20662178        /* Make sure RNG is running */
    2067         err_code = nrf_drv_rng_init(NULL);
    2068         if (err_code != NRF_SUCCESS && err_code != NRF_ERROR_INVALID_STATE) {
    2069             return -1;
     2179        if (!initialized) {
     2180            err_code = nrf_drv_rng_init(NULL);
     2181            if (err_code != NRF_SUCCESS && err_code != NRF_ERROR_INVALID_STATE
     2182            #ifdef NRF_ERROR_MODULE_ALREADY_INITIALIZED
     2183                && err_code != NRF_ERROR_MODULE_ALREADY_INITIALIZED
     2184            #endif
     2185            ) {
     2186                return -1;
     2187            }
     2188            initialized = 1;
    20702189        }
    20712190
    20722191        while (remaining > 0) {
    2073             err_code = nrf_drv_rng_bytes_available(&available);
    2074             if (err_code == NRF_SUCCESS) {
    2075                 length = (remaining < available) ? remaining : available;
    2076                 if (length > 0) {
    2077                     err_code = nrf_drv_rng_rand(&output[pos], length);
    2078                     remaining -= length;
    2079                     pos += length;
     2192            available = 0;
     2193            nrf_drv_rng_bytes_available(&available); /* void func */
     2194            length = (remaining < available) ? remaining : available;
     2195            if (length > 0) {
     2196                err_code = nrf_drv_rng_rand(&output[pos], length);
     2197                if (err_code != NRF_SUCCESS) {
     2198                    break;
    20802199                }
    2081             }
    2082 
    2083             if (err_code != NRF_SUCCESS) {
    2084                 break;
     2200                remaining -= length;
     2201                pos += length;
    20852202            }
    20862203        }
     
    21152232
    21162233        return 0;
    2117     }
    2118 
    2119 #elif defined(WOLFSSL_ATMEL)
    2120     #include <wolfssl/wolfcrypt/port/atmel/atmel.h>
    2121 
    2122     int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
    2123     {
    2124         int ret = 0;
    2125 
    2126         (void)os;
    2127         if (output == NULL) {
    2128             return BUFFER_E;
    2129         }
    2130 
    2131         ret = atmel_get_random_number(sz, output);
    2132 
    2133         return ret;
    21342234    }
    21352235
     
    22902390    #endif /* end WOLFSSL_ESPWROOM32 */
    22912391
     2392#elif defined(WOLFSSL_LINUXKM)
     2393    #include <linux/random.h>
     2394    int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
     2395    {
     2396        (void)os;
     2397
     2398        get_random_bytes(output, sz);
     2399
     2400        return 0;
     2401    }
     2402
    22922403#elif defined(WOLFSSL_RENESAS_TSIP)
    22932404#if defined(WOLFSSL_RENESA_TSIP_IAREWRX)
    2294     #include "r_bsp/mcu/all/r_rx_compiler.h"
    2295 #endif
    2296     #include "r_bsp/platform.h"
     2405   #include "r_bsp/mcu/all/r_rx_compiler.h"
     2406#endif
     2407   #include "r_bsp/platform.h"
    22972408    #include "r_tsip_rx_if.h"
    2298    
     2409
    22992410    int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
    23002411    {
    23012412        int ret;
    2302         uint32_t buffer[4];
     2413        word32 buffer[4];
    23032414
    23042415        while (sz > 0) {
    2305             uint32_t len = sizeof(buffer);
    2306            
     2416            word32 len = sizeof(buffer);
     2417
    23072418            if (sz < len) {
    23082419                len = sz;
     
    23292440    int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz)
    23302441    {
    2331         uint32_t ret;
    2332         uint32_t blocks;
    2333         word32   len = sz;
     2442        word32 ret;
     2443        word32 blocks;
     2444        word32 len = sz;
    23342445
    23352446        ret = WOLFSSL_SCE_TRNG_HANDLE.p_api->open(WOLFSSL_SCE_TRNG_HANDLE.p_ctrl,
     
    23402451        }
    23412452
    2342         blocks = sz / sizeof(uint32_t);
     2453        blocks = sz / sizeof(word32);
    23432454        if (blocks > 0) {
    23442455            ret = WOLFSSL_SCE_TRNG_HANDLE.p_api->read(WOLFSSL_SCE_TRNG_HANDLE.p_ctrl,
    2345                                                       (uint32_t*)output, blocks);
     2456                                                       (word32*)output, blocks);
    23462457            if (ret != SSP_SUCCESS) {
    23472458                return -1;
     
    23492460        }
    23502461
    2351         len = len - (blocks * sizeof(uint32_t));
     2462        len = len - (blocks * sizeof(word32));
    23522463        if (len > 0) {
    2353             uint32_t tmp;
    2354 
    2355             if (len > sizeof(uint32_t)) {
     2464            word32 tmp;
     2465
     2466            if (len > sizeof(word32)) {
    23562467                return -1;
    23572468            }
    23582469            ret = WOLFSSL_SCE_TRNG_HANDLE.p_api->read(WOLFSSL_SCE_TRNG_HANDLE.p_ctrl,
    2359                                                       (uint32_t*)tmp, 1);
     2470                                                      (word32*)tmp, 1);
    23602471            if (ret != SSP_SUCCESS) {
    23612472                return -1;
    23622473            }
    2363             XMEMCPY(output + (blocks * sizeof(uint32_t)), (byte*)&tmp, len);
     2474            XMEMCPY(output + (blocks * sizeof(word32)), (byte*)&tmp, len);
    23642475        }
    23652476
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/rsa.c

    r457 r464  
    2020 */
    2121
    22 
     22/*
     23
     24DESCRIPTION
     25This library provides the interface to the RSA.
     26RSA keys can be used to encrypt, decrypt, sign and verify data.
     27
     28*/
    2329#ifdef HAVE_CONFIG_H
    2430    #include <config.h>
     
    336342}
    337343
    338 #ifdef HAVE_PKCS11
     344#ifdef WOLF_CRYPTO_CB
    339345int wc_InitRsaKey_Id(RsaKey* key, unsigned char* id, int len, void* heap,
    340346                     int devId)
     
    349355    if (ret == 0)
    350356        ret = wc_InitRsaKey_ex(key, heap, devId);
    351 
    352357    if (ret == 0 && id != NULL && len != 0) {
    353358        XMEMCPY(key->id, id, len);
    354359        key->idLen = len;
     360    }
     361
     362    return ret;
     363}
     364
     365int wc_InitRsaKey_Label(RsaKey* key, const char* label, void* heap, int devId)
     366{
     367    int ret = 0;
     368    int labelLen = 0;
     369
     370    if (key == NULL || label == NULL)
     371        ret = BAD_FUNC_ARG;
     372    if (ret == 0) {
     373        labelLen = (int)XSTRLEN(label);
     374        if (labelLen == 0 || labelLen > RSA_MAX_LABEL_LEN)
     375            ret = BUFFER_E;
     376    }
     377
     378    if (ret == 0)
     379        ret = wc_InitRsaKey_ex(key, heap, devId);
     380    if (ret == 0) {
     381        XMEMCPY(key->label, label, labelLen);
     382        key->labelLen = labelLen;
    355383    }
    356384
     
    381409    mSz = mp_unsigned_bin_size(&(key->n));
    382410    m = (unsigned char*)XMALLOC(mSz, key->heap, DYNAMIC_TYPE_KEY);
    383     if (m == 0) {
     411    if (m == NULL) {
    384412        return MEMORY_E;
    385413    }
     
    478506    CRYS_RSAKGFipsContext_t FipsCtx;
    479507    byte ex[3];
    480     uint16_t eSz = sizeof(ex);
     508    word16 eSz = sizeof(ex);
    481509    byte n[256];
    482     uint16_t nSz = sizeof(n);
     510    word16 nSz = sizeof(n);
    483511
    484512    ret = CRYS_RSA_KG_GenerateKeyPair(&wc_rndState,
    485513                        wc_rndGenVectFunc,
    486514                        (byte*)&e,
    487                         3*sizeof(uint8_t),
     515                        3*sizeof(byte),
    488516                        size,
    489517                        &key->ctx.privKey,
     
    606634            ret = MP_READ_E;
    607635    }
    608 
    609636#ifdef WOLFSSL_HAVE_SP_RSA
    610 #ifndef WOLFSSL_SP_NO_2048
    611     if (mp_count_bits(&key->n) == 2048) {
    612         ret = sp_ModExp_2048(k, &key->e, &key->n, tmp);
    613         if (ret != 0)
     637    if (ret == 0) {
     638        switch (mp_count_bits(&key->n)) {
     639    #ifndef WOLFSSL_SP_NO_2048
     640            case 2048:
     641                ret = sp_ModExp_2048(k, &key->e, &key->n, tmp);
     642                if (ret != 0)
     643                    ret = MP_EXPTMOD_E;
     644                if (ret == 0) {
     645                    ret = sp_ModExp_2048(tmp, &key->d, &key->n, tmp);
     646                    if (ret != 0)
     647                        ret = MP_EXPTMOD_E;
     648                }
     649                break;
     650    #endif /* WOLFSSL_SP_NO_2048 */
     651    #ifndef WOLFSSL_SP_NO_3072
     652            case 3072:
     653                ret = sp_ModExp_3072(k, &key->e, &key->n, tmp);
     654                if (ret != 0)
     655                    ret = MP_EXPTMOD_E;
     656                if (ret == 0) {
     657                  ret = sp_ModExp_3072(tmp, &key->d, &key->n, tmp);
     658                  if (ret != 0)
     659                      ret = MP_EXPTMOD_E;
     660                }
     661                break;
     662    #endif /* WOLFSSL_SP_NO_3072 */
     663    #ifdef WOLFSSL_SP_4096
     664            case 4096:
     665                ret = sp_ModExp_4096(k, &key->e, &key->n, tmp);
     666                if (ret != 0)
     667                    ret = MP_EXPTMOD_E;
     668                if (ret == 0) {
     669                  ret = sp_ModExp_4096(tmp, &key->d, &key->n, tmp);
     670                  if (ret != 0)
     671                      ret = MP_EXPTMOD_E;
     672                }
     673                break;
     674    #endif /* WOLFSSL_SP_4096 */
     675                default:
     676                /* If using only single precsision math then issue key size
     677                 * error, otherwise fall-back to multi-precision math
     678                 * calculation */
     679                #if defined(WOLFSSL_SP_MATH)
     680                    ret = WC_KEY_SIZE_E;
     681                #else
     682                    if (mp_exptmod_nct(k, &key->e, &key->n, tmp) != MP_OKAY)
     683                        ret = MP_EXPTMOD_E;
     684                    if (ret == 0) {
     685                        if (mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY)
     686                            ret = MP_EXPTMOD_E;
     687                    }
     688                #endif
     689                    break;
     690        }
     691    }
     692#else
     693    if (ret == 0) {
     694        if (mp_exptmod_nct(k, &key->e, &key->n, tmp) != MP_OKAY)
    614695            ret = MP_EXPTMOD_E;
    615         ret = sp_ModExp_2048(tmp, &key->d, &key->n, tmp);
    616         if (ret != 0)
     696    }
     697
     698    if (ret == 0) {
     699        if (mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY)
    617700            ret = MP_EXPTMOD_E;
    618701    }
    619     else
    620 #endif
    621 #ifndef WOLFSSL_SP_NO_3072
    622     if (mp_count_bits(&key->n) == 3072) {
    623         ret = sp_ModExp_3072(k, &key->e, &key->n, tmp);
    624         if (ret != 0)
    625             ret = MP_EXPTMOD_E;
    626         ret = sp_ModExp_3072(tmp, &key->d, &key->n, tmp);
    627         if (ret != 0)
    628             ret = MP_EXPTMOD_E;
    629     }
    630     else
    631 #endif
    632 #ifdef WOLFSSL_SP_4096
    633     if (mp_count_bits(&key->n) == 4096) {
    634         ret = sp_ModExp_4096(k, &key->e, &key->n, tmp);
    635         if (ret != 0)
    636             ret = MP_EXPTMOD_E;
    637         ret = sp_ModExp_4096(tmp, &key->d, &key->n, tmp);
    638         if (ret != 0)
    639             ret = MP_EXPTMOD_E;
    640     }
    641     else
    642 #endif
    643 #endif
    644 #ifdef WOLFSSL_SP_MATH
    645     {
    646         ret = WC_KEY_SIZE_E;
    647     }
    648 #else
    649     {
    650         if (ret == 0) {
    651             if (mp_exptmod(k, &key->e, &key->n, tmp) != MP_OKAY)
    652                 ret = MP_EXPTMOD_E;
    653         }
    654 
    655         if (ret == 0) {
    656             if (mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY)
    657                 ret = MP_EXPTMOD_E;
    658         }
    659     }
    660 #endif
     702#endif /* WOLFSSL_HAVE_SP_RSA */
    661703
    662704    if (ret == 0) {
     
    757799    return ret;
    758800}
    759 #endif
    760 #endif
     801#endif /* WOLFSSL_KEY_GEN && !WOLFSSL_NO_RSA_KEY_CHECK */
     802#endif /* WOLFSSL_RSA_PUBLIC_ONLY */
    761803
    762804
     
    816858
    817859        /* counter to byte array appended to tmp */
    818         tmp[seedSz]     = (counter >> 24) & 0xFF;
    819         tmp[seedSz + 1] = (counter >> 16) & 0xFF;
    820         tmp[seedSz + 2] = (counter >>  8) & 0xFF;
    821         tmp[seedSz + 3] = (counter)       & 0xFF;
     860        tmp[seedSz]     = (byte)((counter >> 24) & 0xFF);
     861        tmp[seedSz + 1] = (byte)((counter >> 16) & 0xFF);
     862        tmp[seedSz + 2] = (byte)((counter >>  8) & 0xFF);
     863        tmp[seedSz + 3] = (byte)((counter)       & 0xFF);
    822864
    823865        /* hash and append to existing output */
     
    11031145    byte* m;
    11041146    byte* s;
     1147#if defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_STATIC_MEMORY)
     1148    byte msg[RSA_MAX_SIZE/8 + RSA_PSS_PAD_SZ];
     1149#else
     1150    byte* msg = NULL;
     1151#endif
    11051152#if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
    1106     #if defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_STATIC_MEMORY)
    1107         byte salt[RSA_MAX_SIZE/8 + RSA_PSS_PAD_SZ];
    1108     #else
    1109         byte* salt = NULL;
    1110     #endif
     1153    byte* salt;
    11111154#else
    11121155    byte salt[WC_MAX_DIGEST_SIZE];
     
    11221165    if (hLen < 0)
    11231166        return hLen;
     1167    if ((int)inputLen != hLen) {
     1168        return BAD_FUNC_ARG;
     1169    }
    11241170
    11251171    hiBits = (bits - 1) & 0x7;
    11261172    if (hiBits == 0) {
     1173        /* Per RFC8017, set the leftmost 8emLen - emBits bits of the
     1174           leftmost octet in DB to zero.
     1175        */
    11271176        *(pkcsBlock++) = 0;
    11281177        pkcsBlockLen--;
     
    11611210        return PSS_SALTLEN_E;
    11621211    }
    1163 
    11641212    maskLen = pkcsBlockLen - 1 - hLen;
    11651213
    11661214#if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
    11671215    #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
    1168         salt = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inputLen + saltLen, heap,
     1216        msg = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inputLen + saltLen, heap,
    11691217                                                       DYNAMIC_TYPE_RSA_BUFFER);
    1170         if (salt == NULL) {
     1218        if (msg == NULL) {
    11711219            return MEMORY_E;
    11721220        }
    11731221    #endif
    1174     s = m = salt;
     1222    salt = s = m = msg;
    11751223    XMEMSET(m, 0, RSA_PSS_PAD_SZ);
    11761224    m += RSA_PSS_PAD_SZ;
     
    11851233    }
    11861234#else
    1187     s = m = pkcsBlock;
     1235    if (pkcsBlockLen < RSA_PSS_PAD_SZ + inputLen + saltLen) {
     1236    #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
     1237        msg = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inputLen + saltLen, heap,
     1238                                                       DYNAMIC_TYPE_RSA_BUFFER);
     1239        if (msg == NULL) {
     1240            return MEMORY_E;
     1241        }
     1242    #endif
     1243        m = msg;
     1244    }
     1245    else {
     1246        m = pkcsBlock;
     1247    }
     1248    s = m;
    11881249    XMEMSET(m, 0, RSA_PSS_PAD_SZ);
    11891250    m += RSA_PSS_PAD_SZ;
     
    12041265    }
    12051266    if (ret == 0) {
     1267       /* Set the last eight bits or trailer field to the octet 0xbc */
    12061268        pkcsBlock[pkcsBlockLen - 1] = RSA_PSS_PAD_TERM;
    12071269
     
    12091271    }
    12101272    if (ret == 0) {
    1211         pkcsBlock[0] &= (1 << hiBits) - 1;
     1273        /* Clear the first high bit when "8emLen - emBits" is non-zero.
     1274           where emBits = n modBits - 1 */
     1275        if (hiBits)
     1276            pkcsBlock[0] &= (1 << hiBits) - 1;
    12121277
    12131278        m = pkcsBlock + maskLen - saltLen - 1;
     
    12181283    }
    12191284
    1220 #if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
    12211285    #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
    1222         if (salt != NULL) {
    1223             XFREE(salt, heap, DYNAMIC_TYPE_RSA_BUFFER);
     1286        if (msg != NULL) {
     1287            XFREE(msg, heap, DYNAMIC_TYPE_RSA_BUFFER);
    12241288        }
    12251289    #endif
    1226 #endif
    12271290    return ret;
    12281291}
     
    12381301    }
    12391302
     1303    if (pkcsBlockLen - RSA_MIN_PAD_SZ < inputLen) {
     1304        WOLFSSL_MSG("RsaPad error, invalid length");
     1305        return RSA_PAD_E;
     1306    }
    12401307    pkcsBlock[0] = 0x0;       /* set first byte to zero and advance */
    12411308    pkcsBlock++; pkcsBlockLen--;
     
    12431310
    12441311    if (padValue == RSA_BLOCK_TYPE_1) {
    1245         if (pkcsBlockLen < inputLen + 2) {
    1246             WOLFSSL_MSG("RsaPad error, invalid length");
    1247             return RSA_PAD_E;
    1248         }
    12491312
    12501313        /* pad with 0xff bytes */
     
    12561319        word32 padLen, i;
    12571320        int    ret;
    1258 
    1259         if (pkcsBlockLen < inputLen + 1) {
    1260             WOLFSSL_MSG("RsaPad error, invalid length");
    1261             return RSA_PAD_E;
    1262         }
    1263 
    12641321        padLen = pkcsBlockLen - inputLen - 1;
    12651322        ret    = wc_RNG_GenerateBlock(rng, &pkcsBlock[1], padLen);
     
    14581515 * bits          Length of key in bits.
    14591516 * heap          Used for dynamic memory allocation.
    1460  * returns 0 on success, PSS_SALTLEN_E when the salt length is invalid,
    1461  * BAD_PADDING_E when the padding is not valid, MEMORY_E when allocation fails
    1462  * and other negative values on error.
     1517 * returns       the sum of salt length and SHA-256 digest size on success.
     1518 *               Otherwise, PSS_SALTLEN_E for an incorrect salt length,
     1519 *               WC_KEY_SIZE_E for an incorrect encoded message (EM) size
     1520                 and other negative values on error.
    14631521 */
    14641522static int RsaUnPad_PSS(byte *pkcsBlock, unsigned int pkcsBlockLen,
     
    15971655#endif
    15981656
    1599     if (output == NULL || pkcsBlockLen == 0 || pkcsBlockLen > 0xFFFF) {
     1657    if (output == NULL || pkcsBlockLen < 2 || pkcsBlockLen > 0xFFFF) {
    16001658        return BAD_FUNC_ARG;
    16011659    }
     
    17191777}
    17201778
    1721 #if defined(WOLFSSL_XILINX_CRYPT)
    1722 /*
    1723  * Xilinx hardened crypto acceleration.
    1724  *
    1725  * Returns 0 on success and negative values on error.
    1726  */
    1727 static int wc_RsaFunctionXil(const byte* in, word32 inLen, byte* out,
    1728                           word32* outLen, int type, RsaKey* key, WC_RNG* rng)
    1729 {
    1730     int    ret = 0;
    1731     word32 keyLen;
    1732     (void)rng;
    1733 
    1734     keyLen = wc_RsaEncryptSize(key);
    1735     if (keyLen > *outLen) {
    1736         WOLFSSL_MSG("Output buffer is not big enough");
    1737         return BAD_FUNC_ARG;
    1738     }
    1739 
    1740     if (inLen != keyLen) {
    1741         WOLFSSL_MSG("Expected that inLen equals RSA key length");
    1742         return BAD_FUNC_ARG;
    1743     }
    1744 
    1745     switch(type) {
    1746     case RSA_PRIVATE_DECRYPT:
    1747     case RSA_PRIVATE_ENCRYPT:
    1748         /* Currently public exponent is loaded by default.
    1749          * In SDK 2017.1 RSA exponent values are expected to be of 4 bytes
    1750          * leading to private key operations with Xsecure_RsaDecrypt not being
    1751          * supported */
    1752         ret = RSA_WRONG_TYPE_E;
     1779int wc_hash2mgf(enum wc_HashType hType)
     1780{
     1781    switch (hType) {
     1782    case WC_HASH_TYPE_NONE:
     1783        return WC_MGF1NONE;
     1784    case WC_HASH_TYPE_SHA:
     1785#ifndef NO_SHA
     1786        return WC_MGF1SHA1;
     1787#else
    17531788        break;
    1754     case RSA_PUBLIC_ENCRYPT:
    1755     case RSA_PUBLIC_DECRYPT:
    1756         if (XSecure_RsaDecrypt(&(key->xRsa), in, out) != XST_SUCCESS) {
    1757             ret = BAD_STATE_E;
    1758         }
     1789#endif
     1790    case WC_HASH_TYPE_SHA224:
     1791#ifdef WOLFSSL_SHA224
     1792        return WC_MGF1SHA224;
     1793#else
    17591794        break;
     1795#endif
     1796    case WC_HASH_TYPE_SHA256:
     1797#ifndef NO_SHA256
     1798        return WC_MGF1SHA256;
     1799#else
     1800        break;
     1801#endif
     1802    case WC_HASH_TYPE_SHA384:
     1803#ifdef WOLFSSL_SHA384
     1804        return WC_MGF1SHA384;
     1805#else
     1806        break;
     1807#endif
     1808    case WC_HASH_TYPE_SHA512:
     1809#ifdef WOLFSSL_SHA512
     1810        return WC_MGF1SHA512;
     1811#else
     1812        break;
     1813#endif
     1814    case WC_HASH_TYPE_MD2:
     1815    case WC_HASH_TYPE_MD4:
     1816    case WC_HASH_TYPE_MD5:
     1817    case WC_HASH_TYPE_MD5_SHA:
     1818    case WC_HASH_TYPE_SHA3_224:
     1819    case WC_HASH_TYPE_SHA3_256:
     1820    case WC_HASH_TYPE_SHA3_384:
     1821    case WC_HASH_TYPE_SHA3_512:
     1822    case WC_HASH_TYPE_BLAKE2B:
     1823    case WC_HASH_TYPE_BLAKE2S:
    17601824    default:
    1761         ret = RSA_WRONG_TYPE_E;
    1762     }
    1763 
    1764     *outLen = keyLen;
    1765 
    1766     return ret;
    1767 }
    1768 #endif /* WOLFSSL_XILINX_CRYPT */
     1825        break;
     1826    }
     1827    WOLFSSL_MSG("Unrecognized or unsupported hash function");
     1828    return WC_MGF1NONE;
     1829}
    17691830
    17701831#ifdef WC_RSA_NONBLOCK
     
    18461907#endif /* WC_RSA_NONBLOCK */
    18471908
    1848 #ifdef WOLFSSL_AFALG_XILINX_RSA
     1909#ifdef WOLFSSL_XILINX_CRYPT
     1910/*
     1911 * Xilinx hardened crypto acceleration.
     1912 *
     1913 * Returns 0 on success and negative values on error.
     1914 */
     1915static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out,
     1916                          word32* outLen, int type, RsaKey* key, WC_RNG* rng)
     1917{
     1918    int    ret = 0;
     1919    word32 keyLen;
     1920    (void)rng;
     1921
     1922    keyLen = wc_RsaEncryptSize(key);
     1923    if (keyLen > *outLen) {
     1924        WOLFSSL_MSG("Output buffer is not big enough");
     1925        return BAD_FUNC_ARG;
     1926    }
     1927
     1928    if (inLen != keyLen) {
     1929        WOLFSSL_MSG("Expected that inLen equals RSA key length");
     1930        return BAD_FUNC_ARG;
     1931    }
     1932
     1933    switch(type) {
     1934    case RSA_PRIVATE_DECRYPT:
     1935    case RSA_PRIVATE_ENCRYPT:
     1936    #ifdef WOLFSSL_XILINX_CRYPTO_OLD
     1937        /* Currently public exponent is loaded by default.
     1938         * In SDK 2017.1 RSA exponent values are expected to be of 4 bytes
     1939         * leading to private key operations with Xsecure_RsaDecrypt not being
     1940         * supported */
     1941        ret = RSA_WRONG_TYPE_E;
     1942    #else
     1943        {
     1944            byte *d;
     1945            int dSz;
     1946            XSecure_Rsa rsa;
     1947
     1948            dSz = mp_unsigned_bin_size(&key->d);
     1949            d = (byte*)XMALLOC(dSz, key->heap, DYNAMIC_TYPE_PRIVATE_KEY);
     1950            if (d == NULL) {
     1951                ret = MEMORY_E;
     1952            }
     1953            else {
     1954                ret = mp_to_unsigned_bin(&key->d, d);
     1955                XSecure_RsaInitialize(&rsa, key->mod, NULL, d);
     1956            }
     1957
     1958            if (ret == 0) {
     1959                if (XSecure_RsaPrivateDecrypt(&rsa, (u8*)in, inLen, out) !=
     1960                        XST_SUCCESS) {
     1961                    ret = BAD_STATE_E;
     1962                }
     1963            }
     1964
     1965            if (d != NULL) {
     1966                XFREE(d, key->heap, DYNAMIC_TYPE_PRIVATE_KEY);
     1967            }
     1968        }
     1969    #endif
     1970        break;
     1971    case RSA_PUBLIC_ENCRYPT:
     1972    case RSA_PUBLIC_DECRYPT:
     1973#ifdef WOLFSSL_XILINX_CRYPTO_OLD
     1974        if (XSecure_RsaDecrypt(&(key->xRsa), in, out) != XST_SUCCESS) {
     1975            ret = BAD_STATE_E;
     1976        }
     1977#else
     1978        /* starting at Xilinx release 2019 the function XSecure_RsaDecrypt was removed */
     1979        if (XSecure_RsaPublicEncrypt(&(key->xRsa), (u8*)in, inLen, out) != XST_SUCCESS) {
     1980            WOLFSSL_MSG("Error happened when calling hardware RSA public operation");
     1981            ret = BAD_STATE_E;
     1982        }
     1983#endif
     1984        break;
     1985    default:
     1986        ret = RSA_WRONG_TYPE_E;
     1987    }
     1988
     1989    *outLen = keyLen;
     1990
     1991    return ret;
     1992}
     1993
     1994#elif defined(WOLFSSL_AFALG_XILINX_RSA)
    18491995#ifndef ERROR_OUT
    18501996#define ERROR_OUT(x) ret = (x); goto done
     
    20102156                          word32* outLen, int type, RsaKey* key, WC_RNG* rng)
    20112157{
    2012 #ifndef WOLFSSL_SP_MATH
     2158#if !defined(WOLFSSL_SP_MATH)
    20132159#ifdef WOLFSSL_SMALL_STACK
    20142160    mp_int* tmp;
     
    20392185    #endif
    20402186    #ifndef RSA_LOW_MEM
    2041             return sp_RsaPrivate_2048(in, inLen, &key->d, &key->p, &key->q,
    2042                                       &key->dP, &key->dQ, &key->u, &key->n,
    2043                                       out, outLen);
     2187            if ((mp_count_bits(&key->p) == 1024) &&
     2188                                             (mp_count_bits(&key->q) == 1024)) {
     2189                return sp_RsaPrivate_2048(in, inLen, &key->d, &key->p, &key->q,
     2190                                          &key->dP, &key->dQ, &key->u, &key->n,
     2191                                          out, outLen);
     2192            }
     2193            break;
    20442194    #else
    2045             return sp_RsaPrivate_2048(in, inLen, &key->d, &key->p, &key->q,
    2046                                       NULL, NULL, NULL, &key->n, out, outLen);
     2195            return sp_RsaPrivate_2048(in, inLen, &key->d, NULL, NULL, NULL,
     2196                                      NULL, NULL, &key->n, out, outLen);
    20472197    #endif
    20482198#endif
     
    20642214    #endif
    20652215    #ifndef RSA_LOW_MEM
    2066             return sp_RsaPrivate_3072(in, inLen, &key->d, &key->p, &key->q,
    2067                                       &key->dP, &key->dQ, &key->u, &key->n,
    2068                                       out, outLen);
     2216            if ((mp_count_bits(&key->p) == 1536) &&
     2217                                             (mp_count_bits(&key->q) == 1536)) {
     2218                return sp_RsaPrivate_3072(in, inLen, &key->d, &key->p, &key->q,
     2219                                          &key->dP, &key->dQ, &key->u, &key->n,
     2220                                          out, outLen);
     2221            }
     2222            break;
    20692223    #else
    2070             return sp_RsaPrivate_3072(in, inLen, &key->d, &key->p, &key->q,
    2071                                       NULL, NULL, NULL, &key->n, out, outLen);
     2224            return sp_RsaPrivate_3072(in, inLen, &key->d, NULL, NULL, NULL,
     2225                                      NULL, NULL, &key->n, out, outLen);
    20722226    #endif
    20732227#endif
     
    20892243    #endif
    20902244    #ifndef RSA_LOW_MEM
    2091             return sp_RsaPrivate_4096(in, inLen, &key->d, &key->p, &key->q,
    2092                                       &key->dP, &key->dQ, &key->u, &key->n,
    2093                                       out, outLen);
     2245            if ((mp_count_bits(&key->p) == 2048) &&
     2246                                             (mp_count_bits(&key->q) == 2048)) {
     2247                return sp_RsaPrivate_4096(in, inLen, &key->d, &key->p, &key->q,
     2248                                          &key->dP, &key->dQ, &key->u, &key->n,
     2249                                          out, outLen);
     2250            }
     2251            break;
    20942252    #else
    2095             return sp_RsaPrivate_4096(in, inLen, &key->d, &key->p, &key->q,
    2096                                       NULL, NULL, NULL, &key->n, out, outLen);
     2253            return sp_RsaPrivate_4096(in, inLen, &key->d, NULL, NULL, NULL,
     2254                                      NULL, NULL, &key->n, out, outLen);
    20972255    #endif
    20982256#endif
     
    21052263#endif /* WOLFSSL_HAVE_SP_RSA */
    21062264
    2107 #ifdef WOLFSSL_SP_MATH
     2265#if defined(WOLFSSL_SP_MATH)
    21082266    (void)rng;
    21092267    WOLFSSL_MSG("SP Key Size Error");
     
    21162274    if (tmp == NULL)
    21172275        return MEMORY_E;
     2276#if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY)
    21182277#ifdef WC_RSA_BLINDING
    21192278    rnd = (mp_int*)XMALLOC(sizeof(mp_int) * 2, key->heap, DYNAMIC_TYPE_RSA);
     
    21242283    rndi = rnd + 1;
    21252284#endif /* WC_RSA_BLINDING */
     2285#endif
    21262286#endif /* WOLFSSL_SMALL_STACK */
    21272287
     
    21292289        ret = MP_INIT_E;
    21302290
     2291#if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY)
    21312292#ifdef WC_RSA_BLINDING
    21322293    if (ret == 0) {
     
    21392300    }
    21402301#endif
     2302#endif
    21412303
    21422304#ifndef TEST_UNPAD_CONSTANT_TIME
     
    21462308    if (ret == 0) {
    21472309        switch(type) {
    2148     #ifndef WOLFSSL_RSA_PUBLIC_ONLY
     2310    #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY)
    21492311        case RSA_PRIVATE_DECRYPT:
    21502312        case RSA_PRIVATE_ENCRYPT:
     
    21592321
    21602322            /* rnd = rnd^e */
     2323        #ifndef WOLFSSL_SP_MATH_ALL
    21612324            if (ret == 0 && mp_exptmod(rnd, &key->e, &key->n, rnd) != MP_OKAY)
    21622325                ret = MP_EXPTMOD_E;
     2326        #else
     2327            if (ret == 0 && mp_exptmod_nct(rnd, &key->e, &key->n,
     2328                                                              rnd) != MP_OKAY) {
     2329                ret = MP_EXPTMOD_E;
     2330            }
     2331        #endif
    21632332
    21642333            /* tmp = tmp*rnd mod n */
     
    22142383
    22152384                /* tmp = (tmpa - tmpb) * qInv (mod p) */
     2385#if defined(WOLFSSL_SP_MATH) || (defined(WOLFSSL_SP_MATH_ALL) && \
     2386                                              !defined(WOLFSSL_SP_INT_NEGATIVE))
     2387                if (ret == 0 && mp_submod(tmpa, tmpb, &key->p, tmp) != MP_OKAY)
     2388                    ret = MP_SUB_E;
     2389#else
    22162390                if (ret == 0 && mp_sub(tmpa, tmpb, tmp) != MP_OKAY)
    22172391                    ret = MP_SUB_E;
     2392#endif
    22182393
    22192394                if (ret == 0 && mp_mulmod(tmp, &key->u, &key->p,
     
    22542429        case RSA_PUBLIC_ENCRYPT:
    22552430        case RSA_PUBLIC_DECRYPT:
    2256         #ifdef WOLFSSL_XILINX_CRYPT
    2257             ret = wc_RsaFunctionXil(in, inLen, out, outLen, type, key, rng);
    2258         #else
    22592431            if (mp_exptmod_nct(tmp, &key->e, &key->n, tmp) != MP_OKAY)
    22602432                ret = MP_EXPTMOD_E;
    2261         #endif
    22622433            break;
    22632434        default:
     
    22722443            ret = RSA_BUFFER_E;
    22732444    }
     2445
     2446#ifndef WOLFSSL_XILINX_CRYPT
    22742447    if (ret == 0) {
    22752448        *outLen = keyLen;
     
    22772450             ret = MP_TO_E;
    22782451    }
     2452#endif
    22792453#else
    22802454    (void)type;
     
    25102684    CRYSError_t ret = 0;
    25112685    CRYS_RSAPrimeData_t primeData;
    2512     uint16_t actualOutLen = outLen;
     2686    word16 actualOutLen = outLen;
    25132687
    25142688    ret = CRYS_RSA_PKCS1v15_Decrypt(&key->ctx.privKey,
     
    25302704{
    25312705    CRYSError_t ret = 0;
    2532     uint16_t actualOutLen = outLen*sizeof(byte);
     2706    word16 actualOutLen = outLen*sizeof(byte);
    25332707    CRYS_RSAPrivUserContext_t  contextPrivate;
    25342708
     
    25932767#endif
    25942768
     2769#ifndef WOLFSSL_RSA_VERIFY_ONLY
    25952770#ifndef TEST_UNPAD_CONSTANT_TIME
    25962771#ifndef NO_RSA_BOUNDS_CHECK
     
    26122787
    26132788        if (mp_init(c) != MP_OKAY)
    2614             ret = MEMORY_E;
     2789            ret = MP_INIT_E;
    26152790        if (ret == 0) {
    26162791            if (mp_read_unsigned_bin(c, in, inLen) != 0)
     
    26422817    }
    26432818#endif /* NO_RSA_BOUNDS_CHECK */
     2819#endif
    26442820#endif
    26452821
     
    29903166        if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
    29913167                                                   pad_type != WC_RSA_PSS_PAD) {
    2992             if (ret > 0) {
     3168            ret = key->asyncDev.event.ret;
     3169            if (ret >= 0) {
    29933170                /* convert result */
    29943171                byte* dataLen = (byte*)&key->dataLen;
     
    31323309                                                                 RsaKey* key)
    31333310{
    3134     return wc_RsaSSL_Verify_ex(in, inLen, out, outLen, key , WC_RSA_PKCSV15_PAD);
     3311    return wc_RsaSSL_Verify_ex(in, inLen, out, outLen, key, WC_RSA_PKCSV15_PAD);
    31353312}
    31363313
     
    31383315                         RsaKey* key, int pad_type)
    31393316{
     3317    return wc_RsaSSL_Verify_ex2(in, inLen, out, outLen, key, pad_type,
     3318            WC_HASH_TYPE_NONE);
     3319}
     3320
     3321int  wc_RsaSSL_Verify_ex2(const byte* in, word32 inLen, byte* out, word32 outLen,
     3322                         RsaKey* key, int pad_type, enum wc_HashType hash)
     3323{
    31403324    WC_RNG* rng;
    31413325
     
    31503334#endif
    31513335
     3336#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
    31523337    return RsaPrivateDecryptEx((byte*)in, inLen, out, outLen, NULL, key,
    31533338        RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, pad_type,
    3154         WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
     3339        hash, wc_hash2mgf(hash), NULL, 0, RSA_PSS_SALT_LEN_DEFAULT, rng);
     3340#else
     3341    return RsaPrivateDecryptEx((byte*)in, inLen, out, outLen, NULL, key,
     3342        RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, pad_type,
     3343        hash, wc_hash2mgf(hash), NULL, 0, RSA_PSS_SALT_LEN_DISCOVER, rng);
     3344#endif
    31553345}
    31563346#endif
     
    34073597    hLen = wc_HashGetDigestSize(hash);
    34083598    if (hLen < 0)
    3409         return hLen;
     3599        return BAD_FUNC_ARG;
    34103600    if ((word32)hLen != digestLen)
    34113601        return BAD_FUNC_ARG;
     
    36743864        ret = mp_sub(p, q, &d);
    36753865
     3866#if !defined(WOLFSSL_SP_MATH) && (!defined(WOLFSSL_SP_MATH_ALL) || \
     3867                                               defined(WOLFSSL_SP_INT_NEGATIVE))
    36763868    if (ret == 0)
    36773869        ret = mp_abs(&d, &d);
     3870#endif
    36783871
    36793872    /* compare */
     
    38874080{
    38884081#ifndef WC_NO_RNG
    3889     mp_int p, q, tmp1, tmp2, tmp3;
     4082#ifdef WOLFSSL_SMALL_STACK
     4083    mp_int *p = (mp_int *)XMALLOC(sizeof *p, key->heap, DYNAMIC_TYPE_RSA);
     4084    mp_int *q = (mp_int *)XMALLOC(sizeof *q, key->heap, DYNAMIC_TYPE_RSA);
     4085    mp_int *tmp1 = (mp_int *)XMALLOC(sizeof *tmp1, key->heap, DYNAMIC_TYPE_RSA);
     4086    mp_int *tmp2 = (mp_int *)XMALLOC(sizeof *tmp2, key->heap, DYNAMIC_TYPE_RSA);
     4087    mp_int *tmp3 = (mp_int *)XMALLOC(sizeof *tmp3, key->heap, DYNAMIC_TYPE_RSA);
     4088#else
     4089    mp_int p_buf, *p = &p_buf;
     4090    mp_int q_buf, *q = &q_buf;
     4091    mp_int tmp1_buf, *tmp1 = &tmp1_buf;
     4092    mp_int tmp2_buf, *tmp2 = &tmp2_buf;
     4093    mp_int tmp3_buf, *tmp3 = &tmp3_buf;
     4094#endif
    38904095    int err, i, failCount, primeSz, isPrime = 0;
    38914096    byte* buf = NULL;
    38924097
    3893     if (key == NULL || rng == NULL)
    3894         return BAD_FUNC_ARG;
    3895 
    3896     if (!RsaSizeCheck(size))
    3897         return BAD_FUNC_ARG;
    3898 
    3899     if (e < 3 || (e & 1) == 0)
    3900         return BAD_FUNC_ARG;
     4098#ifdef WOLFSSL_SMALL_STACK
     4099    if ((p == NULL) ||
     4100        (q == NULL) ||
     4101        (tmp1 == NULL) ||
     4102        (tmp2 == NULL) ||
     4103        (tmp3 == NULL)) {
     4104      err = MEMORY_E;
     4105      goto out;
     4106    }
     4107#endif
     4108
     4109    if (key == NULL || rng == NULL) {
     4110        err = BAD_FUNC_ARG;
     4111        goto out;
     4112    }
     4113
     4114    if (!RsaSizeCheck(size)) {
     4115        err = BAD_FUNC_ARG;
     4116        goto out;
     4117    }
     4118
     4119    if (e < 3 || (e & 1) == 0) {
     4120        err = BAD_FUNC_ARG;
     4121        goto out;
     4122    }
    39014123
    39024124#if defined(WOLFSSL_CRYPTOCELL)
    39034125
    3904     return cc310_RSA_GenerateKeyPair(key, size, e);
     4126    err = cc310_RSA_GenerateKeyPair(key, size, e);
     4127    goto out;
    39054128
    39064129#endif /*WOLFSSL_CRYPTOCELL*/
     
    39084131#ifdef WOLF_CRYPTO_CB
    39094132    if (key->devId != INVALID_DEVID) {
    3910         int ret = wc_CryptoCb_MakeRsaKey(key, size, e, rng);
    3911         if (ret != CRYPTOCB_UNAVAILABLE)
    3912             return ret;
     4133        err = wc_CryptoCb_MakeRsaKey(key, size, e, rng);
     4134        if (err != CRYPTOCB_UNAVAILABLE)
     4135            goto out;
    39134136        /* fall-through when unavailable */
    39144137    }
     
    39214144        /* TODO: Not implemented */
    39224145    #elif defined(HAVE_INTEL_QA)
    3923         return IntelQaRsaKeyGen(&key->asyncDev, key, size, e, rng);
     4146        err = IntelQaRsaKeyGen(&key->asyncDev, key, size, e, rng);
     4147        goto out;
    39244148    #else
    39254149        if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_RSA_MAKE)) {
     
    39294153            testDev->rsaMake.size = size;
    39304154            testDev->rsaMake.e = e;
    3931             return WC_PENDING_E;
     4155            err = WC_PENDING_E;
     4156            goto out;
    39324157        }
    39334158    #endif
     
    39354160#endif
    39364161
    3937     err = mp_init_multi(&p, &q, &tmp1, &tmp2, &tmp3, NULL);
     4162    err = mp_init_multi(p, q, tmp1, tmp2, tmp3, NULL);
    39384163
    39394164    if (err == MP_OKAY)
    3940         err = mp_set_int(&tmp3, e);
     4165        err = mp_set_int(tmp3, e);
    39414166
    39424167    /* The failCount value comes from NIST FIPS 186-4, section B.3.3,
     
    39704195                buf[primeSz-1] |= 0x01;
    39714196                /* load value */
    3972                 err = mp_read_unsigned_bin(&p, buf, primeSz);
     4197                err = mp_read_unsigned_bin(p, buf, primeSz);
    39734198            }
    39744199
    39754200            if (err == MP_OKAY)
    3976                 err = _CheckProbablePrime(&p, NULL, &tmp3, size, &isPrime, rng);
     4201                err = _CheckProbablePrime(p, NULL, tmp3, size, &isPrime, rng);
    39774202
    39784203#ifdef HAVE_FIPS
     
    40054230                buf[primeSz-1] |= 0x01;
    40064231                /* load value */
    4007                 err = mp_read_unsigned_bin(&q, buf, primeSz);
     4232                err = mp_read_unsigned_bin(q, buf, primeSz);
    40084233            }
    40094234
    40104235            if (err == MP_OKAY)
    4011                 err = _CheckProbablePrime(&p, &q, &tmp3, size, &isPrime, rng);
     4236                err = _CheckProbablePrime(p, q, tmp3, size, &isPrime, rng);
    40124237
    40134238#ifdef HAVE_FIPS
     
    40284253    }
    40294254
    4030     if (err == MP_OKAY && mp_cmp(&p, &q) < 0) {
    4031         err = mp_copy(&p, &tmp1);
     4255    if (err == MP_OKAY && mp_cmp(p, q) < 0) {
     4256        err = mp_copy(p, tmp1);
    40324257        if (err == MP_OKAY)
    4033             err = mp_copy(&q, &p);
     4258            err = mp_copy(q, p);
    40344259        if (err == MP_OKAY)
    4035             mp_copy(&tmp1, &q);
     4260            mp_copy(tmp1, q);
    40364261    }
    40374262
     
    40444269    /* Software Key Calculation */
    40454270    if (err == MP_OKAY)                /* tmp1 = p-1 */
    4046         err = mp_sub_d(&p, 1, &tmp1);
     4271        err = mp_sub_d(p, 1, tmp1);
    40474272    if (err == MP_OKAY)                /* tmp2 = q-1 */
    4048         err = mp_sub_d(&q, 1, &tmp2);
     4273        err = mp_sub_d(q, 1, tmp2);
    40494274#ifdef WC_RSA_BLINDING
    40504275    if (err == MP_OKAY)                /* tmp3 = order of n */
    4051         err = mp_mul(&tmp1, &tmp2, &tmp3);
     4276        err = mp_mul(tmp1, tmp2, tmp3);
    40524277#else
    40534278    if (err == MP_OKAY)                /* tmp3 = lcm(p-1, q-1), last loop */
    4054         err = mp_lcm(&tmp1, &tmp2, &tmp3);
     4279        err = mp_lcm(tmp1, tmp2, tmp3);
    40554280#endif
    40564281    /* make key */
     
    40614286    if (err == MP_OKAY) {
    40624287        do {
    4063             err = mp_rand(&key->p, get_digit_count(&tmp3), rng);
     4288            err = mp_rand(&key->p, get_digit_count(tmp3), rng);
    40644289            if (err == MP_OKAY)
    40654290                err = mp_set_bit(&key->p, 0);
     
    40674292                err = mp_set_bit(&key->p, size - 1);
    40684293            if (err == MP_OKAY)
    4069                 err = mp_gcd(&key->p, &tmp3, &key->q);
     4294                err = mp_gcd(&key->p, tmp3, &key->q);
    40704295        }
    40714296        while ((err == MP_OKAY) && !mp_isone(&key->q));
     
    40754300#endif
    40764301    if (err == MP_OKAY)                /* key->d = 1/e mod lcm(p-1, q-1) */
    4077         err = mp_invmod(&key->e, &tmp3, &key->d);
     4302        err = mp_invmod(&key->e, tmp3, &key->d);
    40784303#ifdef WC_RSA_BLINDING
    40794304    /* Take off blinding from d and reset e */
    40804305    if (err == MP_OKAY)
    4081         err = mp_mulmod(&key->d, &key->p, &tmp3, &key->d);
     4306        err = mp_mulmod(&key->d, &key->p, tmp3, &key->d);
    40824307    if (err == MP_OKAY)
    40834308        err = mp_set_int(&key->e, (mp_digit)e);
    40844309#endif
    40854310    if (err == MP_OKAY)                /* key->n = pq */
    4086         err = mp_mul(&p, &q, &key->n);
     4311        err = mp_mul(p, q, &key->n);
    40874312    if (err == MP_OKAY)                /* key->dP = d mod(p-1) */
    4088         err = mp_mod(&key->d, &tmp1, &key->dP);
     4313        err = mp_mod(&key->d, tmp1, &key->dP);
    40894314    if (err == MP_OKAY)                /* key->dQ = d mod(q-1) */
    4090         err = mp_mod(&key->d, &tmp2, &key->dQ);
     4315        err = mp_mod(&key->d, tmp2, &key->dQ);
    40914316#ifdef WOLFSSL_MP_INVMOD_CONSTANT_TIME
    40924317    if (err == MP_OKAY)                /* key->u = 1/q mod p */
    4093         err = mp_invmod(&q, &p, &key->u);
     4318        err = mp_invmod(q, p, &key->u);
    40944319#else
    40954320    if (err == MP_OKAY)
    4096         err = mp_sub_d(&p, 2, &tmp3);
     4321        err = mp_sub_d(p, 2, tmp3);
    40974322    if (err == MP_OKAY)                /* key->u = 1/q mod p = q^p-2 mod p */
    4098         err = mp_exptmod(&q, &tmp3 , &p, &key->u);
     4323        err = mp_exptmod(q, tmp3 , p, &key->u);
    40994324#endif
    41004325    if (err == MP_OKAY)
    4101         err = mp_copy(&p, &key->p);
     4326        err = mp_copy(p, &key->p);
    41024327    if (err == MP_OKAY)
    4103         err = mp_copy(&q, &key->q);
     4328        err = mp_copy(q, &key->q);
    41044329
    41054330#ifdef HAVE_WOLF_BIGINT
     
    41264351        key->type = RSA_PRIVATE;
    41274352
    4128     mp_clear(&tmp1);
    4129     mp_clear(&tmp2);
    4130     mp_clear(&tmp3);
    4131     mp_clear(&p);
    4132     mp_clear(&q);
     4353    mp_clear(tmp1);
     4354    mp_clear(tmp2);
     4355    mp_clear(tmp3);
     4356    mp_clear(p);
     4357    mp_clear(q);
    41334358
    41344359#if defined(WOLFSSL_KEY_GEN) && !defined(WOLFSSL_NO_RSA_KEY_CHECK)
     
    41404365    if (err != 0) {
    41414366        wc_FreeRsaKey(key);
    4142         return err;
     4367        goto out;
    41434368    }
    41444369
     
    41484373    }
    41494374#endif
    4150     return 0;
     4375
     4376    err = 0;
     4377
     4378  out:
     4379
     4380#ifdef WOLFSSL_SMALL_STACK
     4381    if (p)
     4382        XFREE(p, key->heap, DYNAMIC_TYPE_RSA);
     4383    if (q)
     4384        XFREE(q, key->heap, DYNAMIC_TYPE_RSA);
     4385    if (tmp1)
     4386        XFREE(tmp1, key->heap, DYNAMIC_TYPE_RSA);
     4387    if (tmp2)
     4388        XFREE(tmp2, key->heap, DYNAMIC_TYPE_RSA);
     4389    if (tmp3)
     4390        XFREE(tmp3, key->heap, DYNAMIC_TYPE_RSA);
     4391#endif
     4392
     4393    return err;
    41514394#else
    41524395    return NOT_COMPILED_IN;
     
    41604403int wc_RsaSetRNG(RsaKey* key, WC_RNG* rng)
    41614404{
     4405    if (key == NULL || rng == NULL)
     4406        return BAD_FUNC_ARG;
     4407
     4408    key->rng = rng;
     4409
     4410    return 0;
     4411}
     4412#endif /* WC_RSA_BLINDING */
     4413
     4414#ifdef WC_RSA_NONBLOCK
     4415int wc_RsaSetNonBlock(RsaKey* key, RsaNb* nb)
     4416{
    41624417    if (key == NULL)
    41634418        return BAD_FUNC_ARG;
    41644419
    4165     key->rng = rng;
    4166 
    4167     return 0;
    4168 }
    4169 #endif /* WC_RSA_BLINDING */
    4170 
    4171 #ifdef WC_RSA_NONBLOCK
    4172 int wc_RsaSetNonBlock(RsaKey* key, RsaNb* nb)
    4173 {
    4174     if (key == NULL)
    4175         return BAD_FUNC_ARG;
    4176 
    41774420    if (nb) {
    41784421        XMEMSET(nb, 0, sizeof(RsaNb));
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/sha.c

    r457 r464  
    191191    int wc_ShaFinal(wc_Sha* sha, byte* hash)
    192192    {
    193         uint32_t hashlen = WC_SHA_DIGEST_SIZE;
     193        word32 hashlen = WC_SHA_DIGEST_SIZE;
    194194        LTC_HASH_Finish(&sha->ctx, hash, &hashlen);
    195195        return wc_InitSha(sha);  /* reset state */
     
    225225        cau_sha1_initialize_output(sha->digest);
    226226    #else
    227         MMCAU_SHA1_InitializeOutput((uint32_t*)sha->digest);
     227        MMCAU_SHA1_InitializeOutput((word32*)sha->digest);
    228228    #endif
    229229        wolfSSL_CryptHwMutexUnLock();
     
    243243            cau_sha1_hash_n((byte*)data, 1, sha->digest);
    244244    #else
    245             MMCAU_SHA1_HashN((byte*)data, 1, (uint32_t*)sha->digest);
     245            MMCAU_SHA1_HashN((byte*)data, 1, (word32*)sha->digest);
    246246    #endif
    247247            wolfSSL_CryptHwMutexUnLock();
     
    277277    #else
    278278            MMCAU_SHA1_HashN((byte*)data, len/WC_SHA_BLOCK_SIZE,
    279                 (uint32_t*)sha->digest);
     279                (word32*)sha->digest);
    280280    #endif
    281281            }
     
    328328
    329329    /* implemented in wolfcrypt/src/port/Renesas/renesas_tsip_sha.c */
     330
     331#elif defined(WOLFSSL_IMXRT_DCP)
     332    /* implemented in wolfcrypt/src/port/nxp/dcp_port.c */
     333
     334#elif defined(WOLFSSL_SILABS_SE_ACCEL)
     335
     336    /* implemented in wolfcrypt/src/port/silabs/silabs_hash.c */
    330337
    331338#else
     
    520527    }
    521528
     529    if (data == NULL && len == 0) {
     530        /* valid, but do nothing */
     531        return 0;
     532    }
     533
    522534#ifdef WOLF_CRYPTO_CB
    523535    if (sha->devId != INVALID_DEVID) {
     
    540552    if (sha->buffLen >= WC_SHA_BLOCK_SIZE)
    541553        return BUFFER_E;
    542 
    543     if (data == NULL && len == 0) {
    544         /* valid, but do nothing */
    545         return 0;
    546     }
    547554
    548555    /* add length for final */
     
    680687        if (ret != CRYPTOCB_UNAVAILABLE)
    681688            return ret;
    682         ret = 0; /* reset ret */
    683689        /* fall-through when unavailable */
    684690    }
     
    794800        sha->msg = NULL;
    795801    }
     802#endif
     803#ifdef WOLFSSL_IMXRT_DCP
     804    DCPShaFree(sha);
    796805#endif
    797806}
     
    842851    XMEMCPY(dst, src, sizeof(wc_Sha));
    843852
     853#ifdef WOLFSSL_SILABS_SE_ACCEL
     854    dst->silabsCtx.hash_ctx.cmd_ctx = &(dst->silabsCtx.cmd_ctx);
     855    dst->silabsCtx.hash_ctx.hash_type_ctx = &(dst->silabsCtx.hash_type_ctx);
     856#endif
     857
    844858#ifdef WOLFSSL_ASYNC_CRYPT
    845859    ret = wolfAsync_DevCopy(&src->asyncDev, &dst->asyncDev);
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/sha256.c

    r457 r464  
    2020 */
    2121
     22/* For more info on the algorithm, see https://tools.ietf.org/html/rfc6234 */
     23/*
     24
     25DESCRIPTION
     26This library provides the interface to SHA-256 secure hash algorithms.
     27SHA-256 performs processing on message blocks to produce a final hash digest
     28output. It can be used to hash a message, M, having a length of L bits,
     29where 0 <= L < 2^64.
     30
     31*/
    2232#ifdef HAVE_CONFIG_H
    2333    #include <config.h>
     
    120130#elif defined(WOLFSSL_CRYPTOCELL)
    121131    /* wc_port.c includes wolfcrypt/src/port/arm/cryptoCellHash.c */
     132
     133#elif defined(WOLFSSL_IMXRT_DCP)
     134
     135#elif defined(WOLFSSL_PSOC6_CRYPTO)
     136
     137
    122138#else
    123139
     
    165181    !defined(WOLFSSL_AFALG_HASH) && !defined(WOLFSSL_DEVCRYPTO_HASH) && \
    166182    (!defined(WOLFSSL_ESP32WROOM32_CRYPT) || defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_HASH)) && \
    167     (!defined(WOLFSSL_RENESAS_TSIP_CRYPT) || defined(NO_WOLFSSL_RENESAS_TSIP_HASH))
     183    (!defined(WOLFSSL_RENESAS_TSIP_CRYPT) || defined(NO_WOLFSSL_RENESAS_TSIP_HASH)) && \
     184    !defined(WOLFSSL_PSOC6_CRYPTO) && !defined(WOLFSSL_IMXRT_DCP) && !defined(WOLFSSL_SILABS_SE_ACCEL)
     185
    168186
    169187static int InitSha256(wc_Sha256* sha256)
     
    197215
    198216/* Hardware Acceleration */
    199 #if defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)
     217#if defined(USE_INTEL_SPEEDUP) && (defined(HAVE_INTEL_AVX1) || \
     218                                                       defined(HAVE_INTEL_AVX2))
    200219
    201220    /* in case intel instructions aren't available, plus we need the K[] global */
     
    295314    static int transform_check = 0;
    296315    static word32 intel_flags;
    297 
    298     #define XTRANSFORM(S, D)         (*Transform_Sha256_p)((S),(D))
    299     #define XTRANSFORM_LEN(S, D, L)  (*Transform_Sha256_Len_p)((S),(D),(L))
     316    static int Transform_Sha256_is_vectorized = 0;
     317
     318    static WC_INLINE int inline_XTRANSFORM(wc_Sha256* S, const byte* D) {
     319        int ret;
     320        if (Transform_Sha256_is_vectorized)
     321            SAVE_VECTOR_REGISTERS();
     322        ret = (*Transform_Sha256_p)(S, D);
     323        if (Transform_Sha256_is_vectorized)
     324            RESTORE_VECTOR_REGISTERS();
     325        return ret;
     326    }
     327#define XTRANSFORM(...) inline_XTRANSFORM(__VA_ARGS__)
     328
     329    static WC_INLINE int inline_XTRANSFORM_LEN(wc_Sha256* S, const byte* D, word32 L) {
     330        int ret;
     331        if (Transform_Sha256_is_vectorized)
     332            SAVE_VECTOR_REGISTERS();
     333        ret = (*Transform_Sha256_Len_p)(S, D, L);
     334        if (Transform_Sha256_is_vectorized)
     335            RESTORE_VECTOR_REGISTERS();
     336        return ret;
     337    }
     338#define XTRANSFORM_LEN(...) inline_XTRANSFORM_LEN(__VA_ARGS__)
    300339
    301340    static void Sha256_SetTransform(void)
     
    313352                Transform_Sha256_p = Transform_Sha256_AVX2_RORX;
    314353                Transform_Sha256_Len_p = Transform_Sha256_AVX2_RORX_Len;
     354                Transform_Sha256_is_vectorized = 1;
    315355            }
    316356            else
     
    320360                Transform_Sha256_p = Transform_Sha256_AVX2;
    321361                Transform_Sha256_Len_p = Transform_Sha256_AVX2_Len;
     362                Transform_Sha256_is_vectorized = 1;
    322363            }
    323364        #ifdef HAVE_INTEL_RORX
     
    325366                Transform_Sha256_p = Transform_Sha256_AVX1_RORX;
    326367                Transform_Sha256_Len_p = Transform_Sha256_AVX1_RORX_Len;
     368                Transform_Sha256_is_vectorized = 1;
    327369            }
    328370        #endif
     
    334376            Transform_Sha256_p = Transform_Sha256_AVX1;
    335377            Transform_Sha256_Len_p = Transform_Sha256_AVX1_Len;
     378            Transform_Sha256_is_vectorized = 1;
    336379        }
    337380        else
     
    340383            Transform_Sha256_p = Transform_Sha256;
    341384            Transform_Sha256_Len_p = NULL;
     385            Transform_Sha256_is_vectorized = 0;
    342386        }
    343387
     
    354398    #ifdef WOLF_CRYPTO_CB
    355399        sha256->devId = devId;
     400    #endif
     401    #ifdef WOLFSSL_SMALL_STACK_CACHE
     402        sha256->W = NULL;
    356403    #endif
    357404
     
    415462        cau_sha256_initialize_output(sha256->digest);
    416463    #else
    417         MMCAU_SHA256_InitializeOutput((uint32_t*)sha256->digest);
     464        MMCAU_SHA256_InitializeOutput((word32*)sha256->digest);
    418465    #endif
    419466        wolfSSL_CryptHwMutexUnLock();
     
    495542        (void)heap;
    496543
     544        XMEMSET(sha256, 0, sizeof(wc_Sha256));
    497545        wc_Stm32_Hash_Init(&sha256->stmCtx);
    498546        return 0;
     
    664712    /* implemented in wolfcrypt/src/port/Renesas/renesas_tsip_sha.c */
    665713
     714#elif defined(WOLFSSL_PSOC6_CRYPTO)
     715
     716    /* implemented in wolfcrypt/src/port/cypress/psoc6_crypto.c */
     717
     718#elif defined(WOLFSSL_IMXRT_DCP)
     719    #include <wolfssl/wolfcrypt/port/nxp/dcp_port.h>
     720    /* implemented in wolfcrypt/src/port/nxp/dcp_port.c */
     721
     722#elif defined(WOLFSSL_SILABS_SE_ACCEL)
     723    /* implemented in wolfcrypt/src/port/silabs/silabs_hash.c */
     724
    666725#else
    667726    #define NEED_SOFT_SHA256
     
    678737        sha256->devCtx = NULL;
    679738    #endif
     739    #ifdef WOLFSSL_SMALL_STACK_CACHE
     740        sha256->W = NULL;
     741    #endif
    680742
    681743        ret = InitSha256(sha256);
    682744        if (ret != 0)
    683745            return ret;
    684 
    685     #ifdef WOLFSSL_SMALL_STACK_CACHE
    686         sha256->W = NULL;
    687     #endif
    688746
    689747    #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA256)
     
    700758#ifdef NEED_SOFT_SHA256
    701759
    702     static const ALIGN32 word32 K[64] = {
     760    static const FLASH_QUALIFIER ALIGN32 word32 K[64] = {
    703761        0x428A2F98L, 0x71374491L, 0xB5C0FBCFL, 0xE9B5DBA5L, 0x3956C25BL,
    704762        0x59F111F1L, 0x923F82A4L, 0xAB1C5ED5L, 0xD807AA98L, 0x12835B01L,
     
    929987            if (sha256->buffLen == WC_SHA256_BLOCK_SIZE) {
    930988            #if defined(LITTLE_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU_SHA)
    931                 #if defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)
     989                #if defined(USE_INTEL_SPEEDUP) && \
     990                          (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2))
    932991                if (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags))
    933992                #endif
     
    9611020        /* process blocks */
    9621021    #ifdef XTRANSFORM_LEN
    963         #if defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)
     1022        #if defined(USE_INTEL_SPEEDUP) && \
     1023                          (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2))
    9641024        if (Transform_Sha256_Len_p != NULL)
    9651025        #endif
     
    9761036            }
    9771037        }
    978         #if defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)
     1038        #if defined(USE_INTEL_SPEEDUP) && \
     1039                          (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2))
    9791040        else
    9801041        #endif
    9811042    #endif /* XTRANSFORM_LEN */
    982     #if !defined(XTRANSFORM_LEN) || defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)
     1043    #if !defined(XTRANSFORM_LEN) || (defined(USE_INTEL_SPEEDUP) && \
     1044                         (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)))
    9831045        {
    9841046            while (len >= WC_SHA256_BLOCK_SIZE) {
     
    9881050                /* Little Endian requires byte swap, so can't use data directly */
    9891051            #if defined(WC_HASH_DATA_ALIGNMENT) && !defined(LITTLE_ENDIAN_ORDER) && \
    990                 !defined(HAVE_INTEL_AVX1) && !defined(HAVE_INTEL_AVX2)
     1052                !(defined(USE_INTEL_SPEEDUP) && \
     1053                         (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)))
    9911054                if (((size_t)data % WC_HASH_DATA_ALIGNMENT) == 0) {
    9921055                    local32 = (word32*)data;
     
    10021065
    10031066            #if defined(LITTLE_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU_SHA)
    1004                 #if defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)
     1067                #if defined(USE_INTEL_SPEEDUP) && \
     1068                          (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2))
    10051069                if (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags))
    10061070                #endif
     
    10311095
    10321096        /* save remainder */
    1033         if (len > 0) {
     1097        if (ret == 0 && len > 0) {
    10341098            XMEMCPY(local, data, len);
    10351099            sha256->buffLen = len;
     
    10891153
    10901154        #if defined(LITTLE_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU_SHA)
    1091             #if defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)
     1155            #if defined(USE_INTEL_SPEEDUP) && \
     1156                          (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2))
    10921157            if (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags))
    10931158            #endif
     
    11261191        /* store lengths */
    11271192    #if defined(LITTLE_ENDIAN_ORDER) && !defined(FREESCALE_MMCAU_SHA)
    1128         #if defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)
     1193        #if defined(USE_INTEL_SPEEDUP) && \
     1194                          (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2))
    11291195        if (!IS_INTEL_AVX1(intel_flags) && !IS_INTEL_AVX2(intel_flags))
    11301196        #endif
     
    11391205                sizeof(word32));
    11401206
    1141     #if defined(FREESCALE_MMCAU_SHA) || defined(HAVE_INTEL_AVX1) || \
    1142         defined(HAVE_INTEL_AVX2)
     1207    #if defined(FREESCALE_MMCAU_SHA) || (defined(USE_INTEL_SPEEDUP) && \
     1208                         (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)))
    11431209        /* Kinetis requires only these bytes reversed */
    1144         #if defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)
     1210        #if defined(USE_INTEL_SPEEDUP) && \
     1211                          (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2))
    11451212        if (IS_INTEL_AVX1(intel_flags) || IS_INTEL_AVX2(intel_flags))
    11461213        #endif
     
    12451312        (void)heap;
    12461313
     1314        XMEMSET(sha224, 0, sizeof(wc_Sha224));
    12471315        wc_Stm32_Hash_Init(&sha224->stmCtx);
    12481316        return 0;
     
    12941362#elif defined(WOLFSSL_DEVCRYPTO_HASH)
    12951363    /* implemented in wolfcrypt/src/port/devcrypto/devcrypt_hash.c */
     1364
     1365#elif defined(WOLFSSL_SILABS_SE_ACCEL)
     1366    /* implemented in wolfcrypt/src/port/silabs/silabs_hash.c */
    12961367
    12971368#else
     
    13211392        sha224->hiLen   = 0;
    13221393
    1323     #if defined(HAVE_INTEL_AVX1)|| defined(HAVE_INTEL_AVX2)
     1394    #if defined(USE_INTEL_SPEEDUP) && \
     1395                          (defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2))
    13241396        /* choose best Transform function under this runtime environment */
    13251397        Sha256_SetTransform();
     
    13431415
    13441416        sha224->heap = heap;
     1417    #ifdef WOLFSSL_SMALL_STACK_CACHE
     1418        sha224->W = NULL;
     1419    #endif
    13451420
    13461421        ret = InitSha224(sha224);
    13471422        if (ret != 0)
    13481423            return ret;
    1349 
    1350     #ifdef WOLFSSL_SMALL_STACK_CACHE
    1351         sha224->W = NULL;
    1352     #endif
    13531424
    13541425    #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA224)
     
    14861557    }
    14871558#endif
     1559#ifdef WOLFSSL_IMXRT_DCP
     1560    DCPSha256Free(sha256);
     1561#endif
    14881562}
    14891563
     
    15211595    #endif
    15221596
     1597    #ifdef WOLFSSL_SILABS_SE_ACCEL
     1598        dst->silabsCtx.hash_ctx.cmd_ctx = &(dst->silabsCtx.cmd_ctx);
     1599        dst->silabsCtx.hash_ctx.hash_type_ctx = &(dst->silabsCtx.hash_type_ctx);
     1600    #endif
     1601
    15231602    #ifdef WOLFSSL_ASYNC_CRYPT
    15241603        ret = wolfAsync_DevCopy(&src->asyncDev, &dst->asyncDev);
     
    15601639
    15611640    /* implemented in wolfcrypt/src/port/Renesas/renesas_tsip_sha.c */
     1641#elif defined(WOLFSSL_PSOC6_CRYPTO)
     1642    /* implemented in wolfcrypt/src/port/cypress/psoc6_crypto.c */
     1643#elif defined(WOLFSSL_IMXRT_DCP)
     1644    /* implemented in wolfcrypt/src/port/nxp/dcp_port.c */
    15621645#else
    15631646
     
    16041687#endif
    16051688
     1689#ifdef WOLFSSL_SILABS_SE_ACCEL
     1690    dst->silabsCtx.hash_ctx.cmd_ctx = &(dst->silabsCtx.cmd_ctx);
     1691    dst->silabsCtx.hash_ctx.hash_type_ctx = &(dst->silabsCtx.hash_type_ctx);
     1692#endif
     1693
    16061694#ifdef WOLFSSL_ASYNC_CRYPT
    16071695    ret = wolfAsync_DevCopy(&src->asyncDev, &dst->asyncDev);
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/sha512.c

    r457 r464  
    2727#include <wolfssl/wolfcrypt/settings.h>
    2828
    29 #if (defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)) && !defined(WOLFSSL_ARMASM)
     29#if (defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)) && !defined(WOLFSSL_ARMASM) && !defined(WOLFSSL_PSOC6_CRYPTO)
    3030
    3131#if defined(HAVE_FIPS) && \
     
    188188#if defined(WOLFSSL_IMX6_CAAM) && !defined(NO_IMX6_CAAM_HASH)
    189189    /* functions defined in wolfcrypt/src/port/caam/caam_sha.c */
     190
     191#elif defined(WOLFSSL_SILABS_SHA384)
     192    /* functions defined in wolfcrypt/src/port/silabs/silabs_hash.c */
    190193
    191194#else
     
    338341    static int transform_check = 0;
    339342    static int intel_flags;
    340     #define Transform_Sha512(sha512)     (*Transform_Sha512_p)(sha512)
    341     #define Transform_Sha512_Len(sha512, len) \
    342                                           (*Transform_Sha512_Len_p)(sha512, len)
    343 
    344     static void Sha512_SetTransform()
     343    static int Transform_Sha512_is_vectorized = 0;
     344
     345    static WC_INLINE int Transform_Sha512(wc_Sha512 *sha512) {
     346        int ret;
     347        if (Transform_Sha512_is_vectorized)
     348            SAVE_VECTOR_REGISTERS();
     349        ret = (*Transform_Sha512_p)(sha512);
     350        if (Transform_Sha512_is_vectorized)
     351            RESTORE_VECTOR_REGISTERS();
     352        return ret;
     353    }
     354    static WC_INLINE int Transform_Sha512_Len(wc_Sha512 *sha512, word32 len) {
     355        int ret;
     356        if (Transform_Sha512_is_vectorized)
     357            SAVE_VECTOR_REGISTERS();
     358        ret = (*Transform_Sha512_Len_p)(sha512, len);
     359        if (Transform_Sha512_is_vectorized)
     360            RESTORE_VECTOR_REGISTERS();
     361        return ret;
     362    }
     363
     364    static void Sha512_SetTransform(void)
    345365    {
    346366        if (transform_check)
     
    355375                Transform_Sha512_p = Transform_Sha512_AVX2_RORX;
    356376                Transform_Sha512_Len_p = Transform_Sha512_AVX2_RORX_Len;
     377                Transform_Sha512_is_vectorized = 1;
    357378            }
    358379            else
     
    361382                Transform_Sha512_p = Transform_Sha512_AVX2;
    362383                Transform_Sha512_Len_p = Transform_Sha512_AVX2_Len;
     384                Transform_Sha512_is_vectorized = 1;
    363385            }
    364386        #ifdef HAVE_INTEL_RORX
     
    366388                Transform_Sha512_p = Transform_Sha512_AVX1_RORX;
    367389                Transform_Sha512_Len_p = Transform_Sha512_AVX1_RORX_Len;
     390                Transform_Sha512_is_vectorized = 1;
    368391            }
    369392        #endif
     
    375398            Transform_Sha512_p = Transform_Sha512_AVX1;
    376399            Transform_Sha512_Len_p = Transform_Sha512_AVX1_Len;
     400            Transform_Sha512_is_vectorized = 1;
    377401        }
    378402        else
    379403    #endif
     404        {
    380405            Transform_Sha512_p = _Transform_Sha512;
     406            Transform_Sha512_is_vectorized = 1;
     407        }
    381408
    382409        transform_check = 1;
     
    399426
    400427    sha512->heap = heap;
     428#ifdef WOLFSSL_SMALL_STACK_CACHE
     429    sha512->W = NULL;
     430#endif
    401431
    402432    ret = InitSha512(sha512);
     
    406436#if defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)
    407437    Sha512_SetTransform();
    408 #endif
    409 
    410 #ifdef WOLFSSL_SMALL_STACK_CACHE
    411     sha512->W = NULL;
    412438#endif
    413439
     
    508534    word64* W = sha512->W;
    509535    if (W == NULL) {
    510         W = (word64*) XMALLOC(sizeof(word64) * 16, NULL,
    511                                                        DYNAMIC_TYPE_TMP_BUFFER);
     536        W = (word64*)XMALLOC(sizeof(word64) * 16, NULL,DYNAMIC_TYPE_TMP_BUFFER);
    512537        if (W == NULL)
    513538            return MEMORY_E;
     
    693718#endif
    694719
    695     if (len > 0) {
     720    if (ret == 0 && len > 0) {
    696721        XMEMCPY(local, data, len);
    697722        sha512->buffLen = len;
     
    722747#endif /* WOLFSSL_SHA512 */
    723748
    724 #endif /* WOLFSSL_IMX6_CAAM */
     749#endif /* WOLFSSL_IMX6_CAAM || WOLFSSL_SILABS_SHA384 */
    725750
    726751static WC_INLINE int Sha512Final(wc_Sha512* sha512)
     
    903928    /* functions defined in wolfcrypt/src/port/caam/caam_sha.c */
    904929
     930#elif defined(WOLFSSL_SILABS_SHA512)
     931    /* functions defined in wolfcrypt/src/port/silabs/silabs_hash.c */
     932
    905933#else
    906934
     
    10201048
    10211049    sha384->heap = heap;
     1050#ifdef WOLFSSL_SMALL_STACK_CACHE
     1051    sha384->W = NULL;
     1052#endif
     1053
    10221054    ret = InitSha384(sha384);
    10231055    if (ret != 0)
     
    10261058#if defined(HAVE_INTEL_AVX1) || defined(HAVE_INTEL_AVX2)
    10271059    Sha512_SetTransform();
    1028 #endif
    1029 #ifdef WOLFSSL_SMALL_STACK_CACHE
    1030     sha384->W = NULL;
    10311060#endif
    10321061
     
    10411070}
    10421071
    1043 #endif /* WOLFSSL_IMX6_CAAM */
     1072#endif /* WOLFSSL_IMX6_CAAM || WOLFSSL_SILABS_SHA512 */
    10441073
    10451074int wc_InitSha384(wc_Sha384* sha384)
     
    11121141#endif
    11131142
     1143#ifdef WOLFSSL_SILABS_SHA512
     1144    dst->silabsCtx.hash_ctx.cmd_ctx = &(dst->silabsCtx.cmd_ctx);
     1145    dst->silabsCtx.hash_ctx.hash_type_ctx = &(dst->silabsCtx.hash_type_ctx);
     1146#endif
     1147
    11141148#ifdef WOLFSSL_ASYNC_CRYPT
    11151149    ret = wolfAsync_DevCopy(&src->asyncDev, &dst->asyncDev);
     
    11881222#endif
    11891223
     1224#ifdef WOLFSSL_SILABS_SHA384
     1225    dst->silabsCtx.hash_ctx.cmd_ctx = &(dst->silabsCtx.cmd_ctx);
     1226    dst->silabsCtx.hash_ctx.hash_type_ctx = &(dst->silabsCtx.hash_type_ctx);
     1227#endif
     1228
    11901229#ifdef WOLFSSL_ASYNC_CRYPT
    11911230    ret = wolfAsync_DevCopy(&src->asyncDev, &dst->asyncDev);
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/wc_encrypt.c

    r457 r464  
    2929#include <wolfssl/wolfcrypt/des3.h>
    3030#include <wolfssl/wolfcrypt/hash.h>
     31#include <wolfssl/wolfcrypt/rc2.h>
    3132#include <wolfssl/wolfcrypt/arc4.h>
    3233#include <wolfssl/wolfcrypt/wc_encrypt.h>
     
    239240
    240241
    241 #ifdef WOLFSSL_ENCRYPTED_KEYS
     242#if !defined(NO_ASN) && defined(WOLFSSL_ENCRYPTED_KEYS)
    242243
    243244int wc_BufferKeyDecrypt(EncryptedInfo* info, byte* der, word32 derSz,
     
    361362}
    362363
    363 #endif /* WOLFSSL_ENCRYPTED_KEYS */
     364#endif /* !NO_ASN && WOLFSSL_ENCRYPTED_KEYS */
    364365
    365366
     
    375376                      int length, int version, byte* cbcIv, int enc, int shaOid)
    376377{
    377     int typeH;
     378    int typeH = WC_HASH_TYPE_NONE;
    378379    int derivedLen = 0;
    379380    int ret = 0;
     
    456457            break;
    457458    #endif /* WOLFSSL_AES_128 && !NO_SHA */
     459    #ifdef WC_RC2
     460        case PBE_SHA1_40RC2_CBC:
     461            typeH = WC_SHA;
     462            derivedLen = 5;
     463            break;
     464    #endif
    458465        default:
    459466            WOLFSSL_MSG("Unknown/Unsupported encrypt/decrypt id");
     
    612619        case PBE_AES128_CBC:
    613620        {
    614             Aes aes;
    615             ret = wc_AesInit(&aes, NULL, INVALID_DEVID);
     621#ifdef WOLFSSL_SMALL_STACK
     622            Aes *aes;
     623            aes = (Aes *)XMALLOC(sizeof *aes, NULL, DYNAMIC_TYPE_AES);
     624            if (aes == NULL)
     625                return MEMORY_E;
     626#else
     627            Aes aes[1];
     628#endif
     629            ret = wc_AesInit(aes, NULL, INVALID_DEVID);
    616630            if (ret == 0) {
    617631                if (enc) {
    618                     ret = wc_AesSetKey(&aes, key, derivedLen, cbcIv,
     632                    ret = wc_AesSetKey(aes, key, derivedLen, cbcIv,
    619633                                                                AES_ENCRYPTION);
    620634                }
    621635                else {
    622                     ret = wc_AesSetKey(&aes, key, derivedLen, cbcIv,
     636                    ret = wc_AesSetKey(aes, key, derivedLen, cbcIv,
    623637                                                                AES_DECRYPTION);
    624638                }
     
    626640            if (ret == 0) {
    627641                if (enc)
    628                     ret = wc_AesCbcEncrypt(&aes, input, input, length);
     642                    ret = wc_AesCbcEncrypt(aes, input, input, length);
    629643                else
    630                     ret = wc_AesCbcDecrypt(&aes, input, input, length);
    631             }
     644                    ret = wc_AesCbcDecrypt(aes, input, input, length);
     645            }
     646            ForceZero(aes, sizeof(Aes));
     647#ifdef WOLFSSL_SMALL_STACK
     648            XFREE(aes, NULL, DYNAMIC_TYPE_AES);
     649#endif
    632650            if (ret != 0) {
    633651#ifdef WOLFSSL_SMALL_STACK
     
    636654                return ret;
    637655            }
    638             ForceZero(&aes, sizeof(Aes));
    639656            break;
    640657        }
    641658    #endif /* WOLFSSL_AES_256 */
    642659#endif /* !NO_AES && HAVE_AES_CBC */
     660#ifdef WC_RC2
     661        case PBE_SHA1_40RC2_CBC:
     662        {
     663            Rc2 rc2;
     664            /* effective key size for RC2-40-CBC is 40 bits */
     665            ret = wc_Rc2SetKey(&rc2, key, derivedLen, cbcIv, 40);
     666            if (ret == 0) {
     667                if (enc)
     668                    ret = wc_Rc2CbcEncrypt(&rc2, input, input, length);
     669                else
     670                    ret = wc_Rc2CbcDecrypt(&rc2, input, input, length);
     671            }
     672            if (ret != 0) {
     673#ifdef WOLFSSL_SMALL_STACK
     674                XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
     675#endif
     676                return ret;
     677            }
     678            ForceZero(&rc2, sizeof(Rc2));
     679            break;
     680        }
     681#endif
    643682
    644683        default:
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/wc_port.c

    r457 r464  
    4747#endif
    4848
    49 #if defined(WOLFSSL_ATMEL) || defined(WOLFSSL_ATECC508A)
     49#ifdef WOLFSSL_PSOC6_CRYPTO
     50    #include <wolfssl/wolfcrypt/port/cypress/psoc6_crypto.h>
     51#endif
     52
     53#if defined(WOLFSSL_ATMEL) || defined(WOLFSSL_ATECC508A) || \
     54    defined(WOLFSSL_ATECC608A)
    5055    #include <wolfssl/wolfcrypt/port/atmel/atmel.h>
    5156#endif
     
    6974    defined(WOLFSSL_IMX6_CAAM_BLOB)
    7075    #include <wolfssl/wolfcrypt/port/caam/wolfcaam.h>
     76#endif
     77
     78#ifdef WOLFSSL_IMXRT_DCP
     79    #include <wolfssl/wolfcrypt/port/nxp/dcp_port.h>
    7180#endif
    7281
     
    105114{
    106115    int ret = 0;
    107 
    108116    if (initRefCount == 0) {
    109117        WOLFSSL_ENTER("wolfCrypt_Init");
     
    181189    #endif
    182190
    183     #if defined(WOLFSSL_ATMEL) || defined(WOLFSSL_ATECC508A)
     191    #if defined(WOLFSSL_ATMEL) || defined(WOLFSSL_ATECC508A) || \
     192        defined(WOLFSSL_ATECC608A)
    184193        ret = atmel_init();
    185194        if (ret != 0) {
     
    200209    #endif
    201210
     211    #if defined(WOLFSSL_PSOC6_CRYPTO)
     212        ret = psoc6_crypto_port_init();
     213        if (ret != 0) {
     214            WOLFSSL_MSG("PSoC6 crypto engine init failed");
     215            return ret;
     216        }
     217    #endif
     218
     219    #ifdef WOLFSSL_SILABS_SE_ACCEL
     220        /* init handles if it is already initialized */
     221        ret = sl_se_init();
     222    #endif
     223
    202224    #ifdef WOLFSSL_ARMASM
    203225        WOLFSSL_MSG("Using ARM hardware acceleration");
     
    220242
    221243#ifdef HAVE_ECC
     244    #ifdef FP_ECC
     245        wc_ecc_fp_init();
     246    #endif
    222247    #ifdef ECC_CACHE_CURVE
    223248        if ((ret = wc_ecc_curve_cache_init()) != 0) {
     
    248273#endif
    249274
     275#ifdef WOLFSSL_IMXRT_DCP
     276        if ((ret = wc_dcp_init()) != 0) {
     277            return ret;
     278        }
     279#endif
     280
    250281#if defined(WOLFSSL_DSP) && !defined(WOLFSSL_DSP_BUILD)
    251282        if ((ret = wolfSSL_InitHandle()) != 0) {
     
    260291}
    261292
     293#ifdef WOLFSSL_TRACK_MEMORY_VERBOSE
     294long wolfCrypt_heap_peakAllocs_checkpoint(void) {
     295    long ret = ourMemStats.peakAllocsTripOdometer;
     296    ourMemStats.peakAllocsTripOdometer = ourMemStats.totalAllocs -
     297        ourMemStats.totalDeallocs;
     298    return ret;
     299}
     300long wolfCrypt_heap_peakBytes_checkpoint(void) {
     301    long ret = ourMemStats.peakBytesTripOdometer;
     302    ourMemStats.peakBytesTripOdometer = ourMemStats.currentBytes;
     303    return ret;
     304}
     305#endif
    262306
    263307/* return success value is the same as wolfCrypt_Init */
     
    303347        cc310_Free();
    304348    #endif
     349    #ifdef WOLFSSL_SILABS_SE_ACCEL
     350        ret = sl_se_deinit();
     351    #endif
    305352    #if defined(WOLFSSL_RENESAS_TSIP_CRYPT)
    306353        tsip_Close();
     
    315362}
    316363
    317 #if !defined(NO_FILESYSTEM) && !defined(NO_WOLFSSL_DIR) && \
    318         !defined(WOLFSSL_NUCLEUS) && !defined(WOLFSSL_NUCLEUS_1_2)
     364#ifndef NO_FILESYSTEM
     365
     366/* Helpful function to load file into allocated buffer */
     367int wc_FileLoad(const char* fname, unsigned char** buf, size_t* bufLen,
     368    void* heap)
     369{
     370    int ret;
     371    size_t fileSz;
     372    XFILE f;
     373
     374    if (fname == NULL || buf == NULL || bufLen == NULL) {
     375        return BAD_FUNC_ARG;
     376    }
     377
     378    /* set defaults */
     379    *buf = NULL;
     380    *bufLen = 0;
     381
     382    /* open file (read-only binary) */
     383    f = XFOPEN(fname, "rb");
     384    if (!f) {
     385        WOLFSSL_MSG("wc_LoadFile file load error");
     386        return BAD_PATH_ERROR;
     387    }
     388
     389    XFSEEK(f, 0, XSEEK_END);
     390    fileSz = XFTELL(f);
     391    XREWIND(f);
     392    if (fileSz > 0) {
     393        *bufLen = fileSz;
     394        *buf = (byte*)XMALLOC(*bufLen, heap, DYNAMIC_TYPE_TMP_BUFFER);
     395        if (*buf == NULL) {
     396            WOLFSSL_MSG("wc_LoadFile memory error");
     397            ret = MEMORY_E;
     398        }
     399        else {
     400            size_t readLen = XFREAD(*buf, 1, *bufLen, f);
     401
     402            /* check response code */
     403            ret = (readLen == *bufLen) ? 0 : -1;
     404        }
     405    }
     406    else {
     407        ret = BUFFER_E;
     408    }
     409    XFCLOSE(f);
     410
     411    (void)heap;
     412
     413    return ret;
     414}
     415
     416#if !defined(NO_WOLFSSL_DIR) && \
     417    !defined(WOLFSSL_NUCLEUS) && !defined(WOLFSSL_NUCLEUS_1_2)
    319418
    320419/* File Handling Helpers */
     
    615714}
    616715
    617 #endif /* !NO_FILESYSTEM && !NO_WOLFSSL_DIR */
     716#endif /* !NO_WOLFSSL_DIR */
     717#endif /* !NO_FILESYSTEM */
    618718
    619719#if !defined(NO_FILESYSTEM) && defined(WOLFSSL_ZEPHYR)
     
    622722    XFILE file;
    623723
    624     file = XMALLOC(sizeof(*file), NULL, DYNAMIC_TYPE_FILE);
     724    file = (XFILE)XMALLOC(sizeof(*file), NULL, DYNAMIC_TYPE_FILE);
    625725    if (file != NULL) {
    626726        if (fs_open(file, filename) != 0) {
     
    648748#endif /* !NO_FILESYSTEM && !WOLFSSL_ZEPHYR */
    649749
    650 
     750#if !defined(WOLFSSL_USER_MUTEX)
    651751wolfSSL_Mutex* wc_InitAndAllocMutex(void)
    652752{
     
    666766    return m;
    667767}
     768#endif
    668769
    669770#ifdef USE_WOLF_STRTOK
     
    753854static int wcCryptHwMutexInit = 0;
    754855
    755 int wolfSSL_CryptHwMutexInit(void) {
     856int wolfSSL_CryptHwMutexInit(void)
     857{
    756858    int ret = 0;
    757     if(wcCryptHwMutexInit == 0) {
     859    if (wcCryptHwMutexInit == 0) {
    758860        ret = wc_InitMutex(&wcCryptHwMutex);
    759         if(ret == 0) {
     861        if (ret == 0) {
    760862            wcCryptHwMutexInit = 1;
    761863        }
     
    763865    return ret;
    764866}
    765 
    766 int wolfSSL_CryptHwMutexLock(void) {
     867int wolfSSL_CryptHwMutexLock(void)
     868{
    767869    int ret = BAD_MUTEX_E;
    768 
    769870    /* Make sure HW Mutex has been initialized */
    770     wolfSSL_CryptHwMutexInit();
    771 
    772     if(wcCryptHwMutexInit) {
     871    ret = wolfSSL_CryptHwMutexInit();
     872    if (ret == 0) {
    773873        ret = wc_LockMutex(&wcCryptHwMutex);
    774874    }
    775875    return ret;
    776876}
    777 
    778 int wolfSSL_CryptHwMutexUnLock(void) {
     877int wolfSSL_CryptHwMutexUnLock(void)
     878{
    779879    int ret = BAD_MUTEX_E;
    780 
    781     if(wcCryptHwMutexInit) {
     880    if (wcCryptHwMutexInit) {
    782881        ret = wc_UnLockMutex(&wcCryptHwMutex);
    783882    }
     
    886985    }
    887986
     987#elif defined(RTTHREAD)
     988
     989    int wc_InitMutex(wolfSSL_Mutex* m)
     990    {
     991        int iReturn;
     992
     993        *m = ( wolfSSL_Mutex ) rt_mutex_create("mutex",RT_IPC_FLAG_FIFO);
     994        if( *m != NULL )
     995            iReturn = 0;
     996        else
     997            iReturn = BAD_MUTEX_E;
     998
     999
     1000        return iReturn;
     1001    }
     1002
     1003    int wc_FreeMutex(wolfSSL_Mutex* m)
     1004    {
     1005        rt_mutex_delete( *m );
     1006        return 0;
     1007    }
     1008
     1009
     1010    int wc_LockMutex(wolfSSL_Mutex* m)
     1011    {
     1012        /* Assume an infinite block, or should there be zero block? */
     1013        return rt_mutex_take( *m, RT_WAITING_FOREVER );
     1014    }
     1015
     1016    int wc_UnLockMutex(wolfSSL_Mutex* m)
     1017    {
     1018        return rt_mutex_release( *m );
     1019    }
     1020
    8881021#elif defined(WOLFSSL_SAFERTOS)
    8891022
     
    9801113        else
    9811114            return BAD_MUTEX_E;
     1115    }
     1116
     1117#elif defined(WOLFSSL_KTHREADS)
     1118
     1119    /* Linux kernel mutex routines are voids, alas. */
     1120
     1121    int wc_InitMutex(wolfSSL_Mutex* m)
     1122    {
     1123        mutex_init(m);
     1124        return 0;
     1125    }
     1126
     1127    int wc_FreeMutex(wolfSSL_Mutex* m)
     1128    {
     1129        mutex_destroy(m);
     1130        return 0;
     1131    }
     1132
     1133    int wc_LockMutex(wolfSSL_Mutex* m)
     1134    {
     1135        mutex_lock(m);
     1136        return 0;
     1137    }
     1138
     1139
     1140    int wc_UnLockMutex(wolfSSL_Mutex* m)
     1141    {
     1142        mutex_unlock(m);
     1143        return 0;
    9821144    }
    9831145
     
    11261288
    11271289#elif defined(MICRIUM)
     1290    #if (OS_VERSION < 50000)
     1291        #define MICRIUM_ERR_TYPE OS_ERR
     1292        #define MICRIUM_ERR_NONE OS_ERR_NONE
     1293        #define MICRIUM_ERR_CODE(err) err
     1294    #else
     1295        #define MICRIUM_ERR_TYPE RTOS_ERR
     1296        #define MICRIUM_ERR_NONE RTOS_ERR_NONE
     1297        #define MICRIUM_ERR_CODE(err)    RTOS_ERR_CODE_GET(err)
     1298    #endif
    11281299
    11291300    int wc_InitMutex(wolfSSL_Mutex* m)
    11301301    {
    1131         OS_ERR err;
     1302        MICRIUM_ERR_TYPE err;
    11321303
    11331304        OSMutexCreate(m, "wolfSSL Mutex", &err);
    11341305
    1135         if (err == OS_ERR_NONE)
     1306        if (MICRIUM_ERR_CODE(err) == MICRIUM_ERR_NONE)
    11361307            return 0;
    11371308        else
     
    11421313    {
    11431314        #if (OS_CFG_MUTEX_DEL_EN == DEF_ENABLED)
    1144             OS_ERR err;
     1315            MICRIUM_ERR_TYPE err;
    11451316
    11461317            OSMutexDel(m, OS_OPT_DEL_ALWAYS, &err);
    11471318
    1148             if (err == OS_ERR_NONE)
     1319            if (MICRIUM_ERR_CODE(err) == MICRIUM_ERR_NONE)
    11491320                return 0;
    11501321            else
    11511322                return BAD_MUTEX_E;
    11521323        #else
     1324            (void)m;
    11531325            return 0;
    11541326        #endif
     
    11571329    int wc_LockMutex(wolfSSL_Mutex* m)
    11581330    {
    1159         OS_ERR err;
     1331        MICRIUM_ERR_TYPE err;
    11601332
    11611333        OSMutexPend(m, 0, OS_OPT_PEND_BLOCKING, NULL, &err);
    11621334
    1163         if (err == OS_ERR_NONE)
     1335        if (MICRIUM_ERR_CODE(err) == MICRIUM_ERR_NONE)
    11641336            return 0;
    11651337        else
     
    11691341    int wc_UnLockMutex(wolfSSL_Mutex* m)
    11701342    {
    1171         OS_ERR err;
     1343        MICRIUM_ERR_TYPE err;
    11721344
    11731345        OSMutexPost(m, OS_OPT_POST_NONE, &err);
    11741346
    1175         if (err == OS_ERR_NONE)
     1347        if (MICRIUM_ERR_CODE(err) == MICRIUM_ERR_NONE)
    11761348            return 0;
    11771349        else
     
    18462018    }
    18472019
     2020#elif defined(WOLFSSL_USER_MUTEX)
     2021
     2022    /* Use user own mutex */
     2023   
     2024    /*
     2025    int wc_InitMutex(wolfSSL_Mutex* m) { ... }
     2026    int wc_FreeMutex(wolfSSL_Mutex *m) { ... }
     2027    int wc_LockMutex(wolfSSL_Mutex *m) { ... }
     2028    int wc_UnLockMutex(wolfSSL_Mutex *m) { ... }
     2029    */
     2030
    18482031#else
    18492032    #warning No mutex handling defined
     
    19372120
    19382121    ret->tm_mday  = (int)++dayno;
     2122#ifndef WOLFSSL_LINUXKM
    19392123    ret->tm_isdst = 0;
     2124#endif
    19402125
    19412126    return ret;
     
    19792164    DWORD sec = 0;
    19802165#else
    1981     uint32_t sec = 0;
     2166    word32 sec = 0;
    19822167#endif
    19832168    time_t localTime;
     
    20022187time_t deos_time(time_t* timer)
    20032188{
    2004     const uint32_t systemTickTimeInHz = 1000000 / systemTickInMicroseconds();
    2005     uint32_t *systemTickPtr = systemTickPointer();
     2189    const word32 systemTickTimeInHz = 1000000 / systemTickInMicroseconds();
     2190    word32 *systemTickPtr = systemTickPointer();
    20062191
    20072192    if (timer != NULL)
     
    20712256#include "xrtcpsu.h"
    20722257
    2073 time_t XTIME(time_t * timer)
     2258time_t xilinx_time(time_t * timer)
    20742259{
    20752260    time_t sec = 0;
     
    21802365    #endif /* !NO_CRYPT_BENCHMARK */
    21812366#endif /* WOLFSSL_TELIT_M2MB */
     2367
     2368
     2369#if defined(WOLFSSL_LINUXKM)
     2370time_t time(time_t * timer)
     2371{
     2372    time_t ret;
     2373#if LINUX_VERSION_CODE < KERNEL_VERSION(4, 0, 0)
     2374    struct timespec ts;
     2375    getnstimeofday(&ts);
     2376    ret = ts.tv_sec * 1000000000LL + ts.tv_nsec;
     2377#else
     2378    ret = ktime_get_real_seconds();
     2379#endif
     2380    if (timer)
     2381        *timer = ret;
     2382    return ret;
     2383}
     2384#endif /* WOLFSSL_LINUXKM */
    21822385
    21832386#endif /* !NO_ASN_TIME */
     
    22622465#endif /* WOLFSSL_NUCLEUS_1_2 */
    22632466
     2467#ifdef WOLFSSL_LINUXKM
     2468#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 12, 0)
     2469    /* adapted from kvrealloc() draft by Changli Gao, 2010-05-13 */
     2470    void *lkm_realloc(void *ptr, size_t newsize) {
     2471        void *nptr;
     2472        size_t oldsize;
     2473
     2474        if (unlikely(newsize == 0)) {
     2475            kvfree(ptr);
     2476            return ZERO_SIZE_PTR;
     2477        }
     2478
     2479        if (unlikely(ptr == NULL))
     2480            return kvmalloc(newsize, GFP_KERNEL);
     2481
     2482        if (is_vmalloc_addr(ptr)) {
     2483            /* no way to discern the size of the old allocation,
     2484             * because the kernel doesn't export find_vm_area().  if
     2485             * it did, we could then call get_vm_area_size() on the
     2486             * returned struct vm_struct.
     2487             */
     2488            return NULL;
     2489        } else {
     2490            struct page *page;
     2491
     2492            page = virt_to_head_page(ptr);
     2493            if (PageSlab(page) || PageCompound(page)) {
     2494                if (newsize < PAGE_SIZE)
     2495                    return krealloc(ptr, newsize, GFP_KERNEL);
     2496                oldsize = ksize(ptr);
     2497            } else {
     2498                oldsize = page->private;
     2499                if (newsize <= oldsize)
     2500                    return ptr;
     2501            }
     2502        }
     2503
     2504        nptr = kvmalloc(newsize, GFP_KERNEL);
     2505        if (nptr != NULL) {
     2506            memcpy(nptr, ptr, oldsize);
     2507            kvfree(ptr);
     2508        }
     2509
     2510        return nptr;
     2511    }
     2512#endif /* >= 4.12 */
     2513#endif /* WOLFSSL_LINUXKM */
     2514
    22642515#if defined(WOLFSSL_TI_CRYPT) || defined(WOLFSSL_TI_HASH)
    22652516    #include <wolfcrypt/src/port/ti/ti-ccm.c>  /* initialize and Mutex for TI Crypt Engine */
  • azure_iot_hub_f767zi/trunk/wolfssl-4.7.0/wolfcrypt/src/wolfmath.c

    r457 r464  
    7272
    7373
    74 #if !defined(WOLFSSL_SP_MATH)
    7574int get_digit_count(mp_int* a)
    7675{
     
    8079    return a->used;
    8180}
    82 #endif
    8381
    8482mp_digit get_digit(mp_int* a, int n)
     
    9088}
    9189
     90#if defined(HAVE_ECC) || defined(WOLFSSL_MP_COND_COPY)
    9291/* Conditionally copy a into b. Performed in constant time.
    9392 *
     
    102101    int err = MP_OKAY;
    103102    int i;
     103#if defined(SP_WORD_SIZE) && SP_WORD_SIZE == 8
     104    unsigned int mask = (unsigned int)0 - copy;
     105#else
    104106    mp_digit mask = (mp_digit)0 - copy;
     107#endif
    105108
    106109    if (a == NULL || b == NULL)
     
    124127        }
    125128        b->used ^= (a->used ^ b->used) & (int)mask;
    126     }
    127 
    128     return err;
    129 }
     129#if (!defined(WOLFSSL_SP_MATH) && !defined(WOLFSSL_SP_MATH_ALL)) || \
     130    defined(WOLFSSL_SP_INT_NEGATIVE)
     131        b->sign ^= (a->sign ^ b->sign) & (int)mask;
     132#endif
     133    }
     134
     135    return err;
     136}
     137#endif
    130138
    131139#ifndef WC_NO_RNG
     
    147155        ret = MISSING_RNG_E;
    148156    }
    149     else if (a == NULL) {
     157    else if (a == NULL || digits == 0) {
    150158        ret = BAD_FUNC_ARG;
    151159    }
     
    157165    }
    158166#else
    159 #if defined(WOLFSSL_SP_MATH)
     167#if defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_SP_MATH_ALL)
    160168    if ((ret == MP_OKAY) && (digits > SP_INT_DIGITS))
    161169#else
     
    194202#endif
    195203
     204#if defined(HAVE_ECC) || defined(WOLFSSL_EXPORT_INT)
    196205/* export an mp_int as unsigned char or hex string
    197206 * encType is WC_TYPE_UNSIGNED_BIN or WC_TYPE_HEX_STR
     
    227236    return err;
    228237}
     238#endif
    229239
    230240
Note: See TracChangeset for help on using the changeset viewer.