code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222 values | license stringclasses 20 values | size int64 1 1.05M |
|---|---|---|---|---|---|
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_CMVP_SM
#include "crypt_eal_implprovider.h"
#include "crypt_pbkdf2.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "crypt_cmvp.h"
#include "cmvp_sm.h"
#include "bsl_log_internal.h"
#include "bsl_err_internal.h"
/* Constants for parameter validation */
#define KDF_DEF_MAC_ALGID CRYPT_MAC_HMAC_SM3
#define KDF_DEF_SALT_LEN 16
#define KDF_DEF_PBKDF2_ITER 1024
void *CRYPT_EAL_SmKdfNewCtxEx(CRYPT_EAL_SmProvCtx *provCtx, int32_t algId)
{
if (provCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return NULL;
}
switch (algId) {
#ifdef HITLS_CRYPTO_PBKDF2
case CRYPT_KDF_PBKDF2:
return CRYPT_PBKDF2_NewCtxEx(provCtx->libCtx);
#endif
default:
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_NOT_SUPPORT);
return NULL;
}
}
static int32_t GetPbkdf2Params(const BSL_Param *param, CRYPT_EAL_Pbkdf2Param *pbkdf2Param)
{
int32_t id;
uint32_t iter;
uint32_t len;
const BSL_Param *temp = NULL;
if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_KDF_SALT)) != NULL) {
pbkdf2Param->saltLen = temp->valueLen;
}
if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_KDF_ITER)) != NULL) {
len = sizeof(iter);
int32_t ret = BSL_PARAM_GetValue(temp, CRYPT_PARAM_KDF_ITER, BSL_PARAM_TYPE_UINT32, &iter, &len);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
pbkdf2Param->iter = iter;
}
if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_KDF_MAC_ID)) != NULL) {
len = sizeof(id);
int32_t ret = BSL_PARAM_GetValue(temp, CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &id, &len);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
pbkdf2Param->macId = (CRYPT_MAC_AlgId)id;
}
return CRYPT_SUCCESS;
}
static int32_t CheckKdfParam(const BSL_Param *param)
{
int32_t ret = CRYPT_SUCCESS;
CRYPT_EAL_Pbkdf2Param pbkdf2 = {KDF_DEF_MAC_ALGID, KDF_DEF_SALT_LEN, KDF_DEF_PBKDF2_ITER, 0};
CRYPT_EAL_KdfC2Data data = {&pbkdf2, NULL};
ret = GetPbkdf2Params(param, &pbkdf2);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if (!CMVP_SmKdfC2(&data)) {
BSL_ERR_PUSH_ERROR(CRYPT_CMVP_ERR_PARAM_CHECK);
return CRYPT_CMVP_ERR_PARAM_CHECK;
}
return ret;
}
static int32_t CRYPT_PBKDF2_SetParamWrapper(CRYPT_PBKDF2_Ctx *ctx, const BSL_Param *param)
{
if (ctx == NULL || param == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret = CheckKdfParam(param);
if (ret != CRYPT_SUCCESS) {
return ret;
}
return CRYPT_PBKDF2_SetParam(ctx, param);
}
const CRYPT_EAL_Func g_smKdfPBKdf2[] = {
#ifdef HITLS_CRYPTO_PBKDF2
{CRYPT_EAL_IMPLKDF_NEWCTX, (CRYPT_EAL_ImplKdfNewCtx)CRYPT_EAL_SmKdfNewCtxEx},
{CRYPT_EAL_IMPLKDF_SETPARAM, (CRYPT_EAL_ImplKdfSetParam)CRYPT_PBKDF2_SetParamWrapper},
{CRYPT_EAL_IMPLKDF_DERIVE, (CRYPT_EAL_ImplKdfDerive)CRYPT_PBKDF2_Derive},
{CRYPT_EAL_IMPLKDF_DEINITCTX, (CRYPT_EAL_ImplKdfDeInitCtx)CRYPT_PBKDF2_Deinit},
{CRYPT_EAL_IMPLKDF_FREECTX, (CRYPT_EAL_ImplKdfFreeCtx)CRYPT_PBKDF2_FreeCtx},
#endif
CRYPT_EAL_FUNC_END,
};
#endif /* HITLS_CRYPTO_CMVP_SM */
| 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/cmvp/sm_prov/crypt_sm_kdf.c | C | unknown | 3,897 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_CMVP_SM
#include "crypt_eal_implprovider.h"
#include "crypt_sm2.h"
const CRYPT_EAL_Func g_smExchSm2[] = {
#if defined(HITLS_CRYPTO_SM2_EXCH)
{CRYPT_EAL_IMPLPKEYEXCH_EXCH, (CRYPT_EAL_ImplPkeyExch)CRYPT_SM2_KapComputeKey},
#endif
CRYPT_EAL_FUNC_END
};
#endif /* HITLS_CRYPTO_CMVP_SM */ | 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/cmvp/sm_prov/crypt_sm_keyexch.c | C | unknown | 883 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_CMVP_SM
#include "crypt_eal_implprovider.h"
#ifdef HITLS_CRYPTO_SM2
#include "crypt_sm2.h"
#endif
#include "crypt_errno.h"
#include "bsl_log_internal.h"
#include "bsl_err_internal.h"
#include "crypt_ealinit.h"
#include "cmvp_sm.h"
#include "crypt_sm_provider.h"
void *CRYPT_EAL_SmPkeyMgmtNewCtx(CRYPT_EAL_SmProvCtx *provCtx, int32_t algId)
{
#ifdef HITLS_CRYPTO_ASM_CHECK
if (CRYPT_ASMCAP_Pkey(algId) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_ASM_NOT_SUPPORT);
return NULL;
}
#endif
if (provCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return NULL;
}
switch (algId) {
#ifdef HITLS_CRYPTO_SM2
case CRYPT_PKEY_SM2:
return CRYPT_SM2_NewCtxEx(provCtx->libCtx);
#endif
default:
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_NOT_SUPPORT);
return NULL;
}
};
static int32_t CRYPT_SM2_GenWrapper(CRYPT_SM2_Ctx *ctx)
{
int32_t ret = CRYPT_SM2_Gen(ctx);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (!CMVP_SmPkeyPct(ctx, CRYPT_PKEY_SM2)) {
return CRYPT_CMVP_ERR_PAIRWISETEST;
}
return CRYPT_SUCCESS;
}
const CRYPT_EAL_Func g_smKeyMgmtSm2[] = {
#ifdef HITLS_CRYPTO_SM2
{CRYPT_EAL_IMPLPKEYMGMT_NEWCTX, (CRYPT_EAL_ImplPkeyMgmtNewCtx)CRYPT_EAL_SmPkeyMgmtNewCtx},
{CRYPT_EAL_IMPLPKEYMGMT_GENKEY, (CRYPT_EAL_ImplPkeyMgmtGenKey)CRYPT_SM2_GenWrapper},
{CRYPT_EAL_IMPLPKEYMGMT_SETPRV, (CRYPT_EAL_ImplPkeyMgmtSetPrv)CRYPT_SM2_SetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_SETPUB, (CRYPT_EAL_ImplPkeyMgmtSetPub)CRYPT_SM2_SetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPRV, (CRYPT_EAL_ImplPkeyMgmtGetPrv)CRYPT_SM2_GetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPUB, (CRYPT_EAL_ImplPkeyMgmtGetPub)CRYPT_SM2_GetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_DUPCTX, (CRYPT_EAL_ImplPkeyMgmtDupCtx)CRYPT_SM2_DupCtx},
{CRYPT_EAL_IMPLPKEYMGMT_CHECK, (CRYPT_EAL_ImplPkeyMgmtCheck)CRYPT_SM2_Check},
{CRYPT_EAL_IMPLPKEYMGMT_COMPARE, (CRYPT_EAL_ImplPkeyMgmtCompare)CRYPT_SM2_Cmp},
{CRYPT_EAL_IMPLPKEYMGMT_CTRL, (CRYPT_EAL_ImplPkeyMgmtCtrl)CRYPT_SM2_Ctrl},
{CRYPT_EAL_IMPLPKEYMGMT_FREECTX, (CRYPT_EAL_ImplPkeyMgmtFreeCtx)CRYPT_SM2_FreeCtx},
{CRYPT_EAL_IMPLPKEYMGMT_IMPORT, (CRYPT_EAL_ImplPkeyMgmtImport)CRYPT_SM2_Import},
{CRYPT_EAL_IMPLPKEYMGMT_EXPORT, (CRYPT_EAL_ImplPkeyMgmtExport)CRYPT_SM2_Export},
#endif
CRYPT_EAL_FUNC_END,
};
#endif /* HITLS_CRYPTO_CMVP_SM */
| 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/cmvp/sm_prov/crypt_sm_keymgmt.c | C | unknown | 3,040 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_CMVP_SM
#include "crypt_eal_implprovider.h"
#include "crypt_sm_provider.h"
#include "crypt_hmac.h"
#include "crypt_cbc_mac.h"
#include "crypt_ealinit.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "bsl_log_internal.h"
#include "bsl_err_internal.h"
void *CRYPT_EAL_SmMacNewCtxEx(CRYPT_EAL_SmProvCtx *provCtx, int32_t algId)
{
#ifdef HITLS_CRYPTO_ASM_CHECK
if (CRYPT_ASMCAP_Mac(algId) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_ASM_NOT_SUPPORT);
return NULL;
}
#endif
if (provCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return NULL;
}
switch (algId) {
#ifdef HITLS_CRYPTO_HMAC
case CRYPT_MAC_HMAC_SM3:
return CRYPT_HMAC_NewCtxEx(provCtx->libCtx, algId);
#endif
#ifdef HITLS_CRYPTO_CBC_MAC
case CRYPT_MAC_CBC_MAC_SM4:
return CRYPT_CBC_MAC_NewCtxEx(provCtx->libCtx, algId);
#endif
default:
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_NOT_SUPPORT);
return NULL;
}
}
const CRYPT_EAL_Func g_smMacHmac[] = {
#ifdef HITLS_CRYPTO_HMAC
{CRYPT_EAL_IMPLMAC_NEWCTX, (CRYPT_EAL_ImplMacNewCtx)CRYPT_EAL_SmMacNewCtxEx},
{CRYPT_EAL_IMPLMAC_INIT, (CRYPT_EAL_ImplMacInit)CRYPT_HMAC_Init},
{CRYPT_EAL_IMPLMAC_UPDATE, (CRYPT_EAL_ImplMacUpdate)CRYPT_HMAC_Update},
{CRYPT_EAL_IMPLMAC_FINAL, (CRYPT_EAL_ImplMacFinal)CRYPT_HMAC_Final},
{CRYPT_EAL_IMPLMAC_DEINITCTX, (CRYPT_EAL_ImplMacDeInitCtx)CRYPT_HMAC_Deinit},
{CRYPT_EAL_IMPLMAC_REINITCTX, (CRYPT_EAL_ImplMacReInitCtx)CRYPT_HMAC_Reinit},
{CRYPT_EAL_IMPLMAC_CTRL, (CRYPT_EAL_ImplMacCtrl)CRYPT_HMAC_Ctrl},
{CRYPT_EAL_IMPLMAC_FREECTX, (CRYPT_EAL_ImplMacFreeCtx)CRYPT_HMAC_FreeCtx},
{CRYPT_EAL_IMPLMAC_SETPARAM, (CRYPT_EAL_ImplMacSetParam)CRYPT_HMAC_SetParam},
#endif
CRYPT_EAL_FUNC_END,
};
const CRYPT_EAL_Func g_smMacCbcMac[] = {
#ifdef HITLS_CRYPTO_CBC_MAC
{CRYPT_EAL_IMPLMAC_NEWCTX, (CRYPT_EAL_ImplMacNewCtx)CRYPT_EAL_SmMacNewCtxEx},
{CRYPT_EAL_IMPLMAC_INIT, (CRYPT_EAL_ImplMacInit)CRYPT_CBC_MAC_Init},
{CRYPT_EAL_IMPLMAC_UPDATE, (CRYPT_EAL_ImplMacUpdate)CRYPT_CBC_MAC_Update},
{CRYPT_EAL_IMPLMAC_FINAL, (CRYPT_EAL_ImplMacFinal)CRYPT_CBC_MAC_Final},
{CRYPT_EAL_IMPLMAC_DEINITCTX, (CRYPT_EAL_ImplMacDeInitCtx)CRYPT_CBC_MAC_Deinit},
{CRYPT_EAL_IMPLMAC_REINITCTX, (CRYPT_EAL_ImplMacReInitCtx)CRYPT_CBC_MAC_Reinit},
{CRYPT_EAL_IMPLMAC_CTRL, (CRYPT_EAL_ImplMacCtrl)CRYPT_CBC_MAC_Ctrl},
{CRYPT_EAL_IMPLMAC_FREECTX, (CRYPT_EAL_ImplMacFreeCtx)CRYPT_CBC_MAC_FreeCtx},
#endif
CRYPT_EAL_FUNC_END,
};
#endif /* HITLS_CRYPTO_CMVP_SM */
| 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/cmvp/sm_prov/crypt_sm_mac.c | C | unknown | 3,170 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_CMVP_SM
#include "crypt_eal_implprovider.h"
#include "crypt_sm_provider.h"
#include "crypt_sm3.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "bsl_log_internal.h"
#include "bsl_err_internal.h"
#include "crypt_ealinit.h"
static void *CRYPT_EAL_SmMdNewCtxEx(CRYPT_EAL_SmProvCtx *provCtx, int32_t algId)
{
#ifdef HITLS_CRYPTO_ASM_CHECK
if (CRYPT_ASMCAP_Md(algId) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_ASM_NOT_SUPPORT);
return NULL;
}
#endif
if (provCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return NULL;
}
switch (algId) {
#ifdef HITLS_CRYPTO_SM3
case CRYPT_MD_SM3:
return CRYPT_SM3_NewCtxEx(provCtx->libCtx, algId);
#endif
default:
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_NOT_SUPPORT);
return NULL;
}
}
const CRYPT_EAL_Func g_smMdSm3[] = {
#ifdef HITLS_CRYPTO_SM3
{CRYPT_EAL_IMPLMD_NEWCTX, (CRYPT_EAL_ImplMdNewCtx)CRYPT_EAL_SmMdNewCtxEx},
{CRYPT_EAL_IMPLMD_INITCTX, (CRYPT_EAL_ImplMdInitCtx)CRYPT_SM3_Init},
{CRYPT_EAL_IMPLMD_UPDATE, (CRYPT_EAL_ImplMdUpdate)CRYPT_SM3_Update},
{CRYPT_EAL_IMPLMD_FINAL, (CRYPT_EAL_ImplMdFinal)CRYPT_SM3_Final},
{CRYPT_EAL_IMPLMD_DEINITCTX, (CRYPT_EAL_ImplMdDeInitCtx)CRYPT_SM3_Deinit},
{CRYPT_EAL_IMPLMD_DUPCTX, (CRYPT_EAL_ImplMdDupCtx)CRYPT_SM3_DupCtx},
{CRYPT_EAL_IMPLMD_FREECTX, (CRYPT_EAL_ImplMdFreeCtx)CRYPT_SM3_FreeCtx},
{CRYPT_EAL_IMPLMD_COPYCTX, (CRYPT_EAL_ImplMdCopyCtx)CRYPT_SM3_CopyCtx},
{CRYPT_EAL_IMPLMD_GETPARAM, (CRYPT_EAL_ImplMdGetParam)CRYPT_SM3_GetParam},
#endif
CRYPT_EAL_FUNC_END,
};
#endif /* HITLS_CRYPTO_CMVP_SM */
| 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/cmvp/sm_prov/crypt_sm_md.c | C | unknown | 2,240 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_CMVP_SM
#include "crypt_eal_implprovider.h"
#include "crypt_sm2.h"
const CRYPT_EAL_Func g_smAsymCipherSm2[] = {
#ifdef HITLS_CRYPTO_SM2_CRYPT
{CRYPT_EAL_IMPLPKEYCIPHER_ENCRYPT, (CRYPT_EAL_ImplPkeyEncrypt)CRYPT_SM2_Encrypt},
{CRYPT_EAL_IMPLPKEYCIPHER_DECRYPT, (CRYPT_EAL_ImplPkeyDecrypt)CRYPT_SM2_Decrypt},
#endif
CRYPT_EAL_FUNC_END
};
#endif /* HITLS_CRYPTO_CMVP_SM */ | 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/cmvp/sm_prov/crypt_sm_pkeycipher.c | C | unknown | 972 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
/**
* @defgroup crypt_eal_provider
* @ingroup crypt
* @brief sm provider impl
*/
#ifndef CRYPT_EAL_SM_PROVIDERIMPL_H
#define CRYPT_EAL_SM_PROVIDERIMPL_H
#ifdef HITLS_CRYPTO_CMVP_SM
#include "crypt_eal_implprovider.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
typedef struct {
int32_t algId;
void *ctx;
void *provCtx;
} CRYPT_Sm_Pkey_Ctx;
extern const CRYPT_EAL_Func g_smMdSm3[];
extern const CRYPT_EAL_Func g_smKdfPBKdf2[];
extern const CRYPT_EAL_Func g_smKeyMgmtSm2[];
extern const CRYPT_EAL_Func g_smExchSm2[];
extern const CRYPT_EAL_Func g_smAsymCipherSm2[];
extern const CRYPT_EAL_Func g_smSignSm2[];
extern const CRYPT_EAL_Func g_smMacHmac[];
extern const CRYPT_EAL_Func g_smMacCbcMac[];
extern const CRYPT_EAL_Func g_smRand[];
extern const CRYPT_EAL_Func g_smCbc[];
extern const CRYPT_EAL_Func g_smCfb[];
extern const CRYPT_EAL_Func g_smCtr[];
extern const CRYPT_EAL_Func g_smEcb[];
extern const CRYPT_EAL_Func g_smGcm[];
extern const CRYPT_EAL_Func g_smOfb[];
extern const CRYPT_EAL_Func g_smXts[];
extern const CRYPT_EAL_Func g_smSelftest[];
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* HITLS_CRYPTO_CMVP_SM */
#endif /* CRYPT_EAL_SM_PROVIDERIMPL_H */ | 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/cmvp/sm_prov/crypt_sm_provderimpl.h | C | unknown | 1,763 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_CMVP_SM
#include <stdint.h>
#include <string.h>
#include "bsl_errno.h"
#include "bsl_params.h"
#include "crypt_algid.h"
#include "crypt_errno.h"
#include "crypt_utils.h"
#include "crypt_eal_rand.h"
#include "entropy_seed_pool.h"
#include "crypt_sm_selftest.h"
#include "crypt_sm_provderimpl.h"
#include "crypt_sm_provider.h"
#define CRYPT_ENTROPY_SOURCE_ENTROPY 8
#define CRYPT_ENTROPY_SEED_POOL_SIZE 4096
static const CRYPT_EAL_AlgInfo g_smMds[] = {
{CRYPT_MD_SM3, g_smMdSm3, CRYPT_EAL_SM_ATTR},
CRYPT_EAL_ALGINFO_END
};
static const CRYPT_EAL_AlgInfo g_smKdfs[] = {
{CRYPT_KDF_PBKDF2, g_smKdfPBKdf2, CRYPT_EAL_SM_ATTR},
CRYPT_EAL_ALGINFO_END
};
static const CRYPT_EAL_AlgInfo g_smKeyMgmt[] = {
{CRYPT_PKEY_SM2, g_smKeyMgmtSm2, CRYPT_EAL_SM_ATTR},
CRYPT_EAL_ALGINFO_END
};
static const CRYPT_EAL_AlgInfo g_smAsymCiphers[] = {
{CRYPT_PKEY_SM2, g_smAsymCipherSm2, CRYPT_EAL_SM_ATTR},
CRYPT_EAL_ALGINFO_END
};
static const CRYPT_EAL_AlgInfo g_smKeyExch[] = {
{CRYPT_PKEY_SM2, g_smExchSm2, CRYPT_EAL_SM_ATTR},
CRYPT_EAL_ALGINFO_END
};
static const CRYPT_EAL_AlgInfo g_smSigns[] = {
{CRYPT_PKEY_SM2, g_smSignSm2, CRYPT_EAL_SM_ATTR},
CRYPT_EAL_ALGINFO_END
};
static const CRYPT_EAL_AlgInfo g_smMacs[] = {
{CRYPT_MAC_HMAC_SM3, g_smMacHmac, CRYPT_EAL_SM_ATTR},
{CRYPT_MAC_CBC_MAC_SM4, g_smMacCbcMac, CRYPT_EAL_SM_ATTR},
CRYPT_EAL_ALGINFO_END
};
static const CRYPT_EAL_AlgInfo g_smRands[] = {
{CRYPT_RAND_SM3, g_smRand, CRYPT_EAL_SM_ATTR},
{CRYPT_RAND_SM4_CTR_DF, g_smRand, CRYPT_EAL_SM_ATTR},
CRYPT_EAL_ALGINFO_END
};
static const CRYPT_EAL_AlgInfo g_smCiphers[] = {
{CRYPT_CIPHER_SM4_XTS, g_smXts, CRYPT_EAL_SM_ATTR},
{CRYPT_CIPHER_SM4_CBC, g_smCbc, CRYPT_EAL_SM_ATTR},
{CRYPT_CIPHER_SM4_ECB, g_smEcb, CRYPT_EAL_SM_ATTR},
{CRYPT_CIPHER_SM4_CTR, g_smCtr, CRYPT_EAL_SM_ATTR},
{CRYPT_CIPHER_SM4_GCM, g_smGcm, CRYPT_EAL_SM_ATTR},
{CRYPT_CIPHER_SM4_CFB, g_smCfb, CRYPT_EAL_SM_ATTR},
{CRYPT_CIPHER_SM4_OFB, g_smOfb, CRYPT_EAL_SM_ATTR},
CRYPT_EAL_ALGINFO_END
};
static const CRYPT_EAL_AlgInfo g_smSelftests[] = {
{CRYPT_CMVP_PROVIDER_SELFTEST, g_smSelftest, CRYPT_EAL_SM_ATTR},
CRYPT_EAL_ALGINFO_END
};
static int32_t CRYPT_EAL_SmProvQuery(void *provCtx, int32_t operaId, const CRYPT_EAL_AlgInfo **algInfos)
{
(void)provCtx;
int32_t ret = CRYPT_SUCCESS;
switch (operaId) {
case CRYPT_EAL_OPERAID_SYMMCIPHER:
*algInfos = g_smCiphers;
break;
case CRYPT_EAL_OPERAID_KEYMGMT:
*algInfos = g_smKeyMgmt;
break;
case CRYPT_EAL_OPERAID_SIGN:
*algInfos = g_smSigns;
break;
case CRYPT_EAL_OPERAID_ASYMCIPHER:
*algInfos = g_smAsymCiphers;
break;
case CRYPT_EAL_OPERAID_KEYEXCH:
*algInfos = g_smKeyExch;
break;
case CRYPT_EAL_OPERAID_HASH:
*algInfos = g_smMds;
break;
case CRYPT_EAL_OPERAID_MAC:
*algInfos = g_smMacs;
break;
case CRYPT_EAL_OPERAID_KDF:
*algInfos = g_smKdfs;
break;
case CRYPT_EAL_OPERAID_RAND:
*algInfos = g_smRands;
break;
case CRYPT_EAL_OPERAID_SELFTEST:
*algInfos = g_smSelftests;
break;
default:
*algInfos = NULL;
ret = CRYPT_NOT_SUPPORT;
break;
}
return ret;
}
static void CRYPT_EAL_SmProvFree(void *provCtx)
{
if (provCtx == NULL) {
return;
}
CRYPT_EAL_SmProvCtx *temp = (CRYPT_EAL_SmProvCtx *)provCtx;
CRYPT_EAL_SeedPoolFree(temp->pool);
CRYPT_EAL_EsFree(temp->es);
BSL_SAL_Free(provCtx);
}
static CRYPT_EAL_Func g_smProvOutFuncs[] = {
{CRYPT_EAL_PROVCB_QUERY, CRYPT_EAL_SmProvQuery},
{CRYPT_EAL_PROVCB_FREE, CRYPT_EAL_SmProvFree},
{CRYPT_EAL_PROVCB_CTRL, NULL},
{CRYPT_EAL_PROVCB_GETCAPS, NULL},
CRYPT_EAL_FUNC_END
};
static int32_t ReadDevRandom(void *ctx, uint32_t timeout, uint8_t *buf, uint32_t bufLen)
{
(void)ctx;
(void)timeout;
if (ENTROPY_SysEntropyGet(NULL, buf, bufLen) != bufLen) {
return CRYPT_DRBG_FAIL_GET_ENTROPY;
}
return CRYPT_SUCCESS;
}
static int32_t CreateSmEs(CRYPT_EAL_Es **es)
{
int32_t ret = CRYPT_SUCCESS;
CRYPT_EAL_Es *esTemp = CRYPT_EAL_EsNew();
RETURN_RET_IF(esTemp == NULL, CRYPT_MEM_ALLOC_FAIL);
ret = CRYPT_EAL_EsCtrl(esTemp, CRYPT_ENTROPY_SET_CF, "sm3_df", (uint32_t)strlen("sm3_df"));
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
CRYPT_EAL_NsPara para = {
"dev-random",
false,
5,
{NULL, NULL, ReadDevRandom, NULL},
{5, 39, 512},
};
ret = CRYPT_EAL_EsCtrl(esTemp, CRYPT_ENTROPY_ADD_NS, (void *)¶, sizeof(CRYPT_EAL_NsPara));
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
bool healthTest = true;
ret = CRYPT_EAL_EsCtrl(esTemp, CRYPT_ENTROPY_ENABLE_TEST, &healthTest, sizeof(healthTest));
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
uint32_t size = CRYPT_ENTROPY_SEED_POOL_SIZE;
ret = CRYPT_EAL_EsCtrl(esTemp, CRYPT_ENTROPY_SET_POOL_SIZE, &size, sizeof(size));
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
ret = CRYPT_EAL_EsInit(esTemp);
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
*es = esTemp;
return ret;
ERR:
CRYPT_EAL_EsFree(esTemp);
return ret;
}
static int32_t CreateSeedPool(CRYPT_EAL_SeedPoolCtx **seedPool, CRYPT_EAL_Es **es)
{
CRYPT_EAL_SeedPoolCtx *poolTemp = NULL;
CRYPT_EAL_Es *esTemp = NULL;
int32_t ret = CreateSmEs(&esTemp);
if (ret != CRYPT_SUCCESS) {
return ret;
}
poolTemp = CRYPT_EAL_SeedPoolNew(true);
if (poolTemp == NULL) {
CRYPT_EAL_EsFree(esTemp);
BSL_ERR_PUSH_ERROR(CRYPT_SEED_POOL_NEW_ERROR);
return CRYPT_SEED_POOL_NEW_ERROR;
}
CRYPT_EAL_EsPara para = {false, CRYPT_ENTROPY_SOURCE_ENTROPY, esTemp, (CRYPT_EAL_EntropyGet)CRYPT_EAL_EsEntropyGet};
ret = CRYPT_EAL_SeedPoolAddEs(poolTemp, ¶);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_SeedPoolFree(poolTemp);
CRYPT_EAL_EsFree(esTemp);
return ret;
}
*seedPool = poolTemp;
*es = esTemp;
return CRYPT_SUCCESS;
}
static int32_t CreateProvCtx(void *libCtx, CRYPT_EAL_ProvMgrCtx *mgrCtx, void **provCtx)
{
CRYPT_EAL_SmProvCtx *temp = BSL_SAL_Calloc(1, sizeof(CRYPT_EAL_SmProvCtx));
if (temp == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
CRYPT_EAL_SetRandCallBackEx((CRYPT_EAL_RandFuncEx)CRYPT_EAL_RandbytesEx);
int32_t ret = CreateSeedPool(&temp->pool, &temp->es);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_Free(temp);
return ret;
}
temp->libCtx = libCtx;
temp->mgrCtx = mgrCtx;
*provCtx = temp;
return CRYPT_SUCCESS;
}
int32_t CRYPT_EAL_ProviderInit(CRYPT_EAL_ProvMgrCtx *mgrCtx, BSL_Param *param, CRYPT_EAL_Func *capFuncs,
CRYPT_EAL_Func **outFuncs, void **provCtx)
{
void *libCtx = NULL;
CRYPT_EAL_ProvMgrCtrlCb mgrCtrl = NULL;
int32_t index = 0;
int32_t ret;
while (capFuncs[index].id != 0) {
switch (capFuncs[index].id) {
case CRYPT_EAL_CAP_MGRCTXCTRL:
mgrCtrl = capFuncs[index].func;
break;
default:
break;
}
index++;
}
if (mgrCtrl == NULL) {
return CRYPT_PROVIDER_NOT_SUPPORT;
}
ret = mgrCtrl(mgrCtx, CRYPT_EAL_MGR_GETLIBCTX, &libCtx, 0);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = CRYPT_SM_Selftest(param);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = CreateProvCtx(libCtx, mgrCtx, provCtx);
if (ret != CRYPT_SUCCESS) {
return ret;
}
*outFuncs = g_smProvOutFuncs;
return CRYPT_SUCCESS;
}
#endif /* HITLS_CRYPTO_CMVP_SM */
| 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/cmvp/sm_prov/crypt_sm_provider.c | C | unknown | 8,484 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
/**
* @defgroup crypt_eal_provider
* @ingroup crypt
* @brief sm provider header
*/
#ifndef CRYPT_EAL_SM_PROVIDER_H
#define CRYPT_EAL_SM_PROVIDER_H
#ifdef HITLS_CRYPTO_CMVP_SM
#include <stdint.h>
#include "crypt_eal_entropy.h"
#include "crypt_eal_implprovider.h"
#include "crypt_eal_cmvp.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#define CRYPT_EAL_SM_ATTR "provider=sm"
typedef struct EalSmProvCtx {
void *libCtx;
void *mgrCtx;
CRYPT_EAL_Es *es;
CRYPT_EAL_SeedPoolCtx *pool;
} CRYPT_EAL_SmProvCtx;
int32_t CRYPT_EAL_ProviderInit(CRYPT_EAL_ProvMgrCtx *mgrCtx, BSL_Param *param, CRYPT_EAL_Func *capFuncs,
CRYPT_EAL_Func **outFuncs, void **provCtx);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* HITLS_CRYPTO_CMVP_SM */
#endif /* CRYPT_EAL_SM_PROVIDER_H */ | 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/cmvp/sm_prov/crypt_sm_provider.h | C | unknown | 1,357 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_CMVP_SM
#include "crypt_eal_implprovider.h"
#include "crypt_drbg.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "bsl_log_internal.h"
#include "bsl_err_internal.h"
#include "crypt_ealinit.h"
#include "bsl_params.h"
#include "eal_entropy.h"
#include "crypt_sm_provider.h"
#ifdef HITLS_CRYPTO_ENTROPY
static int32_t GetDefaultSeed(CRYPT_EAL_SmProvCtx *provCtx, BSL_Param *param)
{
CRYPT_RandSeedMethod seedMethod = {0};
int32_t ret = EAL_SetDefaultEntropyMeth(&seedMethod);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
int32_t index = 0;
(void)BSL_PARAM_InitValue(¶m[index++], CRYPT_PARAM_RAND_SEEDCTX, BSL_PARAM_TYPE_CTX_PTR,
provCtx->pool, 0);
(void)BSL_PARAM_InitValue(¶m[index++], CRYPT_PARAM_RAND_SEED_GETENTROPY, BSL_PARAM_TYPE_FUNC_PTR,
seedMethod.getEntropy, 0);
(void)BSL_PARAM_InitValue(¶m[index++], CRYPT_PARAM_RAND_SEED_CLEANENTROPY, BSL_PARAM_TYPE_FUNC_PTR,
seedMethod.cleanEntropy, 0);
(void)BSL_PARAM_InitValue(¶m[index++], CRYPT_PARAM_RAND_SEED_GETNONCE, BSL_PARAM_TYPE_FUNC_PTR,
seedMethod.getNonce, 0);
(void)BSL_PARAM_InitValue(¶m[index++], CRYPT_PARAM_RAND_SEED_CLEANNONCE, BSL_PARAM_TYPE_FUNC_PTR,
seedMethod.cleanNonce, 0);
return CRYPT_SUCCESS;
}
#endif
void *CRYPT_EAL_SmRandNewCtx(CRYPT_EAL_SmProvCtx *provCtx, int32_t algId, BSL_Param *param)
{
void *randCtx = NULL;
#ifdef HITLS_CRYPTO_ASM_CHECK
if (CRYPT_ASMCAP_Drbg(algId) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_ASM_NOT_SUPPORT);
return NULL;
}
#endif
BSL_Param *getEnt = BSL_PARAM_FindParam(param, CRYPT_PARAM_RAND_SEED_GETENTROPY);
BSL_Param *cleanEnt = BSL_PARAM_FindParam(param, CRYPT_PARAM_RAND_SEED_CLEANENTROPY);
BSL_Param *getNonce = BSL_PARAM_FindParam(param, CRYPT_PARAM_RAND_SEED_GETNONCE);
BSL_Param *cleanNonce = BSL_PARAM_FindParam(param, CRYPT_PARAM_RAND_SEED_CLEANNONCE);
BSL_Param *ctx = BSL_PARAM_FindParam(param, CRYPT_PARAM_RAND_SEEDCTX);
/**
* If you use a registered entropy source, the getEntropy callback cannot be NULL,
* and if getEntropy is NULL, cleanEntropy, getNonce, cleanNonce, etc. must be NULL
*/
if (getEnt == NULL && ((cleanEnt != NULL && cleanEnt->value != NULL) ||
(getNonce != NULL && getNonce->value != NULL) || (cleanNonce != NULL && cleanNonce->value != NULL) ||
(ctx != NULL && ctx->value != NULL))) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return NULL;
}
if (param == NULL || getEnt == NULL) {
#ifdef HITLS_CRYPTO_ENTROPY
BSL_Param defaultParam[6] = {BSL_PARAM_END};
if (GetDefaultSeed(provCtx, defaultParam) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return NULL;
}
return DRBG_New(provCtx->libCtx, algId, defaultParam);
#else
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return NULL;
#endif
}
randCtx = DRBG_New(provCtx->libCtx, algId, param);
if (randCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_NOT_SUPPORT);
return NULL;
}
return randCtx;
}
const CRYPT_EAL_Func g_smRand[] = {
#if defined(HITLS_CRYPTO_DRBG)
{CRYPT_EAL_IMPLRAND_DRBGNEWCTX, (CRYPT_EAL_ImplRandDrbgNewCtx)CRYPT_EAL_SmRandNewCtx},
{CRYPT_EAL_IMPLRAND_DRBGINST, (CRYPT_EAL_ImplRandDrbgInst)DRBG_Instantiate},
{CRYPT_EAL_IMPLRAND_DRBGUNINST, (CRYPT_EAL_ImplRandDrbgUnInst)DRBG_Uninstantiate},
{CRYPT_EAL_IMPLRAND_DRBGGEN, (CRYPT_EAL_ImplRandDrbgGen)DRBG_GenerateBytes},
{CRYPT_EAL_IMPLRAND_DRBGRESEED, (CRYPT_EAL_ImplRandDrbgReSeed)DRBG_Reseed},
{CRYPT_EAL_IMPLRAND_DRBGCTRL, (CRYPT_EAL_ImplRandDrbgCtrl)DRBG_Ctrl},
{CRYPT_EAL_IMPLRAND_DRBGFREECTX, (CRYPT_EAL_ImplRandDrbgFreeCtx)DRBG_Free},
#endif
CRYPT_EAL_FUNC_END,
};
#endif /* HITLS_CRYPTO_CMVP_SM */ | 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/cmvp/sm_prov/crypt_sm_rand.c | C | unknown | 4,470 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_CMVP_SM
#include "securec.h"
#include "crypt_types.h"
#include "crypt_errno.h"
#include "bsl_params.h"
#include "cmvp_sm.h"
#include "cmvp_common.h"
#include "crypt_sm_selftest.h"
int32_t CRYPT_SM_Selftest(BSL_Param *param)
{
CRYPT_EAL_LibCtx *libCtx = NULL;
if (CMVP_CheckIsInternalLibCtx(param)) {
return CRYPT_SUCCESS;
}
int32_t ret = CMVP_CreateInternalLibCtx(param, &libCtx, CRYPT_SM_Selftest);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = CMVP_SmCheckIntegrity(libCtx, CRYPT_EAL_SM_ATTR);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_LibCtxFree(libCtx);
return ret;
}
ret = CMVP_SmKat(libCtx, CRYPT_EAL_SM_ATTR);
CRYPT_EAL_LibCtxFree(libCtx);
if (ret != CRYPT_SUCCESS) {
return ret;
}
return CRYPT_SUCCESS;
}
#endif /* HITLS_CRYPTO_CMVP_SM */ | 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/cmvp/sm_prov/crypt_sm_selftest.c | C | unknown | 1,435 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
/**
* @defgroup crypt_eal_provider
* @ingroup crypt
* @brief sm provider header
*/
#ifndef CRYPT_EAL_SM_SELFTEST_H
#define CRYPT_EAL_SM_SELFTEST_H
#ifdef HITLS_CRYPTO_CMVP_SM
#include <stdint.h>
#include "bsl_params.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
int32_t CRYPT_SM_Selftest(BSL_Param *param);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* HITLS_CRYPTO_CMVP_SM */
#endif /* CRYPT_EAL_SM_SELFTEST_H */ | 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/cmvp/sm_prov/crypt_sm_selftest.h | C | unknown | 992 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_CMVP_SM
#include "crypt_eal_implprovider.h"
#include "crypt_sm2.h"
#include "crypt_errno.h"
#include "cmvp_sm.h"
#include "crypt_cmvp.h"
static int32_t CRYPT_SM2_SignWrapper(const CRYPT_SM2_Ctx *ctx, int32_t algId, const uint8_t *data, uint32_t dataLen,
uint8_t *sign, uint32_t *signLen)
{
if (!CMVP_SmPkeyC2(algId)) {
return CRYPT_CMVP_ERR_PARAM_CHECK;
}
return CRYPT_SM2_Sign(ctx, algId, data, dataLen, sign, signLen);
}
static int32_t CRYPT_SM2_VerifyWrapper(const CRYPT_SM2_Ctx *ctx, int32_t algId, const uint8_t *data, uint32_t dataLen,
const uint8_t *sign, uint32_t signLen)
{
if (!CMVP_SmPkeyC2(algId)) {
return CRYPT_CMVP_ERR_PARAM_CHECK;
}
return CRYPT_SM2_Verify(ctx, algId, data, dataLen, sign, signLen);
}
const CRYPT_EAL_Func g_smSignSm2[] = {
#ifdef HITLS_CRYPTO_SM2_SIGN
{CRYPT_EAL_IMPLPKEYSIGN_SIGN, (CRYPT_EAL_ImplPkeySign)CRYPT_SM2_SignWrapper},
{CRYPT_EAL_IMPLPKEYSIGN_VERIFY, (CRYPT_EAL_ImplPkeyVerify)CRYPT_SM2_VerifyWrapper},
#endif
CRYPT_EAL_FUNC_END,
};
#endif /* HITLS_CRYPTO_CMVP_SM */ | 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/cmvp/sm_prov/crypt_sm_sign.c | C | unknown | 1,665 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_CIPHER) && defined(HITLS_CRYPTO_PROVIDER)
#include "crypt_eal_implprovider.h"
#include "crypt_modes_cbc.h"
#include "crypt_modes_ccm.h"
#include "crypt_modes_chacha20poly1305.h"
#include "crypt_modes_ctr.h"
#include "crypt_modes_ecb.h"
#include "crypt_modes_gcm.h"
#include "crypt_modes_ofb.h"
#include "crypt_modes_cfb.h"
#include "crypt_modes_xts.h"
#include "crypt_local_types.h"
#include "crypt_errno.h"
#include "bsl_err_internal.h"
#include "crypt_ealinit.h"
static void *CRYPT_EAL_DefCipherNewCtx(void *provCtx, int32_t algId)
{
(void) provCtx;
#ifdef HITLS_CRYPTO_ASM_CHECK
if (CRYPT_ASMCAP_Cipher(algId) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_ASM_NOT_SUPPORT);
return NULL;
}
#endif
CRYPT_EAL_Func cipherNewCtxFunc[] = {
{CRYPT_CIPHER_AES128_CBC, MODES_CBC_NewCtx},
{CRYPT_CIPHER_AES192_CBC, MODES_CBC_NewCtx},
{CRYPT_CIPHER_AES256_CBC, MODES_CBC_NewCtx},
{CRYPT_CIPHER_AES128_CTR, MODES_CTR_NewCtx},
{CRYPT_CIPHER_AES192_CTR, MODES_CTR_NewCtx},
{CRYPT_CIPHER_AES256_CTR, MODES_CTR_NewCtx},
{CRYPT_CIPHER_AES128_ECB, MODES_ECB_NewCtx},
{CRYPT_CIPHER_AES192_ECB, MODES_ECB_NewCtx},
{CRYPT_CIPHER_AES256_ECB, MODES_ECB_NewCtx},
#ifdef HITLS_CRYPTO_CCM
{CRYPT_CIPHER_AES128_CCM, MODES_CCM_NewCtx},
{CRYPT_CIPHER_AES192_CCM, MODES_CCM_NewCtx},
{CRYPT_CIPHER_AES256_CCM, MODES_CCM_NewCtx},
#endif
{CRYPT_CIPHER_AES128_GCM, MODES_GCM_NewCtx},
{CRYPT_CIPHER_AES192_GCM, MODES_GCM_NewCtx},
{CRYPT_CIPHER_AES256_GCM, MODES_GCM_NewCtx},
{CRYPT_CIPHER_AES128_CFB, MODES_CFB_NewCtx},
{CRYPT_CIPHER_AES192_CFB, MODES_CFB_NewCtx},
{CRYPT_CIPHER_AES256_CFB, MODES_CFB_NewCtx},
{CRYPT_CIPHER_AES128_OFB, MODES_OFB_NewCtx},
{CRYPT_CIPHER_AES192_OFB, MODES_OFB_NewCtx},
{CRYPT_CIPHER_AES256_OFB, MODES_OFB_NewCtx},
{CRYPT_CIPHER_AES128_XTS, MODES_XTS_NewCtx},
{CRYPT_CIPHER_AES256_XTS, MODES_XTS_NewCtx},
#if defined(HITLS_CRYPTO_CHACHA20) && defined(HITLS_CRYPTO_CHACHA20POLY1305)
{CRYPT_CIPHER_CHACHA20_POLY1305, MODES_CHACHA20POLY1305_NewCtx},
#endif
{CRYPT_CIPHER_SM4_XTS, MODES_XTS_NewCtx},
{CRYPT_CIPHER_SM4_CBC, MODES_CBC_NewCtx},
{CRYPT_CIPHER_SM4_ECB, MODES_ECB_NewCtx},
{CRYPT_CIPHER_SM4_CTR, MODES_CTR_NewCtx},
{CRYPT_CIPHER_SM4_GCM, MODES_GCM_NewCtx},
{CRYPT_CIPHER_SM4_CFB, MODES_CFB_NewCtx},
{CRYPT_CIPHER_SM4_OFB, MODES_OFB_NewCtx},
};
for (size_t i = 0; i < sizeof(cipherNewCtxFunc)/sizeof(cipherNewCtxFunc[0]); i++) {
if (cipherNewCtxFunc[i].id == algId) {
return ((CipherNewCtx)cipherNewCtxFunc[i].func)(algId);
}
}
return NULL;
}
#ifdef HITLS_CRYPTO_CBC
const CRYPT_EAL_Func g_defEalCbc[] = {
{CRYPT_EAL_IMPLCIPHER_NEWCTX, (CRYPT_EAL_ImplCipherNewCtx)CRYPT_EAL_DefCipherNewCtx},
{CRYPT_EAL_IMPLCIPHER_INITCTX, (CRYPT_EAL_ImplCipherInitCtx)MODES_CBC_InitCtxEx},
{CRYPT_EAL_IMPLCIPHER_UPDATE, (CRYPT_EAL_ImplCipherUpdate)MODES_CBC_UpdateEx},
{CRYPT_EAL_IMPLCIPHER_FINAL, (CRYPT_EAL_ImplCipherFinal)MODES_CBC_FinalEx},
{CRYPT_EAL_IMPLCIPHER_DEINITCTX, (CRYPT_EAL_ImplCipherDeinitCtx)MODES_CBC_DeInitCtx},
{CRYPT_EAL_IMPLCIPHER_CTRL, (CRYPT_EAL_ImplCipherCtrl)MODES_CBC_Ctrl},
{CRYPT_EAL_IMPLCIPHER_FREECTX, (CRYPT_EAL_ImplCipherFreeCtx)MODES_CBC_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_CCM
const CRYPT_EAL_Func g_defEalCcm[] = {
{CRYPT_EAL_IMPLCIPHER_NEWCTX, (CRYPT_EAL_ImplCipherNewCtx)CRYPT_EAL_DefCipherNewCtx},
{CRYPT_EAL_IMPLCIPHER_INITCTX, (CRYPT_EAL_ImplCipherInitCtx)MODES_CCM_InitCtx},
{CRYPT_EAL_IMPLCIPHER_UPDATE, (CRYPT_EAL_ImplCipherUpdate)MODES_CCM_UpdateEx},
{CRYPT_EAL_IMPLCIPHER_FINAL, (CRYPT_EAL_ImplCipherFinal)MODES_CCM_Final},
{CRYPT_EAL_IMPLCIPHER_DEINITCTX, (CRYPT_EAL_ImplCipherDeinitCtx)MODES_CCM_DeInitCtx},
{CRYPT_EAL_IMPLCIPHER_CTRL, (CRYPT_EAL_ImplCipherCtrl)MODES_CCM_Ctrl},
{CRYPT_EAL_IMPLCIPHER_FREECTX, (CRYPT_EAL_ImplCipherFreeCtx)MODES_CCM_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_CFB
const CRYPT_EAL_Func g_defEalCfb[] = {
{CRYPT_EAL_IMPLCIPHER_NEWCTX, (CRYPT_EAL_ImplCipherNewCtx)CRYPT_EAL_DefCipherNewCtx},
{CRYPT_EAL_IMPLCIPHER_INITCTX, (CRYPT_EAL_ImplCipherInitCtx)MODES_CFB_InitCtxEx},
{CRYPT_EAL_IMPLCIPHER_UPDATE, (CRYPT_EAL_ImplCipherUpdate)MODES_CFB_UpdateEx},
{CRYPT_EAL_IMPLCIPHER_FINAL, (CRYPT_EAL_ImplCipherFinal)MODES_CFB_Final},
{CRYPT_EAL_IMPLCIPHER_DEINITCTX, (CRYPT_EAL_ImplCipherDeinitCtx)MODES_CFB_DeInitCtx},
{CRYPT_EAL_IMPLCIPHER_CTRL, (CRYPT_EAL_ImplCipherCtrl)MODES_CFB_Ctrl},
{CRYPT_EAL_IMPLCIPHER_FREECTX, (CRYPT_EAL_ImplCipherFreeCtx)MODES_CFB_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#if defined(HITLS_CRYPTO_CHACHA20) && defined(HITLS_CRYPTO_CHACHA20POLY1305)
const CRYPT_EAL_Func g_defEalChaCha[] = {
{CRYPT_EAL_IMPLCIPHER_NEWCTX, (CRYPT_EAL_ImplCipherNewCtx)CRYPT_EAL_DefCipherNewCtx},
{CRYPT_EAL_IMPLCIPHER_INITCTX, (CRYPT_EAL_ImplCipherInitCtx)MODES_CHACHA20POLY1305_InitCtx},
{CRYPT_EAL_IMPLCIPHER_UPDATE, (CRYPT_EAL_ImplCipherUpdate)MODES_CHACHA20POLY1305_Update},
{CRYPT_EAL_IMPLCIPHER_FINAL, (CRYPT_EAL_ImplCipherFinal)MODES_CHACHA20POLY1305_Final},
{CRYPT_EAL_IMPLCIPHER_DEINITCTX, (CRYPT_EAL_ImplCipherDeinitCtx)MODES_CHACHA20POLY1305_DeInitCtx},
{CRYPT_EAL_IMPLCIPHER_CTRL, (CRYPT_EAL_ImplCipherCtrl)MODES_CHACHA20POLY1305_Ctrl},
{CRYPT_EAL_IMPLCIPHER_FREECTX, (CRYPT_EAL_ImplCipherFreeCtx)MODES_CHACHA20POLY1305_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_CTR
const CRYPT_EAL_Func g_defEalCtr[] = {
{CRYPT_EAL_IMPLCIPHER_NEWCTX, (CRYPT_EAL_ImplCipherNewCtx)CRYPT_EAL_DefCipherNewCtx},
{CRYPT_EAL_IMPLCIPHER_INITCTX, (CRYPT_EAL_ImplCipherInitCtx)MODES_CTR_InitCtxEx},
{CRYPT_EAL_IMPLCIPHER_UPDATE, (CRYPT_EAL_ImplCipherUpdate)MODES_CTR_UpdateEx},
{CRYPT_EAL_IMPLCIPHER_FINAL, (CRYPT_EAL_ImplCipherFinal)MODES_CTR_Final},
{CRYPT_EAL_IMPLCIPHER_DEINITCTX, (CRYPT_EAL_ImplCipherDeinitCtx)MODES_CTR_DeInitCtx},
{CRYPT_EAL_IMPLCIPHER_CTRL, (CRYPT_EAL_ImplCipherCtrl)MODES_CTR_Ctrl},
{CRYPT_EAL_IMPLCIPHER_FREECTX, (CRYPT_EAL_ImplCipherFreeCtx)MODES_CTR_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_ECB
const CRYPT_EAL_Func g_defEalEcb[] = {
{CRYPT_EAL_IMPLCIPHER_NEWCTX, (CRYPT_EAL_ImplCipherNewCtx)CRYPT_EAL_DefCipherNewCtx},
{CRYPT_EAL_IMPLCIPHER_INITCTX, (CRYPT_EAL_ImplCipherInitCtx)MODES_ECB_InitCtxEx},
{CRYPT_EAL_IMPLCIPHER_UPDATE, (CRYPT_EAL_ImplCipherUpdate)MODES_ECB_UpdateEx},
{CRYPT_EAL_IMPLCIPHER_FINAL, (CRYPT_EAL_ImplCipherFinal)MODES_ECB_FinalEx},
{CRYPT_EAL_IMPLCIPHER_DEINITCTX, (CRYPT_EAL_ImplCipherDeinitCtx)MODES_ECB_DeinitCtx},
{CRYPT_EAL_IMPLCIPHER_CTRL, (CRYPT_EAL_ImplCipherCtrl)MODES_ECB_Ctrl},
{CRYPT_EAL_IMPLCIPHER_FREECTX, (CRYPT_EAL_ImplCipherFreeCtx)MODES_ECB_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_GCM
const CRYPT_EAL_Func g_defEalGcm[] = {
{CRYPT_EAL_IMPLCIPHER_NEWCTX, (CRYPT_EAL_ImplCipherNewCtx)CRYPT_EAL_DefCipherNewCtx},
{CRYPT_EAL_IMPLCIPHER_INITCTX, (CRYPT_EAL_ImplCipherInitCtx)MODES_GCM_InitCtxEx},
{CRYPT_EAL_IMPLCIPHER_UPDATE, (CRYPT_EAL_ImplCipherUpdate)MODES_GCM_UpdateEx},
{CRYPT_EAL_IMPLCIPHER_FINAL, (CRYPT_EAL_ImplCipherFinal)MODES_GCM_Final},
{CRYPT_EAL_IMPLCIPHER_DEINITCTX, (CRYPT_EAL_ImplCipherDeinitCtx)MODES_GCM_DeInitCtx},
{CRYPT_EAL_IMPLCIPHER_CTRL, (CRYPT_EAL_ImplCipherCtrl)MODES_GCM_Ctrl},
{CRYPT_EAL_IMPLCIPHER_FREECTX, (CRYPT_EAL_ImplCipherFreeCtx)MODES_GCM_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_OFB
const CRYPT_EAL_Func g_defEalOfb[] = {
{CRYPT_EAL_IMPLCIPHER_NEWCTX, (CRYPT_EAL_ImplCipherNewCtx)CRYPT_EAL_DefCipherNewCtx},
{CRYPT_EAL_IMPLCIPHER_INITCTX, (CRYPT_EAL_ImplCipherInitCtx)MODES_OFB_InitCtxEx},
{CRYPT_EAL_IMPLCIPHER_UPDATE, (CRYPT_EAL_ImplCipherUpdate)MODES_OFB_UpdateEx},
{CRYPT_EAL_IMPLCIPHER_FINAL, (CRYPT_EAL_ImplCipherFinal)MODES_OFB_Final},
{CRYPT_EAL_IMPLCIPHER_DEINITCTX, (CRYPT_EAL_ImplCipherDeinitCtx)MODES_OFB_DeInitCtx},
{CRYPT_EAL_IMPLCIPHER_CTRL, (CRYPT_EAL_ImplCipherCtrl)MODES_OFB_Ctrl},
{CRYPT_EAL_IMPLCIPHER_FREECTX, (CRYPT_EAL_ImplCipherFreeCtx)MODES_OFB_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_XTS
const CRYPT_EAL_Func g_defEalXts[] = {
{CRYPT_EAL_IMPLCIPHER_NEWCTX, (CRYPT_EAL_ImplCipherNewCtx)CRYPT_EAL_DefCipherNewCtx},
{CRYPT_EAL_IMPLCIPHER_INITCTX, (CRYPT_EAL_ImplCipherInitCtx)MODES_XTS_InitCtxEx},
{CRYPT_EAL_IMPLCIPHER_UPDATE, (CRYPT_EAL_ImplCipherUpdate)MODES_XTS_UpdateEx},
{CRYPT_EAL_IMPLCIPHER_FINAL, (CRYPT_EAL_ImplCipherFinal)MODES_XTS_Final},
{CRYPT_EAL_IMPLCIPHER_DEINITCTX, (CRYPT_EAL_ImplCipherDeinitCtx)MODES_XTS_DeInitCtx},
{CRYPT_EAL_IMPLCIPHER_CTRL, (CRYPT_EAL_ImplCipherCtrl)MODES_XTS_Ctrl},
{CRYPT_EAL_IMPLCIPHER_FREECTX, (CRYPT_EAL_ImplCipherFreeCtx)MODES_XTS_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#endif /* HITLS_CRYPTO_CIPHER && HITLS_CRYPTO_PROVIDER */ | 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/default/crypt_default_cipher.c | C | unknown | 9,722 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_CODECSKEY) && defined(HITLS_CRYPTO_PROVIDER)
#include "crypt_eal_implprovider.h"
#include "crypt_eal_pkey.h"
#include "crypt_decode_key_impl.h"
#ifdef HITLS_CRYPTO_KEY_EPKI
const CRYPT_EAL_Func g_defEalPrvP8Enc2P8[] = {
{CRYPT_DECODER_IMPL_NEWCTX, (CRYPT_DECODER_IMPL_NewCtx)DECODER_EPKI2PKI_NewCtx},
{CRYPT_DECODER_IMPL_SETPARAM, (CRYPT_DECODER_IMPL_SetParam)DECODER_EPKI2PKI_SetParam},
{CRYPT_DECODER_IMPL_GETPARAM, (CRYPT_DECODER_IMPL_GetParam)DECODER_EPKI2PKI_GetParam},
{CRYPT_DECODER_IMPL_DECODE, (CRYPT_DECODER_IMPL_Decode)DECODER_EPKI2PKI_Decode},
{CRYPT_DECODER_IMPL_FREEOUTDATA, (CRYPT_DECODER_IMPL_FreeOutData)DECODER_EPKI2PKI_FreeOutData},
{CRYPT_DECODER_IMPL_FREECTX, (CRYPT_DECODER_IMPL_FreeCtx)DECODER_EPKI2PKI_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_BSL_PEM
const CRYPT_EAL_Func g_defEalPem2Der[] = {
{CRYPT_DECODER_IMPL_NEWCTX, (CRYPT_DECODER_IMPL_NewCtx)DECODER_Pem2DerNewCtx},
{CRYPT_DECODER_IMPL_GETPARAM, (CRYPT_DECODER_IMPL_GetParam)DECODER_Pem2DerGetParam},
{CRYPT_DECODER_IMPL_SETPARAM, (CRYPT_DECODER_IMPL_SetParam)DECODER_Pem2DerSetParam},
{CRYPT_DECODER_IMPL_DECODE, (CRYPT_DECODER_IMPL_Decode)DECODER_Pem2DerDecode},
{CRYPT_DECODER_IMPL_FREEOUTDATA, (CRYPT_DECODER_IMPL_FreeOutData)DECODER_Pem2DerFreeOutData},
{CRYPT_DECODER_IMPL_FREECTX, (CRYPT_DECODER_IMPL_FreeCtx)DECODER_Pem2DerFreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_RSA
const CRYPT_EAL_Func g_defEalRsaPrvDer2Key[] = {
{CRYPT_DECODER_IMPL_NEWCTX, (CRYPT_DECODER_IMPL_NewCtx)DECODER_RsaDer2KeyNewCtx},
{CRYPT_DECODER_IMPL_GETPARAM, (CRYPT_DECODER_IMPL_GetParam)DECODER_DER2KEY_GetParam},
{CRYPT_DECODER_IMPL_SETPARAM, (CRYPT_DECODER_IMPL_SetParam)DECODER_DER2KEY_SetParam},
{CRYPT_DECODER_IMPL_DECODE, (CRYPT_DECODER_IMPL_Decode)DECODER_RsaPrvKeyDer2KeyDecode},
{CRYPT_DECODER_IMPL_FREEOUTDATA, (CRYPT_DECODER_IMPL_FreeOutData)DECODER_DER2KEY_FreeOutData},
{CRYPT_DECODER_IMPL_FREECTX, (CRYPT_DECODER_IMPL_FreeCtx)DECODER_DER2KEY_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_RSA
const CRYPT_EAL_Func g_defEalRsaPubDer2Key[] = {
{CRYPT_DECODER_IMPL_NEWCTX, (CRYPT_DECODER_IMPL_NewCtx)DECODER_RsaDer2KeyNewCtx},
{CRYPT_DECODER_IMPL_GETPARAM, (CRYPT_DECODER_IMPL_GetParam)DECODER_DER2KEY_GetParam},
{CRYPT_DECODER_IMPL_SETPARAM, (CRYPT_DECODER_IMPL_SetParam)DECODER_DER2KEY_SetParam},
{CRYPT_DECODER_IMPL_DECODE, (CRYPT_DECODER_IMPL_Decode)DECODER_RsaPubKeyDer2KeyDecode},
{CRYPT_DECODER_IMPL_FREEOUTDATA, (CRYPT_DECODER_IMPL_FreeOutData)DECODER_DER2KEY_FreeOutData},
{CRYPT_DECODER_IMPL_FREECTX, (CRYPT_DECODER_IMPL_FreeCtx)DECODER_DER2KEY_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_ECDSA
const CRYPT_EAL_Func g_defEalEcdsaPrvDer2Key[] = {
{CRYPT_DECODER_IMPL_NEWCTX, (CRYPT_DECODER_IMPL_NewCtx)DECODER_EcdsaDer2KeyNewCtx},
{CRYPT_DECODER_IMPL_GETPARAM, (CRYPT_DECODER_IMPL_GetParam)DECODER_DER2KEY_GetParam},
{CRYPT_DECODER_IMPL_SETPARAM, (CRYPT_DECODER_IMPL_SetParam)DECODER_DER2KEY_SetParam},
{CRYPT_DECODER_IMPL_DECODE, (CRYPT_DECODER_IMPL_Decode)DECODER_EcdsaPrvKeyDer2KeyDecode},
{CRYPT_DECODER_IMPL_FREEOUTDATA, (CRYPT_DECODER_IMPL_FreeOutData)DECODER_DER2KEY_FreeOutData},
{CRYPT_DECODER_IMPL_FREECTX, (CRYPT_DECODER_IMPL_FreeCtx)DECODER_DER2KEY_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_SM2
const CRYPT_EAL_Func g_defEalSm2PrvDer2Key[] = {
{CRYPT_DECODER_IMPL_NEWCTX, (CRYPT_DECODER_IMPL_NewCtx)DECODER_Sm2Der2KeyNewCtx},
{CRYPT_DECODER_IMPL_GETPARAM, (CRYPT_DECODER_IMPL_GetParam)DECODER_DER2KEY_GetParam},
{CRYPT_DECODER_IMPL_SETPARAM, (CRYPT_DECODER_IMPL_SetParam)DECODER_DER2KEY_SetParam},
{CRYPT_DECODER_IMPL_DECODE, (CRYPT_DECODER_IMPL_Decode)DECODER_Sm2PrvKeyDer2KeyDecode},
{CRYPT_DECODER_IMPL_FREEOUTDATA, (CRYPT_DECODER_IMPL_FreeOutData)DECODER_DER2KEY_FreeOutData},
{CRYPT_DECODER_IMPL_FREECTX, (CRYPT_DECODER_IMPL_FreeCtx)DECODER_DER2KEY_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_RSA
const CRYPT_EAL_Func g_defEalP8Der2RsaKey[] = {
{CRYPT_DECODER_IMPL_NEWCTX, (CRYPT_DECODER_IMPL_NewCtx)DECODER_RsaDer2KeyNewCtx},
{CRYPT_DECODER_IMPL_GETPARAM, (CRYPT_DECODER_IMPL_GetParam)DECODER_DER2KEY_GetParam},
{CRYPT_DECODER_IMPL_SETPARAM, (CRYPT_DECODER_IMPL_SetParam)DECODER_DER2KEY_SetParam},
{CRYPT_DECODER_IMPL_DECODE, (CRYPT_DECODER_IMPL_Decode)DECODER_RsaPkcs8Der2KeyDecode},
{CRYPT_DECODER_IMPL_FREEOUTDATA, (CRYPT_DECODER_IMPL_FreeOutData)DECODER_DER2KEY_FreeOutData},
{CRYPT_DECODER_IMPL_FREECTX, (CRYPT_DECODER_IMPL_FreeCtx)DECODER_DER2KEY_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_ECDSA
const CRYPT_EAL_Func g_defEalP8Der2EcdsaKey[] = {
{CRYPT_DECODER_IMPL_NEWCTX, (CRYPT_DECODER_IMPL_NewCtx)DECODER_EcdsaDer2KeyNewCtx},
{CRYPT_DECODER_IMPL_GETPARAM, (CRYPT_DECODER_IMPL_GetParam)DECODER_DER2KEY_GetParam},
{CRYPT_DECODER_IMPL_SETPARAM, (CRYPT_DECODER_IMPL_SetParam)DECODER_DER2KEY_SetParam},
{CRYPT_DECODER_IMPL_DECODE, (CRYPT_DECODER_IMPL_Decode)DECODER_EcdsaPkcs8Der2KeyDecode},
{CRYPT_DECODER_IMPL_FREEOUTDATA, (CRYPT_DECODER_IMPL_FreeOutData)DECODER_DER2KEY_FreeOutData},
{CRYPT_DECODER_IMPL_FREECTX, (CRYPT_DECODER_IMPL_FreeCtx)DECODER_DER2KEY_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_SM2
const CRYPT_EAL_Func g_defEalP8Der2Sm2Key[] = {
{CRYPT_DECODER_IMPL_NEWCTX, (CRYPT_DECODER_IMPL_NewCtx)DECODER_Sm2Der2KeyNewCtx},
{CRYPT_DECODER_IMPL_GETPARAM, (CRYPT_DECODER_IMPL_GetParam)DECODER_DER2KEY_GetParam},
{CRYPT_DECODER_IMPL_SETPARAM, (CRYPT_DECODER_IMPL_SetParam)DECODER_DER2KEY_SetParam},
{CRYPT_DECODER_IMPL_DECODE, (CRYPT_DECODER_IMPL_Decode)DECODER_Sm2Pkcs8Der2KeyDecode},
{CRYPT_DECODER_IMPL_FREEOUTDATA, (CRYPT_DECODER_IMPL_FreeOutData)DECODER_DER2KEY_FreeOutData},
{CRYPT_DECODER_IMPL_FREECTX, (CRYPT_DECODER_IMPL_FreeCtx)DECODER_DER2KEY_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_ED25519
const CRYPT_EAL_Func g_defEalP8Der2Ed25519Key[] = {
{CRYPT_DECODER_IMPL_NEWCTX, (CRYPT_DECODER_IMPL_NewCtx)DECODER_Ed25519Der2KeyNewCtx},
{CRYPT_DECODER_IMPL_GETPARAM, (CRYPT_DECODER_IMPL_GetParam)DECODER_DER2KEY_GetParam},
{CRYPT_DECODER_IMPL_SETPARAM, (CRYPT_DECODER_IMPL_SetParam)DECODER_DER2KEY_SetParam},
{CRYPT_DECODER_IMPL_DECODE, (CRYPT_DECODER_IMPL_Decode)DECODER_Ed25519Pkcs8Der2KeyDecode},
{CRYPT_DECODER_IMPL_FREEOUTDATA, (CRYPT_DECODER_IMPL_FreeOutData)DECODER_DER2KEY_FreeOutData},
{CRYPT_DECODER_IMPL_FREECTX, (CRYPT_DECODER_IMPL_FreeCtx)DECODER_DER2KEY_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_RSA
const CRYPT_EAL_Func g_defEalSubPubKeyDer2RsaKey[] = {
{CRYPT_DECODER_IMPL_NEWCTX, (CRYPT_DECODER_IMPL_NewCtx)DECODER_RsaDer2KeyNewCtx},
{CRYPT_DECODER_IMPL_GETPARAM, (CRYPT_DECODER_IMPL_GetParam)DECODER_DER2KEY_GetParam},
{CRYPT_DECODER_IMPL_SETPARAM, (CRYPT_DECODER_IMPL_SetParam)DECODER_DER2KEY_SetParam},
{CRYPT_DECODER_IMPL_DECODE, (CRYPT_DECODER_IMPL_Decode)DECODER_RsaSubPubKeyDer2KeyDecode},
{CRYPT_DECODER_IMPL_FREEOUTDATA, (CRYPT_DECODER_IMPL_FreeOutData)DECODER_DER2KEY_FreeOutData},
{CRYPT_DECODER_IMPL_FREECTX, (CRYPT_DECODER_IMPL_FreeCtx)DECODER_DER2KEY_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_ECDSA
const CRYPT_EAL_Func g_defEalSubPubKeyDer2EcdsaKey[] = {
{CRYPT_DECODER_IMPL_NEWCTX, (CRYPT_DECODER_IMPL_NewCtx)DECODER_EcdsaDer2KeyNewCtx},
{CRYPT_DECODER_IMPL_GETPARAM, (CRYPT_DECODER_IMPL_GetParam)DECODER_DER2KEY_GetParam},
{CRYPT_DECODER_IMPL_SETPARAM, (CRYPT_DECODER_IMPL_SetParam)DECODER_DER2KEY_SetParam},
{CRYPT_DECODER_IMPL_DECODE, (CRYPT_DECODER_IMPL_Decode)DECODER_EcdsaSubPubKeyDer2KeyDecode},
{CRYPT_DECODER_IMPL_FREEOUTDATA, (CRYPT_DECODER_IMPL_FreeOutData)DECODER_DER2KEY_FreeOutData},
{CRYPT_DECODER_IMPL_FREECTX, (CRYPT_DECODER_IMPL_FreeCtx)DECODER_DER2KEY_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_SM2
const CRYPT_EAL_Func g_defEalSubPubKeyDer2Sm2Key[] = {
{CRYPT_DECODER_IMPL_NEWCTX, (CRYPT_DECODER_IMPL_NewCtx)DECODER_Sm2Der2KeyNewCtx},
{CRYPT_DECODER_IMPL_GETPARAM, (CRYPT_DECODER_IMPL_GetParam)DECODER_DER2KEY_GetParam},
{CRYPT_DECODER_IMPL_SETPARAM, (CRYPT_DECODER_IMPL_SetParam)DECODER_DER2KEY_SetParam},
{CRYPT_DECODER_IMPL_DECODE, (CRYPT_DECODER_IMPL_Decode)DECODER_Sm2SubPubKeyDer2KeyDecode},
{CRYPT_DECODER_IMPL_FREEOUTDATA, (CRYPT_DECODER_IMPL_FreeOutData)DECODER_DER2KEY_FreeOutData},
{CRYPT_DECODER_IMPL_FREECTX, (CRYPT_DECODER_IMPL_FreeCtx)DECODER_DER2KEY_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_ED25519
const CRYPT_EAL_Func g_defEalSubPubKeyDer2Ed25519Key[] = {
{CRYPT_DECODER_IMPL_NEWCTX, (CRYPT_DECODER_IMPL_NewCtx)DECODER_Ed25519Der2KeyNewCtx},
{CRYPT_DECODER_IMPL_GETPARAM, (CRYPT_DECODER_IMPL_GetParam)DECODER_DER2KEY_GetParam},
{CRYPT_DECODER_IMPL_SETPARAM, (CRYPT_DECODER_IMPL_SetParam)DECODER_DER2KEY_SetParam},
{CRYPT_DECODER_IMPL_DECODE, (CRYPT_DECODER_IMPL_Decode)DECODER_Ed25519SubPubKeyDer2KeyDecode},
{CRYPT_DECODER_IMPL_FREEOUTDATA, (CRYPT_DECODER_IMPL_FreeOutData)DECODER_DER2KEY_FreeOutData},
{CRYPT_DECODER_IMPL_FREECTX, (CRYPT_DECODER_IMPL_FreeCtx)DECODER_DER2KEY_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_RSA
const CRYPT_EAL_Func g_defEalSubPubKeyWithoutSeqDer2RsaKey[] = {
{CRYPT_DECODER_IMPL_NEWCTX, (CRYPT_DECODER_IMPL_NewCtx)DECODER_RsaDer2KeyNewCtx},
{CRYPT_DECODER_IMPL_GETPARAM, (CRYPT_DECODER_IMPL_GetParam)DECODER_DER2KEY_GetParam},
{CRYPT_DECODER_IMPL_SETPARAM, (CRYPT_DECODER_IMPL_SetParam)DECODER_DER2KEY_SetParam},
{CRYPT_DECODER_IMPL_DECODE, (CRYPT_DECODER_IMPL_Decode)DECODER_RsaSubPubKeyWithOutSeqDer2KeyDecode},
{CRYPT_DECODER_IMPL_FREEOUTDATA, (CRYPT_DECODER_IMPL_FreeOutData)DECODER_DER2KEY_FreeOutData},
{CRYPT_DECODER_IMPL_FREECTX, (CRYPT_DECODER_IMPL_FreeCtx)DECODER_DER2KEY_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_ECDSA
const CRYPT_EAL_Func g_defEalSubPubKeyWithoutSeqDer2EcdsaKey[] = {
{CRYPT_DECODER_IMPL_NEWCTX, (CRYPT_DECODER_IMPL_NewCtx)DECODER_EcdsaDer2KeyNewCtx},
{CRYPT_DECODER_IMPL_GETPARAM, (CRYPT_DECODER_IMPL_GetParam)DECODER_DER2KEY_GetParam},
{CRYPT_DECODER_IMPL_SETPARAM, (CRYPT_DECODER_IMPL_SetParam)DECODER_DER2KEY_SetParam},
{CRYPT_DECODER_IMPL_DECODE, (CRYPT_DECODER_IMPL_Decode)DECODER_EcdsaSubPubKeyWithOutSeqDer2KeyDecode},
{CRYPT_DECODER_IMPL_FREEOUTDATA, (CRYPT_DECODER_IMPL_FreeOutData)DECODER_DER2KEY_FreeOutData},
{CRYPT_DECODER_IMPL_FREECTX, (CRYPT_DECODER_IMPL_FreeCtx)DECODER_DER2KEY_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_SM2
const CRYPT_EAL_Func g_defEalSubPubKeyWithoutSeqDer2Sm2Key[] = {
{CRYPT_DECODER_IMPL_NEWCTX, (CRYPT_DECODER_IMPL_NewCtx)DECODER_Sm2Der2KeyNewCtx},
{CRYPT_DECODER_IMPL_GETPARAM, (CRYPT_DECODER_IMPL_GetParam)DECODER_DER2KEY_GetParam},
{CRYPT_DECODER_IMPL_SETPARAM, (CRYPT_DECODER_IMPL_SetParam)DECODER_DER2KEY_SetParam},
{CRYPT_DECODER_IMPL_DECODE, (CRYPT_DECODER_IMPL_Decode)DECODER_Sm2SubPubKeyWithOutSeqDer2KeyDecode},
{CRYPT_DECODER_IMPL_FREEOUTDATA, (CRYPT_DECODER_IMPL_FreeOutData)DECODER_DER2KEY_FreeOutData},
{CRYPT_DECODER_IMPL_FREECTX, (CRYPT_DECODER_IMPL_FreeCtx)DECODER_DER2KEY_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_ED25519
const CRYPT_EAL_Func g_defEalSubPubKeyWithoutSeqDer2Ed25519Key[] = {
{CRYPT_DECODER_IMPL_NEWCTX, (CRYPT_DECODER_IMPL_NewCtx)DECODER_Ed25519Der2KeyNewCtx},
{CRYPT_DECODER_IMPL_GETPARAM, (CRYPT_DECODER_IMPL_GetParam)DECODER_DER2KEY_GetParam},
{CRYPT_DECODER_IMPL_SETPARAM, (CRYPT_DECODER_IMPL_SetParam)DECODER_DER2KEY_SetParam},
{CRYPT_DECODER_IMPL_DECODE, (CRYPT_DECODER_IMPL_Decode)DECODER_Ed25519SubPubKeyWithOutSeqDer2KeyDecode},
{CRYPT_DECODER_IMPL_FREEOUTDATA, (CRYPT_DECODER_IMPL_FreeOutData)DECODER_DER2KEY_FreeOutData},
{CRYPT_DECODER_IMPL_FREECTX, (CRYPT_DECODER_IMPL_FreeCtx)DECODER_DER2KEY_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
const CRYPT_EAL_Func g_defEalLowKeyObject2PkeyObject[] = {
{CRYPT_DECODER_IMPL_NEWCTX, (CRYPT_DECODER_IMPL_NewCtx)DECODER_LowKeyObject2PkeyObjectNewCtx},
{CRYPT_DECODER_IMPL_GETPARAM, (CRYPT_DECODER_IMPL_GetParam)DECODER_LowKeyObject2PkeyObjectGetParam},
{CRYPT_DECODER_IMPL_SETPARAM, (CRYPT_DECODER_IMPL_SetParam)DECODER_LowKeyObject2PkeyObjectSetParam},
{CRYPT_DECODER_IMPL_DECODE, (CRYPT_DECODER_IMPL_Decode)DECODER_LowKeyObject2PkeyObjectDecode},
{CRYPT_DECODER_IMPL_FREEOUTDATA, (CRYPT_DECODER_IMPL_FreeOutData)DECODER_LowKeyObject2PkeyObjectFreeOutData},
{CRYPT_DECODER_IMPL_FREECTX, (CRYPT_DECODER_IMPL_FreeCtx)DECODER_LowKeyObject2PkeyObjectFreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif /* HITLS_CRYPTO_CODECSKEY && HITLS_CRYPTO_PROVIDER */
| 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/default/crypt_default_decode.c | C | unknown | 13,446 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_KDF) && defined(HITLS_CRYPTO_PROVIDER)
#include "crypt_eal_implprovider.h"
#include "crypt_pbkdf2.h"
#include "crypt_kdf_tls12.h"
#include "crypt_hkdf.h"
#include "crypt_scrypt.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "bsl_log_internal.h"
#include "bsl_err_internal.h"
#include "crypt_default_provider.h"
void *CRYPT_EAL_DefKdfNewCtx(CRYPT_EAL_DefProvCtx *provCtx, int32_t algId)
{
void *libCtx = provCtx == NULL ? NULL : provCtx->libCtx;
switch (algId) {
#ifdef HITLS_CRYPTO_SCRYPT
case CRYPT_KDF_SCRYPT:
return CRYPT_SCRYPT_NewCtxEx(libCtx);
#endif
#ifdef HITLS_CRYPTO_PBKDF2
case CRYPT_KDF_PBKDF2:
return CRYPT_PBKDF2_NewCtxEx(libCtx);
#endif
#ifdef HITLS_CRYPTO_KDFTLS12
case CRYPT_KDF_KDFTLS12:
return CRYPT_KDFTLS12_NewCtxEx(libCtx);
#endif
#ifdef HITLS_CRYPTO_HKDF
case CRYPT_KDF_HKDF:
return CRYPT_HKDF_NewCtxEx(libCtx);
#endif
default:
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_NOT_SUPPORT);
return NULL;
}
}
#ifdef HITLS_CRYPTO_SCRYPT
const CRYPT_EAL_Func g_defEalKdfScrypt[] = {
{CRYPT_EAL_IMPLKDF_NEWCTX, (CRYPT_EAL_ImplKdfNewCtx)CRYPT_EAL_DefKdfNewCtx},
{CRYPT_EAL_IMPLKDF_SETPARAM, (CRYPT_EAL_ImplKdfSetParam)CRYPT_SCRYPT_SetParam},
{CRYPT_EAL_IMPLKDF_DERIVE, (CRYPT_EAL_ImplKdfDerive)CRYPT_SCRYPT_Derive},
{CRYPT_EAL_IMPLKDF_DEINITCTX, (CRYPT_EAL_ImplKdfDeInitCtx)CRYPT_SCRYPT_Deinit},
{CRYPT_EAL_IMPLKDF_FREECTX, (CRYPT_EAL_ImplKdfFreeCtx)CRYPT_SCRYPT_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_PBKDF2
const CRYPT_EAL_Func g_defEalKdfPBKdf2[] = {
{CRYPT_EAL_IMPLKDF_NEWCTX, (CRYPT_EAL_ImplKdfNewCtx)CRYPT_EAL_DefKdfNewCtx},
{CRYPT_EAL_IMPLKDF_SETPARAM, (CRYPT_EAL_ImplKdfSetParam)CRYPT_PBKDF2_SetParam},
{CRYPT_EAL_IMPLKDF_DERIVE, (CRYPT_EAL_ImplKdfDerive)CRYPT_PBKDF2_Derive},
{CRYPT_EAL_IMPLKDF_DEINITCTX, (CRYPT_EAL_ImplKdfDeInitCtx)CRYPT_PBKDF2_Deinit},
{CRYPT_EAL_IMPLKDF_FREECTX, (CRYPT_EAL_ImplKdfFreeCtx)CRYPT_PBKDF2_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_KDFTLS12
const CRYPT_EAL_Func g_defEalKdfKdfTLS12[] = {
{CRYPT_EAL_IMPLKDF_NEWCTX, (CRYPT_EAL_ImplKdfNewCtx)CRYPT_EAL_DefKdfNewCtx},
{CRYPT_EAL_IMPLKDF_SETPARAM, (CRYPT_EAL_ImplKdfSetParam)CRYPT_KDFTLS12_SetParam},
{CRYPT_EAL_IMPLKDF_DERIVE, (CRYPT_EAL_ImplKdfDerive)CRYPT_KDFTLS12_Derive},
{CRYPT_EAL_IMPLKDF_DEINITCTX, (CRYPT_EAL_ImplKdfDeInitCtx)CRYPT_KDFTLS12_Deinit},
{CRYPT_EAL_IMPLKDF_FREECTX, (CRYPT_EAL_ImplKdfFreeCtx)CRYPT_KDFTLS12_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_HKDF
const CRYPT_EAL_Func g_defEalKdfHkdf[] = {
{CRYPT_EAL_IMPLKDF_NEWCTX, (CRYPT_EAL_ImplKdfNewCtx)CRYPT_EAL_DefKdfNewCtx},
{CRYPT_EAL_IMPLKDF_SETPARAM, (CRYPT_EAL_ImplKdfSetParam)CRYPT_HKDF_SetParam},
{CRYPT_EAL_IMPLKDF_DERIVE, (CRYPT_EAL_ImplKdfDerive)CRYPT_HKDF_Derive},
{CRYPT_EAL_IMPLKDF_DEINITCTX, (CRYPT_EAL_ImplKdfDeInitCtx)CRYPT_HKDF_Deinit},
{CRYPT_EAL_IMPLKDF_FREECTX, (CRYPT_EAL_ImplKdfFreeCtx)CRYPT_HKDF_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#endif /* HITLS_CRYPTO_KDF && HITLS_CRYPTO_PROVIDER */ | 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/default/crypt_default_kdf.c | C | unknown | 3,764 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#if (defined(HITLS_CRYPTO_MLKEM) || defined(HITLS_CRYPTO_HYBRIDKEM)) && defined(HITLS_CRYPTO_PROVIDER)
#include "crypt_eal_implprovider.h"
#ifdef HITLS_CRYPTO_MLKEM
#include "crypt_mlkem.h"
#endif
#ifdef HITLS_CRYPTO_HYBRIDKEM
#include "crypt_hybridkem.h"
#endif
#ifdef HITLS_CRYPTO_MLKEM
const CRYPT_EAL_Func g_defEalMlKem[] = {
{CRYPT_EAL_IMPLPKEYKEM_ENCAPSULATE, (CRYPT_EAL_ImplPkeyKemEncapsulate)CRYPT_ML_KEM_Encaps},
{CRYPT_EAL_IMPLPKEYKEM_DECAPSULATE, (CRYPT_EAL_ImplPkeyKemDecapsulate)CRYPT_ML_KEM_Decaps},
CRYPT_EAL_FUNC_END
};
#endif
#ifdef HITLS_CRYPTO_HYBRIDKEM
const CRYPT_EAL_Func g_defEalHybridKeyKem[] = {
{CRYPT_EAL_IMPLPKEYKEM_ENCAPSULATE, (CRYPT_EAL_ImplPkeyKemEncapsulate)CRYPT_HYBRID_KEM_Encaps},
{CRYPT_EAL_IMPLPKEYKEM_DECAPSULATE, (CRYPT_EAL_ImplPkeyKemDecapsulate)CRYPT_HYBRID_KEM_Decaps},
CRYPT_EAL_FUNC_END
};
#endif
#endif // HITLS_CRYPTO_PROVIDER
| 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/default/crypt_default_kem.c | C | unknown | 1,470 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#if (defined(HITLS_CRYPTO_X25519) || defined(HITLS_CRYPTO_DH) || defined(HITLS_CRYPTO_ECDH) || \
defined(HITLS_CRYPTO_SM2_EXCH)) && defined(HITLS_CRYPTO_PROVIDER)
#include "crypt_eal_implprovider.h"
#include "crypt_curve25519.h"
#include "crypt_dh.h"
#include "crypt_ecdh.h"
#include "crypt_sm2.h"
typedef struct {
void *pkeyCtx;
int32_t algId;
int32_t index;
} CRYPT_EAL_DefPkeyCtx;
#ifdef HITLS_CRYPTO_X25519
const CRYPT_EAL_Func g_defEalExchX25519[] = {
{CRYPT_EAL_IMPLPKEYEXCH_EXCH, (CRYPT_EAL_ImplPkeyExch)CRYPT_CURVE25519_ComputeSharedKey},
CRYPT_EAL_FUNC_END
};
#endif
#ifdef HITLS_CRYPTO_DH
const CRYPT_EAL_Func g_defEalExchDh[] = {
{CRYPT_EAL_IMPLPKEYEXCH_EXCH, (CRYPT_EAL_ImplPkeyExch)CRYPT_DH_ComputeShareKey},
CRYPT_EAL_FUNC_END
};
#endif
#ifdef HITLS_CRYPTO_ECDH
const CRYPT_EAL_Func g_defEalExchEcdh[] = {
{CRYPT_EAL_IMPLPKEYEXCH_EXCH, (CRYPT_EAL_ImplPkeyExch)CRYPT_ECDH_ComputeShareKey},
CRYPT_EAL_FUNC_END
};
#endif
#ifdef HITLS_CRYPTO_SM2_EXCH
const CRYPT_EAL_Func g_defEalExchSm2[] = {
{CRYPT_EAL_IMPLPKEYEXCH_EXCH, (CRYPT_EAL_ImplPkeyExch)CRYPT_SM2_KapComputeKey},
CRYPT_EAL_FUNC_END
};
#endif
#endif | 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/default/crypt_default_keyexch.c | C | unknown | 1,743 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_PKEY) && defined(HITLS_CRYPTO_PROVIDER)
#include "crypt_eal_implprovider.h"
#ifdef HITLS_CRYPTO_DSA
#include "crypt_dsa.h"
#endif
#ifdef HITLS_CRYPTO_CURVE25519
#include "crypt_curve25519.h"
#endif
#ifdef HITLS_CRYPTO_RSA
#include "crypt_rsa.h"
#endif
#ifdef HITLS_CRYPTO_DH
#include "crypt_dh.h"
#endif
#ifdef HITLS_CRYPTO_ECDSA
#include "crypt_ecdsa.h"
#endif
#ifdef HITLS_CRYPTO_ECDH
#include "crypt_ecdh.h"
#endif
#ifdef HITLS_CRYPTO_SM2
#include "crypt_sm2.h"
#endif
#ifdef HITLS_CRYPTO_PAILLIER
#include "crypt_paillier.h"
#endif
#ifdef HITLS_CRYPTO_ELGAMAL
#include "crypt_elgamal.h"
#endif
#ifdef HITLS_CRYPTO_SLH_DSA
#include "crypt_slh_dsa.h"
#endif
#ifdef HITLS_CRYPTO_MLKEM
#include "crypt_mlkem.h"
#endif
#ifdef HITLS_CRYPTO_MLDSA
#include "crypt_mldsa.h"
#endif
#ifdef HITLS_CRYPTO_HYBRIDKEM
#include "crypt_hybridkem.h"
#endif
#include "crypt_errno.h"
#include "bsl_log_internal.h"
#include "bsl_err_internal.h"
#include "crypt_ealinit.h"
#include "crypt_default_provider.h"
void *CRYPT_EAL_DefPkeyMgmtNewCtx(CRYPT_EAL_DefProvCtx *provCtx, int32_t algId)
{
(void)provCtx;
void *pkeyCtx = NULL;
#ifdef HITLS_CRYPTO_ASM_CHECK
if (CRYPT_ASMCAP_Pkey(algId) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_ASM_NOT_SUPPORT);
return NULL;
}
#endif
switch (algId) {
#ifdef HITLS_CRYPTO_DSA
case CRYPT_PKEY_DSA:
return CRYPT_DSA_NewCtxEx(provCtx->libCtx);
break;
#endif
#ifdef HITLS_CRYPTO_ED25519
case CRYPT_PKEY_ED25519:
pkeyCtx = CRYPT_ED25519_NewCtxEx(provCtx->libCtx);
break;
#endif
#ifdef HITLS_CRYPTO_X25519
case CRYPT_PKEY_X25519:
pkeyCtx = CRYPT_X25519_NewCtxEx(provCtx->libCtx);
break;
#endif
#ifdef HITLS_CRYPTO_RSA
case CRYPT_PKEY_RSA:
pkeyCtx = CRYPT_RSA_NewCtxEx(provCtx->libCtx);
break;
#endif
#ifdef HITLS_CRYPTO_DH
case CRYPT_PKEY_DH:
pkeyCtx = CRYPT_DH_NewCtxEx(provCtx->libCtx);
break;
#endif
#ifdef HITLS_CRYPTO_ECDSA
case CRYPT_PKEY_ECDSA:
pkeyCtx = CRYPT_ECDSA_NewCtxEx(provCtx->libCtx);
break;
#endif
#ifdef HITLS_CRYPTO_ECDH
case CRYPT_PKEY_ECDH:
pkeyCtx = CRYPT_ECDH_NewCtxEx(provCtx->libCtx);
break;
#endif
#ifdef HITLS_CRYPTO_SM2
case CRYPT_PKEY_SM2:
pkeyCtx = CRYPT_SM2_NewCtxEx(provCtx->libCtx);
break;
#endif
#ifdef HITLS_CRYPTO_PAILLIER
case CRYPT_PKEY_PAILLIER:
pkeyCtx = CRYPT_PAILLIER_NewCtxEx(provCtx->libCtx);
break;
#endif
#ifdef HITLS_CRYPTO_ELGAMAL
case CRYPT_PKEY_ELGAMAL:
pkeyCtx = CRYPT_ELGAMAL_NewCtxEx(provCtx->libCtx);
break;
#endif
#ifdef HITLS_CRYPTO_SLH_DSA
case CRYPT_PKEY_SLH_DSA:
pkeyCtx = CRYPT_SLH_DSA_NewCtxEx(provCtx->libCtx);
break;
#endif
#ifdef HITLS_CRYPTO_MLKEM
case CRYPT_PKEY_ML_KEM:
pkeyCtx = CRYPT_ML_KEM_NewCtxEx(provCtx->libCtx);
break;
#endif
#ifdef HITLS_CRYPTO_MLDSA
case CRYPT_PKEY_ML_DSA:
pkeyCtx = CRYPT_ML_DSA_NewCtxEx(provCtx->libCtx);
break;
#endif
#ifdef HITLS_CRYPTO_HYBRIDKEM
case CRYPT_PKEY_HYBRID_KEM:
pkeyCtx = CRYPT_HYBRID_KEM_NewCtx();
break;
#endif
default:
pkeyCtx = NULL;
}
if (pkeyCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_NOT_SUPPORT);
return NULL;
}
return pkeyCtx;
};
#ifdef HITLS_CRYPTO_DSA
const CRYPT_EAL_Func g_defEalKeyMgmtDsa[] = {
{CRYPT_EAL_IMPLPKEYMGMT_NEWCTX, (CRYPT_EAL_ImplPkeyMgmtNewCtx)CRYPT_EAL_DefPkeyMgmtNewCtx},
{CRYPT_EAL_IMPLPKEYMGMT_SETPARAM, (CRYPT_EAL_ImplPkeyMgmtSetParam)CRYPT_DSA_SetParaEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPARAM, (CRYPT_EAL_ImplPkeyMgmtGetParam)CRYPT_DSA_GetParaEx},
{CRYPT_EAL_IMPLPKEYMGMT_GENKEY, (CRYPT_EAL_ImplPkeyMgmtGenKey)CRYPT_DSA_Gen},
{CRYPT_EAL_IMPLPKEYMGMT_SETPRV, (CRYPT_EAL_ImplPkeyMgmtSetPrv)CRYPT_DSA_SetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_SETPUB, (CRYPT_EAL_ImplPkeyMgmtSetPub)CRYPT_DSA_SetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPRV, (CRYPT_EAL_ImplPkeyMgmtGetPrv)CRYPT_DSA_GetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPUB, (CRYPT_EAL_ImplPkeyMgmtGetPub)CRYPT_DSA_GetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_DUPCTX, (CRYPT_EAL_ImplPkeyMgmtDupCtx)CRYPT_DSA_DupCtx},
#ifdef HITLS_CRYPTO_DSA_CHECK
{CRYPT_EAL_IMPLPKEYMGMT_CHECK, (CRYPT_EAL_ImplPkeyMgmtCheck)CRYPT_DSA_Check},
#endif
{CRYPT_EAL_IMPLPKEYMGMT_COMPARE, (CRYPT_EAL_ImplPkeyMgmtCompare)CRYPT_DSA_Cmp},
{CRYPT_EAL_IMPLPKEYMGMT_CTRL, (CRYPT_EAL_ImplPkeyMgmtCtrl)CRYPT_DSA_Ctrl},
{CRYPT_EAL_IMPLPKEYMGMT_FREECTX, (CRYPT_EAL_ImplPkeyMgmtFreeCtx)CRYPT_DSA_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_ED25519
const CRYPT_EAL_Func g_defEalKeyMgmtEd25519[] = {
{CRYPT_EAL_IMPLPKEYMGMT_NEWCTX, (CRYPT_EAL_ImplPkeyMgmtNewCtx)CRYPT_EAL_DefPkeyMgmtNewCtx},
{CRYPT_EAL_IMPLPKEYMGMT_GENKEY, (CRYPT_EAL_ImplPkeyMgmtGenKey)CRYPT_ED25519_GenKey},
{CRYPT_EAL_IMPLPKEYMGMT_SETPRV, (CRYPT_EAL_ImplPkeyMgmtSetPrv)CRYPT_CURVE25519_SetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_SETPUB, (CRYPT_EAL_ImplPkeyMgmtSetPub)CRYPT_CURVE25519_SetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPRV, (CRYPT_EAL_ImplPkeyMgmtGetPrv)CRYPT_CURVE25519_GetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPUB, (CRYPT_EAL_ImplPkeyMgmtGetPub)CRYPT_CURVE25519_GetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_DUPCTX, (CRYPT_EAL_ImplPkeyMgmtDupCtx)CRYPT_CURVE25519_DupCtx},
#ifdef HITLS_CRYPTO_ED25519_CHECK
{CRYPT_EAL_IMPLPKEYMGMT_CHECK, (CRYPT_EAL_ImplPkeyMgmtCheck)CRYPT_ED25519_Check},
#endif
{CRYPT_EAL_IMPLPKEYMGMT_COMPARE, (CRYPT_EAL_ImplPkeyMgmtCompare)CRYPT_CURVE25519_Cmp},
{CRYPT_EAL_IMPLPKEYMGMT_CTRL, (CRYPT_EAL_ImplPkeyMgmtCtrl)CRYPT_CURVE25519_Ctrl},
{CRYPT_EAL_IMPLPKEYMGMT_FREECTX, (CRYPT_EAL_ImplPkeyMgmtFreeCtx)CRYPT_CURVE25519_FreeCtx},
{CRYPT_EAL_IMPLPKEYMGMT_IMPORT, (CRYPT_EAL_ImplPkeyMgmtImport)CRYPT_CURVE25519_Import},
{CRYPT_EAL_IMPLPKEYMGMT_EXPORT, (CRYPT_EAL_ImplPkeyMgmtExport)CRYPT_CURVE25519_Export},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_X25519
const CRYPT_EAL_Func g_defEalKeyMgmtX25519[] = {
{CRYPT_EAL_IMPLPKEYMGMT_NEWCTX, (CRYPT_EAL_ImplPkeyMgmtNewCtx)CRYPT_EAL_DefPkeyMgmtNewCtx},
{CRYPT_EAL_IMPLPKEYMGMT_GENKEY, (CRYPT_EAL_ImplPkeyMgmtGenKey)CRYPT_X25519_GenKey},
{CRYPT_EAL_IMPLPKEYMGMT_SETPRV, (CRYPT_EAL_ImplPkeyMgmtSetPrv)CRYPT_CURVE25519_SetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_SETPUB, (CRYPT_EAL_ImplPkeyMgmtSetPub)CRYPT_CURVE25519_SetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPRV, (CRYPT_EAL_ImplPkeyMgmtGetPrv)CRYPT_CURVE25519_GetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPUB, (CRYPT_EAL_ImplPkeyMgmtGetPub)CRYPT_CURVE25519_GetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_DUPCTX, (CRYPT_EAL_ImplPkeyMgmtDupCtx)CRYPT_CURVE25519_DupCtx},
#ifdef HITLS_CRYPTO_X25519_CHECK
{CRYPT_EAL_IMPLPKEYMGMT_CHECK, (CRYPT_EAL_ImplPkeyMgmtCheck)CRYPT_X25519_Check},
#endif
{CRYPT_EAL_IMPLPKEYMGMT_COMPARE, (CRYPT_EAL_ImplPkeyMgmtCompare)CRYPT_CURVE25519_Cmp},
{CRYPT_EAL_IMPLPKEYMGMT_CTRL, (CRYPT_EAL_ImplPkeyMgmtCtrl)CRYPT_CURVE25519_Ctrl},
{CRYPT_EAL_IMPLPKEYMGMT_FREECTX, (CRYPT_EAL_ImplPkeyMgmtFreeCtx)CRYPT_CURVE25519_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_RSA
const CRYPT_EAL_Func g_defEalKeyMgmtRsa[] = {
{CRYPT_EAL_IMPLPKEYMGMT_NEWCTX, (CRYPT_EAL_ImplPkeyMgmtNewCtx)CRYPT_EAL_DefPkeyMgmtNewCtx},
{CRYPT_EAL_IMPLPKEYMGMT_SETPARAM, (CRYPT_EAL_ImplPkeyMgmtSetParam)CRYPT_RSA_SetParaEx},
{CRYPT_EAL_IMPLPKEYMGMT_GENKEY, (CRYPT_EAL_ImplPkeyMgmtGenKey)CRYPT_RSA_Gen},
{CRYPT_EAL_IMPLPKEYMGMT_SETPRV, (CRYPT_EAL_ImplPkeyMgmtSetPrv)CRYPT_RSA_SetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_SETPUB, (CRYPT_EAL_ImplPkeyMgmtSetPub)CRYPT_RSA_SetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPRV, (CRYPT_EAL_ImplPkeyMgmtGetPrv)CRYPT_RSA_GetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPUB, (CRYPT_EAL_ImplPkeyMgmtGetPub)CRYPT_RSA_GetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_DUPCTX, (CRYPT_EAL_ImplPkeyMgmtDupCtx)CRYPT_RSA_DupCtx},
#ifdef HITLS_CRYPTO_RSA_CHECK
{CRYPT_EAL_IMPLPKEYMGMT_CHECK, (CRYPT_EAL_ImplPkeyMgmtCheck)CRYPT_RSA_Check},
#endif
{CRYPT_EAL_IMPLPKEYMGMT_COMPARE, (CRYPT_EAL_ImplPkeyMgmtCompare)CRYPT_RSA_Cmp},
{CRYPT_EAL_IMPLPKEYMGMT_CTRL, (CRYPT_EAL_ImplPkeyMgmtCtrl)CRYPT_RSA_Ctrl},
{CRYPT_EAL_IMPLPKEYMGMT_FREECTX, (CRYPT_EAL_ImplPkeyMgmtFreeCtx)CRYPT_RSA_FreeCtx},
{CRYPT_EAL_IMPLPKEYMGMT_IMPORT, (CRYPT_EAL_ImplPkeyMgmtImport)CRYPT_RSA_Import},
{CRYPT_EAL_IMPLPKEYMGMT_EXPORT, (CRYPT_EAL_ImplPkeyMgmtExport)CRYPT_RSA_Export},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_DH
const CRYPT_EAL_Func g_defEalKeyMgmtDh[] = {
{CRYPT_EAL_IMPLPKEYMGMT_NEWCTX, (CRYPT_EAL_ImplPkeyMgmtNewCtx)CRYPT_EAL_DefPkeyMgmtNewCtx},
{CRYPT_EAL_IMPLPKEYMGMT_SETPARAM, (CRYPT_EAL_ImplPkeyMgmtSetParam)CRYPT_DH_SetParaEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPARAM, (CRYPT_EAL_ImplPkeyMgmtGetParam)CRYPT_DH_GetParaEx},
{CRYPT_EAL_IMPLPKEYMGMT_GENKEY, (CRYPT_EAL_ImplPkeyMgmtGenKey)CRYPT_DH_Gen},
{CRYPT_EAL_IMPLPKEYMGMT_SETPRV, (CRYPT_EAL_ImplPkeyMgmtSetPrv)CRYPT_DH_SetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_SETPUB, (CRYPT_EAL_ImplPkeyMgmtSetPub)CRYPT_DH_SetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPRV, (CRYPT_EAL_ImplPkeyMgmtGetPrv)CRYPT_DH_GetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPUB, (CRYPT_EAL_ImplPkeyMgmtGetPub)CRYPT_DH_GetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_DUPCTX, (CRYPT_EAL_ImplPkeyMgmtDupCtx)CRYPT_DH_DupCtx},
#ifdef HITLS_CRYPTO_DH_CHECK
{CRYPT_EAL_IMPLPKEYMGMT_CHECK, (CRYPT_EAL_ImplPkeyMgmtCheck)CRYPT_DH_Check},
#endif
{CRYPT_EAL_IMPLPKEYMGMT_COMPARE, (CRYPT_EAL_ImplPkeyMgmtCompare)CRYPT_DH_Cmp},
{CRYPT_EAL_IMPLPKEYMGMT_CTRL, (CRYPT_EAL_ImplPkeyMgmtCtrl)CRYPT_DH_Ctrl},
{CRYPT_EAL_IMPLPKEYMGMT_FREECTX, (CRYPT_EAL_ImplPkeyMgmtFreeCtx)CRYPT_DH_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_ECDSA
const CRYPT_EAL_Func g_defEalKeyMgmtEcdsa[] = {
{CRYPT_EAL_IMPLPKEYMGMT_NEWCTX, (CRYPT_EAL_ImplPkeyMgmtNewCtx)CRYPT_EAL_DefPkeyMgmtNewCtx},
{CRYPT_EAL_IMPLPKEYMGMT_SETPARAM, (CRYPT_EAL_ImplPkeyMgmtSetParam)CRYPT_ECDSA_SetParaEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPARAM, (CRYPT_EAL_ImplPkeyMgmtGetParam)CRYPT_ECDSA_GetParaEx},
{CRYPT_EAL_IMPLPKEYMGMT_GENKEY, (CRYPT_EAL_ImplPkeyMgmtGenKey)CRYPT_ECDSA_Gen},
{CRYPT_EAL_IMPLPKEYMGMT_SETPRV, (CRYPT_EAL_ImplPkeyMgmtSetPrv)CRYPT_ECDSA_SetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_SETPUB, (CRYPT_EAL_ImplPkeyMgmtSetPub)CRYPT_ECDSA_SetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPRV, (CRYPT_EAL_ImplPkeyMgmtGetPrv)CRYPT_ECDSA_GetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPUB, (CRYPT_EAL_ImplPkeyMgmtGetPub)CRYPT_ECDSA_GetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_DUPCTX, (CRYPT_EAL_ImplPkeyMgmtDupCtx)CRYPT_ECDSA_DupCtx},
#ifdef HITLS_CRYPTO_ECDSA_CHECK
{CRYPT_EAL_IMPLPKEYMGMT_CHECK, (CRYPT_EAL_ImplPkeyMgmtCheck)CRYPT_ECDSA_Check},
#endif
{CRYPT_EAL_IMPLPKEYMGMT_COMPARE, (CRYPT_EAL_ImplPkeyMgmtCompare)CRYPT_ECDSA_Cmp},
{CRYPT_EAL_IMPLPKEYMGMT_CTRL, (CRYPT_EAL_ImplPkeyMgmtCtrl)CRYPT_ECDSA_Ctrl},
{CRYPT_EAL_IMPLPKEYMGMT_FREECTX, (CRYPT_EAL_ImplPkeyMgmtFreeCtx)CRYPT_ECDSA_FreeCtx},
{CRYPT_EAL_IMPLPKEYMGMT_IMPORT, (CRYPT_EAL_ImplPkeyMgmtImport)CRYPT_ECDSA_Import},
{CRYPT_EAL_IMPLPKEYMGMT_EXPORT, (CRYPT_EAL_ImplPkeyMgmtExport)CRYPT_ECDSA_Export},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_ECDH
const CRYPT_EAL_Func g_defEalKeyMgmtEcdh[] = {
{CRYPT_EAL_IMPLPKEYMGMT_NEWCTX, (CRYPT_EAL_ImplPkeyMgmtNewCtx)CRYPT_EAL_DefPkeyMgmtNewCtx},
{CRYPT_EAL_IMPLPKEYMGMT_SETPARAM, (CRYPT_EAL_ImplPkeyMgmtSetParam)CRYPT_ECDH_SetParaEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPARAM, (CRYPT_EAL_ImplPkeyMgmtGetParam)CRYPT_ECDH_GetParaEx},
{CRYPT_EAL_IMPLPKEYMGMT_GENKEY, (CRYPT_EAL_ImplPkeyMgmtGenKey)CRYPT_ECDH_Gen},
{CRYPT_EAL_IMPLPKEYMGMT_SETPRV, (CRYPT_EAL_ImplPkeyMgmtSetPrv)CRYPT_ECDH_SetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_SETPUB, (CRYPT_EAL_ImplPkeyMgmtSetPub)CRYPT_ECDH_SetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPRV, (CRYPT_EAL_ImplPkeyMgmtGetPrv)CRYPT_ECDH_GetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPUB, (CRYPT_EAL_ImplPkeyMgmtGetPub)CRYPT_ECDH_GetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_DUPCTX, (CRYPT_EAL_ImplPkeyMgmtDupCtx)CRYPT_ECDH_DupCtx},
#ifdef HITLS_CRYPTO_ECDH_CHECK
{CRYPT_EAL_IMPLPKEYMGMT_CHECK, (CRYPT_EAL_ImplPkeyMgmtCheck)CRYPT_ECDH_Check},
#endif
{CRYPT_EAL_IMPLPKEYMGMT_COMPARE, (CRYPT_EAL_ImplPkeyMgmtCompare)CRYPT_ECDH_Cmp},
{CRYPT_EAL_IMPLPKEYMGMT_CTRL, (CRYPT_EAL_ImplPkeyMgmtCtrl)CRYPT_ECDH_Ctrl},
{CRYPT_EAL_IMPLPKEYMGMT_FREECTX, (CRYPT_EAL_ImplPkeyMgmtFreeCtx)CRYPT_ECDH_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_SM2
const CRYPT_EAL_Func g_defEalKeyMgmtSm2[] = {
{CRYPT_EAL_IMPLPKEYMGMT_NEWCTX, (CRYPT_EAL_ImplPkeyMgmtNewCtx)CRYPT_EAL_DefPkeyMgmtNewCtx},
{CRYPT_EAL_IMPLPKEYMGMT_GENKEY, (CRYPT_EAL_ImplPkeyMgmtGenKey)CRYPT_SM2_Gen},
{CRYPT_EAL_IMPLPKEYMGMT_SETPRV, (CRYPT_EAL_ImplPkeyMgmtSetPrv)CRYPT_SM2_SetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_SETPUB, (CRYPT_EAL_ImplPkeyMgmtSetPub)CRYPT_SM2_SetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPRV, (CRYPT_EAL_ImplPkeyMgmtGetPrv)CRYPT_SM2_GetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPUB, (CRYPT_EAL_ImplPkeyMgmtGetPub)CRYPT_SM2_GetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_DUPCTX, (CRYPT_EAL_ImplPkeyMgmtDupCtx)CRYPT_SM2_DupCtx},
#ifdef HITLS_CRYPTO_SM2_CHECK
{CRYPT_EAL_IMPLPKEYMGMT_CHECK, (CRYPT_EAL_ImplPkeyMgmtCheck)CRYPT_SM2_Check},
#endif
{CRYPT_EAL_IMPLPKEYMGMT_COMPARE, (CRYPT_EAL_ImplPkeyMgmtCompare)CRYPT_SM2_Cmp},
{CRYPT_EAL_IMPLPKEYMGMT_CTRL, (CRYPT_EAL_ImplPkeyMgmtCtrl)CRYPT_SM2_Ctrl},
{CRYPT_EAL_IMPLPKEYMGMT_FREECTX, (CRYPT_EAL_ImplPkeyMgmtFreeCtx)CRYPT_SM2_FreeCtx},
{CRYPT_EAL_IMPLPKEYMGMT_IMPORT, (CRYPT_EAL_ImplPkeyMgmtImport)CRYPT_SM2_Import},
{CRYPT_EAL_IMPLPKEYMGMT_EXPORT, (CRYPT_EAL_ImplPkeyMgmtExport)CRYPT_SM2_Export},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_PAILLIER
const CRYPT_EAL_Func g_defEalKeyMgmtPaillier[] = {
{CRYPT_EAL_IMPLPKEYMGMT_NEWCTX, (CRYPT_EAL_ImplPkeyMgmtNewCtx)CRYPT_EAL_DefPkeyMgmtNewCtx},
{CRYPT_EAL_IMPLPKEYMGMT_SETPARAM, (CRYPT_EAL_ImplPkeyMgmtSetParam)CRYPT_PAILLIER_SetParaEx},
{CRYPT_EAL_IMPLPKEYMGMT_GENKEY, (CRYPT_EAL_ImplPkeyMgmtGenKey)CRYPT_PAILLIER_Gen},
{CRYPT_EAL_IMPLPKEYMGMT_SETPRV, (CRYPT_EAL_ImplPkeyMgmtSetPrv)CRYPT_PAILLIER_SetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_SETPUB, (CRYPT_EAL_ImplPkeyMgmtSetPub)CRYPT_PAILLIER_SetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPRV, (CRYPT_EAL_ImplPkeyMgmtGetPrv)CRYPT_PAILLIER_GetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPUB, (CRYPT_EAL_ImplPkeyMgmtGetPub)CRYPT_PAILLIER_GetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_DUPCTX, (CRYPT_EAL_ImplPkeyMgmtDupCtx)CRYPT_PAILLIER_DupCtx},
{CRYPT_EAL_IMPLPKEYMGMT_CTRL, (CRYPT_EAL_ImplPkeyMgmtCtrl)CRYPT_PAILLIER_Ctrl},
{CRYPT_EAL_IMPLPKEYMGMT_FREECTX, (CRYPT_EAL_ImplPkeyMgmtFreeCtx)CRYPT_PAILLIER_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_ELGAMAL
const CRYPT_EAL_Func g_defEalKeyMgmtElGamal[] = {
{CRYPT_EAL_IMPLPKEYMGMT_NEWCTX, (CRYPT_EAL_ImplPkeyMgmtNewCtx)CRYPT_EAL_DefPkeyMgmtNewCtx},
{CRYPT_EAL_IMPLPKEYMGMT_SETPARAM, (CRYPT_EAL_ImplPkeyMgmtSetParam)CRYPT_ELGAMAL_SetParaEx},
{CRYPT_EAL_IMPLPKEYMGMT_GENKEY, (CRYPT_EAL_ImplPkeyMgmtGenKey)CRYPT_ELGAMAL_Gen},
{CRYPT_EAL_IMPLPKEYMGMT_SETPRV, (CRYPT_EAL_ImplPkeyMgmtSetPrv)CRYPT_ELGAMAL_SetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_SETPUB, (CRYPT_EAL_ImplPkeyMgmtSetPub)CRYPT_ELGAMAL_SetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPRV, (CRYPT_EAL_ImplPkeyMgmtGetPrv)CRYPT_ELGAMAL_GetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPUB, (CRYPT_EAL_ImplPkeyMgmtGetPub)CRYPT_ELGAMAL_GetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_DUPCTX, (CRYPT_EAL_ImplPkeyMgmtDupCtx)CRYPT_ELGAMAL_DupCtx},
{CRYPT_EAL_IMPLPKEYMGMT_CTRL, (CRYPT_EAL_ImplPkeyMgmtCtrl)CRYPT_ELGAMAL_Ctrl},
{CRYPT_EAL_IMPLPKEYMGMT_FREECTX, (CRYPT_EAL_ImplPkeyMgmtFreeCtx)CRYPT_ELGAMAL_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_MLKEM
const CRYPT_EAL_Func g_defEalKeyMgmtMlKem[] = {
{CRYPT_EAL_IMPLPKEYMGMT_NEWCTX, (CRYPT_EAL_ImplPkeyMgmtNewCtx)CRYPT_EAL_DefPkeyMgmtNewCtx},
{CRYPT_EAL_IMPLPKEYMGMT_GENKEY, (CRYPT_EAL_ImplPkeyMgmtGenKey)CRYPT_ML_KEM_GenKey},
{CRYPT_EAL_IMPLPKEYMGMT_SETPRV, (CRYPT_EAL_ImplPkeyMgmtSetPrv)CRYPT_ML_KEM_SetDecapsKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_SETPUB, (CRYPT_EAL_ImplPkeyMgmtSetPub)CRYPT_ML_KEM_SetEncapsKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPRV, (CRYPT_EAL_ImplPkeyMgmtGetPrv)CRYPT_ML_KEM_GetDecapsKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPUB, (CRYPT_EAL_ImplPkeyMgmtGetPub)CRYPT_ML_KEM_GetEncapsKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_DUPCTX, (CRYPT_EAL_ImplPkeyMgmtDupCtx)CRYPT_ML_KEM_DupCtx},
#ifdef HITLS_CRYPTO_MLKEM_CHECK
{CRYPT_EAL_IMPLPKEYMGMT_CHECK, (CRYPT_EAL_ImplPkeyMgmtCheck)CRYPT_ML_KEM_Check},
#endif
{CRYPT_EAL_IMPLPKEYMGMT_COMPARE, (CRYPT_EAL_ImplPkeyMgmtCompare)CRYPT_ML_KEM_Cmp},
{CRYPT_EAL_IMPLPKEYMGMT_CTRL, (CRYPT_EAL_ImplPkeyMgmtCtrl)CRYPT_ML_KEM_Ctrl},
{CRYPT_EAL_IMPLPKEYMGMT_FREECTX, (CRYPT_EAL_ImplPkeyMgmtFreeCtx)CRYPT_ML_KEM_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_MLDSA
const CRYPT_EAL_Func g_defEalKeyMgmtMlDsa[] = {
{CRYPT_EAL_IMPLPKEYMGMT_NEWCTX, (CRYPT_EAL_ImplPkeyMgmtNewCtx)CRYPT_EAL_DefPkeyMgmtNewCtx},
{CRYPT_EAL_IMPLPKEYMGMT_GENKEY, (CRYPT_EAL_ImplPkeyMgmtGenKey)CRYPT_ML_DSA_GenKey},
{CRYPT_EAL_IMPLPKEYMGMT_SETPRV, (CRYPT_EAL_ImplPkeyMgmtSetPrv)CRYPT_ML_DSA_SetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_SETPUB, (CRYPT_EAL_ImplPkeyMgmtSetPub)CRYPT_ML_DSA_SetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPRV, (CRYPT_EAL_ImplPkeyMgmtGetPrv)CRYPT_ML_DSA_GetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPUB, (CRYPT_EAL_ImplPkeyMgmtGetPub)CRYPT_ML_DSA_GetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_DUPCTX, (CRYPT_EAL_ImplPkeyMgmtDupCtx)CRYPT_ML_DSA_DupCtx},
#ifdef HITLS_CRYPTO_MLDSA_CHECK
{CRYPT_EAL_IMPLPKEYMGMT_CHECK, (CRYPT_EAL_ImplPkeyMgmtCheck)CRYPT_ML_DSA_Check},
#endif
{CRYPT_EAL_IMPLPKEYMGMT_COMPARE, (CRYPT_EAL_ImplPkeyMgmtCompare)CRYPT_ML_DSA_Cmp},
{CRYPT_EAL_IMPLPKEYMGMT_CTRL, (CRYPT_EAL_ImplPkeyMgmtCtrl)CRYPT_ML_DSA_Ctrl},
{CRYPT_EAL_IMPLPKEYMGMT_FREECTX, (CRYPT_EAL_ImplPkeyMgmtFreeCtx)CRYPT_ML_DSA_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_SLH_DSA
const CRYPT_EAL_Func g_defEalKeyMgmtSlhDsa[] = {
{CRYPT_EAL_IMPLPKEYMGMT_NEWCTX, (CRYPT_EAL_ImplPkeyMgmtNewCtx)CRYPT_EAL_DefPkeyMgmtNewCtx},
{CRYPT_EAL_IMPLPKEYMGMT_GENKEY, (CRYPT_EAL_ImplPkeyMgmtGenKey)CRYPT_SLH_DSA_Gen},
{CRYPT_EAL_IMPLPKEYMGMT_SETPRV, (CRYPT_EAL_ImplPkeyMgmtSetPrv)CRYPT_SLH_DSA_SetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_SETPUB, (CRYPT_EAL_ImplPkeyMgmtSetPub)CRYPT_SLH_DSA_SetPubKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPRV, (CRYPT_EAL_ImplPkeyMgmtGetPrv)CRYPT_SLH_DSA_GetPrvKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPUB, (CRYPT_EAL_ImplPkeyMgmtGetPub)CRYPT_SLH_DSA_GetPubKeyEx},
#ifdef HITLS_CRYPTO_SLH_DSA_CHECK
{CRYPT_EAL_IMPLPKEYMGMT_CHECK, (CRYPT_EAL_ImplPkeyMgmtCheck)CRYPT_SLH_DSA_Check},
#endif
{CRYPT_EAL_IMPLPKEYMGMT_CTRL, (CRYPT_EAL_ImplPkeyMgmtCtrl)CRYPT_SLH_DSA_Ctrl},
{CRYPT_EAL_IMPLPKEYMGMT_FREECTX, (CRYPT_EAL_ImplPkeyMgmtFreeCtx)CRYPT_SLH_DSA_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_HYBRIDKEM
const CRYPT_EAL_Func g_defEalKeyMgmtHybridKem[] = {
{CRYPT_EAL_IMPLPKEYMGMT_NEWCTX, (CRYPT_EAL_ImplPkeyMgmtNewCtx)CRYPT_EAL_DefPkeyMgmtNewCtx},
{CRYPT_EAL_IMPLPKEYMGMT_GENKEY, (CRYPT_EAL_ImplPkeyMgmtGenKey)CRYPT_HYBRID_KEM_GenKey},
{CRYPT_EAL_IMPLPKEYMGMT_SETPRV, (CRYPT_EAL_ImplPkeyMgmtSetPrv)CRYPT_HYBRID_KEM_SetDecapsKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_SETPUB, (CRYPT_EAL_ImplPkeyMgmtSetPub)CRYPT_HYBRID_KEM_SetEncapsKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPRV, (CRYPT_EAL_ImplPkeyMgmtGetPrv)CRYPT_HYBRID_KEM_GetDecapsKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_GETPUB, (CRYPT_EAL_ImplPkeyMgmtGetPub)CRYPT_HYBRID_KEM_GetEncapsKeyEx},
{CRYPT_EAL_IMPLPKEYMGMT_CTRL, (CRYPT_EAL_ImplPkeyMgmtCtrl)CRYPT_HYBRID_KEM_KeyCtrl},
{CRYPT_EAL_IMPLPKEYMGMT_FREECTX, (CRYPT_EAL_ImplPkeyMgmtFreeCtx)CRYPT_HYBRID_KEM_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#endif /* HITLS_CRYPTO_PKEY && HITLS_CRYPTO_PROVIDER */ | 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/default/crypt_default_keymgmt.c | C | unknown | 20,876 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_MAC) && defined(HITLS_CRYPTO_PROVIDER)
#include "crypt_eal_implprovider.h"
#include "crypt_hmac.h"
#include "crypt_cmac.h"
#include "crypt_cbc_mac.h"
#include "crypt_gmac.h"
#include "crypt_siphash.h"
#include "crypt_ealinit.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "bsl_log_internal.h"
#include "bsl_err_internal.h"
#include "crypt_default_provider.h"
void *CRYPT_EAL_DefMacNewCtx(CRYPT_EAL_DefProvCtx *provCtx, int32_t algId)
{
void *libCtx = provCtx == NULL ? NULL : provCtx->libCtx;
#ifdef HITLS_CRYPTO_ASM_CHECK
if (CRYPT_ASMCAP_Mac(algId) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_ASM_NOT_SUPPORT);
return NULL;
}
#endif
switch (algId) {
#ifdef HITLS_CRYPTO_HMAC
case CRYPT_MAC_HMAC_MD5:
case CRYPT_MAC_HMAC_SHA1:
case CRYPT_MAC_HMAC_SHA224:
case CRYPT_MAC_HMAC_SHA256:
case CRYPT_MAC_HMAC_SHA384:
case CRYPT_MAC_HMAC_SHA512:
case CRYPT_MAC_HMAC_SHA3_224:
case CRYPT_MAC_HMAC_SHA3_256:
case CRYPT_MAC_HMAC_SHA3_384:
case CRYPT_MAC_HMAC_SHA3_512:
case CRYPT_MAC_HMAC_SM3:
return CRYPT_HMAC_NewCtxEx(libCtx, algId);
#endif
#ifdef HITLS_CRYPTO_CMAC
case CRYPT_MAC_CMAC_AES128:
case CRYPT_MAC_CMAC_AES192:
case CRYPT_MAC_CMAC_AES256:
case CRYPT_MAC_CMAC_SM4:
return CRYPT_CMAC_NewCtxEx(libCtx, algId);
#endif
#ifdef HITLS_CRYPTO_CBC_MAC
case CRYPT_MAC_CBC_MAC_SM4:
return CRYPT_CBC_MAC_NewCtxEx(libCtx, algId);
#endif
#ifdef HITLS_CRYPTO_SIPHASH
case CRYPT_MAC_SIPHASH64:
case CRYPT_MAC_SIPHASH128:
return CRYPT_SIPHASH_NewCtxEx(libCtx, algId);
#endif
#ifdef HITLS_CRYPTO_GMAC
case CRYPT_MAC_GMAC_AES128:
case CRYPT_MAC_GMAC_AES192:
case CRYPT_MAC_GMAC_AES256:
return CRYPT_GMAC_NewCtxEx(libCtx, algId);
#endif
default:
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_NOT_SUPPORT);
return NULL;
}
}
#ifdef HITLS_CRYPTO_HMAC
const CRYPT_EAL_Func g_defEalMacHmac[] = {
{CRYPT_EAL_IMPLMAC_NEWCTX, (CRYPT_EAL_ImplMacNewCtx)CRYPT_EAL_DefMacNewCtx},
{CRYPT_EAL_IMPLMAC_INIT, (CRYPT_EAL_ImplMacInit)CRYPT_HMAC_Init},
{CRYPT_EAL_IMPLMAC_UPDATE, (CRYPT_EAL_ImplMacUpdate)CRYPT_HMAC_Update},
{CRYPT_EAL_IMPLMAC_FINAL, (CRYPT_EAL_ImplMacFinal)CRYPT_HMAC_Final},
{CRYPT_EAL_IMPLMAC_DEINITCTX, (CRYPT_EAL_ImplMacDeInitCtx)CRYPT_HMAC_Deinit},
{CRYPT_EAL_IMPLMAC_REINITCTX, (CRYPT_EAL_ImplMacReInitCtx)CRYPT_HMAC_Reinit},
{CRYPT_EAL_IMPLMAC_CTRL, (CRYPT_EAL_ImplMacCtrl)CRYPT_HMAC_Ctrl},
{CRYPT_EAL_IMPLMAC_FREECTX, (CRYPT_EAL_ImplMacFreeCtx)CRYPT_HMAC_FreeCtx},
{CRYPT_EAL_IMPLMAC_SETPARAM, (CRYPT_EAL_ImplMacSetParam)CRYPT_HMAC_SetParam},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_CMAC
const CRYPT_EAL_Func g_defEalMacCmac[] = {
{CRYPT_EAL_IMPLMAC_NEWCTX, (CRYPT_EAL_ImplMacNewCtx)CRYPT_EAL_DefMacNewCtx},
{CRYPT_EAL_IMPLMAC_INIT, (CRYPT_EAL_ImplMacInit)CRYPT_CMAC_Init},
{CRYPT_EAL_IMPLMAC_UPDATE, (CRYPT_EAL_ImplMacUpdate)CRYPT_CMAC_Update},
{CRYPT_EAL_IMPLMAC_FINAL, (CRYPT_EAL_ImplMacFinal)CRYPT_CMAC_Final},
{CRYPT_EAL_IMPLMAC_DEINITCTX, (CRYPT_EAL_ImplMacDeInitCtx)CRYPT_CMAC_Deinit},
{CRYPT_EAL_IMPLMAC_REINITCTX, (CRYPT_EAL_ImplMacReInitCtx)CRYPT_CMAC_Reinit},
{CRYPT_EAL_IMPLMAC_CTRL, (CRYPT_EAL_ImplMacCtrl)CRYPT_CMAC_Ctrl},
{CRYPT_EAL_IMPLMAC_FREECTX, (CRYPT_EAL_ImplMacFreeCtx)CRYPT_CMAC_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_CBC_MAC
const CRYPT_EAL_Func g_defEalMacCbcMac[] = {
{CRYPT_EAL_IMPLMAC_NEWCTX, (CRYPT_EAL_ImplMacNewCtx)CRYPT_EAL_DefMacNewCtx},
{CRYPT_EAL_IMPLMAC_INIT, (CRYPT_EAL_ImplMacInit)CRYPT_CBC_MAC_Init},
{CRYPT_EAL_IMPLMAC_UPDATE, (CRYPT_EAL_ImplMacUpdate)CRYPT_CBC_MAC_Update},
{CRYPT_EAL_IMPLMAC_FINAL, (CRYPT_EAL_ImplMacFinal)CRYPT_CBC_MAC_Final},
{CRYPT_EAL_IMPLMAC_DEINITCTX, (CRYPT_EAL_ImplMacDeInitCtx)CRYPT_CBC_MAC_Deinit},
{CRYPT_EAL_IMPLMAC_REINITCTX, (CRYPT_EAL_ImplMacReInitCtx)CRYPT_CBC_MAC_Reinit},
{CRYPT_EAL_IMPLMAC_CTRL, (CRYPT_EAL_ImplMacCtrl)CRYPT_CBC_MAC_Ctrl},
{CRYPT_EAL_IMPLMAC_FREECTX, (CRYPT_EAL_ImplMacFreeCtx)CRYPT_CBC_MAC_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_GMAC
const CRYPT_EAL_Func g_defEalMacGmac[] = {
{CRYPT_EAL_IMPLMAC_NEWCTX, (CRYPT_EAL_ImplMacNewCtx)CRYPT_EAL_DefMacNewCtx},
{CRYPT_EAL_IMPLMAC_INIT, (CRYPT_EAL_ImplMacInit)CRYPT_GMAC_Init},
{CRYPT_EAL_IMPLMAC_UPDATE, (CRYPT_EAL_ImplMacUpdate)CRYPT_GMAC_Update},
{CRYPT_EAL_IMPLMAC_FINAL, (CRYPT_EAL_ImplMacFinal)CRYPT_GMAC_Final},
{CRYPT_EAL_IMPLMAC_DEINITCTX, (CRYPT_EAL_ImplMacDeInitCtx)CRYPT_GMAC_Deinit},
{CRYPT_EAL_IMPLMAC_CTRL, (CRYPT_EAL_ImplMacCtrl)CRYPT_GMAC_Ctrl},
{CRYPT_EAL_IMPLMAC_FREECTX, (CRYPT_EAL_ImplMacFreeCtx)CRYPT_GMAC_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_SIPHASH
const CRYPT_EAL_Func g_defEalMacSiphash[] = {
{CRYPT_EAL_IMPLMAC_NEWCTX, (CRYPT_EAL_ImplMacNewCtx)CRYPT_EAL_DefMacNewCtx},
{CRYPT_EAL_IMPLMAC_INIT, (CRYPT_EAL_ImplMacInit)CRYPT_SIPHASH_Init},
{CRYPT_EAL_IMPLMAC_UPDATE, (CRYPT_EAL_ImplMacUpdate)CRYPT_SIPHASH_Update},
{CRYPT_EAL_IMPLMAC_FINAL, (CRYPT_EAL_ImplMacFinal)CRYPT_SIPHASH_Final},
{CRYPT_EAL_IMPLMAC_DEINITCTX, (CRYPT_EAL_ImplMacDeInitCtx)CRYPT_SIPHASH_Deinit},
{CRYPT_EAL_IMPLMAC_REINITCTX, (CRYPT_EAL_ImplMacReInitCtx)CRYPT_SIPHASH_Reinit},
{CRYPT_EAL_IMPLMAC_CTRL, (CRYPT_EAL_ImplMacCtrl)CRYPT_SIPHASH_Ctrl},
{CRYPT_EAL_IMPLMAC_FREECTX, (CRYPT_EAL_ImplMacFreeCtx)CRYPT_SIPHASH_FreeCtx},
CRYPT_EAL_FUNC_END,
};
#endif
#endif /* HITLS_CRYPTO_MAC && HITLS_CRYPTO_PROVIDER */ | 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/default/crypt_default_mac.c | C | unknown | 6,296 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_MD) && defined(HITLS_CRYPTO_PROVIDER)
#include "crypt_eal_implprovider.h"
#include "crypt_md5.h"
#include "crypt_sha1.h"
#include "crypt_sha2.h"
#include "crypt_sha3.h"
#include "crypt_sm3.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "bsl_log_internal.h"
#include "bsl_err_internal.h"
#include "crypt_ealinit.h"
#include "crypt_default_provider.h"
static void *CRYPT_EAL_DefMdNewCtx(CRYPT_EAL_DefProvCtx *provCtx, int32_t algId)
{
void *libCtx = provCtx == NULL ? NULL : provCtx->libCtx;
#ifdef HITLS_CRYPTO_ASM_CHECK
if (CRYPT_ASMCAP_Md(algId) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_ASM_NOT_SUPPORT);
return NULL;
}
#endif
switch (algId) {
#ifdef HITLS_CRYPTO_MD5
case CRYPT_MD_MD5:
return CRYPT_MD5_NewCtxEx(libCtx, algId);
#endif
#ifdef HITLS_CRYPTO_SHA1
case CRYPT_MD_SHA1:
return CRYPT_SHA1_NewCtxEx(libCtx, algId);
#endif
#ifdef HITLS_CRYPTO_SHA224
case CRYPT_MD_SHA224:
return CRYPT_SHA2_224_NewCtxEx(libCtx, algId);
#endif
#ifdef HITLS_CRYPTO_SHA256
case CRYPT_MD_SHA256:
return CRYPT_SHA2_256_NewCtxEx(libCtx, algId);
#endif
#ifdef HITLS_CRYPTO_SHA384
case CRYPT_MD_SHA384:
return CRYPT_SHA2_384_NewCtxEx(libCtx, algId);
#endif
#ifdef HITLS_CRYPTO_SHA512
case CRYPT_MD_SHA512:
return CRYPT_SHA2_512_NewCtxEx(libCtx, algId);
#endif
#ifdef HITLS_CRYPTO_SHA3
case CRYPT_MD_SHA3_224:
case CRYPT_MD_SHA3_256:
case CRYPT_MD_SHA3_384:
case CRYPT_MD_SHA3_512:
return CRYPT_SHA3_256_NewCtxEx(libCtx, algId);
case CRYPT_MD_SHAKE128:
case CRYPT_MD_SHAKE256:
return CRYPT_SHAKE256_NewCtxEx(libCtx, algId);
#endif
#ifdef HITLS_CRYPTO_SM3
case CRYPT_MD_SM3:
return CRYPT_SM3_NewCtxEx(libCtx, algId);
#endif
default:
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_NOT_SUPPORT);
return NULL;
}
}
#ifdef HITLS_CRYPTO_MD5
const CRYPT_EAL_Func g_defEalMdMd5[] = {
{CRYPT_EAL_IMPLMD_NEWCTX, (CRYPT_EAL_ImplMdNewCtx)CRYPT_EAL_DefMdNewCtx},
{CRYPT_EAL_IMPLMD_INITCTX, (CRYPT_EAL_ImplMdInitCtx)CRYPT_MD5_Init},
{CRYPT_EAL_IMPLMD_UPDATE, (CRYPT_EAL_ImplMdUpdate)CRYPT_MD5_Update},
{CRYPT_EAL_IMPLMD_FINAL, (CRYPT_EAL_ImplMdFinal)CRYPT_MD5_Final},
{CRYPT_EAL_IMPLMD_DEINITCTX, (CRYPT_EAL_ImplMdDeInitCtx)CRYPT_MD5_Deinit},
{CRYPT_EAL_IMPLMD_DUPCTX, (CRYPT_EAL_ImplMdDupCtx)CRYPT_MD5_DupCtx},
{CRYPT_EAL_IMPLMD_FREECTX, (CRYPT_EAL_ImplMdFreeCtx)CRYPT_MD5_FreeCtx},
{CRYPT_EAL_IMPLMD_COPYCTX, (CRYPT_EAL_ImplMdCopyCtx)CRYPT_MD5_CopyCtx},
{CRYPT_EAL_IMPLMD_GETPARAM, (CRYPT_EAL_ImplMdGetParam)CRYPT_MD5_GetParam},
CRYPT_EAL_FUNC_END,
};
#endif // HITLS_CRYPTO_MD5
#ifdef HITLS_CRYPTO_SHA1
const CRYPT_EAL_Func g_defEalMdSha1[] = {
{CRYPT_EAL_IMPLMD_NEWCTX, (CRYPT_EAL_ImplMdNewCtx)CRYPT_EAL_DefMdNewCtx},
{CRYPT_EAL_IMPLMD_INITCTX, (CRYPT_EAL_ImplMdInitCtx)CRYPT_SHA1_Init},
{CRYPT_EAL_IMPLMD_UPDATE, (CRYPT_EAL_ImplMdUpdate)CRYPT_SHA1_Update},
{CRYPT_EAL_IMPLMD_FINAL, (CRYPT_EAL_ImplMdFinal)CRYPT_SHA1_Final},
{CRYPT_EAL_IMPLMD_DEINITCTX, (CRYPT_EAL_ImplMdDeInitCtx)CRYPT_SHA1_Deinit},
{CRYPT_EAL_IMPLMD_DUPCTX, (CRYPT_EAL_ImplMdDupCtx)CRYPT_SHA1_DupCtx},
{CRYPT_EAL_IMPLMD_FREECTX, (CRYPT_EAL_ImplMdFreeCtx)CRYPT_SHA1_FreeCtx},
{CRYPT_EAL_IMPLMD_COPYCTX, (CRYPT_EAL_ImplMdCopyCtx)CRYPT_SHA1_CopyCtx},
{CRYPT_EAL_IMPLMD_GETPARAM, (CRYPT_EAL_ImplMdGetParam)CRYPT_SHA1_GetParam},
CRYPT_EAL_FUNC_END,
};
#endif // HITLS_CRYPTO_SHA1
#ifdef HITLS_CRYPTO_SHA224
const CRYPT_EAL_Func g_defEalMdSha224[] = {
{CRYPT_EAL_IMPLMD_NEWCTX, (CRYPT_EAL_ImplMdNewCtx)CRYPT_EAL_DefMdNewCtx},
{CRYPT_EAL_IMPLMD_INITCTX, (CRYPT_EAL_ImplMdInitCtx)CRYPT_SHA2_224_Init},
{CRYPT_EAL_IMPLMD_UPDATE, (CRYPT_EAL_ImplMdUpdate)CRYPT_SHA2_224_Update},
{CRYPT_EAL_IMPLMD_FINAL, (CRYPT_EAL_ImplMdFinal)CRYPT_SHA2_224_Final},
{CRYPT_EAL_IMPLMD_DEINITCTX, (CRYPT_EAL_ImplMdDeInitCtx)CRYPT_SHA2_224_Deinit},
{CRYPT_EAL_IMPLMD_DUPCTX, (CRYPT_EAL_ImplMdDupCtx)CRYPT_SHA2_224_DupCtx},
{CRYPT_EAL_IMPLMD_FREECTX, (CRYPT_EAL_ImplMdFreeCtx)CRYPT_SHA2_224_FreeCtx},
{CRYPT_EAL_IMPLMD_COPYCTX, (CRYPT_EAL_ImplMdCopyCtx)CRYPT_SHA2_224_CopyCtx},
{CRYPT_EAL_IMPLMD_GETPARAM, (CRYPT_EAL_ImplMdGetParam)CRYPT_SHA2_224_GetParam},
CRYPT_EAL_FUNC_END,
};
#endif // HITLS_CRYPTO_SHA224
#ifdef HITLS_CRYPTO_SHA256
const CRYPT_EAL_Func g_defEalMdSha256[] = {
{CRYPT_EAL_IMPLMD_NEWCTX, (CRYPT_EAL_ImplMdNewCtx)CRYPT_EAL_DefMdNewCtx},
{CRYPT_EAL_IMPLMD_INITCTX, (CRYPT_EAL_ImplMdInitCtx)CRYPT_SHA2_256_Init},
{CRYPT_EAL_IMPLMD_UPDATE, (CRYPT_EAL_ImplMdUpdate)CRYPT_SHA2_256_Update},
{CRYPT_EAL_IMPLMD_FINAL, (CRYPT_EAL_ImplMdFinal)CRYPT_SHA2_256_Final},
{CRYPT_EAL_IMPLMD_DEINITCTX, (CRYPT_EAL_ImplMdDeInitCtx)CRYPT_SHA2_256_Deinit},
{CRYPT_EAL_IMPLMD_DUPCTX, (CRYPT_EAL_ImplMdDupCtx)CRYPT_SHA2_256_DupCtx},
{CRYPT_EAL_IMPLMD_FREECTX, (CRYPT_EAL_ImplMdFreeCtx)CRYPT_SHA2_256_FreeCtx},
{CRYPT_EAL_IMPLMD_COPYCTX, (CRYPT_EAL_ImplMdCopyCtx)CRYPT_SHA2_256_CopyCtx},
{CRYPT_EAL_IMPLMD_GETPARAM, (CRYPT_EAL_ImplMdGetParam)CRYPT_SHA2_256_GetParam},
CRYPT_EAL_FUNC_END,
};
#endif // HITLS_CRYPTO_SHA256
#ifdef HITLS_CRYPTO_SHA384
const CRYPT_EAL_Func g_defEalMdSha384[] = {
{CRYPT_EAL_IMPLMD_NEWCTX, (CRYPT_EAL_ImplMdNewCtx)CRYPT_EAL_DefMdNewCtx},
{CRYPT_EAL_IMPLMD_INITCTX, (CRYPT_EAL_ImplMdInitCtx)CRYPT_SHA2_384_Init},
{CRYPT_EAL_IMPLMD_UPDATE, (CRYPT_EAL_ImplMdUpdate)CRYPT_SHA2_384_Update},
{CRYPT_EAL_IMPLMD_FINAL, (CRYPT_EAL_ImplMdFinal)CRYPT_SHA2_384_Final},
{CRYPT_EAL_IMPLMD_DEINITCTX, (CRYPT_EAL_ImplMdDeInitCtx)CRYPT_SHA2_384_Deinit},
{CRYPT_EAL_IMPLMD_DUPCTX, (CRYPT_EAL_ImplMdDupCtx)CRYPT_SHA2_384_DupCtx},
{CRYPT_EAL_IMPLMD_FREECTX, (CRYPT_EAL_ImplMdFreeCtx)CRYPT_SHA2_384_FreeCtx},
{CRYPT_EAL_IMPLMD_COPYCTX, (CRYPT_EAL_ImplMdCopyCtx)CRYPT_SHA2_384_CopyCtx},
{CRYPT_EAL_IMPLMD_GETPARAM, (CRYPT_EAL_ImplMdGetParam)CRYPT_SHA2_384_GetParam},
CRYPT_EAL_FUNC_END,
};
#endif // HITLS_CRYPTO_SHA384
#ifdef HITLS_CRYPTO_SHA512
const CRYPT_EAL_Func g_defEalMdSha512[] = {
{CRYPT_EAL_IMPLMD_NEWCTX, (CRYPT_EAL_ImplMdNewCtx)CRYPT_EAL_DefMdNewCtx},
{CRYPT_EAL_IMPLMD_INITCTX, (CRYPT_EAL_ImplMdInitCtx)CRYPT_SHA2_512_Init},
{CRYPT_EAL_IMPLMD_UPDATE, (CRYPT_EAL_ImplMdUpdate)CRYPT_SHA2_512_Update},
{CRYPT_EAL_IMPLMD_FINAL, (CRYPT_EAL_ImplMdFinal)CRYPT_SHA2_512_Final},
{CRYPT_EAL_IMPLMD_DEINITCTX, (CRYPT_EAL_ImplMdDeInitCtx)CRYPT_SHA2_512_Deinit},
{CRYPT_EAL_IMPLMD_DUPCTX, (CRYPT_EAL_ImplMdDupCtx)CRYPT_SHA2_512_DupCtx},
{CRYPT_EAL_IMPLMD_FREECTX, (CRYPT_EAL_ImplMdFreeCtx)CRYPT_SHA2_512_FreeCtx},
{CRYPT_EAL_IMPLMD_COPYCTX, (CRYPT_EAL_ImplMdCopyCtx)CRYPT_SHA2_512_CopyCtx},
{CRYPT_EAL_IMPLMD_GETPARAM, (CRYPT_EAL_ImplMdGetParam)CRYPT_SHA2_512_GetParam},
CRYPT_EAL_FUNC_END,
};
#endif // HITLS_CRYPTO_SHA512
#ifdef HITLS_CRYPTO_SHA3
const CRYPT_EAL_Func g_defEalMdSha3224[] = {
{CRYPT_EAL_IMPLMD_NEWCTX, (CRYPT_EAL_ImplMdNewCtx)CRYPT_EAL_DefMdNewCtx},
{CRYPT_EAL_IMPLMD_INITCTX, (CRYPT_EAL_ImplMdInitCtx)CRYPT_SHA3_224_Init},
{CRYPT_EAL_IMPLMD_UPDATE, (CRYPT_EAL_ImplMdUpdate)CRYPT_SHA3_224_Update},
{CRYPT_EAL_IMPLMD_FINAL, (CRYPT_EAL_ImplMdFinal)CRYPT_SHA3_224_Final},
{CRYPT_EAL_IMPLMD_DEINITCTX, (CRYPT_EAL_ImplMdDeInitCtx)CRYPT_SHA3_224_Deinit},
{CRYPT_EAL_IMPLMD_DUPCTX, (CRYPT_EAL_ImplMdDupCtx)CRYPT_SHA3_224_DupCtx},
{CRYPT_EAL_IMPLMD_FREECTX, (CRYPT_EAL_ImplMdFreeCtx)CRYPT_SHA3_224_FreeCtx},
{CRYPT_EAL_IMPLMD_COPYCTX, (CRYPT_EAL_ImplMdCopyCtx)CRYPT_SHA3_224_CopyCtx},
{CRYPT_EAL_IMPLMD_GETPARAM, (CRYPT_EAL_ImplMdGetParam)CRYPT_SHA3_224_GetParam},
CRYPT_EAL_FUNC_END,
};
const CRYPT_EAL_Func g_defEalMdSha3256[] = {
{CRYPT_EAL_IMPLMD_NEWCTX, (CRYPT_EAL_ImplMdNewCtx)CRYPT_EAL_DefMdNewCtx},
{CRYPT_EAL_IMPLMD_INITCTX, (CRYPT_EAL_ImplMdInitCtx)CRYPT_SHA3_256_Init},
{CRYPT_EAL_IMPLMD_UPDATE, (CRYPT_EAL_ImplMdUpdate)CRYPT_SHA3_256_Update},
{CRYPT_EAL_IMPLMD_FINAL, (CRYPT_EAL_ImplMdFinal)CRYPT_SHA3_256_Final},
{CRYPT_EAL_IMPLMD_DEINITCTX, (CRYPT_EAL_ImplMdDeInitCtx)CRYPT_SHA3_256_Deinit},
{CRYPT_EAL_IMPLMD_DUPCTX, (CRYPT_EAL_ImplMdDupCtx)CRYPT_SHA3_256_DupCtx},
{CRYPT_EAL_IMPLMD_FREECTX, (CRYPT_EAL_ImplMdFreeCtx)CRYPT_SHA3_256_FreeCtx},
{CRYPT_EAL_IMPLMD_COPYCTX, (CRYPT_EAL_ImplMdCopyCtx)CRYPT_SHA3_256_CopyCtx},
{CRYPT_EAL_IMPLMD_GETPARAM, (CRYPT_EAL_ImplMdGetParam)CRYPT_SHA3_256_GetParam},
CRYPT_EAL_FUNC_END,
};
const CRYPT_EAL_Func g_defEalMdSha3384[] = {
{CRYPT_EAL_IMPLMD_NEWCTX, (CRYPT_EAL_ImplMdNewCtx)CRYPT_EAL_DefMdNewCtx},
{CRYPT_EAL_IMPLMD_INITCTX, (CRYPT_EAL_ImplMdInitCtx)CRYPT_SHA3_384_Init},
{CRYPT_EAL_IMPLMD_UPDATE, (CRYPT_EAL_ImplMdUpdate)CRYPT_SHA3_384_Update},
{CRYPT_EAL_IMPLMD_FINAL, (CRYPT_EAL_ImplMdFinal)CRYPT_SHA3_384_Final},
{CRYPT_EAL_IMPLMD_DEINITCTX, (CRYPT_EAL_ImplMdDeInitCtx)CRYPT_SHA3_384_Deinit},
{CRYPT_EAL_IMPLMD_DUPCTX, (CRYPT_EAL_ImplMdDupCtx)CRYPT_SHA3_384_DupCtx},
{CRYPT_EAL_IMPLMD_FREECTX, (CRYPT_EAL_ImplMdFreeCtx)CRYPT_SHA3_384_FreeCtx},
{CRYPT_EAL_IMPLMD_COPYCTX, (CRYPT_EAL_ImplMdCopyCtx)CRYPT_SHA3_384_CopyCtx},
{CRYPT_EAL_IMPLMD_GETPARAM, (CRYPT_EAL_ImplMdGetParam)CRYPT_SHA3_384_GetParam},
CRYPT_EAL_FUNC_END,
};
const CRYPT_EAL_Func g_defEalMdSha3512[] = {
{CRYPT_EAL_IMPLMD_NEWCTX, (CRYPT_EAL_ImplMdNewCtx)CRYPT_EAL_DefMdNewCtx},
{CRYPT_EAL_IMPLMD_INITCTX, (CRYPT_EAL_ImplMdInitCtx)CRYPT_SHA3_512_Init},
{CRYPT_EAL_IMPLMD_UPDATE, (CRYPT_EAL_ImplMdUpdate)CRYPT_SHA3_512_Update},
{CRYPT_EAL_IMPLMD_FINAL, (CRYPT_EAL_ImplMdFinal)CRYPT_SHA3_512_Final},
{CRYPT_EAL_IMPLMD_DEINITCTX, (CRYPT_EAL_ImplMdDeInitCtx)CRYPT_SHA3_512_Deinit},
{CRYPT_EAL_IMPLMD_DUPCTX, (CRYPT_EAL_ImplMdDupCtx)CRYPT_SHA3_512_DupCtx},
{CRYPT_EAL_IMPLMD_FREECTX, (CRYPT_EAL_ImplMdFreeCtx)CRYPT_SHA3_512_FreeCtx},
{CRYPT_EAL_IMPLMD_COPYCTX, (CRYPT_EAL_ImplMdCopyCtx)CRYPT_SHA3_512_CopyCtx},
{CRYPT_EAL_IMPLMD_GETPARAM, (CRYPT_EAL_ImplMdGetParam)CRYPT_SHA3_512_GetParam},
CRYPT_EAL_FUNC_END,
};
const CRYPT_EAL_Func g_defEalMdShake128[] = {
{CRYPT_EAL_IMPLMD_NEWCTX, (CRYPT_EAL_ImplMdNewCtx)CRYPT_EAL_DefMdNewCtx},
{CRYPT_EAL_IMPLMD_INITCTX, (CRYPT_EAL_ImplMdInitCtx)CRYPT_SHAKE128_Init},
{CRYPT_EAL_IMPLMD_UPDATE, (CRYPT_EAL_ImplMdUpdate)CRYPT_SHAKE128_Update},
{CRYPT_EAL_IMPLMD_FINAL, (CRYPT_EAL_ImplMdFinal)CRYPT_SHAKE128_Final},
{CRYPT_EAL_IMPLMD_DEINITCTX, (CRYPT_EAL_ImplMdDeInitCtx)CRYPT_SHAKE128_Deinit},
{CRYPT_EAL_IMPLMD_DUPCTX, (CRYPT_EAL_ImplMdDupCtx)CRYPT_SHAKE128_DupCtx},
{CRYPT_EAL_IMPLMD_FREECTX, (CRYPT_EAL_ImplMdFreeCtx)CRYPT_SHAKE128_FreeCtx},
{CRYPT_EAL_IMPLMD_SQUEEZE, (CRYPT_EAL_ImplMdSqueeze)CRYPT_SHAKE128_Squeeze},
{CRYPT_EAL_IMPLMD_COPYCTX, (CRYPT_EAL_ImplMdCopyCtx)CRYPT_SHAKE128_CopyCtx},
{CRYPT_EAL_IMPLMD_GETPARAM, (CRYPT_EAL_ImplMdGetParam)CRYPT_SHAKE128_GetParam},
CRYPT_EAL_FUNC_END,
};
const CRYPT_EAL_Func g_defEalMdShake256[] = {
{CRYPT_EAL_IMPLMD_NEWCTX, (CRYPT_EAL_ImplMdNewCtx)CRYPT_EAL_DefMdNewCtx},
{CRYPT_EAL_IMPLMD_INITCTX, (CRYPT_EAL_ImplMdInitCtx)CRYPT_SHAKE256_Init},
{CRYPT_EAL_IMPLMD_UPDATE, (CRYPT_EAL_ImplMdUpdate)CRYPT_SHAKE256_Update},
{CRYPT_EAL_IMPLMD_FINAL, (CRYPT_EAL_ImplMdFinal)CRYPT_SHAKE256_Final},
{CRYPT_EAL_IMPLMD_DEINITCTX, (CRYPT_EAL_ImplMdDeInitCtx)CRYPT_SHAKE256_Deinit},
{CRYPT_EAL_IMPLMD_DUPCTX, (CRYPT_EAL_ImplMdDupCtx)CRYPT_SHAKE256_DupCtx},
{CRYPT_EAL_IMPLMD_FREECTX, (CRYPT_EAL_ImplMdFreeCtx)CRYPT_SHAKE256_FreeCtx},
{CRYPT_EAL_IMPLMD_SQUEEZE, (CRYPT_EAL_ImplMdSqueeze)CRYPT_SHAKE256_Squeeze},
{CRYPT_EAL_IMPLMD_COPYCTX, (CRYPT_EAL_ImplMdCopyCtx)CRYPT_SHAKE256_CopyCtx},
{CRYPT_EAL_IMPLMD_GETPARAM, (CRYPT_EAL_ImplMdGetParam)CRYPT_SHAKE256_GetParam},
CRYPT_EAL_FUNC_END,
};
#endif // HITLS_CRYPTO_SHA3
#ifdef HITLS_CRYPTO_SM3
const CRYPT_EAL_Func g_defEalMdSm3[] = {
{CRYPT_EAL_IMPLMD_NEWCTX, (CRYPT_EAL_ImplMdNewCtx)CRYPT_EAL_DefMdNewCtx},
{CRYPT_EAL_IMPLMD_INITCTX, (CRYPT_EAL_ImplMdInitCtx)CRYPT_SM3_Init},
{CRYPT_EAL_IMPLMD_UPDATE, (CRYPT_EAL_ImplMdUpdate)CRYPT_SM3_Update},
{CRYPT_EAL_IMPLMD_FINAL, (CRYPT_EAL_ImplMdFinal)CRYPT_SM3_Final},
{CRYPT_EAL_IMPLMD_DEINITCTX, (CRYPT_EAL_ImplMdDeInitCtx)CRYPT_SM3_Deinit},
{CRYPT_EAL_IMPLMD_DUPCTX, (CRYPT_EAL_ImplMdDupCtx)CRYPT_SM3_DupCtx},
{CRYPT_EAL_IMPLMD_FREECTX, (CRYPT_EAL_ImplMdFreeCtx)CRYPT_SM3_FreeCtx},
{CRYPT_EAL_IMPLMD_COPYCTX, (CRYPT_EAL_ImplMdCopyCtx)CRYPT_SM3_CopyCtx},
{CRYPT_EAL_IMPLMD_GETPARAM, (CRYPT_EAL_ImplMdGetParam)CRYPT_SM3_GetParam},
CRYPT_EAL_FUNC_END,
};
#endif // HITLS_CRYPTO_SM3
#endif /* HITLS_CRYPTO_MD && HITLS_CRYPTO_PROVIDER */ | 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/default/crypt_default_md.c | C | unknown | 13,376 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#if (defined(HITLS_CRYPTO_RSA_ENCRYPT) || defined(HITLS_CRYPTO_RSA_DECRYPT) || \
defined(HITLS_CRYPTO_SM2_CRYPT) || defined(HITLS_CRYPTO_PAILLIER) || defined(HITLS_CRYPTO_ELGAMAL)) && \
defined(HITLS_CRYPTO_PROVIDER)
#include "crypt_eal_implprovider.h"
#include "crypt_rsa.h"
#include "crypt_sm2.h"
#include "crypt_paillier.h"
#include "crypt_elgamal.h"
#if defined(HITLS_CRYPTO_RSA_ENCRYPT) || defined(HITLS_CRYPTO_RSA_DECRYPT)
const CRYPT_EAL_Func g_defEalAsymCipherRsa[] = {
#ifdef HITLS_CRYPTO_RSA_ENCRYPT
{CRYPT_EAL_IMPLPKEYCIPHER_ENCRYPT, (CRYPT_EAL_ImplPkeyEncrypt)CRYPT_RSA_Encrypt},
#endif
#ifdef HITLS_CRYPTO_RSA_DECRYPT
{CRYPT_EAL_IMPLPKEYCIPHER_DECRYPT, (CRYPT_EAL_ImplPkeyDecrypt)CRYPT_RSA_Decrypt},
#endif
CRYPT_EAL_FUNC_END
};
#endif
#ifdef HITLS_CRYPTO_SM2_CRYPT
const CRYPT_EAL_Func g_defEalAsymCipherSm2[] = {
{CRYPT_EAL_IMPLPKEYCIPHER_ENCRYPT, (CRYPT_EAL_ImplPkeyEncrypt)CRYPT_SM2_Encrypt},
{CRYPT_EAL_IMPLPKEYCIPHER_DECRYPT, (CRYPT_EAL_ImplPkeyDecrypt)CRYPT_SM2_Decrypt},
CRYPT_EAL_FUNC_END
};
#endif
#ifdef HITLS_CRYPTO_PAILLIER
const CRYPT_EAL_Func g_defEalAsymCipherPaillier[] = {
{CRYPT_EAL_IMPLPKEYCIPHER_ENCRYPT, (CRYPT_EAL_ImplPkeyEncrypt)CRYPT_PAILLIER_Encrypt},
{CRYPT_EAL_IMPLPKEYCIPHER_DECRYPT, (CRYPT_EAL_ImplPkeyDecrypt)CRYPT_PAILLIER_Decrypt},
{CRYPT_EAL_IMPLPKEYCIPHER_HEADD, (CRYPT_EAL_ImplPkeyHEAdd)CRYPT_PAILLIER_Add},
CRYPT_EAL_FUNC_END
};
#endif
#ifdef HITLS_CRYPTO_ELGAMAL
const CRYPT_EAL_Func g_defEalAsymCipherElGamal[] = {
{CRYPT_EAL_IMPLPKEYCIPHER_ENCRYPT, CRYPT_ELGAMAL_Encrypt},
{CRYPT_EAL_IMPLPKEYCIPHER_DECRYPT, CRYPT_ELGAMAL_Decrypt},
CRYPT_EAL_FUNC_END
};
#endif
#endif | 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/default/crypt_default_pkeycipher.c | C | unknown | 2,255 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_PROVIDER
#include <stdint.h>
#include <string.h>
#include "bsl_sal.h"
#include "bsl_obj.h"
#include "bsl_errno.h"
#include "bsl_params.h"
#include "bsl_err_internal.h"
#include "crypt_utils.h"
#include "crypt_algid.h"
#include "crypt_errno.h"
#include "crypt_params_key.h"
#ifdef HITLS_TLS_FEATURE_PROVIDER
#include "hitls_crypt_type.h"
#include "hitls_cert_type.h"
#include "hitls_type.h"
#endif
#include "crypt_eal_implprovider.h"
#include "crypt_eal_provider.h"
#include "crypt_provider.h"
#include "crypt_default_provderimpl.h"
#include "crypt_default_provider.h"
#define CRYPT_EAL_DEFAULT_ATTR "provider=default"
#ifdef HITLS_CRYPTO_MD
static const CRYPT_EAL_AlgInfo g_defEalMds[] = {
#ifdef HITLS_CRYPTO_MD5
{CRYPT_MD_MD5, g_defEalMdMd5, CRYPT_EAL_DEFAULT_ATTR},
#endif // HITLS_CRYPTO_MD5
#ifdef HITLS_CRYPTO_SHA1
{CRYPT_MD_SHA1, g_defEalMdSha1, CRYPT_EAL_DEFAULT_ATTR},
#endif // HITLS_CRYPTO_SHA1
#ifdef HITLS_CRYPTO_SHA224
{CRYPT_MD_SHA224, g_defEalMdSha224, CRYPT_EAL_DEFAULT_ATTR},
#endif // HITLS_CRYPTO_SHA224
#ifdef HITLS_CRYPTO_SHA256
{CRYPT_MD_SHA256, g_defEalMdSha256, CRYPT_EAL_DEFAULT_ATTR},
#endif // HITLS_CRYPTO_SHA256
#ifdef HITLS_CRYPTO_SHA384
{CRYPT_MD_SHA384, g_defEalMdSha384, CRYPT_EAL_DEFAULT_ATTR},
#endif // HITLS_CRYPTO_SHA384
#ifdef HITLS_CRYPTO_SHA512
{CRYPT_MD_SHA512, g_defEalMdSha512, CRYPT_EAL_DEFAULT_ATTR},
#endif // HITLS_CRYPTO_SHA512
#ifdef HITLS_CRYPTO_SHA3
{CRYPT_MD_SHA3_224, g_defEalMdSha3224, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_MD_SHA3_256, g_defEalMdSha3256, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_MD_SHA3_384, g_defEalMdSha3384, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_MD_SHA3_512, g_defEalMdSha3512, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_MD_SHAKE128, g_defEalMdShake128, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_MD_SHAKE256, g_defEalMdShake256, CRYPT_EAL_DEFAULT_ATTR},
#endif // HITLS_CRYPTO_SHA3
#ifdef HITLS_CRYPTO_SM3
{CRYPT_MD_SM3, g_defEalMdSm3, CRYPT_EAL_DEFAULT_ATTR},
#endif // HITLS_CRYPTO_SM3
CRYPT_EAL_ALGINFO_END
};
#endif // HITLS_CRYPTO_MD
#ifdef HITLS_CRYPTO_MAC
static const CRYPT_EAL_AlgInfo g_defEalMacs[] = {
#ifdef HITLS_CRYPTO_HMAC
#ifdef HITLS_CRYPTO_MD5
{CRYPT_MAC_HMAC_MD5, g_defEalMacHmac, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SHA1
{CRYPT_MAC_HMAC_SHA1, g_defEalMacHmac, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SHA224
{CRYPT_MAC_HMAC_SHA224, g_defEalMacHmac, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SHA256
{CRYPT_MAC_HMAC_SHA256, g_defEalMacHmac, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SHA384
{CRYPT_MAC_HMAC_SHA384, g_defEalMacHmac, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SHA512
{CRYPT_MAC_HMAC_SHA512, g_defEalMacHmac, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SHA3
{CRYPT_MAC_HMAC_SHA3_224, g_defEalMacHmac, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_MAC_HMAC_SHA3_256, g_defEalMacHmac, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_MAC_HMAC_SHA3_384, g_defEalMacHmac, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_MAC_HMAC_SHA3_512, g_defEalMacHmac, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SM3
{CRYPT_MAC_HMAC_SM3, g_defEalMacHmac, CRYPT_EAL_DEFAULT_ATTR},
#endif
#endif
#ifdef HITLS_CRYPTO_CMAC
#ifdef HITLS_CRYPTO_AES
{CRYPT_MAC_CMAC_AES128, g_defEalMacCmac, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_MAC_CMAC_AES192, g_defEalMacCmac, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_MAC_CMAC_AES256, g_defEalMacCmac, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SM4
{CRYPT_MAC_CMAC_SM4, g_defEalMacCmac, CRYPT_EAL_DEFAULT_ATTR},
#endif
#endif
#ifdef HITLS_CRYPTO_CBC_MAC
{CRYPT_MAC_CBC_MAC_SM4, g_defEalMacCbcMac, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SIPHASH
{CRYPT_MAC_SIPHASH64, g_defEalMacSiphash, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_MAC_SIPHASH128, g_defEalMacSiphash, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_GMAC
{CRYPT_MAC_GMAC_AES128, g_defEalMacGmac, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_MAC_GMAC_AES192, g_defEalMacGmac, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_MAC_GMAC_AES256, g_defEalMacGmac, CRYPT_EAL_DEFAULT_ATTR},
#endif
CRYPT_EAL_ALGINFO_END
};
#endif
#ifdef HITLS_CRYPTO_KDF
static const CRYPT_EAL_AlgInfo g_defEalKdfs[] = {
#ifdef HITLS_CRYPTO_SCRYPT
{CRYPT_KDF_SCRYPT, g_defEalKdfScrypt, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_PBKDF2
{CRYPT_KDF_PBKDF2, g_defEalKdfPBKdf2, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_KDFTLS12
{CRYPT_KDF_KDFTLS12, g_defEalKdfKdfTLS12, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_HKDF
{CRYPT_KDF_HKDF, g_defEalKdfHkdf, CRYPT_EAL_DEFAULT_ATTR},
#endif
CRYPT_EAL_ALGINFO_END
};
#endif
#ifdef HITLS_CRYPTO_CIPHER
static const CRYPT_EAL_AlgInfo g_defEalCiphers[] = {
#ifdef HITLS_CRYPTO_AES
#ifdef HITLS_CRYPTO_CBC
{CRYPT_CIPHER_AES128_CBC, g_defEalCbc, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_CIPHER_AES192_CBC, g_defEalCbc, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_CIPHER_AES256_CBC, g_defEalCbc, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_CTR
{CRYPT_CIPHER_AES128_CTR, g_defEalCtr, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_CIPHER_AES192_CTR, g_defEalCtr, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_CIPHER_AES256_CTR, g_defEalCtr, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_ECB
{CRYPT_CIPHER_AES128_ECB, g_defEalEcb, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_CIPHER_AES192_ECB, g_defEalEcb, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_CIPHER_AES256_ECB, g_defEalEcb, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_CCM
{CRYPT_CIPHER_AES128_CCM, g_defEalCcm, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_CIPHER_AES192_CCM, g_defEalCcm, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_CIPHER_AES256_CCM, g_defEalCcm, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_GCM
{CRYPT_CIPHER_AES128_GCM, g_defEalGcm, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_CIPHER_AES192_GCM, g_defEalGcm, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_CIPHER_AES256_GCM, g_defEalGcm, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_XTS
{CRYPT_CIPHER_AES128_XTS, g_defEalXts, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_CIPHER_AES256_XTS, g_defEalXts, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_CFB
{CRYPT_CIPHER_AES128_CFB, g_defEalCfb, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_CIPHER_AES192_CFB, g_defEalCfb, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_CIPHER_AES256_CFB, g_defEalCfb, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_OFB
{CRYPT_CIPHER_AES128_OFB, g_defEalOfb, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_CIPHER_AES192_OFB, g_defEalOfb, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_CIPHER_AES256_OFB, g_defEalOfb, CRYPT_EAL_DEFAULT_ATTR},
#endif
#endif // HITLS_CRYPTO_AES
#if defined(HITLS_CRYPTO_CHACHA20) && defined(HITLS_CRYPTO_CHACHA20POLY1305)
{CRYPT_CIPHER_CHACHA20_POLY1305, g_defEalChaCha, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SM4
#ifdef HITLS_CRYPTO_XTS
{CRYPT_CIPHER_SM4_XTS, g_defEalXts, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_CBC
{CRYPT_CIPHER_SM4_CBC, g_defEalCbc, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_ECB
{CRYPT_CIPHER_SM4_ECB, g_defEalEcb, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_CTR
{CRYPT_CIPHER_SM4_CTR, g_defEalCtr, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_GCM
{CRYPT_CIPHER_SM4_GCM, g_defEalGcm, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_CFB
{CRYPT_CIPHER_SM4_CFB, g_defEalCfb, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_OFB
{CRYPT_CIPHER_SM4_OFB, g_defEalOfb, CRYPT_EAL_DEFAULT_ATTR},
#endif
#endif // HITLS_CRYPTO_SM4
CRYPT_EAL_ALGINFO_END
};
#endif
#ifdef HITLS_CRYPTO_DRBG
static const CRYPT_EAL_AlgInfo g_defEalRands[] = {
#ifdef HITLS_CRYPTO_DRBG_HASH
#ifdef HITLS_CRYPTO_SHA1
{CRYPT_RAND_SHA1, g_defEalRand, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SHA224
{CRYPT_RAND_SHA224, g_defEalRand, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SHA256
{CRYPT_RAND_SHA256, g_defEalRand, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SHA384
{CRYPT_RAND_SHA384, g_defEalRand, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SHA512
{CRYPT_RAND_SHA512, g_defEalRand, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SM3
{CRYPT_RAND_SM3, g_defEalRand, CRYPT_EAL_DEFAULT_ATTR},
#endif
#endif // HITLS_CRYPTO_DRBG_HASH
#ifdef HITLS_CRYPTO_DRBG_HMAC
#ifdef HITLS_CRYPTO_SHA1
{CRYPT_RAND_HMAC_SHA1, g_defEalRand, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SHA224
{CRYPT_RAND_HMAC_SHA224, g_defEalRand, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SHA256
{CRYPT_RAND_HMAC_SHA256, g_defEalRand, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SHA384
{CRYPT_RAND_HMAC_SHA384, g_defEalRand, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SHA512
{CRYPT_RAND_HMAC_SHA512, g_defEalRand, CRYPT_EAL_DEFAULT_ATTR},
#endif
#endif // HITLS_CRYPTO_DRBG_HMAC
#ifdef HITLS_CRYPTO_DRBG_CTR
#ifdef HITLS_CRYPTO_AES
{CRYPT_RAND_AES128_CTR, g_defEalRand, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_RAND_AES192_CTR, g_defEalRand, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_RAND_AES256_CTR, g_defEalRand, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_RAND_AES128_CTR_DF, g_defEalRand, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_RAND_AES192_CTR_DF, g_defEalRand, CRYPT_EAL_DEFAULT_ATTR},
{CRYPT_RAND_AES256_CTR_DF, g_defEalRand, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SM4
{CRYPT_RAND_SM4_CTR_DF, g_defEalRand, CRYPT_EAL_DEFAULT_ATTR},
#endif
#endif // HITLS_CRYPTO_DRBG_CTR
CRYPT_EAL_ALGINFO_END
};
#endif
#ifdef HITLS_CRYPTO_PKEY
static const CRYPT_EAL_AlgInfo g_defEalKeyMgmt[] = {
#ifdef HITLS_CRYPTO_DSA
{CRYPT_PKEY_DSA, g_defEalKeyMgmtDsa, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_ED25519
{CRYPT_PKEY_ED25519, g_defEalKeyMgmtEd25519, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_X25519
{CRYPT_PKEY_X25519, g_defEalKeyMgmtX25519, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_RSA
{CRYPT_PKEY_RSA, g_defEalKeyMgmtRsa, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_DH
{CRYPT_PKEY_DH, g_defEalKeyMgmtDh, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_ECDSA
{CRYPT_PKEY_ECDSA, g_defEalKeyMgmtEcdsa, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_ECDH
{CRYPT_PKEY_ECDH, g_defEalKeyMgmtEcdh, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SM2
{CRYPT_PKEY_SM2, g_defEalKeyMgmtSm2, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_PAILLIER
{CRYPT_PKEY_PAILLIER, g_defEalKeyMgmtPaillier, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_ELGAMAL
{CRYPT_PKEY_ELGAMAL, g_defEalKeyMgmtElGamal, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SLH_DSA
{CRYPT_PKEY_SLH_DSA, g_defEalKeyMgmtSlhDsa, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_MLKEM
{CRYPT_PKEY_ML_KEM, g_defEalKeyMgmtMlKem, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_MLDSA
{CRYPT_PKEY_ML_DSA, g_defEalKeyMgmtMlDsa, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_HYBRIDKEM
{CRYPT_PKEY_HYBRID_KEM, g_defEalKeyMgmtHybridKem, CRYPT_EAL_DEFAULT_ATTR},
#endif
CRYPT_EAL_ALGINFO_END
};
#if (defined(HITLS_CRYPTO_RSA_ENCRYPT) || defined(HITLS_CRYPTO_RSA_DECRYPT) || \
defined(HITLS_CRYPTO_SM2_CRYPT) || defined(HITLS_CRYPTO_PAILLIER) || defined(HITLS_CRYPTO_ELGAMAL)) && \
defined(HITLS_CRYPTO_PROVIDER)
static const CRYPT_EAL_AlgInfo g_defEalAsymCiphers[] = {
#if defined(HITLS_CRYPTO_RSA_ENCRYPT) || defined(HITLS_CRYPTO_RSA_DECRYPT)
{CRYPT_PKEY_RSA, g_defEalAsymCipherRsa, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SM2_CRYPT
{CRYPT_PKEY_SM2, g_defEalAsymCipherSm2, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_PAILLIER
{CRYPT_PKEY_PAILLIER, g_defEalAsymCipherPaillier, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_ELGAMAL
{CRYPT_PKEY_ELGAMAL, g_defEalAsymCipherElGamal, CRYPT_EAL_DEFAULT_ATTR},
#endif
CRYPT_EAL_ALGINFO_END
};
#endif
#if (defined(HITLS_CRYPTO_X25519) || defined(HITLS_CRYPTO_DH) || defined(HITLS_CRYPTO_ECDH) || \
defined(HITLS_CRYPTO_SM2_EXCH)) && defined(HITLS_CRYPTO_PROVIDER)
static const CRYPT_EAL_AlgInfo g_defEalKeyExch[] = {
#ifdef HITLS_CRYPTO_X25519
{CRYPT_PKEY_X25519, g_defEalExchX25519, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_DH
{CRYPT_PKEY_DH, g_defEalExchDh, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_ECDH
{CRYPT_PKEY_ECDH, g_defEalExchEcdh, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SM2_EXCH
{CRYPT_PKEY_SM2, g_defEalExchSm2, CRYPT_EAL_DEFAULT_ATTR},
#endif
CRYPT_EAL_ALGINFO_END
};
#endif
#if (defined(HITLS_CRYPTO_DSA) || defined(HITLS_CRYPTO_ED25519) || defined(HITLS_CRYPTO_RSA_SIGN) || \
defined(HITLS_CRYPTO_RSA_VERIFY) || defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2_SIGN) || \
defined(HITLS_CRYPTO_SLH_DSA) || defined(HITLS_CRYPTO_MLDSA)) && defined(HITLS_CRYPTO_PROVIDER)
static const CRYPT_EAL_AlgInfo g_defEalSigns[] = {
#ifdef HITLS_CRYPTO_DSA
{CRYPT_PKEY_DSA, g_defEalSignDsa, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_ED25519
{CRYPT_PKEY_ED25519, g_defEalSignEd25519, CRYPT_EAL_DEFAULT_ATTR},
#endif
#if defined(HITLS_CRYPTO_RSA_SIGN) || defined(HITLS_CRYPTO_RSA_VERIFY)
{CRYPT_PKEY_RSA, g_defEalSignRsa, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_ECDSA
{CRYPT_PKEY_ECDSA, g_defEalSignEcdsa, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SM2_SIGN
{CRYPT_PKEY_SM2, g_defEalSignSm2, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_SLH_DSA
{CRYPT_PKEY_SLH_DSA, g_defEalSignSlhDsa, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_MLDSA
{CRYPT_PKEY_ML_DSA, g_defEalSignMlDsa, CRYPT_EAL_DEFAULT_ATTR},
#endif
CRYPT_EAL_ALGINFO_END
};
#endif
#if defined(HITLS_CRYPTO_MLKEM) || defined(HITLS_CRYPTO_HYBRIDKEM)
static const CRYPT_EAL_AlgInfo g_defEalKems[] = {
#ifdef HITLS_CRYPTO_MLKEM
{CRYPT_PKEY_ML_KEM, g_defEalMlKem, CRYPT_EAL_DEFAULT_ATTR},
#endif
#ifdef HITLS_CRYPTO_HYBRIDKEM
{CRYPT_PKEY_HYBRID_KEM, g_defEalHybridKeyKem, CRYPT_EAL_DEFAULT_ATTR},
#endif
CRYPT_EAL_ALGINFO_END
};
#endif
#endif
#ifdef HITLS_CRYPTO_CODECSKEY
static const CRYPT_EAL_AlgInfo g_defEalDecoders[] = {
#ifdef HITLS_BSL_PEM
{BSL_CID_DECODE_UNKNOWN, g_defEalPem2Der,
"provider=default, inFormat=PEM, outFormat=ASN1"},
#endif
#ifdef HITLS_CRYPTO_KEY_EPKI
{BSL_CID_DECODE_UNKNOWN, g_defEalPrvP8Enc2P8,
"provider=default, inFormat=ASN1, inType=PRIKEY_PKCS8_ENCRYPT, outFormat=ASN1, outType=PRIKEY_PKCS8_UNENCRYPT"},
#endif
#ifdef HITLS_CRYPTO_RSA
{CRYPT_PKEY_RSA, g_defEalRsaPrvDer2Key,
"provider=default, inFormat=ASN1, inType=PRIKEY_RSA, outFormat=OBJECT, outType=LOW_KEY"},
{CRYPT_PKEY_RSA, g_defEalRsaPubDer2Key,
"provider=default, inFormat=ASN1, inType=PUBKEY_RSA, outFormat=OBJECT, outType=LOW_KEY"},
#endif
#ifdef HITLS_CRYPTO_ECDSA
{CRYPT_PKEY_ECDSA, g_defEalEcdsaPrvDer2Key,
"provider=default, inFormat=ASN1, inType=PRIKEY_ECC, outFormat=OBJECT, outType=LOW_KEY"},
#endif
#ifdef HITLS_CRYPTO_SM2
{CRYPT_PKEY_SM2, g_defEalSm2PrvDer2Key,
"provider=default, inFormat=ASN1, inType=PRIKEY_ECC, outFormat=OBJECT, outType=LOW_KEY"},
#endif
#ifdef HITLS_CRYPTO_RSA
{CRYPT_PKEY_RSA, g_defEalP8Der2RsaKey,
"provider=default, inFormat=ASN1, inType=PRIKEY_PKCS8_UNENCRYPT, outFormat=OBJECT, outType=LOW_KEY"},
#endif
#ifdef HITLS_CRYPTO_ECDSA
{CRYPT_PKEY_ECDSA, g_defEalP8Der2EcdsaKey,
"provider=default, inFormat=ASN1, inType=PRIKEY_PKCS8_UNENCRYPT, outFormat=OBJECT, outType=LOW_KEY"},
#endif
#ifdef HITLS_CRYPTO_SM2
{CRYPT_PKEY_SM2, g_defEalP8Der2Sm2Key,
"provider=default, inFormat=ASN1, inType=PRIKEY_PKCS8_UNENCRYPT, outFormat=OBJECT, outType=LOW_KEY"},
#endif
#ifdef HITLS_CRYPTO_ED25519
{CRYPT_PKEY_ED25519, g_defEalP8Der2Ed25519Key,
"provider=default, inFormat=ASN1, inType=PRIKEY_PKCS8_UNENCRYPT, outFormat=OBJECT, outType=LOW_KEY"},
#endif
#ifdef HITLS_CRYPTO_RSA
{CRYPT_PKEY_RSA, g_defEalSubPubKeyDer2RsaKey,
"provider=default, inFormat=ASN1, inType=PUBKEY_SUBKEY, outFormat=OBJECT, outType=LOW_KEY"},
#endif
#ifdef HITLS_CRYPTO_ECDSA
{CRYPT_PKEY_ECDSA, g_defEalSubPubKeyDer2EcdsaKey,
"provider=default, inFormat=ASN1, inType=PUBKEY_SUBKEY, outFormat=OBJECT, outType=LOW_KEY"},
#endif
#ifdef HITLS_CRYPTO_SM2
{CRYPT_PKEY_SM2, g_defEalSubPubKeyDer2Sm2Key,
"provider=default, inFormat=ASN1, inType=PUBKEY_SUBKEY, outFormat=OBJECT, outType=LOW_KEY"},
#endif
#ifdef HITLS_CRYPTO_ED25519
{CRYPT_PKEY_ED25519, g_defEalSubPubKeyDer2Ed25519Key,
"provider=default, inFormat=ASN1, inType=PUBKEY_SUBKEY, outFormat=OBJECT, outType=LOW_KEY"},
#endif
#ifdef HITLS_CRYPTO_RSA
{CRYPT_PKEY_RSA, g_defEalSubPubKeyWithoutSeqDer2RsaKey,
"provider=default, inFormat=ASN1, inType=PUBKEY_SUBKEY_WITHOUT_SEQ, outFormat=OBJECT, outType=LOW_KEY"},
#endif
#ifdef HITLS_CRYPTO_ECDSA
{CRYPT_PKEY_ECDSA, g_defEalSubPubKeyWithoutSeqDer2EcdsaKey,
"provider=default, inFormat=ASN1, inType=PUBKEY_SUBKEY_WITHOUT_SEQ, outFormat=OBJECT, outType=LOW_KEY"},
#endif
#ifdef HITLS_CRYPTO_SM2
{CRYPT_PKEY_SM2, g_defEalSubPubKeyWithoutSeqDer2Sm2Key,
"provider=default, inFormat=ASN1, inType=PUBKEY_SUBKEY_WITHOUT_SEQ, outFormat=OBJECT, outType=LOW_KEY"},
#endif
#ifdef HITLS_CRYPTO_ED25519
{CRYPT_PKEY_ED25519, g_defEalSubPubKeyWithoutSeqDer2Ed25519Key,
"provider=default, inFormat=ASN1, inType=PUBKEY_SUBKEY_WITHOUT_SEQ, outFormat=OBJECT, outType=LOW_KEY"},
#endif
{BSL_CID_DECODE_UNKNOWN, g_defEalLowKeyObject2PkeyObject,
"provider=default, inFormat=OBJECT, inType=LOW_KEY, outFormat=OBJECT, outType=HIGH_KEY"},
CRYPT_EAL_ALGINFO_END
};
#endif
static int32_t CRYPT_EAL_DefaultProvQuery(void *provCtx, int32_t operaId, const CRYPT_EAL_AlgInfo **algInfos)
{
(void)provCtx;
int32_t ret = CRYPT_SUCCESS;
switch (operaId) {
#ifdef HITLS_CRYPTO_CIPHER
case CRYPT_EAL_OPERAID_SYMMCIPHER:
*algInfos = g_defEalCiphers;
break;
#endif
#ifdef HITLS_CRYPTO_PKEY
case CRYPT_EAL_OPERAID_KEYMGMT:
*algInfos = g_defEalKeyMgmt;
break;
#if (defined(HITLS_CRYPTO_DSA) || defined(HITLS_CRYPTO_ED25519) || defined(HITLS_CRYPTO_RSA_SIGN) || \
defined(HITLS_CRYPTO_RSA_VERIFY) || defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2_SIGN) || \
defined(HITLS_CRYPTO_SLH_DSA) || defined(HITLS_CRYPTO_MLDSA)) && defined(HITLS_CRYPTO_PROVIDER)
case CRYPT_EAL_OPERAID_SIGN:
*algInfos = g_defEalSigns;
break;
#endif
#if (defined(HITLS_CRYPTO_RSA_ENCRYPT) || defined(HITLS_CRYPTO_RSA_DECRYPT) || \
defined(HITLS_CRYPTO_SM2_CRYPT) || defined(HITLS_CRYPTO_PAILLIER) || defined(HITLS_CRYPTO_ELGAMAL)) && \
defined(HITLS_CRYPTO_PROVIDER)
case CRYPT_EAL_OPERAID_ASYMCIPHER:
*algInfos = g_defEalAsymCiphers;
break;
#endif
#if (defined(HITLS_CRYPTO_X25519) || defined(HITLS_CRYPTO_DH) || defined(HITLS_CRYPTO_ECDH) || \
defined(HITLS_CRYPTO_SM2_EXCH)) && defined(HITLS_CRYPTO_PROVIDER)
case CRYPT_EAL_OPERAID_KEYEXCH:
*algInfos = g_defEalKeyExch;
break;
#endif
#if defined(HITLS_CRYPTO_MLKEM) || defined(HITLS_CRYPTO_HYBRIDKEM)
case CRYPT_EAL_OPERAID_KEM:
*algInfos = g_defEalKems;
break;
#endif
#endif
#ifdef HITLS_CRYPTO_MD
case CRYPT_EAL_OPERAID_HASH:
*algInfos = g_defEalMds;
break;
#endif
#ifdef HITLS_CRYPTO_MAC
case CRYPT_EAL_OPERAID_MAC:
*algInfos = g_defEalMacs;
break;
#endif
#ifdef HITLS_CRYPTO_KDF
case CRYPT_EAL_OPERAID_KDF:
*algInfos = g_defEalKdfs;
break;
#endif
#ifdef HITLS_CRYPTO_DRBG
case CRYPT_EAL_OPERAID_RAND:
*algInfos = g_defEalRands;
break;
#endif
#ifdef HITLS_CRYPTO_CODECSKEY
case CRYPT_EAL_OPERAID_DECODER:
*algInfos = g_defEalDecoders;
break;
#endif
default:
ret = CRYPT_NOT_SUPPORT;
break;
}
return ret;
}
static void CRYPT_EAL_DefaultProvFree(void *provCtx)
{
BSL_SAL_Free(provCtx);
}
#ifdef HITLS_TLS_FEATURE_PROVIDER
#define TLS_GROUP_PARAM_COUNT 11
#define TLS_SIGN_SCHEME_PARAM_COUNT 18
typedef struct {
const char *name; // group name
int32_t paraId; // parameter id CRYPT_PKEY_ParaId
int32_t algId; // algorithm id CRYPT_PKEY_AlgId
int32_t secBits; // security bits
uint16_t groupId; // iana group id, HITLS_NamedGroup
uint32_t pubkeyLen; // public key length(CH keyshare / SH keyshare)
uint32_t sharedkeyLen; // shared key length
uint32_t ciphertextLen; // ciphertext length(SH keyshare)
uint32_t versionBits; // TLS_VERSION_MASK
bool isKem; // true: KEM, false: KEX
} TLS_GroupInfo;
static const TLS_GroupInfo g_tlsGroupInfo[] = {
{
"x25519",
CRYPT_PKEY_PARAID_MAX,
CRYPT_PKEY_X25519,
128, // secBits
HITLS_EC_GROUP_CURVE25519, // groupId
32, 32, 0, // pubkeyLen=32, sharedkeyLen=32 (256 bits)
TLS_VERSION_MASK | DTLS_VERSION_MASK, // versionBits
false,
},
#ifdef HITLS_TLS_FEATURE_KEM
{
"X25519MLKEM768",
CRYPT_HYBRID_X25519_MLKEM768,
CRYPT_PKEY_HYBRID_KEM,
192, // secBits
HITLS_HYBRID_X25519_MLKEM768, // groupId
1184 + 32, 32 + 32, 1088 + 32, // pubkeyLen=1216, sharedkeyLen=64, ciphertextLen=1120
TLS13_VERSION_BIT, // versionBits
true,
},
{
"SecP256r1MLKEM768",
CRYPT_HYBRID_ECDH_NISTP256_MLKEM768,
CRYPT_PKEY_HYBRID_KEM,
192, // secBits
HITLS_HYBRID_ECDH_NISTP256_MLKEM768, // groupId
1184 + 65, 32 + 32, 1088 + 65, // pubkeyLen=1249, sharedkeyLen=64, ciphertextLen=1153
TLS13_VERSION_BIT, // versionBits
true,
},
{
"SecP384r1MLKEM1024",
CRYPT_HYBRID_ECDH_NISTP384_MLKEM1024,
CRYPT_PKEY_HYBRID_KEM,
256, // secBits
HITLS_HYBRID_ECDH_NISTP384_MLKEM1024, // groupId
1568 + 97, 32 + 48, 1568 + 97, // pubkeyLen=1665, sharedkeyLen=80, ciphertextLen=1665
TLS13_VERSION_BIT, // versionBits
true,
},
#endif /* HITLS_TLS_FEATURE_KEM */
{
"secp256r1",
CRYPT_ECC_NISTP256, // CRYPT_ECC_NISTP256
CRYPT_PKEY_ECDH, // CRYPT_PKEY_ECDH
128, // secBits
HITLS_EC_GROUP_SECP256R1, // groupId
65, 32, 0, // pubkeyLen=65, sharedkeyLen=32 (256 bits)
TLS_VERSION_MASK | DTLS_VERSION_MASK, // versionBits
false,
},
{
"secp384r1",
CRYPT_ECC_NISTP384, // CRYPT_ECC_NISTP384
CRYPT_PKEY_ECDH, // CRYPT_PKEY_ECDH
192, // secBits
HITLS_EC_GROUP_SECP384R1, // groupId
97, 48, 0, // pubkeyLen=97, sharedkeyLen=48 (384 bits)
TLS_VERSION_MASK | DTLS_VERSION_MASK, // versionBits
false,
},
{
"secp521r1",
CRYPT_ECC_NISTP521, // CRYPT_ECC_NISTP521
CRYPT_PKEY_ECDH, // CRYPT_PKEY_ECDH
256, // secBits
HITLS_EC_GROUP_SECP521R1, // groupId
133, 66, 0, // pubkeyLen=133, sharedkeyLen=66 (521 bits)
TLS_VERSION_MASK | DTLS_VERSION_MASK, // versionBits
false,
},
{
"brainpoolP256r1",
CRYPT_ECC_BRAINPOOLP256R1, // CRYPT_ECC_BRAINPOOLP256R1
CRYPT_PKEY_ECDH, // CRYPT_PKEY_ECDH
128, // secBits
HITLS_EC_GROUP_BRAINPOOLP256R1, // groupId
65, 32, 0, // pubkeyLen=65, sharedkeyLen=32 (256 bits)
TLS10_VERSION_BIT | TLS11_VERSION_BIT | TLS12_VERSION_BIT | DTLS_VERSION_MASK, // versionBits
false,
},
{
"brainpoolP384r1",
CRYPT_ECC_BRAINPOOLP384R1, // CRYPT_ECC_BRAINPOOLP384R1
CRYPT_PKEY_ECDH, // CRYPT_PKEY_ECDH
192, // secBits
HITLS_EC_GROUP_BRAINPOOLP384R1, // groupId
97, 48, 0, // pubkeyLen=97, sharedkeyLen=48 (384 bits)
TLS10_VERSION_BIT | TLS11_VERSION_BIT | TLS12_VERSION_BIT | DTLS_VERSION_MASK, // versionBits
false,
},
{
"brainpoolP512r1",
CRYPT_ECC_BRAINPOOLP512R1, // CRYPT_ECC_BRAINPOOLP512R1
CRYPT_PKEY_ECDH, // CRYPT_PKEY_ECDH
256, // secBits
HITLS_EC_GROUP_BRAINPOOLP512R1, // groupId
129, 64, 0, // pubkeyLen=129, sharedkeyLen=64 (512 bits)
TLS10_VERSION_BIT | TLS11_VERSION_BIT | TLS12_VERSION_BIT | DTLS_VERSION_MASK, // versionBits
false,
},
{
"sm2",
CRYPT_PKEY_PARAID_MAX, // CRYPT_PKEY_PARAID_MAX
CRYPT_PKEY_SM2, // CRYPT_PKEY_SM2
128, // secBits
HITLS_EC_GROUP_SM2, // groupId
65, 32, 0, // pubkeyLen=65, sharedkeyLen=32 (256 bits)
TLCP11_VERSION_BIT | DTLCP11_VERSION_BIT, // versionBits
false,
},
{
"ffdhe8192",
CRYPT_DH_RFC7919_8192, // CRYPT_DH_8192
CRYPT_PKEY_DH, // CRYPT_PKEY_DH
192, // secBits
HITLS_FF_DHE_8192, // groupId
1024, 1024, 0, // pubkeyLen=1024, sharedkeyLen=1024 (8192 bits)
TLS13_VERSION_BIT, // versionBits
false,
},
{
"ffdhe6144",
CRYPT_DH_RFC7919_6144, // CRYPT_DH_6144
CRYPT_PKEY_DH, // CRYPT_PKEY_DH
128, // secBits
HITLS_FF_DHE_6144, // groupId
768, 768, 0, // pubkeyLen=768, sharedkeyLen=768 (6144 bits)
TLS13_VERSION_BIT, // versionBits
false,
},
{
"ffdhe4096",
CRYPT_DH_RFC7919_4096, // CRYPT_DH_4096
CRYPT_PKEY_DH, // CRYPT_PKEY_DH
128, // secBits
HITLS_FF_DHE_4096, // groupId
512, 512, 0, // pubkeyLen=512, sharedkeyLen=512 (4096 bits)
TLS13_VERSION_BIT, // versionBits
false,
},
{
"ffdhe3072",
CRYPT_DH_RFC7919_3072, // Fixed constant name
CRYPT_PKEY_DH,
128,
HITLS_FF_DHE_3072,
384, 384, 0, // pubkeyLen=384, sharedkeyLen=384 (3072 bits)
TLS13_VERSION_BIT,
false,
},
{
"ffdhe2048",
CRYPT_DH_RFC7919_2048, // CRYPT_DH_2048
CRYPT_PKEY_DH, // CRYPT_PKEY_DH
112, // secBits
HITLS_FF_DHE_2048, // groupId
256, 256, 0, // pubkeyLen=256, sharedkeyLen=256 (2048 bits)
TLS13_VERSION_BIT, // versionBits
false,
}
};
static int32_t BuildTlsGroupParam(const TLS_GroupInfo *groupInfo, BSL_Param *param)
{
int32_t ret = 0;
RETURN_RET_IF_ERR_EX(BSL_PARAM_InitValue(¶m[0], CRYPT_PARAM_CAP_TLS_GROUP_IANA_GROUP_NAME,
BSL_PARAM_TYPE_OCTETS_PTR, (void *)(uintptr_t)groupInfo->name, (uint32_t)strlen(groupInfo->name)), ret);
RETURN_RET_IF_ERR_EX(BSL_PARAM_InitValue(¶m[1], CRYPT_PARAM_CAP_TLS_GROUP_IANA_GROUP_ID, BSL_PARAM_TYPE_UINT16,
(void *)(uintptr_t)&(groupInfo->groupId), sizeof(groupInfo->groupId)), ret);
RETURN_RET_IF_ERR_EX(BSL_PARAM_InitValue(¶m[2], CRYPT_PARAM_CAP_TLS_GROUP_PARA_ID, BSL_PARAM_TYPE_INT32,
(void *)(uintptr_t)&(groupInfo->paraId), sizeof(groupInfo->paraId)), ret);
RETURN_RET_IF_ERR_EX(BSL_PARAM_InitValue(¶m[3], CRYPT_PARAM_CAP_TLS_GROUP_ALG_ID, BSL_PARAM_TYPE_INT32,
(void *)(uintptr_t)&(groupInfo->algId), sizeof(groupInfo->algId)), ret);
RETURN_RET_IF_ERR_EX(BSL_PARAM_InitValue(¶m[4], CRYPT_PARAM_CAP_TLS_GROUP_SEC_BITS, BSL_PARAM_TYPE_INT32,
(void *)(uintptr_t)&(groupInfo->secBits), sizeof(groupInfo->secBits)), ret);
RETURN_RET_IF_ERR_EX(BSL_PARAM_InitValue(¶m[5], CRYPT_PARAM_CAP_TLS_GROUP_VERSION_BITS, BSL_PARAM_TYPE_UINT32,
(void *)(uintptr_t)&(groupInfo->versionBits), sizeof(groupInfo->versionBits)), ret);
RETURN_RET_IF_ERR_EX(BSL_PARAM_InitValue(¶m[6], CRYPT_PARAM_CAP_TLS_GROUP_IS_KEM, BSL_PARAM_TYPE_BOOL,
(void *)(uintptr_t)&(groupInfo->isKem), sizeof(groupInfo->isKem)), ret);
RETURN_RET_IF_ERR_EX(BSL_PARAM_InitValue(¶m[7], CRYPT_PARAM_CAP_TLS_GROUP_PUBKEY_LEN, BSL_PARAM_TYPE_INT32,
(void *)(uintptr_t)&(groupInfo->pubkeyLen), sizeof(groupInfo->pubkeyLen)), ret);
RETURN_RET_IF_ERR_EX(BSL_PARAM_InitValue(¶m[8], CRYPT_PARAM_CAP_TLS_GROUP_SHAREDKEY_LEN, BSL_PARAM_TYPE_INT32,
(void *)(uintptr_t)&(groupInfo->sharedkeyLen), sizeof(groupInfo->sharedkeyLen)), ret);
RETURN_RET_IF_ERR_EX(BSL_PARAM_InitValue(¶m[9], CRYPT_PARAM_CAP_TLS_GROUP_CIPHERTEXT_LEN, BSL_PARAM_TYPE_INT32,
(void *)(uintptr_t)&(groupInfo->ciphertextLen), sizeof(groupInfo->ciphertextLen)), ret);
return ret;
}
static int32_t CryptGetGroupCaps(CRYPT_EAL_ProcessFuncCb cb, void *args)
{
for (size_t i = 0; i < sizeof(g_tlsGroupInfo) / sizeof(g_tlsGroupInfo[0]); i++) {
BSL_Param param[TLS_GROUP_PARAM_COUNT] = {0};
int32_t ret = BuildTlsGroupParam(&g_tlsGroupInfo[i], param);
if (ret != BSL_SUCCESS) {
return ret;
}
ret = cb(param, args);
if (ret != CRYPT_SUCCESS) {
return ret;
}
}
return CRYPT_SUCCESS;
}
typedef struct {
const char *name; // name
uint16_t signatureScheme; // HITLS_SignHashAlgo, IANA specified
int32_t keyType; // HITLS_CERT_KeyType
int32_t paraId; // CRYPT_PKEY_ParaId
int32_t signHashAlgId; // combined sign hash algorithm id
int32_t signAlgId; // CRYPT_PKEY_AlgId
int32_t hashAlgId; // CRYPT_MD_AlgId
int32_t secBits; // security bits
uint32_t certVersionBits; // TLS_VERSION_MASK
uint32_t chainVersionBits; // TLS_VERSION_MASK
} TLS_SigSchemeInfo;
static const TLS_SigSchemeInfo g_signSchemeInfo[] = {
{
"ecdsa_secp521r1_sha512",
CERT_SIG_SCHEME_ECDSA_SECP521R1_SHA512,
TLS_CERT_KEY_TYPE_ECDSA,
CRYPT_ECC_NISTP521,
BSL_CID_ECDSAWITHSHA512,
HITLS_SIGN_ECDSA,
HITLS_HASH_SHA_512,
256,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
},
{
"ecdsa_secp384r1_sha384",
CERT_SIG_SCHEME_ECDSA_SECP384R1_SHA384,
TLS_CERT_KEY_TYPE_ECDSA,
CRYPT_ECC_NISTP384,
BSL_CID_ECDSAWITHSHA384,
HITLS_SIGN_ECDSA,
HITLS_HASH_SHA_384,
192,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
},
{
"ed25519",
CERT_SIG_SCHEME_ED25519,
TLS_CERT_KEY_TYPE_ED25519,
CRYPT_PKEY_PARAID_MAX,
BSL_CID_ED25519,
HITLS_SIGN_ED25519,
HITLS_HASH_SHA_512,
128,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
},
{
"ecdsa_secp256r1_sha256",
CERT_SIG_SCHEME_ECDSA_SECP256R1_SHA256,
TLS_CERT_KEY_TYPE_ECDSA,
CRYPT_ECC_NISTP256,
BSL_CID_ECDSAWITHSHA256,
HITLS_SIGN_ECDSA,
HITLS_HASH_SHA_256,
128,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
},
{
"sm2_sm3",
CERT_SIG_SCHEME_SM2_SM3,
TLS_CERT_KEY_TYPE_SM2,
CRYPT_PKEY_PARAID_MAX,
BSL_CID_SM2DSAWITHSM3,
HITLS_SIGN_SM2,
HITLS_HASH_SM3,
128,
TLCP11_VERSION_BIT | DTLCP11_VERSION_BIT,
TLCP11_VERSION_BIT | DTLCP11_VERSION_BIT,
},
{
"rsa_pss_pss_sha512",
CERT_SIG_SCHEME_RSA_PSS_PSS_SHA512,
TLS_CERT_KEY_TYPE_RSA_PSS,
CRYPT_PKEY_PARAID_MAX,
BSL_CID_RSASSAPSS,
HITLS_SIGN_RSA_PSS,
HITLS_HASH_SHA_512,
256,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
},
{
"rsa_pss_pss_sha384",
CERT_SIG_SCHEME_RSA_PSS_PSS_SHA384,
TLS_CERT_KEY_TYPE_RSA_PSS,
CRYPT_PKEY_PARAID_MAX,
BSL_CID_RSASSAPSS,
HITLS_SIGN_RSA_PSS,
HITLS_HASH_SHA_384,
192,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
},
{
"rsa_pss_pss_sha256",
CERT_SIG_SCHEME_RSA_PSS_PSS_SHA256,
TLS_CERT_KEY_TYPE_RSA_PSS,
CRYPT_PKEY_PARAID_MAX,
BSL_CID_RSASSAPSS,
HITLS_SIGN_RSA_PSS,
HITLS_HASH_SHA_256,
128,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
},
{
"rsa_pss_rsae_sha512",
CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA512,
TLS_CERT_KEY_TYPE_RSA,
CRYPT_PKEY_PARAID_MAX,
BSL_CID_RSASSAPSS,
HITLS_SIGN_RSA_PSS,
HITLS_HASH_SHA_512,
256,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
},
{
"rsa_pss_rsae_sha384",
CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA384,
TLS_CERT_KEY_TYPE_RSA,
CRYPT_PKEY_PARAID_MAX,
BSL_CID_RSASSAPSS,
HITLS_SIGN_RSA_PSS,
HITLS_HASH_SHA_384,
192,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
},
{
"rsa_pss_rsae_sha256",
CERT_SIG_SCHEME_RSA_PSS_RSAE_SHA256,
TLS_CERT_KEY_TYPE_RSA,
CRYPT_PKEY_PARAID_MAX,
BSL_CID_RSASSAPSS,
HITLS_SIGN_RSA_PSS,
HITLS_HASH_SHA_256,
128,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
},
{
"rsa_pkcs1_sha512",
CERT_SIG_SCHEME_RSA_PKCS1_SHA512,
TLS_CERT_KEY_TYPE_RSA,
CRYPT_PKEY_PARAID_MAX,
BSL_CID_SHA512WITHRSAENCRYPTION,
HITLS_SIGN_RSA_PKCS1_V15,
HITLS_HASH_SHA_512,
256,
TLS12_VERSION_BIT | DTLS12_VERSION_BIT,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
},
{
"dsa_sha512",
CERT_SIG_SCHEME_DSA_SHA512,
TLS_CERT_KEY_TYPE_DSA,
CRYPT_PKEY_PARAID_MAX,
BSL_CID_DSAWITHSHA512,
HITLS_SIGN_DSA,
HITLS_HASH_SHA_512,
256,
TLS12_VERSION_BIT | DTLS12_VERSION_BIT,
TLS12_VERSION_BIT | DTLS12_VERSION_BIT,
},
{
"rsa_pkcs1_sha384",
CERT_SIG_SCHEME_RSA_PKCS1_SHA384,
TLS_CERT_KEY_TYPE_RSA,
CRYPT_PKEY_PARAID_MAX,
BSL_CID_SHA384WITHRSAENCRYPTION,
HITLS_SIGN_RSA_PKCS1_V15,
HITLS_HASH_SHA_384,
192,
TLS12_VERSION_BIT | DTLS12_VERSION_BIT,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
},
{
"dsa_sha384",
CERT_SIG_SCHEME_DSA_SHA384,
TLS_CERT_KEY_TYPE_DSA,
CRYPT_PKEY_PARAID_MAX,
BSL_CID_DSAWITHSHA384,
HITLS_SIGN_DSA,
HITLS_HASH_SHA_384,
192,
TLS12_VERSION_BIT | DTLS12_VERSION_BIT,
TLS12_VERSION_BIT | DTLS12_VERSION_BIT,
},
{
"rsa_pkcs1_sha256",
CERT_SIG_SCHEME_RSA_PKCS1_SHA256,
TLS_CERT_KEY_TYPE_RSA,
CRYPT_PKEY_PARAID_MAX,
BSL_CID_SHA256WITHRSAENCRYPTION,
HITLS_SIGN_RSA_PKCS1_V15,
HITLS_HASH_SHA_256,
128,
TLS12_VERSION_BIT | DTLS12_VERSION_BIT,
TLS_VERSION_MASK | DTLS_VERSION_MASK,
},
{
"dsa_sha256",
CERT_SIG_SCHEME_DSA_SHA256,
TLS_CERT_KEY_TYPE_DSA,
CRYPT_PKEY_PARAID_MAX,
BSL_CID_DSAWITHSHA256,
HITLS_SIGN_DSA,
HITLS_HASH_SHA_256,
128,
TLS12_VERSION_BIT | DTLS12_VERSION_BIT,
TLS12_VERSION_BIT | DTLS12_VERSION_BIT,
},
{
"ecdsa_sha224",
CERT_SIG_SCHEME_ECDSA_SHA224,
TLS_CERT_KEY_TYPE_ECDSA,
CRYPT_PKEY_PARAID_MAX,
BSL_CID_ECDSAWITHSHA224,
HITLS_SIGN_ECDSA,
HITLS_HASH_SHA_224,
112,
TLS12_VERSION_BIT | DTLS12_VERSION_BIT,
TLS12_VERSION_BIT | DTLS12_VERSION_BIT,
},
{
"rsa_pkcs1_sha224",
CERT_SIG_SCHEME_RSA_PKCS1_SHA224,
TLS_CERT_KEY_TYPE_RSA,
CRYPT_PKEY_PARAID_MAX,
BSL_CID_SHA224WITHRSAENCRYPTION,
HITLS_SIGN_RSA_PKCS1_V15,
HITLS_HASH_SHA_224,
112,
TLS12_VERSION_BIT | DTLS12_VERSION_BIT,
TLS12_VERSION_BIT | DTLS12_VERSION_BIT,
},
{
"dsa_sha224",
CERT_SIG_SCHEME_DSA_SHA224,
TLS_CERT_KEY_TYPE_DSA,
CRYPT_PKEY_PARAID_MAX,
BSL_CID_DSAWITHSHA224,
HITLS_SIGN_DSA,
HITLS_HASH_SHA_224,
112,
TLS12_VERSION_BIT | DTLS12_VERSION_BIT,
TLS12_VERSION_BIT | DTLS12_VERSION_BIT,
},
{
"ecdsa_sha1",
CERT_SIG_SCHEME_ECDSA_SHA1,
TLS_CERT_KEY_TYPE_ECDSA,
CRYPT_PKEY_PARAID_MAX,
BSL_CID_ECDSAWITHSHA1,
HITLS_SIGN_ECDSA,
HITLS_HASH_SHA1,
-1,
TLS12_VERSION_BIT | DTLS12_VERSION_BIT,
TLS12_VERSION_BIT | DTLS12_VERSION_BIT,
},
{
"rsa_pkcs1_sha1",
CERT_SIG_SCHEME_RSA_PKCS1_SHA1,
TLS_CERT_KEY_TYPE_RSA,
CRYPT_PKEY_PARAID_MAX,
BSL_CID_SHA1WITHRSA,
HITLS_SIGN_RSA_PKCS1_V15,
HITLS_HASH_SHA1,
-1,
TLS12_VERSION_BIT | DTLS12_VERSION_BIT,
TLS12_VERSION_BIT | DTLS12_VERSION_BIT,
},
{
"dsa_sha1",
CERT_SIG_SCHEME_DSA_SHA1,
TLS_CERT_KEY_TYPE_DSA,
CRYPT_PKEY_PARAID_MAX,
BSL_CID_DSAWITHSHA1,
HITLS_SIGN_DSA,
HITLS_HASH_SHA1,
-1,
TLS12_VERSION_BIT | DTLS12_VERSION_BIT,
TLS12_VERSION_BIT | DTLS12_VERSION_BIT,
},
};
static int32_t BuildTlsSigAlgParam(const TLS_SigSchemeInfo *sigSchemeInfo, BSL_Param *param)
{
int32_t ret = 0;
RETURN_RET_IF_ERR_EX(BSL_PARAM_InitValue(¶m[0], CRYPT_PARAM_CAP_TLS_SIGNALG_IANA_SIGN_NAME,
BSL_PARAM_TYPE_OCTETS_PTR, (void *)(uintptr_t)sigSchemeInfo->name, (uint32_t)strlen(sigSchemeInfo->name)), ret);
RETURN_RET_IF_ERR_EX(BSL_PARAM_InitValue(¶m[1], CRYPT_PARAM_CAP_TLS_SIGNALG_IANA_SIGN_ID, BSL_PARAM_TYPE_UINT16,
(void *)(uintptr_t)&(sigSchemeInfo->signatureScheme), sizeof(sigSchemeInfo->signatureScheme)), ret);
RETURN_RET_IF_ERR_EX(BSL_PARAM_InitValue(¶m[2], CRYPT_PARAM_CAP_TLS_SIGNALG_KEY_TYPE, BSL_PARAM_TYPE_INT32,
(void *)(uintptr_t)&(sigSchemeInfo->keyType), sizeof(sigSchemeInfo->keyType)), ret);
RETURN_RET_IF_ERR_EX(BSL_PARAM_InitValue(¶m[3], CRYPT_PARAM_CAP_TLS_SIGNALG_PARA_ID, BSL_PARAM_TYPE_INT32,
(void *)(uintptr_t)&(sigSchemeInfo->paraId), sizeof(sigSchemeInfo->paraId)), ret);
RETURN_RET_IF_ERR_EX(BSL_PARAM_InitValue(¶m[4], CRYPT_PARAM_CAP_TLS_SIGNALG_SIGNWITHMD_ID, BSL_PARAM_TYPE_INT32,
(void *)(uintptr_t)&(sigSchemeInfo->signHashAlgId), sizeof(sigSchemeInfo->signHashAlgId)), ret);
RETURN_RET_IF_ERR_EX(BSL_PARAM_InitValue(¶m[5], CRYPT_PARAM_CAP_TLS_SIGNALG_SIGN_ID, BSL_PARAM_TYPE_INT32,
(void *)(uintptr_t)&(sigSchemeInfo->signAlgId), sizeof(sigSchemeInfo->signAlgId)), ret);
RETURN_RET_IF_ERR_EX(BSL_PARAM_InitValue(¶m[6], CRYPT_PARAM_CAP_TLS_SIGNALG_MD_ID, BSL_PARAM_TYPE_INT32,
(void *)(uintptr_t)&(sigSchemeInfo->hashAlgId), sizeof(sigSchemeInfo->hashAlgId)), ret);
RETURN_RET_IF_ERR_EX(BSL_PARAM_InitValue(¶m[7], CRYPT_PARAM_CAP_TLS_SIGNALG_SEC_BITS, BSL_PARAM_TYPE_INT32,
(void *)(uintptr_t)&(sigSchemeInfo->secBits), sizeof(sigSchemeInfo->secBits)), ret);
RETURN_RET_IF_ERR_EX(BSL_PARAM_InitValue(¶m[8], CRYPT_PARAM_CAP_TLS_SIGNALG_CERT_VERSION_BITS,
BSL_PARAM_TYPE_UINT32, (void *)(uintptr_t)&(sigSchemeInfo->certVersionBits),
sizeof(sigSchemeInfo->certVersionBits)), ret);
RETURN_RET_IF_ERR_EX(BSL_PARAM_InitValue(¶m[9], CRYPT_PARAM_CAP_TLS_SIGNALG_CHAIN_VERSION_BITS,
BSL_PARAM_TYPE_UINT32, (void *)(uintptr_t)&(sigSchemeInfo->chainVersionBits),
sizeof(sigSchemeInfo->chainVersionBits)), ret);
return ret;
}
static int32_t CryptGetSignAlgCaps(CRYPT_EAL_ProcessFuncCb cb, void *args)
{
for (size_t i = 0; i < sizeof(g_signSchemeInfo) / sizeof(g_signSchemeInfo[0]); i++) {
BSL_Param param[TLS_SIGN_SCHEME_PARAM_COUNT] = {0};
int32_t ret = BuildTlsSigAlgParam(&g_signSchemeInfo[i], param);
if (ret != BSL_SUCCESS) {
return ret;
}
ret = cb(param, args);
if (ret != CRYPT_SUCCESS) {
return ret;
}
}
return CRYPT_SUCCESS;
}
static int32_t CRYPT_EAL_DefaultProvGetCaps(void *provCtx, int32_t cmd, CRYPT_EAL_ProcessFuncCb cb, void *args)
{
(void)provCtx;
if (cb == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
switch (cmd) {
case CRYPT_EAL_GET_GROUP_CAP:
return CryptGetGroupCaps(cb, args);
case CRYPT_EAL_GET_SIGALG_CAP:
return CryptGetSignAlgCaps(cb, args);
default:
BSL_ERR_PUSH_ERROR(CRYPT_NOT_SUPPORT);
return CRYPT_NOT_SUPPORT;
}
}
#endif
static CRYPT_EAL_Func g_defEalProvOutFuncs[] = {
{CRYPT_EAL_PROVCB_QUERY, CRYPT_EAL_DefaultProvQuery},
{CRYPT_EAL_PROVCB_FREE, CRYPT_EAL_DefaultProvFree},
{CRYPT_EAL_PROVCB_CTRL, NULL},
#ifdef HITLS_TLS_FEATURE_PROVIDER
{CRYPT_EAL_PROVCB_GETCAPS, CRYPT_EAL_DefaultProvGetCaps},
#endif
CRYPT_EAL_FUNC_END
};
#ifdef HITLS_CRYPTO_ENTROPY
static void *g_providerSeedCtx = NULL;
static CRYPT_RandSeedMethod g_providerSeedMethod = {0};
int32_t CRYPT_EAL_ProviderGetSeed(CRYPT_RandSeedMethod **method, void **seedCtx)
{
if (method == NULL || seedCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
*method = &g_providerSeedMethod;
*seedCtx = g_providerSeedCtx;
return CRYPT_SUCCESS;
}
#endif
int32_t CRYPT_EAL_DefaultProvInit(CRYPT_EAL_ProvMgrCtx *mgrCtx, BSL_Param *param,
CRYPT_EAL_Func *capFuncs, CRYPT_EAL_Func **outFuncs, void **provCtx)
{
(void)param;
void *libCtx = NULL;
CRYPT_EAL_ProvMgrCtrlCb mgrCtrl = NULL;
int32_t index = 0;
int32_t ret;
while (capFuncs[index].id != 0) {
switch (capFuncs[index].id) {
#ifdef HITLS_CRYPTO_ENTROPY_DEFAULT
case CRYPT_EAL_CAP_GETENTROPY:
g_providerSeedMethod.getEntropy = capFuncs[index].func;
break;
case CRYPT_EAL_CAP_CLEANENTROPY:
g_providerSeedMethod.cleanEntropy = capFuncs[index].func;
break;
case CRYPT_EAL_CAP_GETNONCE:
g_providerSeedMethod.getNonce = capFuncs[index].func;
break;
case CRYPT_EAL_CAP_CLEANNONCE:
g_providerSeedMethod.cleanNonce = capFuncs[index].func;
break;
#endif
case CRYPT_EAL_CAP_MGRCTXCTRL:
mgrCtrl = capFuncs[index].func;
break;
default:
break;
}
index++;
}
if (mgrCtrl == NULL) {
return CRYPT_PROVIDER_NOT_SUPPORT;
}
#ifdef HITLS_CRYPTO_ENTROPY_DEFAULT
RETURN_RET_IF_ERR_EX(mgrCtrl(mgrCtx, CRYPT_EAL_MGR_GETSEEDCTX, &g_providerSeedCtx, 0), ret);
#endif
RETURN_RET_IF_ERR_EX(mgrCtrl(mgrCtx, CRYPT_EAL_MGR_GETLIBCTX, &libCtx, 0), ret);
CRYPT_EAL_DefProvCtx *temp = BSL_SAL_Malloc(sizeof(CRYPT_EAL_DefProvCtx));
if (temp == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
temp->libCtx = libCtx;
*provCtx = temp;
*outFuncs = g_defEalProvOutFuncs;
return CRYPT_SUCCESS;
}
#endif /* HITLS_CRYPTO_PROVIDER */
| 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/default/crypt_default_provider.c | C | unknown | 44,214 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
/**
* @defgroup crypt_eal_provider
* @ingroup crypt
* @brief default provider header
*/
#ifndef CRYPT_EAL_DEFAULT_PROVIDER_H
#define CRYPT_EAL_DEFAULT_PROVIDER_H
#ifdef HITLS_CRYPTO_PROVIDER
#include <stdint.h>
#include "crypt_eal_implprovider.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
typedef struct EalDefProvCtx {
void *libCtx;
} CRYPT_EAL_DefProvCtx;
int32_t CRYPT_EAL_ProviderGetSeed(CRYPT_RandSeedMethod **method, void **seedCtx);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif /* HITLS_CRYPTO_PROVIDER */
#endif // CRYPT_EAL_DEFAULT_PROVIDER_H | 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/default/crypt_default_provider.h | C | unknown | 1,128 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_DRBG) && defined(HITLS_CRYPTO_PROVIDER)
#include "crypt_eal_implprovider.h"
#include "crypt_drbg.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "bsl_log_internal.h"
#include "bsl_err_internal.h"
#include "crypt_ealinit.h"
#include "bsl_params.h"
#include "crypt_default_provider.h"
#ifdef HITLS_CRYPTO_ENTROPY
static int32_t GetDefaultSeed(BSL_Param *param)
{
void *defaultSeedCtx = NULL;
CRYPT_RandSeedMethod *defaultSeedMethod = NULL;
int32_t ret = CRYPT_EAL_ProviderGetSeed(&defaultSeedMethod, &defaultSeedCtx);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
(void)BSL_PARAM_InitValue(¶m[0], CRYPT_PARAM_RAND_SEEDCTX, BSL_PARAM_TYPE_CTX_PTR, defaultSeedCtx, 0);
(void)BSL_PARAM_InitValue(¶m[1], CRYPT_PARAM_RAND_SEED_GETENTROPY, BSL_PARAM_TYPE_FUNC_PTR,
defaultSeedMethod->getEntropy, 0);
(void)BSL_PARAM_InitValue(¶m[2], CRYPT_PARAM_RAND_SEED_CLEANENTROPY, BSL_PARAM_TYPE_FUNC_PTR,
defaultSeedMethod->cleanEntropy, 0);
(void)BSL_PARAM_InitValue(¶m[3], CRYPT_PARAM_RAND_SEED_GETNONCE, BSL_PARAM_TYPE_FUNC_PTR,
defaultSeedMethod->getNonce, 0);
(void)BSL_PARAM_InitValue(¶m[4], CRYPT_PARAM_RAND_SEED_CLEANNONCE, BSL_PARAM_TYPE_FUNC_PTR,
defaultSeedMethod->cleanNonce, 0);
return CRYPT_SUCCESS;
}
#endif
void *CRYPT_EAL_DefRandNewCtx(CRYPT_EAL_DefProvCtx *provCtx, int32_t algId, BSL_Param *param)
{
void *libCtx = provCtx == NULL ? NULL : provCtx->libCtx;
void *randCtx = NULL;
#ifdef HITLS_CRYPTO_ASM_CHECK
if (CRYPT_ASMCAP_Drbg(algId) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_ASM_NOT_SUPPORT);
return NULL;
}
#endif
BSL_Param *getEnt = BSL_PARAM_FindParam(param, CRYPT_PARAM_RAND_SEED_GETENTROPY);
BSL_Param *cleanEnt = BSL_PARAM_FindParam(param, CRYPT_PARAM_RAND_SEED_CLEANENTROPY);
BSL_Param *getNonce = BSL_PARAM_FindParam(param, CRYPT_PARAM_RAND_SEED_GETNONCE);
BSL_Param *cleanNonce = BSL_PARAM_FindParam(param, CRYPT_PARAM_RAND_SEED_CLEANNONCE);
BSL_Param *ctx = BSL_PARAM_FindParam(param, CRYPT_PARAM_RAND_SEEDCTX);
/**
* If you use a registered entropy source, the getEntropy callback cannot be NULL,
* and if getEntropy is NULL, cleanEntropy, getNonce, cleanNonce, etc. must be NULL
*/
if (getEnt == NULL && ((cleanEnt != NULL && cleanEnt->value != NULL) ||
(getNonce != NULL && getNonce->value != NULL) || (cleanNonce != NULL && cleanNonce->value != NULL) ||
(ctx != NULL && ctx->value != NULL))) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return NULL;
}
if (param == NULL || getEnt == NULL) {
#ifdef HITLS_CRYPTO_ENTROPY
BSL_Param defaultParam[6] = {BSL_PARAM_END};
if (GetDefaultSeed(defaultParam) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return NULL;
}
return DRBG_New(libCtx, algId, defaultParam);
#else
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return NULL;
#endif
}
randCtx = DRBG_New(libCtx, algId, param);
if (randCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_NOT_SUPPORT);
return NULL;
}
return randCtx;
}
const CRYPT_EAL_Func g_defEalRand[] = {
{CRYPT_EAL_IMPLRAND_DRBGNEWCTX, (CRYPT_EAL_ImplRandDrbgNewCtx)CRYPT_EAL_DefRandNewCtx},
{CRYPT_EAL_IMPLRAND_DRBGINST, (CRYPT_EAL_ImplRandDrbgInst)DRBG_Instantiate},
{CRYPT_EAL_IMPLRAND_DRBGUNINST, (CRYPT_EAL_ImplRandDrbgUnInst)DRBG_Uninstantiate},
{CRYPT_EAL_IMPLRAND_DRBGGEN, (CRYPT_EAL_ImplRandDrbgGen)DRBG_GenerateBytes},
{CRYPT_EAL_IMPLRAND_DRBGRESEED, (CRYPT_EAL_ImplRandDrbgReSeed)DRBG_Reseed},
{CRYPT_EAL_IMPLRAND_DRBGCTRL, (CRYPT_EAL_ImplRandDrbgCtrl)DRBG_Ctrl},
{CRYPT_EAL_IMPLRAND_DRBGFREECTX, (CRYPT_EAL_ImplRandDrbgFreeCtx)DRBG_Free},
CRYPT_EAL_FUNC_END,
};
#endif /* HITLS_CRYPTO_DRBG && HITLS_CRYPTO_PROVIDER */ | 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/default/crypt_default_rand.c | C | unknown | 4,519 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#if (defined(HITLS_CRYPTO_DSA) || defined(HITLS_CRYPTO_ED25519) || defined(HITLS_CRYPTO_RSA_SIGN) || \
defined(HITLS_CRYPTO_RSA_VERIFY) || defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2_SIGN) || \
defined(HITLS_CRYPTO_SLH_DSA) || defined(HITLS_CRYPTO_MLDSA)) && defined(HITLS_CRYPTO_PROVIDER)
#include "crypt_eal_implprovider.h"
#include "crypt_dsa.h"
#include "crypt_rsa.h"
#include "crypt_ecdsa.h"
#include "crypt_sm2.h"
#include "crypt_curve25519.h"
#include "crypt_slh_dsa.h"
#include "crypt_mldsa.h"
#ifdef HITLS_CRYPTO_DSA
const CRYPT_EAL_Func g_defEalSignDsa[] = {
{CRYPT_EAL_IMPLPKEYSIGN_SIGN, (CRYPT_EAL_ImplPkeySign)CRYPT_DSA_Sign},
{CRYPT_EAL_IMPLPKEYSIGN_SIGNDATA, (CRYPT_EAL_ImplPkeySignData)CRYPT_DSA_SignData},
{CRYPT_EAL_IMPLPKEYSIGN_VERIFY, (CRYPT_EAL_ImplPkeyVerify)CRYPT_DSA_Verify},
{CRYPT_EAL_IMPLPKEYSIGN_VERIFYDATA, (CRYPT_EAL_ImplPkeyVerifyData)CRYPT_DSA_VerifyData},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_ED25519
const CRYPT_EAL_Func g_defEalSignEd25519[] = {
{CRYPT_EAL_IMPLPKEYSIGN_SIGN, (CRYPT_EAL_ImplPkeySign)CRYPT_CURVE25519_Sign},
{CRYPT_EAL_IMPLPKEYSIGN_VERIFY, (CRYPT_EAL_ImplPkeyVerify)CRYPT_CURVE25519_Verify},
CRYPT_EAL_FUNC_END,
};
#endif
#if defined(HITLS_CRYPTO_RSA_SIGN) || defined(HITLS_CRYPTO_RSA_VERIFY)
const CRYPT_EAL_Func g_defEalSignRsa[] = {
#ifdef HITLS_CRYPTO_RSA_SIGN
{CRYPT_EAL_IMPLPKEYSIGN_SIGN, (CRYPT_EAL_ImplPkeySign)CRYPT_RSA_Sign},
{CRYPT_EAL_IMPLPKEYSIGN_SIGNDATA, (CRYPT_EAL_ImplPkeySignData)CRYPT_RSA_SignData},
#endif
#ifdef HITLS_CRYPTO_RSA_VERIFY
{CRYPT_EAL_IMPLPKEYSIGN_VERIFY, (CRYPT_EAL_ImplPkeyVerify)CRYPT_RSA_Verify},
{CRYPT_EAL_IMPLPKEYSIGN_VERIFYDATA, (CRYPT_EAL_ImplPkeyVerifyData)CRYPT_RSA_VerifyData},
{CRYPT_EAL_IMPLPKEYSIGN_RECOVER, (CRYPT_EAL_ImplPkeyRecover)CRYPT_RSA_Recover},
#endif
#ifdef HITLS_CRYPTO_RSA_BSSA
#ifdef HITLS_CRYPTO_RSA_SIGN
{CRYPT_EAL_IMPLPKEYSIGN_BLIND, (CRYPT_EAL_ImplPkeyBlind)CRYPT_RSA_Blind},
#endif
#ifdef HITLS_CRYPTO_RSA_VERIFY
{CRYPT_EAL_IMPLPKEYSIGN_UNBLIND, (CRYPT_EAL_ImplPkeyUnBlind)CRYPT_RSA_UnBlind},
#endif
#endif
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_ECDSA
const CRYPT_EAL_Func g_defEalSignEcdsa[] = {
{CRYPT_EAL_IMPLPKEYSIGN_SIGN, (CRYPT_EAL_ImplPkeySign)CRYPT_ECDSA_Sign},
{CRYPT_EAL_IMPLPKEYSIGN_SIGNDATA, (CRYPT_EAL_ImplPkeySignData)CRYPT_ECDSA_SignData},
{CRYPT_EAL_IMPLPKEYSIGN_VERIFY, (CRYPT_EAL_ImplPkeyVerify)CRYPT_ECDSA_Verify},
{CRYPT_EAL_IMPLPKEYSIGN_VERIFYDATA, (CRYPT_EAL_ImplPkeyVerifyData)CRYPT_ECDSA_VerifyData},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_SM2_SIGN
const CRYPT_EAL_Func g_defEalSignSm2[] = {
{CRYPT_EAL_IMPLPKEYSIGN_SIGN, (CRYPT_EAL_ImplPkeySign)CRYPT_SM2_Sign},
{CRYPT_EAL_IMPLPKEYSIGN_VERIFY, (CRYPT_EAL_ImplPkeyVerify)CRYPT_SM2_Verify},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_SLH_DSA
const CRYPT_EAL_Func g_defEalSignSlhDsa[] = {
{CRYPT_EAL_IMPLPKEYSIGN_SIGN, (CRYPT_EAL_ImplPkeySign)CRYPT_SLH_DSA_Sign},
{CRYPT_EAL_IMPLPKEYSIGN_VERIFY, (CRYPT_EAL_ImplPkeyVerify)CRYPT_SLH_DSA_Verify},
CRYPT_EAL_FUNC_END,
};
#endif
#ifdef HITLS_CRYPTO_MLDSA
const CRYPT_EAL_Func g_defEalSignMlDsa[] = {
{CRYPT_EAL_IMPLPKEYSIGN_SIGN, (CRYPT_EAL_ImplPkeySign)CRYPT_ML_DSA_Sign},
{CRYPT_EAL_IMPLPKEYSIGN_VERIFY, (CRYPT_EAL_ImplPkeyVerify)CRYPT_ML_DSA_Verify},
CRYPT_EAL_FUNC_END,
};
#endif
#endif /* HITLS_CRYPTO_PKEY && HITLS_CRYPTO_PROVIDER */ | 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/default/crypt_default_sign.c | C | unknown | 4,035 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_PROVIDER
#include <stdlib.h>
#include "securec.h"
#include "crypt_utils.h"
#include "crypt_errno.h"
#include "bsl_sal.h"
#include "bsl_err_internal.h"
#include "crypt_eal_provider.h"
#include "crypt_eal_implprovider.h"
#include "crypt_provider_local.h"
#include "crypt_provider.h"
#include "crypt_drbg_local.h"
// Name of the dl initialization function
#define PROVIDER_INIT_FUNC "CRYPT_EAL_ProviderInit"
// Maximum length of search path
static uint32_t g_threadRunOnce = 0;
CRYPT_EAL_LibCtx *CRYPT_EAL_LibCtxNew(void)
{
return CRYPT_EAL_LibCtxNewInternal();
}
// Free EAL_LibCtx context
void CRYPT_EAL_LibCtxFree(CRYPT_EAL_LibCtx *libCtx)
{
if (libCtx == NULL) {
return;
}
#ifdef HITLS_CRYPTO_DRBG
if (libCtx->drbg != NULL) {
EAL_RandDeinit(libCtx->drbg);
libCtx->drbg = NULL;
}
#endif
if (libCtx->providers != NULL) {
BSL_LIST_FREE(libCtx->providers, (BSL_LIST_PFUNC_FREE)CRYPT_EAL_ProviderMgrCtxFree);
}
if (libCtx->lock != NULL) {
BSL_SAL_ThreadLockFree(libCtx->lock);
}
BSL_SAL_FREE(libCtx->searchProviderPath);
BSL_SAL_Free(libCtx);
}
static void InitPreDefinedProviders(void)
{
CRYPT_EAL_LibCtx *globalCtx = CRYPT_EAL_GetGlobalLibCtx();
if (globalCtx == NULL) {
int32_t ret = CRYPT_EAL_InitPreDefinedProviders();
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
}
}
static CRYPT_EAL_LibCtx *GetCurrentProviderLibCtx(CRYPT_EAL_LibCtx *libCtx)
{
CRYPT_EAL_LibCtx *curLibCtx = libCtx;
if (curLibCtx == NULL) {
int32_t ret = BSL_SAL_ThreadRunOnce(&g_threadRunOnce, InitPreDefinedProviders);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return NULL;
}
curLibCtx = CRYPT_EAL_GetGlobalLibCtx();
}
return curLibCtx;
}
// Write a function to search for providers according to BSL_LIST_Search requirements,
// comparing the input providerName with the providerName in EAL_ProviderMgrCtx for an exact match
static int32_t ListCompareProvider(const void *a, const void *b)
{
const CRYPT_EAL_ProvMgrCtx *ctx = (const CRYPT_EAL_ProvMgrCtx *)a;
const char *providerName = (const char *)b;
return (strcmp(ctx->providerName, providerName) == 0) ? 0 : 1;
}
static int32_t CheckProviderLoaded(CRYPT_EAL_LibCtx *libCtx, const char *providerName, bool increaseRef,
CRYPT_EAL_ProvMgrCtx **providerMgr)
{
int32_t ret = BSL_SAL_ThreadReadLock(libCtx->lock);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
CRYPT_EAL_ProvMgrCtx *tempProviderMgr =
(CRYPT_EAL_ProvMgrCtx *)BSL_LIST_Search(libCtx->providers, providerName, ListCompareProvider, NULL);
if (tempProviderMgr != NULL && increaseRef) {
// Provider is already loaded, increase the reference count
int32_t tempCount = 0;
ret = BSL_SAL_AtomicUpReferences(&tempProviderMgr->ref, &tempCount);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
(void)BSL_SAL_ThreadUnlock(libCtx->lock);
return ret;
}
}
(void)BSL_SAL_ThreadUnlock(libCtx->lock);
*providerMgr = tempProviderMgr;
return CRYPT_SUCCESS;
}
static bool IsEalPreDefinedProvider(const char *providerName)
{
const char *preProvider[] = {CRYPT_EAL_DEFAULT_PROVIDER};
for (size_t i = 0; i < sizeof(preProvider) / sizeof(preProvider[0]); i++) {
if (strcmp(preProvider[i], providerName) == 0) {
return true;
}
}
return false;
}
static int32_t FindProviderInitFunc(CRYPT_EAL_LibCtx *libCtx, char *providerName, void **initFunc)
{
uint32_t pathLen = BSL_SAL_Strnlen(providerName, DEFAULT_PROVIDER_NAME_LEN_MAX) +
BSL_SAL_Strnlen(libCtx->searchProviderPath, DEFAULT_PROVIDER_PATH_LEN_MAX) + 1;
if (pathLen > DEFAULT_PROVIDER_PATH_LEN_MAX) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
char *providerPath = providerName;
int32_t ret;
// Construct the full path of the provider
if (libCtx->searchProviderPath != NULL) {
providerPath = (char *)BSL_SAL_Calloc(pathLen + 1, sizeof(char));
if (providerPath == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
ret = snprintf_s(providerPath, pathLen + 1, pathLen, "%s/%s", libCtx->searchProviderPath, providerName);
if (ret < 0) {
BSL_SAL_Free(providerPath);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
// Attempt to load the dynamic library
void *handle = NULL;
ret = BSL_SAL_LoadLib(providerPath, &handle);
if (libCtx->searchProviderPath != NULL) {
BSL_SAL_Free(providerPath);
}
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// Attempt to get the initialization function
ret = BSL_SAL_GetFuncAddress(handle, PROVIDER_INIT_FUNC, initFunc);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
// Load provider dynamic library
int32_t CRYPT_EAL_ProviderLoad(CRYPT_EAL_LibCtx *libCtx, BSL_SAL_LibFmtCmd cmd,
const char *providerName, BSL_Param *param, CRYPT_EAL_ProvMgrCtx **mgrCtx)
{
if (providerName == NULL || (mgrCtx != NULL && *mgrCtx != NULL)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_EAL_LibCtx *localCtx = GetCurrentProviderLibCtx(libCtx);
if (localCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_INVALID_LIB_CTX);
return CRYPT_PROVIDER_INVALID_LIB_CTX;
}
CRYPT_EAL_ProvMgrCtx *providerMgr = NULL;
char *providerFullName = NULL;
int32_t ret = BSL_SAL_LibNameFormat(cmd, providerName, &providerFullName);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// Check if the provider is already loaded
ret = CheckProviderLoaded(localCtx, providerFullName, true, &providerMgr);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_Free(providerFullName);
return ret;
}
if (providerMgr != NULL) {
BSL_SAL_Free(providerFullName);
if (mgrCtx != NULL) {
*mgrCtx = providerMgr;
}
return CRYPT_SUCCESS;
}
CRYPT_EAL_ImplProviderInit initFunc = NULL;
if (IsEalPreDefinedProvider(providerFullName)) {
initFunc = CRYPT_EAL_DefaultProvInit;
} else {
ret = FindProviderInitFunc(localCtx, providerFullName, (void **)&initFunc);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_Free(providerFullName);
return ret;
}
}
ret = CRYPT_EAL_AddNewProvMgrCtx(localCtx, providerFullName, localCtx->searchProviderPath, initFunc, param,
mgrCtx);
BSL_SAL_Free(providerFullName);
return ret;
}
int32_t CRYPT_EAL_ProviderRegister(CRYPT_EAL_LibCtx *libCtx, const char *providerName, CRYPT_EAL_ImplProviderInit init,
BSL_Param *param, CRYPT_EAL_ProvMgrCtx **mgrCtx)
{
if (providerName == NULL || (mgrCtx != NULL && *mgrCtx != NULL)) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
uint32_t providerNameLen = BSL_SAL_Strnlen(providerName, DEFAULT_PROVIDER_NAME_LEN_MAX + 1);
if (providerNameLen == DEFAULT_PROVIDER_NAME_LEN_MAX + 1 || providerNameLen == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
CRYPT_EAL_ProvMgrCtx *providerMgr = NULL;
CRYPT_EAL_ImplProviderInit initFunc = init;
CRYPT_EAL_LibCtx *localCtx = GetCurrentProviderLibCtx(libCtx);
if (localCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_INVALID_LIB_CTX);
return CRYPT_PROVIDER_INVALID_LIB_CTX;
}
int32_t ret = CheckProviderLoaded(localCtx, providerName, true, &providerMgr);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if (providerMgr != NULL) {
if (mgrCtx != NULL) {
*mgrCtx = providerMgr;
}
return CRYPT_SUCCESS;
}
if (IsEalPreDefinedProvider(providerName)) {
initFunc = CRYPT_EAL_DefaultProvInit;
} else {
if (initFunc == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
}
return CRYPT_EAL_AddNewProvMgrCtx(localCtx, providerName, NULL, initFunc, param, mgrCtx);
}
int32_t CRYPT_EAL_ProviderIsLoaded(CRYPT_EAL_LibCtx *libCtx, BSL_SAL_LibFmtCmd cmd, const char *providerName,
bool *isLoaded)
{
if (providerName == NULL || isLoaded == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_EAL_LibCtx *localCtx = GetCurrentProviderLibCtx(libCtx);
if (localCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_INVALID_LIB_CTX);
return CRYPT_PROVIDER_INVALID_LIB_CTX;
}
char *providerFullName = NULL;
int32_t ret = BSL_SAL_LibNameFormat(cmd, providerName, &providerFullName);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// Check if the provider is already loaded
CRYPT_EAL_ProvMgrCtx *providerMgr = NULL;
ret = CheckProviderLoaded(localCtx, providerFullName, false, &providerMgr);
BSL_SAL_Free(providerFullName);
if (ret != CRYPT_SUCCESS) {
return ret;
}
*isLoaded = providerMgr != NULL ? true : false;
return CRYPT_SUCCESS;
}
// Remove provider from the list
static void RemoveAndFreeProvider(BslList *providers, CRYPT_EAL_ProvMgrCtx *providerMgr)
{
BslListNode *node = BSL_LIST_FirstNode(providers);
while (node != NULL) {
if (BSL_LIST_GetData(node) == providerMgr) {
BSL_LIST_DetachNode(providers, &node);
break;
}
node = BSL_LIST_GetNextNode(providers, node);
}
CRYPT_EAL_ProviderMgrCtxFree(providerMgr);
}
// Unload provider
int32_t CRYPT_EAL_ProviderUnload(CRYPT_EAL_LibCtx *libCtx, BSL_SAL_LibFmtCmd cmd, const char *providerName)
{
if (providerName == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_EAL_LibCtx *localCtx = libCtx;
if (localCtx == NULL) {
localCtx = CRYPT_EAL_GetGlobalLibCtx();
}
if (localCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_INVALID_LIB_CTX);
return CRYPT_PROVIDER_INVALID_LIB_CTX;
}
char *providerFullName = NULL;
int32_t ret = BSL_SAL_LibNameFormat(cmd, providerName, &providerFullName);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// Search for the specified provider
ret = BSL_SAL_ThreadReadLock(localCtx->lock);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
BSL_SAL_FREE(providerFullName);
return ret;
}
CRYPT_EAL_ProvMgrCtx *providerMgr =
(CRYPT_EAL_ProvMgrCtx *)BSL_LIST_Search(localCtx->providers, providerFullName, ListCompareProvider, NULL);
BSL_SAL_FREE(providerFullName);
if (providerMgr == NULL) {
(void)BSL_SAL_ThreadUnlock(localCtx->lock);
return CRYPT_SUCCESS;
}
// Decrease reference count
int refCount = 0;
ret = BSL_SAL_AtomicDownReferences(&providerMgr->ref, &refCount);
if (ret != BSL_SUCCESS) {
(void)BSL_SAL_ThreadUnlock(localCtx->lock);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (refCount <= 0) {
RemoveAndFreeProvider(localCtx->providers, providerMgr);
}
(void)BSL_SAL_ThreadUnlock(localCtx->lock);
return CRYPT_SUCCESS;
}
// Set the path for loading providers
int32_t CRYPT_EAL_ProviderSetLoadPath(CRYPT_EAL_LibCtx *libCtx, const char *searchPath)
{
if (BSL_SAL_Strnlen(searchPath, DEFAULT_PROVIDER_PATH_LEN_MAX) >= DEFAULT_PROVIDER_PATH_LEN_MAX) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
CRYPT_EAL_LibCtx *localCtx = GetCurrentProviderLibCtx(libCtx);
if (localCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_INVALID_LIB_CTX);
return CRYPT_PROVIDER_INVALID_LIB_CTX;
}
char *tempPath = NULL;
if (searchPath != NULL) {
tempPath = BSL_SAL_Dump(searchPath, BSL_SAL_Strnlen(searchPath, DEFAULT_PROVIDER_PATH_LEN_MAX) + 1);
if (tempPath == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
}
BSL_SAL_FREE(localCtx->searchProviderPath);
localCtx->searchProviderPath = tempPath;
return CRYPT_SUCCESS;
}
static int32_t GetProviderUserCtx(CRYPT_EAL_ProvMgrCtx *ctx, void **val)
{
if (val == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
*val = ctx->provCtx;
return CRYPT_SUCCESS;
}
int32_t CRYPT_EAL_ProviderCtrl(CRYPT_EAL_ProvMgrCtx *ctx, int32_t cmd, void *val, uint32_t valLen)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (cmd == CRYPT_PROVIDER_GET_USER_CTX) {
return GetProviderUserCtx(ctx, val);
}
if (ctx->provCtrlCb == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_NOT_SUPPORT);
return CRYPT_PROVIDER_NOT_SUPPORT;
}
return ctx->provCtrlCb(ctx->provCtx, cmd, val, valLen);
}
int32_t CRYPT_EAL_ProviderGetCaps(CRYPT_EAL_ProvMgrCtx *ctx, int32_t cmd, CRYPT_EAL_ProcessFuncCb cb, void *args)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->provGetCap == NULL) {
return CRYPT_SUCCESS;
}
return ctx->provGetCap(ctx->provCtx, cmd, cb, args);
}
int32_t CRYPT_EAL_ProviderProcessAll(CRYPT_EAL_LibCtx *ctx, CRYPT_EAL_ProviderProcessCb cb, void *args)
{
if (cb == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_EAL_LibCtx *localCtx = ctx;
if (localCtx == NULL) {
localCtx = CRYPT_EAL_GetGlobalLibCtx();
}
if (localCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_INVALID_LIB_CTX);
return CRYPT_PROVIDER_INVALID_LIB_CTX;
}
BslListNode *node = BSL_LIST_FirstNode(localCtx->providers);
while (node != NULL) {
CRYPT_EAL_ProvMgrCtx *providerMgr = (CRYPT_EAL_ProvMgrCtx *)BSL_LIST_GetData(node);
int32_t ret = cb(providerMgr, args);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
node = BSL_LIST_GetNextNode(localCtx->providers, node);
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_EAL_ProviderQuery(CRYPT_EAL_ProvMgrCtx *ctx, int32_t operaId, CRYPT_EAL_AlgInfo **algInfos)
{
if (ctx == NULL || algInfos == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->provQueryCb == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_NOT_SUPPORT);
return CRYPT_PROVIDER_NOT_SUPPORT;
}
return ctx->provQueryCb(ctx->provCtx, operaId, algInfos);
}
#endif // HITLS_CRYPTO_PROVIDER
| 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/mgr/crypt_provider.c | C | unknown | 15,597 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifdef HITLS_CRYPTO_PROVIDER
#include "securec.h"
#include "bsl_list.h"
#include "bsl_err_internal.h"
#include "crypt_errno.h"
#include "eal_entropy.h"
#include "crypt_eal_entropy.h"
#include "crypt_drbg_local.h"
#include "crypt_drbg.h"
#include "crypt_provider_local.h"
#include "crypt_provider.h"
static CRYPT_EAL_LibCtx *g_libCtx = NULL;
CRYPT_EAL_LibCtx *CRYPT_EAL_GetGlobalLibCtx(void)
{
return g_libCtx;
}
int32_t CRYPT_EAL_ProviderGetFuncs(CRYPT_EAL_LibCtx *libCtx, int32_t operaId, int32_t algId,
const char *attribute, const CRYPT_EAL_Func **funcs, void **provCtx)
{
CRYPT_EAL_ProvMgrCtx *mgrCtx = NULL;
int32_t ret = CRYPT_EAL_ProviderGetFuncsAndMgrCtx(libCtx, operaId, algId, attribute, funcs, &mgrCtx);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (mgrCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_NOT_FOUND);
return CRYPT_PROVIDER_NOT_FOUND;
}
if (provCtx != NULL) {
*provCtx = mgrCtx->provCtx;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_EAL_ProviderGetFuncsAndMgrCtx(CRYPT_EAL_LibCtx *libCtx, int32_t operaId, int32_t algId,
const char *attribute, const CRYPT_EAL_Func **funcs, CRYPT_EAL_ProvMgrCtx **mgrCtx)
{
if (funcs == NULL || mgrCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_EAL_LibCtx *localCtx = libCtx;
if (localCtx == NULL) {
localCtx = g_libCtx;
}
if (localCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (attribute != NULL && strlen(attribute) > (INT32_MAX >> 1)) {
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_ERR_ATTRIBUTE);
return CRYPT_PROVIDER_ERR_ATTRIBUTE;
}
return CRYPT_EAL_CompareAlgAndAttr(localCtx, operaId, algId, attribute, funcs, mgrCtx);
}
int32_t CRYPT_EAL_ProvMgrCtrl(CRYPT_EAL_ProvMgrCtx *ctx, int32_t cmd, void *val, uint32_t valLen)
{
(void)valLen;
if (ctx == NULL || val == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
switch (cmd) {
#ifdef HITLS_CRYPTO_ENTROPY_DEFAULT
case CRYPT_EAL_MGR_GETSEEDCTX:
*(void **)val = ctx->providerSeed.seed;
return CRYPT_SUCCESS;
#endif
case CRYPT_EAL_MGR_GETLIBCTX:
*(void **)val = ctx->libCtx;
return CRYPT_SUCCESS;
default:
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_NOT_FOUND);
return CRYPT_PROVIDER_NOT_FOUND;
}
}
static void MountMgrMethod(CRYPT_EAL_Func *funcs, CRYPT_EAL_ProvMgrCtx *ctx)
{
// Mount function addresses to corresponding positions in mgr according to method definition
for (uint32_t i = 0; funcs[i].id != 0; i++) {
switch (funcs[i].id) {
case CRYPT_EAL_PROVCB_FREE:
ctx->provFreeCb = (CRYPT_EAL_ProvFreeCb)funcs[i].func;
break;
case CRYPT_EAL_PROVCB_QUERY:
ctx->provQueryCb = (CRYPT_EAL_ProvQueryCb)funcs[i].func;
break;
case CRYPT_EAL_PROVCB_CTRL:
ctx->provCtrlCb = (CRYPT_EAL_ProvCtrlCb)funcs[i].func;
break;
case CRYPT_EAL_PROVCB_GETCAPS:
ctx->provGetCap = (CRYPT_EAL_ProvGetCapsCb)funcs[i].func;
break;
default:
break;
}
}
}
#ifdef HITLS_CRYPTO_ENTROPY_DEFAULT
static void ProviderSeedDeinit(EAL_SeedDrbg *seedDrbg)
{
if (seedDrbg == NULL) {
return;
}
if (seedDrbg->seed != NULL) {
EAL_SeedDrbgRandDeinit(seedDrbg->seed);
seedDrbg->seed = NULL;
CRYPT_EAL_SeedPoolFree(seedDrbg->seedCtx);
seedDrbg->seedCtx = NULL;
BSL_SAL_ReferencesFree(&(seedDrbg->references));
(void)memset_s(seedDrbg, sizeof(EAL_SeedDrbg), 0, sizeof(EAL_SeedDrbg));
}
}
#endif
// Function to get provider methods
int32_t CRYPT_EAL_InitProviderMethod(CRYPT_EAL_ProvMgrCtx *ctx, BSL_Param *param,
CRYPT_EAL_ImplProviderInit providerInit)
{
int32_t ret;
#ifdef HITLS_CRYPTO_ENTROPY_DEFAULT
CRYPT_RandSeedMethod meth = {0};
// The implementer of provider may not use the default entropy source
(void)EAL_SeedDrbgEntropyMeth(&meth);
ctx->providerSeed.id = HITLS_SEED_DRBG_INIT_RAND_ALG;
ret = EAL_SeedDrbgInit(&(ctx->providerSeed));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
#endif
// Construct input method structure array
CRYPT_EAL_Func capFuncs[] = {
#ifdef HITLS_CRYPTO_ENTROPY_DEFAULT
{CRYPT_EAL_CAP_GETENTROPY, (CRYPT_EAL_GetEntropyCb)meth.getEntropy},
{CRYPT_EAL_CAP_CLEANENTROPY, (CRYPT_EAL_CleanEntropyCb)meth.cleanEntropy},
{CRYPT_EAL_CAP_GETNONCE, (CRYPT_EAL_GetNonceCb)meth.getNonce},
{CRYPT_EAL_CAP_CLEANNONCE, (CRYPT_EAL_CleanNonceCb)meth.cleanNonce},
#endif
{CRYPT_EAL_CAP_MGRCTXCTRL, (CRYPT_EAL_ProvMgrCtrlCb)CRYPT_EAL_ProvMgrCtrl},
CRYPT_EAL_FUNC_END // End marker
};
CRYPT_EAL_Func *outFuncs = NULL;
// Call CRYPT_EAL_ImplProviderInit to get methods
ret = providerInit(ctx, param, capFuncs, &outFuncs, &ctx->provCtx);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
if (outFuncs == NULL) {
ret = CRYPT_PROVIDER_ERR_UNEXPECTED_IMPL;
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_ERR_UNEXPECTED_IMPL);
goto ERR;
}
MountMgrMethod(outFuncs, ctx);
if (ctx->provQueryCb == NULL) {
if (ctx->provFreeCb != NULL) {
ctx->provFreeCb(ctx->provCtx);
ctx->provCtx = NULL;
}
ret = CRYPT_PROVIDER_ERR_IMPL_NULL;
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_ERR_IMPL_NULL);
goto ERR;
}
return CRYPT_SUCCESS;
ERR:
#ifdef HITLS_CRYPTO_ENTROPY_DEFAULT
ProviderSeedDeinit(&(ctx->providerSeed));
#endif
return ret;
}
CRYPT_EAL_LibCtx *CRYPT_EAL_LibCtxNewInternal(void)
{
CRYPT_EAL_LibCtx *libCtx = (CRYPT_EAL_LibCtx *)BSL_SAL_Calloc(1, sizeof(CRYPT_EAL_LibCtx));
if (libCtx == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return NULL;
}
// Initialize providers list
libCtx->providers = BSL_LIST_New(sizeof(struct EAL_ProviderMgrCtx *));
if (libCtx->providers == NULL) {
goto ERR;
}
// Initialize thread lock
if (BSL_SAL_ThreadLockNew(&libCtx->lock) != BSL_SUCCESS) {
BSL_LIST_FREE(libCtx->providers, NULL);
goto ERR;
}
return libCtx;
ERR:
BSL_SAL_Free(libCtx);
libCtx = NULL;
return NULL;
}
void CRYPT_EAL_ProviderMgrCtxFree(CRYPT_EAL_ProvMgrCtx *ctx)
{
if (ctx == NULL) {
return;
}
if (ctx->provFreeCb != NULL) {
ctx->provFreeCb(ctx->provCtx);
ctx->provCtx = NULL;
}
BSL_SAL_FREE(ctx->providerName);
BSL_SAL_FREE(ctx->providerPath);
BSL_SAL_ReferencesFree(&(ctx->ref));
if (ctx->handle != NULL) {
BSL_SAL_UnLoadLib(ctx->handle);
ctx->handle = NULL;
}
#ifdef HITLS_CRYPTO_ENTROPY_DEFAULT
ProviderSeedDeinit(&(ctx->providerSeed));
#endif
BSL_SAL_Free(ctx);
}
// Add provider to the list
static int32_t AddProviderToList(CRYPT_EAL_LibCtx *libCtx, CRYPT_EAL_ProvMgrCtx *providerMgr)
{
int32_t ret = BSL_SAL_ThreadWriteLock(libCtx->lock);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = BSL_LIST_AddElement(libCtx->providers, providerMgr, BSL_LIST_POS_END);
(void)BSL_SAL_ThreadUnlock(libCtx->lock);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
int32_t CRYPT_EAL_AddNewProvMgrCtx(CRYPT_EAL_LibCtx *libCtx, const char *providerName, const char *providerPath,
CRYPT_EAL_ImplProviderInit init, BSL_Param *param, CRYPT_EAL_ProvMgrCtx **ctx)
{
CRYPT_EAL_ProvMgrCtx *mgrCtx = (CRYPT_EAL_ProvMgrCtx *)BSL_SAL_Calloc(1, sizeof(CRYPT_EAL_ProvMgrCtx));
if (mgrCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
mgrCtx->libCtx = libCtx;
mgrCtx->providerName = BSL_SAL_Dump(providerName, BSL_SAL_Strnlen(providerName, DEFAULT_PROVIDER_NAME_LEN_MAX) + 1);
if (mgrCtx->providerName == NULL) {
BSL_SAL_Free(mgrCtx);
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
if (providerPath != NULL) {
mgrCtx->providerPath = BSL_SAL_Dump(providerPath,
BSL_SAL_Strnlen(providerPath, DEFAULT_PROVIDER_PATH_LEN_MAX) + 1);
if (mgrCtx->providerPath == NULL) {
BSL_SAL_Free(mgrCtx->providerName);
BSL_SAL_Free(mgrCtx);
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
}
int32_t ret = BSL_SAL_ReferencesInit(&mgrCtx->ref);
if (ret != BSL_SUCCESS) {
CRYPT_EAL_ProviderMgrCtxFree(mgrCtx);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = AddProviderToList(libCtx, mgrCtx);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_ProviderMgrCtxFree(mgrCtx);
return ret;
}
ret = CRYPT_EAL_InitProviderMethod(mgrCtx, param, init);
if (ret != BSL_SUCCESS) {
BSL_LIST_DeleteCurrent(libCtx->providers, (BSL_LIST_PFUNC_FREE)CRYPT_EAL_ProviderMgrCtxFree);
return ret;
}
if (ctx != NULL) {
*ctx = mgrCtx;
}
return ret;
}
int32_t CRYPT_EAL_InitPreDefinedProviders(void)
{
CRYPT_EAL_LibCtx *libCtx = CRYPT_EAL_LibCtxNewInternal();
if (libCtx == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
g_libCtx = libCtx;
int32_t ret = CRYPT_EAL_AddNewProvMgrCtx(libCtx, CRYPT_EAL_DEFAULT_PROVIDER, NULL, CRYPT_EAL_DefaultProvInit,
NULL, NULL);
if (ret != CRYPT_SUCCESS) {
BSL_LIST_FREE(libCtx->providers, NULL);
BSL_SAL_ThreadLockFree(libCtx->lock);
BSL_SAL_FREE(g_libCtx);
return ret;
}
return ret;
}
void CRYPT_EAL_FreePreDefinedProviders(void)
{
CRYPT_EAL_LibCtx *libCtx = g_libCtx;
if (libCtx == NULL) {
return;
}
#ifdef HITLS_CRYPTO_DRBG
if (libCtx->drbg != NULL) {
EAL_RandDeinit(libCtx->drbg);
libCtx->drbg = NULL;
}
#endif
// Free the providers list and each EAL_ProviderMgrCtx in it
if (libCtx->providers != NULL) {
BSL_LIST_FREE(libCtx->providers, (BSL_LIST_PFUNC_FREE)CRYPT_EAL_ProviderMgrCtxFree);
}
BSL_SAL_FREE(libCtx->searchProviderPath);
// Free thread lock
if (libCtx->lock != NULL) {
BSL_SAL_ThreadLockFree(libCtx->lock);
libCtx->lock = NULL;
}
// Free the libctx structure itself
BSL_SAL_Free(libCtx);
g_libCtx = NULL;
}
#endif /* HITLS_CRYPTO_PROVIDER */ | 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/mgr/crypt_provider_common.c | C | unknown | 11,323 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_PROVIDER
#include <string.h>
#include "securec.h"
#include "bsl_list.h"
#include "bsl_err_internal.h"
#include "bsl_hash.h"
#include "list_base.h"
#include "crypt_errno.h"
#include "crypt_provider.h"
#include "crypt_provider_local.h"
#include "crypt_eal_provider.h"
#include "crypt_eal_implprovider.h"
#define HISH_SIZE 8
#define NOT_EQUAL_SIZE 2
// Store the information of the input attribute string
typedef struct {
const char *attribute; // Attribute string
BSL_HASH_Hash *hash; // Hash table
uint32_t attributeNum; // Number of attributes
uint32_t mustAttributeNum; // Number of mandatory attributes
bool repeatFlag; // Repeat search flag
} InputAttributeStrInfo;
// Define the data structure for values
typedef struct {
char *judgeStr; // Judge string
char *valueStr; // Value string
} AttributeValue;
// Define a function to free AttributeValue resources
static void AttributeValueFree(void *ptr)
{
if (ptr == NULL) {
return;
}
AttributeValue *value = (AttributeValue *)ptr;
BSL_SAL_FREE(value->judgeStr);
BSL_SAL_FREE(value->valueStr);
BSL_SAL_Free(value);
}
// Define a function to free the value list
static void FreeValueList(void *ptr)
{
if (ptr == NULL) {
return;
}
BslList *valueList = (BslList *)ptr;
BSL_LIST_DeleteAll(valueList, AttributeValueFree);
BSL_SAL_Free(valueList);
}
// Value copy callback function, essentially a function to create a new value list
static void *ValueDupFunc(void *ptr, size_t size)
{
if (ptr == NULL || size == 0) {
return NULL;
}
int32_t ret;
AttributeValue *srcValue = (AttributeValue *)ptr;
BslList *newList = BSL_LIST_New(sizeof(AttributeValue));
if (newList == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
AttributeValue *newValue = BSL_SAL_Calloc(1, sizeof(AttributeValue));
if (newValue == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
goto ERR;
}
newValue->judgeStr = BSL_SAL_Dump(srcValue->judgeStr, BSL_SAL_Strnlen(srcValue->judgeStr, UINT32_MAX) + 1);
newValue->valueStr = BSL_SAL_Dump(srcValue->valueStr, BSL_SAL_Strnlen(srcValue->valueStr, UINT32_MAX) + 1);
if (newValue->judgeStr == NULL || newValue->valueStr == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
goto ERR;
}
ret = BSL_LIST_AddElement(newList, newValue, BSL_LIST_POS_END);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
return newList;
ERR:
AttributeValueFree(newValue);
BSL_SAL_Free(newList);
return NULL;
}
// Key copy callback function
static void *KeyDupFunc(void *ptr, size_t size)
{
if (ptr == NULL || size == 0) {
return NULL;
}
return BSL_SAL_Dump(ptr, size);
}
// Key release callback function
static void KeyFreeFunc(void *ptr)
{
BSL_SAL_FREE(ptr);
}
// Implement the BSL_HASH_UpdateNodeFunc callback function for BSL_HASH_Put to call
static int32_t UpdateAttributeValueNode(BSL_HASH_Hash *hash, BSL_HASH_Iterator node,
uintptr_t value, uint32_t valueSize)
{
if (hash == NULL || valueSize == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
AttributeValue *srcValue = (AttributeValue *)value;
AttributeValue *newValue = BSL_SAL_Calloc(1, sizeof(AttributeValue));
if (newValue == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
newValue->judgeStr = BSL_SAL_Dump(srcValue->judgeStr, BSL_SAL_Strnlen(srcValue->judgeStr, UINT32_MAX) + 1);
newValue->valueStr = BSL_SAL_Dump(srcValue->valueStr, BSL_SAL_Strnlen(srcValue->valueStr, UINT32_MAX) + 1);
if (newValue->judgeStr == NULL || newValue->valueStr == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
AttributeValueFree(newValue);
return CRYPT_MEM_ALLOC_FAIL;
}
BslList *valueList = (BslList *)BSL_HASH_IterValue(hash, node);
int32_t ret = BSL_LIST_AddElement(valueList, (AttributeValue *)newValue, BSL_LIST_POS_END);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
AttributeValueFree(newValue);
}
return ret;
}
// Get key-value pair positions
static int32_t GetAttributePositions(const char *attribute, int32_t start, int32_t *keyStart, int32_t *keyEnd,
int32_t *judgeStart, int32_t *judgeEnd, int32_t *valueStart, int32_t *valueEnd)
{
int32_t temp = start;
*keyStart = *keyEnd = *judgeStart = *judgeEnd = *valueStart = *valueEnd = temp;
// Find key
while (attribute[temp] != '\0' && attribute[temp] != '=' && attribute[temp] != '?' && attribute[temp] != '!') {
temp++;
}
*keyEnd = temp;
if (*keyEnd <= *keyStart) {
return CRYPT_PROVIDER_ERR_ATTRIBUTE;
}
// Find judge string
*judgeStart = temp;
if (attribute[temp] == '!' && attribute[temp + 1] == '=') {
temp = temp + NOT_EQUAL_SIZE;
} else if (attribute[temp] == '=' || attribute[temp] == '?') {
temp++;
} else {
return CRYPT_PROVIDER_ERR_ATTRIBUTE;
}
*judgeEnd = temp;
if (*judgeEnd <= *judgeStart) {
return CRYPT_PROVIDER_ERR_ATTRIBUTE;
}
// Find value
*valueStart = temp;
while (attribute[temp] != '\0' && attribute[temp] != ',') {
temp++;
}
*valueEnd = temp;
if (*valueEnd <= *valueStart) {
return CRYPT_PROVIDER_ERR_ATTRIBUTE;
}
return CRYPT_SUCCESS;
}
static int32_t ParseAttributeValue(const char *attribute, int32_t *startPos, char **key, AttributeValue **value)
{
int32_t start = *startPos;
char *tempKey = NULL;
AttributeValue *tempValue = NULL;
// Call the sub-function to get key-value pair positions
int32_t keyStart, keyEnd, judgeStart, judgeEnd, valueStart, valueEnd;
int32_t ret = GetAttributePositions(attribute, start, &keyStart, &keyEnd, &judgeStart, &judgeEnd, &valueStart, &valueEnd);
if (ret != CRYPT_SUCCESS) {
return ret;
}
int32_t keyLen = keyEnd - keyStart;
int32_t judgeLen = judgeEnd - judgeStart;
int32_t valueLen = valueEnd - valueStart;
// Allocate space for keys and values
tempValue = BSL_SAL_Calloc(1, sizeof(AttributeValue));
if (tempValue == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
tempKey = BSL_SAL_Calloc(1, keyLen + 1);
tempValue->judgeStr = BSL_SAL_Calloc(1, judgeLen + 1);
tempValue->valueStr = BSL_SAL_Calloc(1, valueLen + 1);
if (tempKey == NULL || tempValue->judgeStr == NULL || tempValue->valueStr == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
// Copy the string corresponding to the key and value
if (memcpy_s(tempKey, keyLen + 1, attribute + keyStart, keyLen) != EOK ||
memcpy_s(tempValue->judgeStr, judgeLen + 1, attribute + judgeStart, judgeLen) != EOK ||
memcpy_s(tempValue->valueStr, valueLen + 1, attribute + valueStart, valueLen) != EOK) {
ret = CRYPT_SECUREC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
*startPos = attribute[valueEnd] == '\0' ? valueEnd : valueEnd + 1;
*key = tempKey;
*value = tempValue;
return CRYPT_SUCCESS;
ERR:
BSL_SAL_FREE(tempKey);
AttributeValueFree(tempValue);
return ret;
}
static int32_t ParseAttributeString(InputAttributeStrInfo *attrInfo)
{
int32_t ret;
const char *attribute = attrInfo->attribute;
BSL_HASH_Hash *hash = NULL;
int32_t startPos = 0;
char *key = NULL;
AttributeValue *value = NULL;
uint32_t tempMustAttributeNum = 0, tempAttributeNum = 0;
ListDupFreeFuncPair keyFunc = {KeyDupFunc, KeyFreeFunc};
ListDupFreeFuncPair valueFunc = {ValueDupFunc, FreeValueList};
// Create a hash table with a bucket size of 8
hash = BSL_HASH_Create(HISH_SIZE, BSL_HASH_CodeCalcStr, BSL_HASH_MatchStr, &keyFunc, &valueFunc);
if (hash == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
while (attribute[startPos] != '\0') {
// Extract a key-value pair
ret = ParseAttributeValue(attribute, &startPos, &key, &value);
// An unknown error occurred during the lookup
if (ret != CRYPT_SUCCESS) {
BSL_HASH_Destory(hash);
return ret;
}
tempAttributeNum++;
if (value->judgeStr[0] == '=' || value->judgeStr[0] == '!') {
tempMustAttributeNum++;
}
ret = BSL_HASH_Put(hash, (uintptr_t)key, BSL_SAL_Strnlen(key, UINT32_MAX) + 1,
(uintptr_t)value, sizeof(AttributeValue), UpdateAttributeValueNode);
BSL_SAL_FREE(key);
AttributeValueFree(value);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
BSL_HASH_Destory(hash);
return ret;
}
}
if (tempAttributeNum == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_ERR_ATTRIBUTE);
BSL_HASH_Destory(hash);
return CRYPT_PROVIDER_ERR_ATTRIBUTE;
}
attrInfo->attributeNum = tempAttributeNum;
attrInfo->mustAttributeNum = tempMustAttributeNum;
attrInfo->hash = hash;
return CRYPT_SUCCESS;
}
static int32_t CompareAttributeValue(AttributeValue *value, AttributeValue *hashValue,
uint32_t *comparedCount, uint32_t *satisfiedMustCount, int32_t *totalScore)
{
if (hashValue->judgeStr[0] == '=') {
if (strcmp(value->valueStr, hashValue->valueStr) == 0) {
(*comparedCount)++;
(*satisfiedMustCount)++;
} else {
return -1;
}
} else if (hashValue->judgeStr[0] == '!' && hashValue->judgeStr[1] == '=') {
if (strcmp(value->valueStr, hashValue->valueStr) != 0) {
(*comparedCount)++;
(*satisfiedMustCount)++;
} else {
return -1;
}
} else if (hashValue->judgeStr[0] == '?') {
(*comparedCount)++;
if (strcmp(value->valueStr, hashValue->valueStr) == 0) {
(*totalScore)++;
}
}
return 0;
}
static int32_t CompareAttribute(BSL_HASH_Hash *hash, const char *attribute,
uint32_t mustAttributeNum, uint32_t attributeNum)
{
int32_t ret;
int32_t startPos = 0;
char *key = NULL;
AttributeValue *value = NULL;
uint32_t comparedCount = 0;
uint32_t satisfiedMustCount = 0;
int32_t totalScore = 0;
while (attribute[startPos] != '\0') {
ret = ParseAttributeValue(attribute, &startPos, &key, &value);
if (ret != CRYPT_SUCCESS) {
break;
}
BSL_HASH_Iterator it = BSL_HASH_Find(hash, (uintptr_t)key);
if (it == BSL_HASH_IterEnd(hash)) {
BSL_SAL_Free(key);
AttributeValueFree(value);
continue;
}
BslList *valueList = (BslList *)BSL_HASH_IterValue(hash, it);
for (void *listValue = BSL_LIST_GET_FIRST(valueList);
listValue != NULL; listValue = BSL_LIST_GET_NEXT(valueList)) {
AttributeValue *hashValue = (AttributeValue *)listValue;
ret = CompareAttributeValue(value, hashValue, &comparedCount,
&satisfiedMustCount, &totalScore);
if (ret == -1) {
BSL_SAL_Free(key);
AttributeValueFree(value);
return -1;
}
if (comparedCount == attributeNum) {
BSL_SAL_Free(key);
AttributeValueFree(value);
return (satisfiedMustCount < mustAttributeNum) ? -1 : totalScore;
}
}
BSL_SAL_Free(key);
AttributeValueFree(value);
}
if (satisfiedMustCount < mustAttributeNum) {
return -1;
}
return totalScore;
}
static void FindHighestScoreFunc(CRYPT_EAL_LibCtx *localCtx, int32_t operaId, int32_t algId,
InputAttributeStrInfo attrInfo, const CRYPT_EAL_Func **implFunc, CRYPT_EAL_ProvMgrCtx **mgrCtx)
{
int32_t ret;
int32_t totalScore = -1;
int32_t index = 0;
const char *attribute = attrInfo.attribute;
BSL_HASH_Hash *hash = attrInfo.hash;
uint32_t attributeNum = attrInfo.attributeNum;
uint32_t mustAttributeNum = attrInfo.mustAttributeNum;
uint32_t repeatFlag = attrInfo.repeatFlag;
CRYPT_EAL_ProvMgrCtx *node = BSL_LIST_GET_FIRST(localCtx->providers);
for (; node!= NULL; node = BSL_LIST_GET_NEXT(localCtx->providers)) {
CRYPT_EAL_AlgInfo *algInfos = NULL;
ret = node->provQueryCb(node->provCtx, operaId, &algInfos);
if (ret != CRYPT_SUCCESS) {
continue;
}
for (index = 0; algInfos != NULL && algInfos[index].algId != 0; index++) {
if (algInfos[index].algId != algId) {
continue;
}
if (attribute == NULL) {
*implFunc = algInfos[index].implFunc;
*mgrCtx = node;
return;
}
int32_t tempScore;
tempScore = CompareAttribute(hash, algInfos[index].attr, mustAttributeNum, attributeNum);
if (tempScore <= totalScore) {
continue;
}
totalScore = tempScore;
*implFunc = algInfos[index].implFunc;
*mgrCtx = node;
if (repeatFlag) {
continue;
}
return;
}
}
}
int32_t CRYPT_EAL_CompareAlgAndAttr(CRYPT_EAL_LibCtx *localCtx, int32_t operaId,
int32_t algId, const char *attribute, const CRYPT_EAL_Func **funcs, CRYPT_EAL_ProvMgrCtx **mgrCtx)
{
int32_t ret;
const CRYPT_EAL_Func *implFunc = NULL;
CRYPT_EAL_ProvMgrCtx *ctx = NULL;
InputAttributeStrInfo attrInfo = {0};
if (attribute != NULL) {
attrInfo.attribute = attribute;
ret = ParseAttributeString(&attrInfo);
if (ret != BSL_SUCCESS) {
return ret;
}
attrInfo.repeatFlag = (attrInfo.attributeNum != attrInfo.mustAttributeNum) ? true : false;
}
ret = BSL_SAL_ThreadWriteLock(localCtx->lock);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
BSL_HASH_Destory(attrInfo.hash);
return ret;
}
FindHighestScoreFunc(localCtx, operaId, algId, attrInfo, &implFunc, &ctx);
BSL_SAL_ThreadUnlock(localCtx->lock);
BSL_HASH_Destory(attrInfo.hash);
if (implFunc == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NOT_SUPPORT);
return CRYPT_NOT_SUPPORT;
}
*funcs = implFunc;
if (mgrCtx != NULL) {
*mgrCtx = ctx;
}
return CRYPT_SUCCESS;
}
#endif // HITLS_CRYPTO_PROVIDER
| 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/mgr/crypt_provider_compare.c | C | unknown | 15,323 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
/**
* @defgroup crypt_eal_provider
* @ingroup crypt
* @brief Internal use of provider
*/
#ifndef CRYPT_EAL_PROVIDER_LOCAL_H
#define CRYPT_EAL_PROVIDER_LOCAL_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_PROVIDER
#include <stdint.h>
#include "sal_atomic.h"
#include "crypt_eal_implprovider.h"
#include "bsl_list.h"
#include "crypt_drbg_local.h"
#include "crypt_provider.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
#define DEFAULT_PROVIDER_PATH_LEN_MAX 4095
struct EAL_ProviderMgrCtx {
void *handle; // so handle
void *provCtx;
BSL_SAL_RefCount ref;
char *providerName;
char *providerPath;
#ifdef HITLS_CRYPTO_ENTROPY_DEFAULT
EAL_SeedDrbg providerSeed; // entropy ctx
#endif
struct EAL_LibCtx *libCtx;
CRYPT_EAL_ImplProviderInit provInitFunc;
// out funcs
CRYPT_EAL_ProvFreeCb provFreeCb;
CRYPT_EAL_ProvQueryCb provQueryCb;
CRYPT_EAL_ProvCtrlCb provCtrlCb;
CRYPT_EAL_ProvGetCapsCb provGetCap;
};
int32_t CRYPT_EAL_InitProviderMethod(CRYPT_EAL_ProvMgrCtx *ctx, BSL_Param *param,
CRYPT_EAL_ImplProviderInit providerInit);
CRYPT_EAL_LibCtx *CRYPT_EAL_LibCtxNewInternal(void);
int32_t CRYPT_EAL_CompareAlgAndAttr(CRYPT_EAL_LibCtx *localCtx, int32_t operaId,
int32_t algId, const char *attribute, const CRYPT_EAL_Func **funcs, CRYPT_EAL_ProvMgrCtx **mgrCtx);
void CRYPT_EAL_ProviderMgrCtxFree(CRYPT_EAL_ProvMgrCtx *ctx);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif /* HITLS_CRYPTO_PROVIDER */
#endif // CRYPT_EAL_PROVIDER_LOCAL_H | 2302_82127028/openHiTLS-examples_1508 | crypto/provider/src/mgr/crypt_provider_local.h | C | unknown | 2,060 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef CRYPT_RSA_H
#define CRYPT_RSA_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_RSA
#include <stdlib.h>
#include <stdint.h>
#include "crypt_local_types.h"
#include "bsl_params.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
#define RSA_MIN_MODULUS_BITS 1024
#define RSA_MAX_MODULUS_BITS 16384
#define RSA_SMALL_MODULUS_BYTES (3072 / 8)
#define RSA_MAX_PUBEXP_BYTES (64 / 8)
#define RSA_MIN_MODULUS_LEN (RSA_MIN_MODULUS_BITS / 8)
#define RSA_MAX_MODULUS_LEN (RSA_MAX_MODULUS_BITS / 8)
/* RSA */
typedef struct RSA_Ctx CRYPT_RSA_Ctx;
typedef struct RSA_Para CRYPT_RSA_Para;
/* RSA method */
/**
* @ingroup rsa
* @brief Allocate rsa context memory space.
*
* @retval (CRYPT_RSA_Ctx *) Pointer to the memory space of the allocated context
* @retval NULL Invalid null pointer.
*/
CRYPT_RSA_Ctx *CRYPT_RSA_NewCtx(void); // create key structure
/**
* @ingroup rsa
* @brief Allocate rsa context memory space.
*
* @param libCtx [IN] Library context
*
* @retval (CRYPT_RSA_Ctx *) Pointer to the memory space of the allocated context
* @retval NULL Invalid null pointer.
*/
CRYPT_RSA_Ctx *CRYPT_RSA_NewCtxEx(void *libCtx);
/**
* @ingroup rsa
* @brief Copy the RSA context. After the duplication is complete, call the CRYPT_RSA_FreeCtx to release the memory.
*
* @param ctx [IN] RSA context
*
* @return CRYPT_RSA_Ctx Rsa context pointer
* If the operation fails, a null value is returned.
*/
CRYPT_RSA_Ctx *CRYPT_RSA_DupCtx(CRYPT_RSA_Ctx *keyCtx);
/**
* @ingroup rsa
* @brief Create rsa key parameter structure
*
* @param para [IN] RSA External parameter
*
* @retval (CRYPT_RSA_Para *) Pointer to the allocated memory space of the structure
* @retval NULL Invalid null pointer.
*/
CRYPT_RSA_Para *CRYPT_RSA_NewParaEx(const BSL_Param *para);
/**
* @ingroup rsa
* @brief Release rsa key parameter structure
*
* @param para [IN] Storage pointer in the parameter structure to be released. The parameter is set NULL by the invoker.
*/
void CRYPT_RSA_FreePara(CRYPT_RSA_Para *para);
/**
* @ingroup rsa
* @brief release rsa key context structure
*
* @param ctx [IN] Pointer to the context structure to be released. The ctx is set NULL by the invoker.
*/
void CRYPT_RSA_FreeCtx(CRYPT_RSA_Ctx *ctx);
/**
* @ingroup rsa
* @brief Set the data of the key parameter structure to the key structure.
*
* @param ctx [OUT] Key structure for which related parameters need to be set
* @param para [IN] Key parameter structure
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input.
* @retval CRYPT_RSA_ERR_KEY_BITS The expected key length does not meet the requirements.
* @retval CRYPT_RSA_ERR_E_VALUE The expected value of e does not meet the requirements.
* @retval CRYPT_MEM_ALLOC_FAIL internal memory allocation error
* @retval CRYPT_SUCCESS set successfully.
*/
int32_t CRYPT_RSA_SetPara(CRYPT_RSA_Ctx *ctx, const CRYPT_RsaPara *para);
/**
* @ingroup rsa
* @brief Obtain the valid length of the key.
*
* @param ctx [IN] Structure from which the key length is expected to be obtained
*
* @retval 0: The input is incorrect or the corresponding key structure does not have a valid key length.
* @retval uint32_t: Valid key length
*/
uint32_t CRYPT_RSA_GetBits(const CRYPT_RSA_Ctx *ctx);
#ifdef HITLS_CRYPTO_RSA_GEN
/**
* @ingroup rsa
* @brief Generate the RSA key pair.
*
* @param ctx [IN/OUT] rsa context structure
*
* @retval CRYPT_NULL_INPUT Error null pointer input
* @retval CRYPT_RSA_ERR_KEY_BITS The value of e in the context structure does not meet the requirements.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval BN error An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS The key pair is successfully generated.
*/
int32_t CRYPT_RSA_Gen(CRYPT_RSA_Ctx *ctx);
#endif
#if defined(HITLS_CRYPTO_RSA_ENCRYPT) || defined(HITLS_CRYPTO_RSA_VERIFY) || defined(HITLS_CRYPTO_RSA_SIGN)
/**
* @ingroup rsa
* @brief RSA public key encryption
*
* @param ctx [IN] RSA context structure
* @param input [IN] Information to be encrypted
* @param inputLen [IN] Length of the information to be encrypted
* @param out [OUT] Pointer to the encrypted information output.
* @param outLen [IN/OUT] Pointer to the length of the encrypted information.
* Before being transferred, the value must be set to the maximum length of the array.
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_RSA_NO_KEY_INFO does not contain the key information.
* @retval CRYPT_RSA_ERR_INPUT_VALUE The entered value does not meet the calculation conditions.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_SECUREC_FAIL A security function error occurs.
* @retval BN error An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS encryption succeeded.
*/
int32_t CRYPT_RSA_PubEnc(const CRYPT_RSA_Ctx *ctx, const uint8_t *input, uint32_t inputLen,
uint8_t *out, uint32_t *outLen);
#endif
/**
* @ingroup rsa
* @brief RSA private key decryption
*
* @param ctx [IN] RSA context structure
* @param input [IN] Information to be decrypted
* @param inputLen [IN] Length of the information to be decrypted
* @param out [OUT] Pointer to the decrypted information output.
* @param outLen [IN/OUT] Pointer to the length of the decrypted information.
* Before being transferred, the value must be set to the maximum length of the array.
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_RSA_ERR_DEC_BITS Incorrect length of the encrypted private key.
* @retval CRYPT_RSA_NO_KEY_INFO does not contain the key information.
* @retval CRYPT_RSA_ERR_INPUT_VALUE The entered value does not meet the calculation conditions.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_SECUREC_FAIL A security function error occurs.
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS Decrypted Successfully
*/
int32_t CRYPT_RSA_PrvDec(const CRYPT_RSA_Ctx *ctx, const uint8_t *input, uint32_t inputLen,
uint8_t *out, uint32_t *outLen);
/**
* @ingroup rsa
* @brief RSA Set the private key information.
*
* @param ctx [OUT] rsa context structure
* @param prv [IN] Private key data
*
* @retval CRYPT_NULL_INPUT Error null pointer input
* @retval CRYPT_RSA_ERR_KEY_BITS The key length does not meet the requirements.
* @retval CRYPT_RSA_NO_KEY_INFO does not contain the key information.
* @retval CRYPT_RSA_ERR_INPUT_VALUE The entered value does not meet the calculation conditions.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS The private key is successfully set.
*/
int32_t CRYPT_RSA_SetPrvKey(CRYPT_RSA_Ctx *ctx, const CRYPT_RsaPrv *prv);
/**
* @ingroup rsa
* @brief RSA Set the public key information.
*
* @param ctx [OUT] RSA context structure
* @param pub [IN] Public key data
*
* @retval CRYPT_NULL_INPUT Error null pointer input
* @retval CRYPT_RSA_ERR_KEY_BITS The key length does not meet the requirements.
* @retval CRYPT_RSA_ERR_INPUT_VALUE The entered value does not meet the calculation conditions.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS The public key is successfully set.
*/
int32_t CRYPT_RSA_SetPubKey(CRYPT_RSA_Ctx *ctx, const CRYPT_RsaPub *pub);
/**
* @ingroup rsa
* @brief RSA Obtain the private key information.
*
* @param ctx [IN] RSA context structure
* @param prv [OUT] Private key data
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS The private key is obtained successfully.
*/
int32_t CRYPT_RSA_GetPrvKey(const CRYPT_RSA_Ctx *ctx, CRYPT_RsaPrv *prv);
/**
* @ingroup rsa
* @brief RSA Obtain the public key information.
*
* @param ctx [IN] RSA context structure
* @param pub [OUT] Public key data
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS The public key is obtained successfully.
*/
int32_t CRYPT_RSA_GetPubKey(const CRYPT_RSA_Ctx *ctx, CRYPT_RsaPub *pub);
#ifdef HITLS_BSL_PARAMS
/**
* @ingroup rsa
* @brief RSA Set the private key information.
*
* @param ctx [OUT] rsa context structure
* @param para [IN] Private key data
*
* @retval CRYPT_NULL_INPUT Error null pointer input
* @retval CRYPT_RSA_ERR_KEY_BITS The key length does not meet the requirements.
* @retval CRYPT_RSA_NO_KEY_INFO does not contain the key information.
* @retval CRYPT_RSA_ERR_INPUT_VALUE The entered value does not meet the calculation conditions.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS The private key is successfully set.
*/
int32_t CRYPT_RSA_SetPrvKeyEx(CRYPT_RSA_Ctx *ctx, const BSL_Param *para);
/**
* @ingroup rsa
* @brief RSA Set the public key information.
*
* @param ctx [OUT] RSA context structure
* @param para [IN] Public key data
*
* @retval CRYPT_NULL_INPUT Error null pointer input
* @retval CRYPT_RSA_ERR_KEY_BITS The key length does not meet the requirements.
* @retval CRYPT_RSA_ERR_INPUT_VALUE The entered value does not meet the calculation conditions.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS The public key is successfully set.
*/
int32_t CRYPT_RSA_SetPubKeyEx(CRYPT_RSA_Ctx *ctx, const BSL_Param *para);
/**
* @ingroup rsa
* @brief RSA Obtain the private key information.
*
* @param ctx [IN] RSA context structure
* @param para [OUT] Private key data
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS The private key is obtained successfully.
*/
int32_t CRYPT_RSA_GetPrvKeyEx(const CRYPT_RSA_Ctx *ctx, BSL_Param *para);
/**
* @ingroup rsa
* @brief RSA Obtain the public key information.
*
* @param ctx [IN] RSA context structure
* @param para [OUT] Public key data
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS The public key is obtained successfully.
*/
int32_t CRYPT_RSA_GetPubKeyEx(const CRYPT_RSA_Ctx *ctx, BSL_Param *para);
/**
* @ingroup rsa
* @brief Set the data of the key parameter structure to the key structure.
*
* @param ctx [OUT] Key structure for which related parameters need to be set
* @param para [IN] Key parameter structure
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input.
* @retval CRYPT_RSA_ERR_KEY_BITS The expected key length does not meet the requirements.
* @retval CRYPT_RSA_ERR_E_VALUE The expected value of e does not meet the requirements.
* @retval CRYPT_MEM_ALLOC_FAIL internal memory allocation error
* @retval CRYPT_SUCCESS set successfully.
*/
int32_t CRYPT_RSA_SetParaEx(CRYPT_RSA_Ctx *ctx, const BSL_Param *para);
#endif
int32_t CRYPT_RSA_Ctrl(CRYPT_RSA_Ctx *ctx, int32_t opt, void *val, uint32_t len);
#ifdef HITLS_CRYPTO_RSA_BSSA
#ifdef HITLS_CRYPTO_RSA_SIGN
/**
* @ingroup RSA
* @brief RSA blind operation for blind signature
*
* @param ctx [IN] RSA Context structure
* @param algId [IN] hash Id for input
* @param input [IN] Message to be blinded
* @param inputLen [IN] Length of input message
* @param out [OUT] Blinded message
* @param outLen [OUT] Length of blinded message
*
* @retval CRYPT_SUCCESS on success
* For other error codes, see crypt_errno.h.
*/
int32_t CRYPT_RSA_Blind(CRYPT_RSA_Ctx *ctx, int32_t algId, const uint8_t *input, uint32_t inputLen,
uint8_t *out, uint32_t *outLen);
#endif
#ifdef HITLS_CRYPTO_RSA_VERIFY
/**
* @ingroup RSA
* @brief RSA unblind operation for blind signature
*
* @param ctx [IN] RSA Context structure
* @param input [IN] Blind signature to be unblinded
* @param inputLen [IN] Length of blind signature
* @param out [OUT] Final unblinded signature
* @param outLen [OUT] Length of unblinded signature
*
* @retval CRYPT_SUCCESS on success
* For other error codes, see crypt_errno.h.
*/
int32_t CRYPT_RSA_UnBlind(const CRYPT_RSA_Ctx *ctx, const uint8_t *input, uint32_t inputLen,
uint8_t *out, uint32_t *outLen);
#endif
#endif
#ifdef HITLS_CRYPTO_RSA_EMSA_PSS
#if defined(HITLS_CRYPTO_RSA_SIGN) || defined(HITLS_CRYPTO_RSA_BSSA)
/**
* @ingroup rsa
* @brief Set the PSS for the original data.
*
* @param ctx [IN] CRYPT_RSA_Ctx
* @param hashMethod [IN] pss Required Hash Method
* @param mgfMethod [IN] pss Internal hash method required by the mgf.
* @param saltLen [IN] Length of the input salt.
* @param data [IN] Original data
* @param dataLen [IN] Length of the original data
* @param pad [OUT] pss Output buffer
* @param padLen [OUT] Maximum length of the array output by the PSS.
*
* @retval CRYPT_NULL_INPUT Error null pointer input
* @retval CRYPT_RSA_ERR_PSS_SALT_DATA The salt value does not meet the requirements.
* @retval CRYPT_RSA_ERR_KEY_BITS The key length does not meet the requirements.
* @retval CRYPT_RSA_ERR_PSS_SALT_LEN The salt length does not meet the requirements.
* @retval CRYPT_RSA_BUFF_LEN_NOT_ENOUGH The length of the reserved buffer is insufficient.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_SUCCESS Succeeded in setting the PSS.
*/
int32_t CRYPT_RSA_SetPss(CRYPT_RSA_Ctx *ctx, const EAL_MdMethod *hashMethod, const EAL_MdMethod *mgfMethod,
uint32_t saltLen, const uint8_t *data, uint32_t dataLen, uint8_t *pad, uint32_t padLen);
#endif // HITLS_CRYPTO_RSA_SIGN || HITLS_CRYPTO_RSA_BSSA
#ifdef HITLS_CRYPTO_RSA_VERIFY
/**
* @ingroup rsa
* @brief Compare the original data from the PSS.
*
* @param ctx [IN] CRYPT_RSA_Ctx
* @param hashMethod [IN] pss Required the hash method
* @param mgfMethod [IN] pss Internal hash method required by the mgf.
* @param saltLen [IN] Salt value length
* @param data [IN] Original data
* @param dataLen [IN] Length of the original data
* @param pad [IN] Data after PSS is set.
* @param padLen [IN] Data length after PSS is set.
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_RSA_ERR_PSS_SALT_DATA The salt value does not meet the requirements.
* @retval CRYPT_RSA_ERR_PSS_SALT_LEN The salt length does not meet the requirements.
* @retval CRYPT_RSA_BUFF_LEN_NOT_ENOUGH The length required for padding does not match the input parameter.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_SUCCESS pss comparison succeeded.
*/
int32_t CRYPT_RSA_VerifyPss(CRYPT_RSA_Ctx *ctx, const EAL_MdMethod *hashMethod, const EAL_MdMethod *mgfMethod,
uint32_t saltLen, const uint8_t *data, uint32_t dataLen, const uint8_t *pad, uint32_t padLen);
#endif // HITLS_CRYPTO_RSA_VERIFY
#endif // HITLS_CRYPTO_RSA_EMSA_PSS
#ifdef HITLS_CRYPTO_RSA_EMSA_PKCSV15
/**
* @ingroup rsa
* @brief Set pkcsv1.5 padding.
*
* @param hashId [IN] the hash method required by pkcsv1.5 setting.
* @param data [IN] Original data
* @param dataLen [IN] Length of the original data
* @param pad [OUT] Pointer to the array for receiving the padding.
* @param padLen [IN] Array length for receiving padding.
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_RSA_NO_KEY_INFO The key information is insufficient.
* @retval CRYPT_SECUREC_FAIL The security function fails.
* @retval CRYPT_RSA_BUFF_LEN_NOT_ENOUGH The length required by the padding does not match the input parameter.
* @retval CRYPT_RSA_ERR_INPUT_VALUE The hash algorithm ID is not supported.
* @retval CRYPT_SUCCESS The pkcsv1.5 padding is successfully set.
*/
int32_t CRYPT_RSA_SetPkcsV15Type1(CRYPT_MD_AlgId hashId, const uint8_t *data, uint32_t dataLen,
uint8_t *pad, uint32_t padLen);
#ifdef HITLS_CRYPTO_RSA_VERIFY
/**
* @ingroup rsa
* @brief Verify pkcsv1.5 padding.
*
* @param hashId [IN] the hash method corresponding to pkcsv1.5 verification.
* @param pad [IN] Data after padding
* @param padLen [IN] Data length after padding
* @param data [IN] Original data
* @param dataLen [IN] Length of the original data
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_RSA_ERR_PKCSV15_SALT_DATA Incorrect padding value.
* @retval CRYPT_SECUREC_FAIL Security Function Failure
* @retval CRYPT_RSA_BUFF_LEN_NOT_ENOUGH The length required for padding does not match the input parameter.
* @retval CRYPT_RSA_ERR_INPUT_VALUE The hash algorithm ID is not supported.
* @retval CRYPT_SUCCESS Verify pkcsv1.5 is padded successfully.
*/
int32_t CRYPT_RSA_VerifyPkcsV15Type1(CRYPT_MD_AlgId hashId, const uint8_t *pad, uint32_t padLen,
const uint8_t *data, uint32_t dataLen);
#endif // HITLS_CRYPTO_RSA_VERIFY
#endif // HITLS_CRYPTO_RSA_EMSA_PKCSV15
#if defined(HITLS_CRYPTO_RSA_SIGN) || defined(HITLS_CRYPTO_RSA_VERIFY)
/**
* @ingroup rsa
* @brief Obtain the maximum length of RSA signature data.
*
* @param ctx [IN] Maximum length of the RSA signature data that is expected to be obtained
*
* @retval 0 The input is incorrect or the corresponding key structure does not contain valid key information.
* @retval uint32_t Maximum length of the signature data
*/
uint32_t CRYPT_RSA_GetSignLen(const CRYPT_RSA_Ctx *ctx);
#endif
#ifdef HITLS_CRYPTO_RSA_VERIFY
int32_t CRYPT_RSA_VerifyData(CRYPT_RSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen,
const uint8_t *sign, uint32_t signLen);
int32_t CRYPT_RSA_Verify(CRYPT_RSA_Ctx *ctx, int32_t algId, const uint8_t *data, uint32_t dataLen,
const uint8_t *sign, uint32_t signLen);
#endif
#ifdef HITLS_CRYPTO_RSA_SIGN
int32_t CRYPT_RSA_SignData(CRYPT_RSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen,
uint8_t *sign, uint32_t *signLen);
int32_t CRYPT_RSA_Sign(CRYPT_RSA_Ctx *ctx, int32_t algId, const uint8_t *data, uint32_t dataLen,
uint8_t *sign, uint32_t *signLen);
#endif
#ifdef HITLS_CRYPTO_RSA_ENCRYPT
/**
* @ingroup rsa
* @brief RSA public key encryption
*
* @param ctx [IN] RSA context structure
* @param data [IN] Information to be encrypted
* @param dataLen [IN] Length of the information to be encrypted
* @param out [OUT] Pointer to the encrypted information output.
* @param outLen [OUT] Pointer to the length of the encrypted information
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_RSA_NO_KEY_INFO does not contain the key information.
* @retval CRYPT_RSA_ERR_INPUT_VALUE The entered value does not meet the calculation conditions.
* @retval CRYPT_RSA_BUFF_LEN_NOT_ENOUGH Outbuf Insufficient
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_SECUREC_FAIL A safe function error occurs.
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_EAL_ALG_NOT_SUPPORT does not register the encryption method.
* @retval CRYPT_SUCCESS encryption succeeded.
*/
int32_t CRYPT_RSA_Encrypt(CRYPT_RSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen,
uint8_t *out, uint32_t *outLen);
#endif
#ifdef HITLS_CRYPTO_RSA_DECRYPT
/**
* @ingroup rsa
* @brief RSA private key decryption
*
* @param ctx [IN] RSA context structure
* @param data [IN] Information to be decrypted
* @param dataLen [IN] Length of the information to be decrypted
* @param out [OUT] Pointer to the output information after decryption.
* @param outLen [OUT] Pointer to the length of the decrypted information
*
* @retval CRYPT_NULL_INPUT Error null pointer input
* @retval CRYPT_RSA_NO_KEY_INFO does not contain the key information.
* @retval CRYPT_RSA_ERR_INPUT_VALUE The entered value does not meet the calculation conditions.
* @retval CRYPT_RSA_BUFF_LEN_NOT_ENOUGH Outbuf Insufficient
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_SECUREC_FAIL A security function error occurs.
* @retval CRYPT_EAL_ALG_NOT_SUPPORT does not register the decryption method.
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS Decryption succeeded.
*/
int32_t CRYPT_RSA_Decrypt(CRYPT_RSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen,
uint8_t *out, uint32_t *outLen);
#endif
#ifdef HITLS_CRYPTO_RSA_VERIFY
/**
* @ingroup rsa
* @brief RSA public key decryption
*
* @param ctx [IN] RSA context structure
* @param data [IN] Information to be decrypted
* @param dataLen [IN] Length of the information to be decrypted
* @param out [OUT] Pointer to the output information after decryption.
* @param outLen [IN/OUT] Pointer to the length of the decrypted information.
* Before being transferred, the value must be set to the maximum length of the array.
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_RSA_NO_KEY_INFO does not contain the key information.
* @retval CRYPT_RSA_PAD_NO_SET_ERROR The padding type is not set.
* @retval CRYPT_RSA_BUFF_LEN_NOT_ENOUGH The space is insufficient after decryption.
* @retval CRYPT_RSA_ERR_INPUT_VALUE The input parameter does not meet the requirements.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval Other error codes, for example, the CRYPT_RSA_UnPackPkcsV15Type1 de-padding function.
* @retval CRYPT_SUCCESS Decrypted Successfully
*/
int32_t CRYPT_RSA_Recover(CRYPT_RSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint8_t *out, uint32_t *outLen);
#endif
/**
* @ingroup rsa
* @brief RSA compare the public key
*
* @param a [IN] RSA context structure
* @param b [IN] RSA context structure
*
* @retval CRYPT_SUCCESS is the same
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_RSA_NO_KEY_INFO No public key
* @retval CRYPT_RSA_PUBKEY_NOT_EQUAL Public Keys are not equal
*/
int32_t CRYPT_RSA_Cmp(const CRYPT_RSA_Ctx *a, const CRYPT_RSA_Ctx *b);
#ifdef HITLS_CRYPTO_RSAES_OAEP
#ifdef HITLS_CRYPTO_RSA_ENCRYPT
/**
* @ingroup rsa
* @brief oaep padding
*
* @param hashMethod [IN] Hash method. Only sha1, sha244, sha256, sha384, and sha512 are supported.
* @param mgfMethod [IN] Hash method required by mgf
* @param in [IN] Original data
* @param inLen [IN] Original data length
* @param param [IN] oaep parameter, which can be null
* @param paramLen [IN] oaep Parameter length
* @param pad [IN] Data after padding
* @param padLen [IN] Data length after padding
*
* @retval CRYPT_NULL_INPUT Error null pointer input
* @retval CRYPT_RSA_ERR_INPUT_VALUE The entered value does not meet the calculation conditions.
* @retval CRYPT_SECUREC_FAIL A security function error occurs.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_RSA_BUFF_LEN_NOT_ENOUGH Outbuf Insufficient
* */
int32_t CRYPT_RSA_SetPkcs1Oaep(CRYPT_RSA_Ctx *ctx, const uint8_t *in, uint32_t inLen, uint8_t *pad, uint32_t padLen);
#endif // HITLS_CRYPTO_RSA_ENCRYPT
#ifdef HITLS_CRYPTO_RSA_DECRYPT
/**
* @ingroup rsa
* @brief Verify the oaep padding.
*
* @param pad [IN] oaep parameter, which can be null
* @param in [IN] Data after padding
* @param inLen [IN] Data length after padding
* @param param [IN] oaep parameter, which can be null
* @param paramLen [IN] oaep Parameter length
* @param msg [IN] Data after the de-padding
* @param msgLen [IN/OUT] The input parameter is the length of the msg buffer,
* and the output parameter is the length of the msg after the de-padding.
*
* @retval CRYPT_NULL_INPUT Error null pointer input
* @retval CRYPT_RSA_ERR_INPUT_VALUE The entered value does not meet the calculation conditions.
* @retval CRYPT_SECUREC_FAIL A security function error occurs.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* */
int32_t CRYPT_RSA_VerifyPkcs1Oaep(RSA_PadingPara *pad, const uint8_t *in, uint32_t inLen, const uint8_t *param,
uint32_t paramLen, uint8_t *msg, uint32_t *msgLen);
#endif // HITLS_CRYPTO_RSA_DECRYPT
#endif // HITLS_CRYPTO_RSAES_OAEP
#if defined(HITLS_CRYPTO_RSA_ENCRYPT) && \
(defined(HITLS_CRYPTO_RSAES_PKCSV15_TLS) || defined(HITLS_CRYPTO_RSAES_PKCSV15))
int32_t CRYPT_RSA_SetPkcsV15Type2(void *libCtx, const uint8_t *in, uint32_t inLen,
uint8_t *out, uint32_t outLen);
#endif
#ifdef HITLS_CRYPTO_RSA_DECRYPT
#ifdef HITLS_CRYPTO_RSAES_PKCSV15
int32_t CRYPT_RSA_VerifyPkcsV15Type2(const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen);
#endif
#ifdef HITLS_CRYPTO_RSAES_PKCSV15_TLS
int32_t CRYPT_RSA_VerifyPkcsV15Type2TLS(const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen);
#endif
#endif // HITLS_CRYPTO_RSA_DECRYPT
/**
* @ingroup rsa
* @brief rsa get security bits
*
* @param ctx [IN] rsa Context structure
*
* @retval security bits
*/
int32_t CRYPT_RSA_GetSecBits(const CRYPT_RSA_Ctx *ctx);
#ifdef HITLS_CRYPTO_RSA_CHECK
/**
* @ingroup rsa
* @brief check the key pair consistency
*
* @param checkType [IN] check type
* @param pkey1 [IN] rsa key context structure
* @param pkey2 [IN] rsa key context structure
*
* @retval CRYPT_SUCCESS check success.
* Others. For details, see error code in errno.
*/
int32_t CRYPT_RSA_Check(uint32_t checkType, const CRYPT_RSA_Ctx *pkey1, const CRYPT_RSA_Ctx *pkey2);
#endif // HITLS_CRYPTO_RSA_CHECK
#ifdef HITLS_CRYPTO_PROVIDER
/**
* @ingroup RSA
* @brief RSA import key
*
* @param ctx [IN/OUT] RSA context structure
* @param params [IN] parameters
*/
int32_t CRYPT_RSA_Import(CRYPT_RSA_Ctx *ctx, const BSL_Param *params);
/**
* @ingroup RSA
* @brief RSA export key
*
* @param ctx [IN] RSA context structure
* @param params [IN/OUT] key parameters
*/
int32_t CRYPT_RSA_Export(const CRYPT_RSA_Ctx *ctx, BSL_Param *params);
#endif // HITLS_CRYPTO_PROVIDER
#ifdef __cplusplus
}
#endif
#endif // HITLS_CRYPTO_RSA
#endif // CRYPT_RSA_H
| 2302_82127028/openHiTLS-examples_1508 | crypto/rsa/include/crypt_rsa.h | C | unknown | 27,743 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_RSA_BLINDING) || defined(HITLS_CRYPTO_RSA_BSSA)
#include "crypt_utils.h"
#include "crypt_rsa.h"
#include "rsa_local.h"
#include "crypt_errno.h"
#include "bsl_sal.h"
#include "securec.h"
#include "bsl_err_internal.h"
RSA_Blind *RSA_BlindNewCtx(void)
{
RSA_Blind *ret = BSL_SAL_Malloc(sizeof(RSA_Blind));
if (ret == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
(void)memset_s(ret, sizeof(RSA_Blind), 0, sizeof(RSA_Blind));
return ret;
}
void RSA_BlindFreeCtx(RSA_Blind *b)
{
if (b == NULL) {
return;
}
BN_Destroy(b->r);
BN_Destroy(b->rInv);
BSL_SAL_FREE(b);
}
static int32_t BlindUpdate(RSA_Blind *b, BN_BigNum *n, BN_Optimizer *opt)
{
int32_t ret = BN_ModMul(b->r, b->r, b->r, n, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = BN_ModMul(b->rInv, b->rInv, b->rInv, n, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
int32_t RSA_BlindCovert(RSA_Blind *b, BN_BigNum *data, BN_BigNum *n, BN_Optimizer *opt)
{
int32_t ret;
ret = BlindUpdate(b, n, opt);
if (ret != CRYPT_SUCCESS) {
return ret;
}
// 8. z = m * x mod n
ret = BN_ModMul(data, data, b->r, n, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
int32_t RSA_BlindInvert(RSA_Blind *b, BN_BigNum *data, BN_BigNum *n, BN_Optimizer *opt)
{
int32_t ret;
ret = BN_ModMul(data, data, b->rInv, n, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
int32_t RSA_CreateBlind(RSA_Blind *b, uint32_t bits)
{
// create a BigNum
b->r = BN_Create(bits);
if (b->r == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
b->rInv = BN_Create(bits);
if (b->rInv == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
return CRYPT_SUCCESS;
}
/*
* Initializes blind signature parameters for an RSA key.
* Ref. https://www.rfc-editor.org/rfc/rfc9474.html#name-blind
*
* As RFC-9474 Section 2.1, we need to do this.
* 1. Generates a random blinding factor r
* 2. Computes r^(-1) mod n (modular inverse)
* 3. Computes r^e mod n (where e is the public exponent)
*/
int32_t RSA_BlindCreateParam(void *libCtx, RSA_Blind *b, BN_BigNum *e, BN_BigNum *n, uint32_t bits, BN_Optimizer *opt)
{
int32_t ret;
if (b == NULL || e == NULL || n == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
BN_Destroy(b->r);
BN_Destroy(b->rInv);
b->r = NULL;
b->rInv = NULL;
ret = RSA_CreateBlind(b, bits);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto END;
}
// b->r = random_integer_uniform(1, n)
ret = BN_RandRangeEx(libCtx, b->r, n);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto END;
}
// b->rInv = inverse_mod(r, n)
ret = BN_ModInv(b->rInv, b->r, n, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto END;
}
// b->r = RSAVP1(pk, r)
ret = BN_ModExp(b->r, b->r, e, n, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto END;
}
return ret;
END:
BN_Destroy(b->r);
BN_Destroy(b->rInv);
b->r = NULL;
b->rInv = NULL;
return ret;
}
#endif /* HITLS_CRYPTO_RSA_BLINDING || HITLS_CRYPTO_RSA_BSSA */ | 2302_82127028/openHiTLS-examples_1508 | crypto/rsa/src/rsa_blinding.c | C | unknown | 4,123 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_RSA
#include "crypt_utils.h"
#include "rsa_local.h"
#include "crypt_errno.h"
#include "securec.h"
#include "eal_md_local.h"
#ifdef HITLS_CRYPTO_RSA_EMSA_PKCSV15
static int32_t SetEmsaPkcsV15(CRYPT_RSA_Ctx *ctx, void *val, uint32_t len)
{
if (val == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (len != sizeof(int32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_SET_EMS_PKCSV15_LEN_ERROR);
return CRYPT_RSA_SET_EMS_PKCSV15_LEN_ERROR;
}
static const uint32_t SIGN_MD_ID_LIST[] = { CRYPT_MD_SHA224, CRYPT_MD_SHA256,
CRYPT_MD_SHA384, CRYPT_MD_SHA512, CRYPT_MD_SM3, CRYPT_MD_SHA1, CRYPT_MD_MD5
};
int32_t mdId = *(int32_t *)val;
if (ParamIdIsValid(mdId, SIGN_MD_ID_LIST, sizeof(SIGN_MD_ID_LIST) / sizeof(SIGN_MD_ID_LIST[0])) == false) {
// This hash algorithm is not supported.
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_MD_ALGID);
return CRYPT_RSA_ERR_MD_ALGID;
}
(void)memset_s(&(ctx->pad), sizeof(RSAPad), 0, sizeof(RSAPad));
ctx->pad.type = EMSA_PKCSV15;
ctx->pad.para.pkcsv15.mdId = mdId;
return CRYPT_SUCCESS;
}
#endif
#ifdef HITLS_CRYPTO_RSA_EMSA_PSS
static int32_t SetEmsaPss(CRYPT_RSA_Ctx *ctx, RSA_PadingPara *pad, void *mdProvCtx, void *mgfProvCtx)
{
uint32_t bits = CRYPT_RSA_GetBits(ctx);
if (bits == 0) {
// The valid key information does not exist.
BSL_ERR_PUSH_ERROR(CRYPT_RSA_NO_KEY_INFO);
return CRYPT_RSA_NO_KEY_INFO;
}
if (pad->saltLen < CRYPT_RSA_SALTLEN_TYPE_AUTOLEN) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_SALT_LEN);
return CRYPT_RSA_ERR_SALT_LEN;
}
uint32_t saltLen = (uint32_t)pad->saltLen;
if (pad->saltLen == CRYPT_RSA_SALTLEN_TYPE_HASHLEN) {
saltLen = pad->mdMeth.mdSize;
}
uint32_t bytes = BN_BITS_TO_BYTES(bits);
// The minimum specification supported by RSA is 1K,
// and the maximum hash length supported by the hash algorithm is 64 bytes.
// Therefore, specifying the salt length as the maximum available length is satisfied.
if (pad->saltLen != CRYPT_RSA_SALTLEN_TYPE_MAXLEN && pad->saltLen != CRYPT_RSA_SALTLEN_TYPE_AUTOLEN &&
saltLen > bytes - pad->mdMeth.mdSize - 2) { // maximum length of the salt is padLen-mdMethod->GetDigestSize-2
// The configured salt length does not meet the specification.
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_PSS_SALT_LEN);
return CRYPT_RSA_ERR_PSS_SALT_LEN;
}
(void)memset_s(&(ctx->pad), sizeof(RSAPad), 0, sizeof(RSAPad));
(void)memcpy_s(&(ctx->pad.para.pss), sizeof(RSA_PadingPara), pad, sizeof(RSA_PadingPara));
ctx->pad.type = EMSA_PSS;
ctx->pad.para.pss.mdId = pad->mdId;
ctx->pad.para.pss.mgfId = pad->mgfId;
ctx->pad.para.pss.mdProvCtx = mdProvCtx;
ctx->pad.para.pss.mgfProvCtx = mgfProvCtx;
return CRYPT_SUCCESS;
}
#endif // HITLS_CRYPTO_RSA_EMSA_PSS
#ifdef HITLS_CRYPTO_RSAES_OAEP
void SetOaep(CRYPT_RSA_Ctx *ctx, const RSA_PadingPara *val)
{
(void)memset_s(&(ctx->pad), sizeof(RSAPad), 0, sizeof(RSAPad));
(void)memcpy_s(&(ctx->pad.para.oaep), sizeof(RSA_PadingPara), val, sizeof(RSA_PadingPara));
ctx->pad.type = RSAES_OAEP;
return;
}
static int32_t SetOaepLabel(CRYPT_RSA_Ctx *ctx, const void *val, uint32_t len)
{
uint8_t *data = NULL;
// val can be NULL
if ((val == NULL && len != 0) || (len == 0 && val != NULL)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (len == 0 && val == NULL) {
BSL_SAL_FREE(ctx->label.data);
ctx->label.data = NULL;
ctx->label.len = 0;
return CRYPT_SUCCESS;
}
data = (uint8_t *)BSL_SAL_Malloc(len);
if (data == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
BSL_SAL_FREE(ctx->label.data);
ctx->label.data = data;
ctx->label.len = len;
(void)memcpy_s(ctx->label.data, ctx->label.len, val, len);
return CRYPT_SUCCESS;
}
#endif
#if defined(HITLS_CRYPTO_RSAES_PKCSV15) || defined(HITLS_CRYPTO_RSAES_PKCSV15_TLS)
static int32_t SetRsaesPkcsV15(CRYPT_RSA_Ctx *ctx, const void *val, uint32_t len)
{
if (val == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (len != sizeof(int32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_SET_EMS_PKCSV15_LEN_ERROR);
return CRYPT_RSA_SET_EMS_PKCSV15_LEN_ERROR;
}
(void)memset_s(&(ctx->pad), sizeof(RSAPad), 0, sizeof(RSAPad));
ctx->pad.para.pkcsv15.mdId = *(const int32_t *)val;
ctx->pad.type = RSAES_PKCSV15;
return CRYPT_SUCCESS;
}
#endif
#ifdef HITLS_CRYPTO_RSAES_PKCSV15_TLS
static int32_t SetRsaesPkcsV15Tls(CRYPT_RSA_Ctx *ctx, const void *val, uint32_t len)
{
int32_t ret = SetRsaesPkcsV15(ctx, val, len);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ctx->pad.type = RSAES_PKCSV15_TLS;
return CRYPT_SUCCESS;
}
#endif
#ifdef HITLS_CRYPTO_RSA_EMSA_PSS
static int32_t SetSalt(CRYPT_RSA_Ctx *ctx, void *val, uint32_t len)
{
if (val == NULL || len == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->prvKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_NO_KEY_INFO);
return CRYPT_RSA_NO_KEY_INFO;
}
if (ctx->pad.type != EMSA_PSS) {
// In non-PSS mode, salt information cannot be set.
BSL_ERR_PUSH_ERROR(CRYPT_RSA_SET_SALT_NOT_PSS_ERROR);
return CRYPT_RSA_SET_SALT_NOT_PSS_ERROR;
}
RSA_PadingPara *pad = &(ctx->pad.para.pss);
if (pad->mdMeth.id == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
uint32_t bytes = BN_BITS_TO_BYTES(CRYPT_RSA_GetBits(ctx));
// The maximum salt length is padLen - mdMethod->GetDigestSize - 2
if (len > bytes - pad->mdMeth.mdSize - 2) {
// The configured salt length does not meet the specification.
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_SALT_LEN);
return CRYPT_RSA_ERR_SALT_LEN;
}
ctx->pad.salt.data = val;
ctx->pad.salt.len = len;
return CRYPT_SUCCESS;
}
static int32_t GetSaltLen(CRYPT_RSA_Ctx *ctx, void *val, uint32_t len)
{
if (val == NULL || len == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (len != sizeof(int32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_GET_SALT_LEN_ERROR);
return CRYPT_RSA_GET_SALT_LEN_ERROR;
}
if (ctx->prvKey == NULL && ctx->pubKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_NO_KEY_INFO);
return CRYPT_RSA_NO_KEY_INFO;
}
if (ctx->pad.type != EMSA_PSS) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_GET_SALT_NOT_PSS_ERROR);
return CRYPT_RSA_GET_SALT_NOT_PSS_ERROR;
}
int32_t *ret = val;
int32_t valTmp;
RSA_PadingPara *pad = &(ctx->pad.para.pss);
if (pad->mdMeth.id == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_PSS_PARAMS);
return CRYPT_RSA_ERR_PSS_PARAMS;
}
uint32_t bytes = BN_BITS_TO_BYTES(CRYPT_RSA_GetBits(ctx));
if (pad->saltLen == CRYPT_RSA_SALTLEN_TYPE_HASHLEN) { // saltLen is -1
valTmp = (int32_t)pad->mdMeth.mdSize;
} else if (pad->saltLen == CRYPT_RSA_SALTLEN_TYPE_MAXLEN ||
pad->saltLen == CRYPT_RSA_SALTLEN_TYPE_AUTOLEN) {
// RFC 8017: Max(salt length) = ceil(bits/8) - mdSize - 2
valTmp = (int32_t)(bytes - pad->mdMeth.mdSize - 2);
} else {
valTmp = (int32_t)pad->saltLen;
}
if (valTmp < 0) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_SALT_LEN);
return CRYPT_RSA_ERR_SALT_LEN;
}
*ret = valTmp;
return CRYPT_SUCCESS;
}
#endif
static uint32_t RSAGetKeyLen(CRYPT_RSA_Ctx *ctx)
{
return BN_BITS_TO_BYTES(CRYPT_RSA_GetBits(ctx));
}
static int32_t GetPadding(CRYPT_RSA_Ctx *ctx, void *val, uint32_t len)
{
RSA_PadType *valTmp = val;
if (val == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (len != sizeof(int32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
*valTmp = ctx->pad.type;
return CRYPT_SUCCESS;
}
static int32_t GetMd(CRYPT_RSA_Ctx *ctx, void *val, uint32_t len)
{
CRYPT_MD_AlgId *valTmp = val;
if (val == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (len != sizeof(int32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
if (ctx->pad.type == EMSA_PKCSV15) {
*valTmp = ctx->pad.para.pkcsv15.mdId;
return CRYPT_SUCCESS;
}
*valTmp = ctx->pad.para.pss.mdId;
return CRYPT_SUCCESS;
}
static int32_t GetMgf(CRYPT_RSA_Ctx *ctx, void *val, uint32_t len)
{
CRYPT_MD_AlgId *valTmp = val;
if (val == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (len != sizeof(int32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
if (ctx->pad.type == EMSA_PKCSV15) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_ALGID);
return CRYPT_RSA_ERR_ALGID;
}
*valTmp = ctx->pad.para.pss.mgfId;
return CRYPT_SUCCESS;
}
static int32_t SetFlag(CRYPT_RSA_Ctx *ctx, const void *val, uint32_t len)
{
if (val == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (len != sizeof(uint32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_SET_FLAG_LEN_ERROR);
return CRYPT_RSA_SET_FLAG_LEN_ERROR;
}
uint32_t flag = *(const uint32_t *)val;
if (flag == 0 || flag >= CRYPT_RSA_MAXFLAG) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_FLAG_NOT_SUPPORT_ERROR);
return CRYPT_RSA_FLAG_NOT_SUPPORT_ERROR;
}
ctx->flags |= flag;
return CRYPT_SUCCESS;
}
static int32_t ClearFlag(CRYPT_RSA_Ctx *ctx, const void *val, uint32_t len)
{
if (val == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (len != sizeof(uint32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
uint32_t flag = *(const uint32_t *)val;
if (flag == 0 || flag >= CRYPT_RSA_MAXFLAG) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_FLAG_NOT_SUPPORT_ERROR);
return CRYPT_RSA_FLAG_NOT_SUPPORT_ERROR;
}
ctx->flags &= ~flag;
return CRYPT_SUCCESS;
}
static int32_t RsaUpReferences(CRYPT_RSA_Ctx *ctx, void *val, uint32_t len)
{
if (val != NULL && len == (uint32_t)sizeof(int)) {
return BSL_SAL_AtomicUpReferences(&(ctx->references), (int *)val);
}
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
static int32_t SetRsaPad(CRYPT_RSA_Ctx *ctx, const void *val, uint32_t len)
{
if (val == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (len != sizeof(int32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
int32_t pad = *(const int32_t *)val;
if (pad < EMSA_PKCSV15 || pad > RSA_NO_PAD) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
ctx->pad.type = pad;
return CRYPT_SUCCESS;
}
#if defined(HITLS_CRYPTO_RSAES_OAEP) || defined(HITLS_CRYPTO_RSA_EMSA_PSS)
static int32_t MdIdCheckSha1Sha2(CRYPT_MD_AlgId id)
{
if (id < CRYPT_MD_MD5 || id > CRYPT_MD_SHA512) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_ALGID);
return CRYPT_EAL_ERR_ALGID;
}
return CRYPT_SUCCESS;
}
#endif
#ifdef HITLS_CRYPTO_RSAES_OAEP
static int32_t RsaSetOaep(CRYPT_RSA_Ctx *ctx, BSL_Param *param)
{
int32_t ret;
uint32_t len = 0;
RSA_PadingPara padPara = {0};
const BSL_Param *temp = NULL;
if (param == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_RSA_MD_ID)) != NULL) {
len = sizeof(padPara.mdId);
GOTO_ERR_IF(BSL_PARAM_GetValue(temp, CRYPT_PARAM_RSA_MD_ID,
BSL_PARAM_TYPE_INT32, &padPara.mdId, &len), ret);
}
if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_RSA_MGF1_ID)) != NULL) {
len = sizeof(padPara.mgfId);
GOTO_ERR_IF(BSL_PARAM_GetValue(temp, CRYPT_PARAM_RSA_MGF1_ID,
BSL_PARAM_TYPE_INT32, &padPara.mgfId, &len), ret);
}
ret = MdIdCheckSha1Sha2(padPara.mdId);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = MdIdCheckSha1Sha2(padPara.mgfId);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
void *mdProvCtx = NULL;
void *mgfProvCtx = NULL;
EAL_MdMethod *mdMeth = EAL_MdFindMethodEx(padPara.mdId, LIBCTX_FROM_RSA_CTX(ctx), MDATTR_FROM_RSA_CTX(ctx),
&padPara.mdMeth, &mdProvCtx);
EAL_MdMethod *mgfMeth = EAL_MdFindMethodEx(padPara.mgfId, LIBCTX_FROM_RSA_CTX(ctx), MDATTR_FROM_RSA_CTX(ctx),
&padPara.mgfMeth, &mgfProvCtx);
if (mdMeth == NULL || mgfMeth == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_ALGID);
return CRYPT_EAL_ERR_ALGID;
}
padPara.mdProvCtx = mdProvCtx;
padPara.mgfProvCtx = mgfProvCtx;
SetOaep(ctx, &padPara);
ERR:
return ret;
}
#endif
#ifdef HITLS_CRYPTO_RSA_EMSA_PSS
static int32_t RsaSetPss(CRYPT_RSA_Ctx *ctx, BSL_Param *param)
{
int32_t ret;
uint32_t len = 0;
RSA_PadingPara padPara = {0};
const BSL_Param *temp = NULL;
if (param == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_RSA_MD_ID)) != NULL) {
len = sizeof(padPara.mdId);
GOTO_ERR_IF(BSL_PARAM_GetValue(temp, CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &padPara.mdId, &len), ret);
}
if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_RSA_MGF1_ID)) != NULL) {
len = sizeof(padPara.mgfId);
GOTO_ERR_IF(BSL_PARAM_GetValue(temp, CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &padPara.mgfId, &len), ret);
}
if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_RSA_SALTLEN)) != NULL) {
len = sizeof(padPara.saltLen);
GOTO_ERR_IF(BSL_PARAM_GetValue(temp, CRYPT_PARAM_RSA_SALTLEN,
BSL_PARAM_TYPE_INT32, &padPara.saltLen, &len), ret);
}
ret = MdIdCheckSha1Sha2(padPara.mdId);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = MdIdCheckSha1Sha2(padPara.mgfId);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
void *mdProvCtx = NULL;
void *mgfProvCtx = NULL;
EAL_MdMethod *mdMeth = EAL_MdFindMethodEx(padPara.mdId, LIBCTX_FROM_RSA_CTX(ctx), MDATTR_FROM_RSA_CTX(ctx),
&padPara.mdMeth, &mdProvCtx);
EAL_MdMethod *mgfMeth = EAL_MdFindMethodEx(padPara.mgfId, LIBCTX_FROM_RSA_CTX(ctx), MDATTR_FROM_RSA_CTX(ctx),
&padPara.mgfMeth, &mgfProvCtx);
if (mdMeth == NULL || mgfMeth == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_ALGID);
return CRYPT_EAL_ERR_ALGID;
}
ret = SetEmsaPss(ctx, &padPara, mdProvCtx, mgfProvCtx);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
ERR:
return ret;
}
#endif
static int32_t RsaCommonCtrl(CRYPT_RSA_Ctx *ctx, int32_t opt, void *val, uint32_t len)
{
switch (opt) {
case CRYPT_CTRL_UP_REFERENCES:
return RsaUpReferences(ctx, val, len);
case CRYPT_CTRL_GET_BITS:
return GetUintCtrl(ctx, val, len, (GetUintCallBack)CRYPT_RSA_GetBits);
case CRYPT_CTRL_GET_SECBITS:
return GetUintCtrl(ctx, val, len, (GetUintCallBack)CRYPT_RSA_GetSecBits);
case CRYPT_CTRL_SET_RSA_FLAG:
return SetFlag(ctx, val, len);
case CRYPT_CTRL_CLR_RSA_FLAG:
return ClearFlag(ctx, val, len);
case CRYPT_CTRL_GET_PUBKEY_LEN:
case CRYPT_CTRL_GET_PRVKEY_LEN:
return GetUintCtrl(ctx, val, len, (GetUintCallBack)RSAGetKeyLen);
default:
BSL_ERR_PUSH_ERROR(CRYPT_RSA_CTRL_NOT_SUPPORT_ERROR);
return CRYPT_RSA_CTRL_NOT_SUPPORT_ERROR;
}
}
#ifdef HITLS_CRYPTO_RSA_BSSA
static int32_t SetBssaParamCheck(CRYPT_RSA_Ctx *ctx, const void *val, uint32_t len)
{
if (val == NULL || len == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->pubKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_NO_PUBKEY_INFO);
return CRYPT_RSA_ERR_NO_PUBKEY_INFO;
}
return CRYPT_SUCCESS;
}
static int32_t RsaSetBssa(CRYPT_RSA_Ctx *ctx, const void *val, uint32_t len)
{
int32_t ret = SetBssaParamCheck(ctx, val, len);
if (ret != CRYPT_SUCCESS) {
return ret;
}
const uint8_t *r = (const uint8_t *)val;
BN_Optimizer *opt = BN_OptimizerCreate();
if (opt == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
RSA_Blind *blind = NULL;
RSA_BlindParam *param = ctx->blindParam;
if (param == NULL) {
param = BSL_SAL_Calloc(1u, sizeof(RSA_BlindParam));
if (param == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
goto ERR;
}
param->type = RSABSSA;
}
if (param->para.bssa != NULL) {
RSA_BlindFreeCtx(param->para.bssa);
param->para.bssa = NULL;
}
param->para.bssa = RSA_BlindNewCtx();
if (param->para.bssa == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
goto ERR;
}
blind = param->para.bssa;
GOTO_ERR_IF(RSA_CreateBlind(blind, 0), ret);
GOTO_ERR_IF(BN_Bin2Bn(blind->r, r, len), ret);
if (BN_IsZero(blind->r) || (BN_Cmp(blind->r, ctx->pubKey->n) >= 0)) { // 1 <= r < n
ret = CRYPT_RSA_ERR_BSSA_PARAM;
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_BSSA_PARAM);
goto ERR;
}
GOTO_ERR_IF(BN_ModInv(blind->rInv, blind->r, ctx->pubKey->n, opt), ret);
GOTO_ERR_IF(BN_ModExp(blind->r, blind->r, ctx->pubKey->e, ctx->pubKey->n, opt), ret);
ctx->blindParam = param;
ERR:
if (ret != CRYPT_SUCCESS && ctx->blindParam == NULL && param != NULL) {
RSA_BlindFreeCtx(param->para.bssa);
BSL_SAL_FREE(param);
}
BN_OptimizerDestroy(opt);
return ret;
}
#endif
int32_t CRYPT_RSA_Ctrl(CRYPT_RSA_Ctx *ctx, int32_t opt, void *val, uint32_t len)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
switch (opt) {
#ifdef HITLS_CRYPTO_RSA_EMSA_PKCSV15
case CRYPT_CTRL_SET_RSA_EMSA_PKCSV15:
return SetEmsaPkcsV15(ctx, val, len);
#endif
#ifdef HITLS_CRYPTO_RSA_EMSA_PSS
case CRYPT_CTRL_SET_RSA_EMSA_PSS:
return RsaSetPss(ctx, val);
case CRYPT_CTRL_SET_RSA_SALT:
return SetSalt(ctx, val, len);
case CRYPT_CTRL_GET_RSA_SALTLEN:
return GetSaltLen(ctx, val, len);
#endif
case CRYPT_CTRL_GET_RSA_PADDING:
return GetPadding(ctx, val, len);
case CRYPT_CTRL_GET_RSA_MD:
return GetMd(ctx, val, len);
case CRYPT_CTRL_GET_RSA_MGF:
return GetMgf(ctx, val, len);
#ifdef HITLS_CRYPTO_RSAES_OAEP
case CRYPT_CTRL_SET_RSA_RSAES_OAEP:
return RsaSetOaep(ctx, val);
case CRYPT_CTRL_SET_RSA_OAEP_LABEL:
return SetOaepLabel(ctx, val, len);
#endif
#ifdef HITLS_CRYPTO_RSAES_PKCSV15
case CRYPT_CTRL_SET_RSA_RSAES_PKCSV15:
return SetRsaesPkcsV15(ctx, val, len);
#endif
#ifdef HITLS_CRYPTO_RSAES_PKCSV15_TLS
case CRYPT_CTRL_SET_RSA_RSAES_PKCSV15_TLS:
return SetRsaesPkcsV15Tls(ctx, val, len);
#endif
#ifdef HITLS_CRYPTO_RSA_NO_PAD
case CRYPT_CTRL_SET_NO_PADDING:
ctx->pad.type = RSA_NO_PAD;
return CRYPT_SUCCESS;
#endif
case CRYPT_CTRL_SET_RSA_PADDING:
return SetRsaPad(ctx, val, len);
#if defined(HITLS_CRYPTO_RSA_SIGN) || defined(HITLS_CRYPTO_RSA_VERIFY)
case CRYPT_CTRL_GET_SIGNLEN:
return GetUintCtrl(ctx, val, len, (GetUintCallBack)CRYPT_RSA_GetSignLen);
#endif
#ifdef HITLS_CRYPTO_RSA_BSSA
case CRYPT_CTRL_SET_RSA_BSSA_FACTOR_R:
return RsaSetBssa(ctx, val, len);
#endif
default:
return RsaCommonCtrl(ctx, opt, val, len);
}
}
#endif /* HITLS_CRYPTO_RSA */ | 2302_82127028/openHiTLS-examples_1508 | crypto/rsa/src/rsa_ctrl.c | C | unknown | 21,570 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_RSA
#include "crypt_utils.h"
#include "crypt_rsa.h"
#include "rsa_local.h"
#include "crypt_errno.h"
#include "crypt_eal_md.h"
#include "bsl_sal.h"
#include "securec.h"
#include "bsl_err_internal.h"
#include "eal_pkey_local.h"
#include "eal_md_local.h"
#include "bsl_params.h"
#include "crypt_params_key.h"
// rsa-decrypt Calculation used by Chinese Remainder Theorem(CRT). intermediate variables:
typedef struct {
BN_BigNum *cP;
BN_BigNum *cQ;
BN_BigNum *mP;
BN_BigNum *mQ;
BN_Mont *montP;
BN_Mont *montQ;
} RsaDecProcedurePara;
static int32_t InputRangeCheck(const BN_BigNum *input, const BN_BigNum *n, uint32_t bits)
{
// The value range defined in RFC is [0, n - 1]. Because the operation result of 0, 1, n - 1 is relatively fixed,
// it is considered invalid here. The actual valid value range is [2, n - 2].
int32_t ret;
BN_BigNum *nMinusOne = NULL;
if (BN_IsZero(input) == true || BN_IsOne(input) == true) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_INPUT_VALUE);
return CRYPT_RSA_ERR_INPUT_VALUE;
}
/* Allocate 8 extra bits to prevent calculation errors due to the feature of BigNum calculation. */
nMinusOne = BN_Create(bits);
if (nMinusOne == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
ret = BN_SubLimb(nMinusOne, n, 1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
BN_Destroy(nMinusOne);
return ret;
}
if (BN_Cmp(input, nMinusOne) >= 0) {
ret = CRYPT_RSA_ERR_INPUT_VALUE;
BSL_ERR_PUSH_ERROR(ret);
}
BN_Destroy(nMinusOne);
return ret;
}
static int32_t AddZero(uint32_t bits, uint8_t *out, uint32_t *outLen)
{
uint32_t i;
uint32_t zeros = 0;
uint32_t needBytes = BN_BITS_TO_BYTES(bits);
/* Divide bits by 8 to obtain the byte length. If it is smaller than the key length, pad it with 0. */
if ((*outLen) < needBytes) {
/* Divide bits by 8 to obtain the byte length. If it is smaller than the key length, pad it with 0. */
zeros = needBytes - (*outLen);
if (memmove_s(out + zeros, needBytes - zeros, out, (*outLen)) != EOK) {
BSL_ERR_PUSH_ERROR(CRYPT_SECUREC_FAIL);
return CRYPT_SECUREC_FAIL;
}
for (i = 0; i < zeros; i++) {
out[i] = 0x0;
}
}
*outLen = needBytes;
return CRYPT_SUCCESS;
}
static int32_t ResultToOut(uint32_t bits, const BN_BigNum *result, uint8_t *out, uint32_t *outLen)
{
int32_t ret = BN_Bn2Bin(result, out, outLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
return AddZero(bits, out, outLen);
}
static int32_t AllocResultAndInputBN(uint32_t bits, BN_BigNum **result, BN_BigNum **inputBN,
const uint8_t *input, uint32_t inputLen)
{
if (inputLen > BN_BITS_TO_BYTES(bits)) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_INPUT_VALUE);
return CRYPT_RSA_ERR_INPUT_VALUE;
}
*result = BN_Create(bits + 1);
*inputBN = BN_Create(bits);
if (*result == NULL || *inputBN == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
return BN_Bin2Bn(*inputBN, input, inputLen);
}
static int32_t CalcMontExp(CRYPT_RSA_PrvKey *prvKey,
BN_BigNum *result, const BN_BigNum *input, BN_Optimizer *opt, bool consttime)
{
int32_t ret;
BN_Mont *mont = NULL;
if (BN_IsZero(prvKey->n) || BN_IsZero(prvKey->d)) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_NO_KEY_INFO);
return CRYPT_RSA_NO_KEY_INFO;
}
mont = BN_MontCreate(prvKey->n);
if (mont == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
if (consttime) {
ret = BN_MontExpConsttime(result, input, prvKey->d, mont, opt);
} else {
ret = BN_MontExp(result, input, prvKey->d, mont, opt);
}
BN_MontDestroy(mont);
return ret;
}
#if defined(HITLS_CRYPTO_RSA_ENCRYPT) || defined(HITLS_CRYPTO_RSA_VERIFY) || defined(HITLS_CRYPTO_RSA_SIGN)
int32_t CRYPT_RSA_PubEnc(const CRYPT_RSA_Ctx *ctx, const uint8_t *input, uint32_t inputLen,
uint8_t *out, uint32_t *outLen)
{
int32_t ret;
BN_BigNum *inputBN = NULL;
BN_BigNum *result = NULL;
if (ctx == NULL || input == NULL || out == NULL || outLen == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_RSA_PubKey *pubKey = ctx->pubKey;
if (pubKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_NO_KEY_INFO);
return CRYPT_RSA_NO_KEY_INFO;
}
uint32_t bits = CRYPT_RSA_GetBits(ctx);
if ((*outLen) < BN_BITS_TO_BYTES(bits)) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_BUFF_LEN_NOT_ENOUGH);
return CRYPT_RSA_BUFF_LEN_NOT_ENOUGH;
}
BN_Optimizer *optimizer = BN_OptimizerCreate();
if (optimizer == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
GOTO_ERR_IF_EX(AllocResultAndInputBN(bits, &result, &inputBN, input, inputLen), ret);
GOTO_ERR_IF_EX(InputRangeCheck(inputBN, pubKey->n, bits), ret);
// pubKey->mont: Ensure that this value is not empty when the public key is set or generated.
GOTO_ERR_IF(BN_MontExp(result, inputBN, pubKey->e, pubKey->mont, optimizer), ret);
ret = ResultToOut(bits, result, out, outLen);
ERR:
BN_Destroy(result);
BN_Destroy(inputBN);
BN_OptimizerDestroy(optimizer);
return ret;
}
#endif
/* Release intermediate variables. */
static void RsaDecProcedureFree(RsaDecProcedurePara *para)
{
if (para == NULL) {
return;
}
BN_Destroy(para->cP);
BN_Destroy(para->cQ);
BN_Destroy(para->mP);
BN_Destroy(para->mQ);
BN_MontDestroy(para->montP);
BN_MontDestroy(para->montQ);
}
/* Apply for intermediate variables. */
static int32_t RsaDecProcedureAlloc(RsaDecProcedurePara *para, uint32_t bits, const CRYPT_RSA_PrvKey *priKey)
{
para->cP = BN_Create(bits);
para->cQ = BN_Create(bits);
para->mP = BN_Create(bits);
para->mQ = BN_Create(bits);
para->montP = BN_MontCreate(priKey->p);
para->montQ = BN_MontCreate(priKey->q);
if (para->cP == NULL || para->cQ == NULL ||
para->mP == NULL || para->mQ == NULL || para->montP == NULL || para->montQ == NULL) {
RsaDecProcedureFree(para);
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
return CRYPT_SUCCESS;
}
/* rsa decryption calculation by CRT. Message is the BigNum converted from the original input ciphertext. */
static int32_t NormalDecProcedure(const CRYPT_RSA_Ctx *ctx, const BN_BigNum *message, BN_BigNum *result,
BN_Optimizer *opt)
{
CRYPT_RSA_PrvKey *priKey = ctx->prvKey;
uint32_t bits = CRYPT_RSA_GetBits(ctx);
RsaDecProcedurePara procedure = {0}; // Temporary variable
/* Apply for temporary variable */
int32_t ret = RsaDecProcedureAlloc(&procedure, bits, priKey);
if (ret != CRYPT_SUCCESS) {
return ret;
}
/* cP = M mod P where inp = M = Message */
ret = BN_Mod(procedure.cP, message, priKey->p, opt);
if (ret != CRYPT_SUCCESS) {
goto EXIT;
}
/* cQ = M mod Q where inp = M = Message */
ret = BN_Mod(procedure.cQ, message, priKey->q, opt);
if (ret != CRYPT_SUCCESS) {
goto EXIT;
}
/* mP = cP^dP mod p */
ret = BN_MontExpConsttime(procedure.mP, procedure.cP, priKey->dP, procedure.montP, opt);
if (ret != CRYPT_SUCCESS) {
goto EXIT;
}
/* mQ = cQ^dQ mod q */
ret = BN_MontExpConsttime(procedure.mQ, procedure.cQ, priKey->dQ, procedure.montQ, opt);
if (ret != CRYPT_SUCCESS) {
goto EXIT;
}
/* result = (mP - mQ) mod p */
ret = BN_ModSub(result, procedure.mP, procedure.mQ, priKey->p, opt);
if (ret != CRYPT_SUCCESS) {
goto EXIT;
}
/* result = result * qInv mod p */
ret = MontMulCore(result, result, priKey->qInv, procedure.montP, opt);
if (ret != CRYPT_SUCCESS) {
goto EXIT;
}
/* result = result * q */
ret = BN_Mul(result, result, priKey->q, opt);
if (ret != CRYPT_SUCCESS) {
goto EXIT;
}
/* result = result + mQ */
ret = BN_Add(result, result, procedure.mQ);
EXIT:
RsaDecProcedureFree(&procedure);
return ret;
}
#ifdef HITLS_CRYPTO_RSA_BLINDING
static int32_t RSA_GetSub(const BN_BigNum *p, const BN_BigNum *q, BN_BigNum *r1, BN_BigNum *r2)
{
int32_t ret = BN_SubLimb(r1, p, 1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = BN_SubLimb(r2, q, 1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
static int32_t RSA_GetL(BN_BigNum *l, BN_BigNum *u, BN_BigNum *r1, BN_BigNum *r2, BN_Optimizer *opt)
{
int32_t ret = BN_Mul(l, r1, r2, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = BN_Gcd(u, r1, r2, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = BN_Div(l, NULL, l, u, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
static BN_BigNum *RSA_GetPublicExp(const BN_BigNum *d, const BN_BigNum *p,
const BN_BigNum *q, uint32_t bits, BN_Optimizer *opt)
{
int32_t ret;
/* Apply for the temporary space of the BN object */
BN_BigNum *l = BN_Create(bits);
BN_BigNum *r1 = BN_Create(bits >> 1);
BN_BigNum *r2 = BN_Create(bits >> 1);
BN_BigNum *u = BN_Create(bits + 1);
BN_BigNum *e = BN_Create(bits);
if (l == NULL || r1 == NULL || r2 == NULL || u == NULL || e == NULL) {
ret = CRYPT_NULL_INPUT;
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = RSA_GetSub(p, q, r1, r2);
// The push error in GetSub can be used to locate the fault. Therefore, it is not added here.
if (ret != CRYPT_SUCCESS) {
goto EXIT;
}
ret = RSA_GetL(l, u, r1, r2, opt);
// The push error in GetL can be used to locate the fault. Therefore, it is not added here.
if (ret != CRYPT_SUCCESS) {
goto EXIT;
}
ret = BN_ModInv(e, d, l, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
EXIT:
BN_Destroy(r1);
BN_Destroy(r2);
BN_Destroy(l);
BN_Destroy(u);
if (ret != CRYPT_SUCCESS) {
BN_Destroy(e);
e = NULL;
}
return e;
}
static int32_t RSA_InitBlind(CRYPT_RSA_Ctx *ctx, BN_Optimizer *opt)
{
uint32_t bits = BN_Bits(ctx->prvKey->n);
bool needDestoryE = false;
BN_BigNum *e = ctx->prvKey->e;
if (e == NULL || BN_IsZero(e)) {
e = RSA_GetPublicExp(ctx->prvKey->d, ctx->prvKey->p, ctx->prvKey->q, bits, opt);
if (e == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_E_VALUE);
return CRYPT_RSA_ERR_E_VALUE;
}
needDestoryE = true;
}
ctx->scBlind = RSA_BlindNewCtx();
int32_t ret = RSA_BlindCreateParam(LIBCTX_FROM_RSA_CTX(ctx), ctx->scBlind, e, ctx->prvKey->n, bits, opt);
if (needDestoryE) {
BN_Destroy(e);
}
return ret;
}
static int32_t RSA_BlindProcess(CRYPT_RSA_Ctx *ctx, BN_BigNum *message, BN_Optimizer *opt)
{
int32_t ret;
if (ctx->scBlind == NULL) {
ret = RSA_InitBlind(ctx, opt);
if (ret != CRYPT_SUCCESS) {
return ret;
}
}
return RSA_BlindCovert(ctx->scBlind, message, ctx->prvKey->n, opt);
}
#endif
static int32_t RSA_AllocAndCheck(const CRYPT_RSA_Ctx *ctx, const uint8_t *input, uint32_t inputLen,
BN_BigNum **result, BN_BigNum **message)
{
int32_t ret;
if (ctx->prvKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_NO_KEY_INFO);
return CRYPT_RSA_NO_KEY_INFO;
}
uint32_t bits = CRYPT_RSA_GetBits(ctx);
ret = AllocResultAndInputBN(bits, result, message, input, inputLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
ret = InputRangeCheck(*message, ctx->prvKey->n, bits);
if (ret != CRYPT_SUCCESS) {
goto ERR;
}
return ret;
ERR:
BN_Destroy(*result);
BN_Destroy(*message);
return ret;
}
static int32_t RSA_PrvProcess(const CRYPT_RSA_Ctx *ctx, BN_BigNum *message, BN_BigNum *result, BN_Optimizer *opt)
{
#ifndef HITLS_CRYPTO_RSA_BLINDING
(void)opt;
#endif
int32_t ret;
#ifdef HITLS_CRYPTO_RSA_BLINDING
// blinding
if ((ctx->flags & CRYPT_RSA_BLINDING) != 0) {
ret = RSA_BlindProcess((CRYPT_RSA_Ctx *)(uintptr_t)ctx, message, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
#endif
/* If ctx->prvKey->p is set to 0, the standard mode is used for RSA decryption.
Otherwise, the CRT mode is used for RSA decryption. */
if (BN_IsZero(ctx->prvKey->p)) {
ret = CalcMontExp(ctx->prvKey, result, message, opt, true);
} else {
ret = NormalDecProcedure(ctx, message, result, opt);
}
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
#ifdef HITLS_CRYPTO_RSA_BLINDING
// unblinding
if ((ctx->flags & CRYPT_RSA_BLINDING) != 0) {
ret = RSA_BlindInvert(ctx->scBlind, result, ctx->prvKey->n, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
}
#endif
return ret;
}
int32_t CRYPT_RSA_PrvDec(const CRYPT_RSA_Ctx *ctx, const uint8_t *input, uint32_t inputLen,
uint8_t *out, uint32_t *outLen)
{
int32_t ret;
uint32_t bits;
BN_BigNum *result = NULL;
BN_BigNum *message = NULL;
BN_Optimizer *opt = NULL;
if (ctx == NULL || input == NULL || out == NULL || outLen == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->prvKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_NO_KEY_INFO);
return CRYPT_RSA_NO_KEY_INFO;
}
bits = CRYPT_RSA_GetBits(ctx);
if ((*outLen) < BN_BITS_TO_BYTES(bits)) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_BUFF_LEN_NOT_ENOUGH);
return CRYPT_RSA_BUFF_LEN_NOT_ENOUGH;
}
opt = BN_OptimizerCreate();
if (opt == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
ret = RSA_AllocAndCheck(ctx, input, inputLen, &result, &message);
if (ret != CRYPT_SUCCESS) {
BN_OptimizerDestroy(opt);
return ret;
}
(void)OptimizerStart(opt);
ret = RSA_PrvProcess(ctx, message, result, opt);
if (ret != CRYPT_SUCCESS) {
goto EXIT;
}
ret = ResultToOut(bits, result, out, outLen);
EXIT:
OptimizerEnd(opt);
BN_OptimizerDestroy(opt);
BN_Destroy(result);
BN_Destroy(message);
return ret;
}
#if defined(HITLS_CRYPTO_RSA_SIGN) || defined(HITLS_CRYPTO_RSA_VERIFY)
static uint32_t GetHashLen(const CRYPT_RSA_Ctx *ctx)
{
if (ctx->pad.type == EMSA_PKCSV15) {
return CRYPT_GetMdSizeById(ctx->pad.para.pkcsv15.mdId);
}
return (uint32_t)(ctx->pad.para.pss.mdMeth.mdSize);
}
static int32_t CheckHashLen(uint32_t inputLen)
{
if (inputLen > 64) { // 64 is the maximum of the hash length.
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_ALGID);
return CRYPT_RSA_ERR_ALGID;
}
// Inconsistent length
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_ALGID);
return CRYPT_RSA_ERR_ALGID;
}
#endif
#if defined(HITLS_CRYPTO_RSA_EMSA_PSS) && defined(HITLS_CRYPTO_RSA_SIGN)
static int32_t PssPad(CRYPT_RSA_Ctx *ctx, const uint8_t *input, uint32_t inputLen, uint8_t *out, uint32_t outLen)
{
uint32_t saltLen = 0;
bool kat = false; // mark
if (ctx->pad.salt.data != NULL) {
// If the salt contains data, that is the kat test.
kat = true;
}
if (kat == true) {
saltLen = ctx->pad.salt.len;
} else if (ctx->pad.para.pss.saltLen != 0) {
saltLen = ctx->pad.para.pss.saltLen;
}
int32_t ret = CRYPT_RSA_SetPss(ctx, &ctx->pad.para.pss.mdMeth, &ctx->pad.para.pss.mgfMeth,
saltLen, input, inputLen, out, outLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
#endif
#ifdef HITLS_CRYPTO_RSA_BSSA
static int32_t BlindInputCheck(const CRYPT_RSA_Ctx *ctx, const uint8_t *input, uint32_t inputLen,
const uint8_t *out, const uint32_t *outLen)
{
if (ctx == NULL || input == NULL || inputLen == 0 || out == NULL || outLen == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->pubKey == NULL) {
// Check whether the private key information exists.
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_NO_PUBKEY_INFO);
return CRYPT_RSA_ERR_NO_PUBKEY_INFO;
}
uint32_t bits = CRYPT_RSA_GetBits(ctx);
if ((*outLen) < BN_BITS_TO_BYTES(bits)) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_BUFF_LEN_NOT_ENOUGH);
return CRYPT_RSA_BUFF_LEN_NOT_ENOUGH;
}
if (ctx->pad.type != EMSA_PSS) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_PADDING_NOT_SUPPORTED);
return CRYPT_RSA_PADDING_NOT_SUPPORTED;
}
return CRYPT_SUCCESS;
}
#ifdef HITLS_CRYPTO_RSA_SIGN
static RSA_BlindParam *BssaParamNew(void)
{
RSA_BlindParam *param = BSL_SAL_Calloc(1u, sizeof(RSA_BlindParam));
if (param == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
param->para.bssa = RSA_BlindNewCtx();
if (param->para.bssa == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
BSL_SAL_FREE(param);
return NULL;
}
param->type = RSABSSA;
return param;
}
static int32_t BssaBlind(CRYPT_RSA_Ctx *ctx, const uint8_t *input, uint32_t inputLen,
uint8_t *out, uint32_t *outLen)
{
int32_t ret;
uint32_t bits = CRYPT_RSA_GetBits(ctx);
uint32_t padLen = BN_BITS_TO_BYTES(bits);
RSA_BlindParam *param = NULL;
BN_BigNum *e = ctx->pubKey->e;
BN_BigNum *n = ctx->pubKey->n;
RSA_Blind *blind = NULL;
uint8_t *pad = BSL_SAL_Malloc(padLen);
BN_Optimizer *opt = BN_OptimizerCreate();
BN_BigNum *enMsg = BN_Create(bits);
BN_BigNum *gcd = BN_Create(bits);
if (pad == NULL || opt == NULL || enMsg == NULL || gcd == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
ret = CRYPT_MEM_ALLOC_FAIL;
goto ERR;
}
// encoded_msg = EMSA-PSS-ENCODE(msg, bit_len(n))
GOTO_ERR_IF(PssPad(ctx, input, inputLen, pad, padLen), ret);
GOTO_ERR_IF(BN_Bin2Bn(enMsg, pad, padLen), ret);
// Check if bigNumOut and n are coprime using GCD
GOTO_ERR_IF(BN_Gcd(gcd, enMsg, n, opt), ret);
// Check if gcd is 1
if (!BN_IsOne(gcd)) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
ret = CRYPT_INVALID_ARG;
goto ERR;
}
param = ctx->blindParam;
if (param == NULL) {
param = BssaParamNew();
if (param == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
goto ERR;
}
GOTO_ERR_IF(RSA_BlindCreateParam(LIBCTX_FROM_RSA_CTX(ctx), param->para.bssa, e, n, bits, opt), ret);
}
blind = param->para.bssa;
GOTO_ERR_IF(BN_ModMul(enMsg, enMsg, blind->r, n, opt), ret);
GOTO_ERR_IF(ResultToOut(bits, enMsg, out, outLen), ret);
ctx->blindParam = param;
ERR:
if (ret != CRYPT_SUCCESS && ctx->blindParam == NULL && param != NULL) {
RSA_BlindFreeCtx(param->para.bssa);
BSL_SAL_Free(param);
}
BN_Destroy(enMsg);
BN_Destroy(gcd);
BSL_SAL_FREE(pad);
BN_OptimizerDestroy(opt);
return ret;
}
static int32_t BlindSign(CRYPT_RSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen,
uint8_t *sign, uint32_t *signLen)
{
int32_t ret;
uint32_t bits = CRYPT_RSA_GetBits(ctx);
uint32_t sLen = BN_BITS_TO_BYTES(bits);
uint32_t mLen = BN_BITS_TO_BYTES(bits);
uint8_t *s = BSL_SAL_Malloc(sLen);
uint8_t *m = BSL_SAL_Malloc(mLen);
if (s == NULL || m == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
ret = CRYPT_MEM_ALLOC_FAIL;
goto EXIT;
}
/* Step 1: Compute blind signature using RSA private key operation */
ret = CRYPT_RSA_PrvDec(ctx, data, dataLen, s, &sLen);
if (ret != CRYPT_SUCCESS) {
goto EXIT;
}
/* Step 2: Verify the signature by applying the public key operation
* This step ensures the signature is valid under the RSA key pair */
ret = CRYPT_RSA_PubEnc(ctx, s, sLen, m, &mLen);
if (ret != CRYPT_SUCCESS) {
goto EXIT;
}
/* Step 3: Verify that the result matches the input blinded message
* This ensures the signature operation was performed correctly */
if (dataLen != mLen || memcmp(data, m, mLen) != 0) {
ret = CRYPT_RSA_NOR_VERIFY_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
/* Copy the blind signature to output buffer */
(void)memcpy_s(sign, *signLen, s, sLen);
*signLen = sLen;
EXIT:
BSL_SAL_FREE(m);
BSL_SAL_FREE(s);
return ret;
}
int32_t CRYPT_RSA_Blind(CRYPT_RSA_Ctx *ctx, int32_t algId, const uint8_t *input, uint32_t inputLen,
uint8_t *out, uint32_t *outLen)
{
int32_t ret = BlindInputCheck(ctx, input, inputLen, out, outLen);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if ((int32_t)ctx->pad.para.pss.mdId != algId) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_MD_ALGID);
return CRYPT_RSA_ERR_MD_ALGID;
}
uint8_t hash[64]; // 64 is max hash len
uint32_t hashLen = sizeof(hash);
ret = EAL_Md(algId, LIBCTX_FROM_RSA_CTX(ctx), MDATTR_FROM_RSA_CTX(ctx), input, inputLen, hash, &hashLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if ((ctx->flags & CRYPT_RSA_BSSA) != 0) {
ret = BssaBlind(ctx, hash, hashLen, out, outLen);
} else {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_BLIND_TYPE);
ret = CRYPT_RSA_ERR_BLIND_TYPE;
}
return ret;
}
#endif // HITLS_CRYPTO_RSA_SIGN
#ifdef HITLS_CRYPTO_RSA_VERIFY
static int32_t BssaUnBlind(const CRYPT_RSA_Ctx *ctx, const uint8_t *input, uint32_t inputLen,
uint8_t *out, uint32_t *outLen)
{
uint32_t bits = CRYPT_RSA_GetBits(ctx);
uint32_t sigLen = BN_BITS_TO_BYTES(bits);
if (inputLen != sigLen) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
int32_t ret;
RSA_Blind *blind = NULL;
BN_BigNum *n = ctx->pubKey->n;
BN_Optimizer *opt = BN_OptimizerCreate();
BN_BigNum *z = BN_Create(bits);
BN_BigNum *s = BN_Create(bits);
if (opt == NULL || z == NULL || s == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
ret = CRYPT_MEM_ALLOC_FAIL;
goto ERR;
}
if (ctx->blindParam == NULL || ctx->blindParam->para.bssa == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_NO_BLIND_INFO);
ret = CRYPT_RSA_ERR_NO_BLIND_INFO;
goto ERR;
}
if (ctx->blindParam->type != RSABSSA) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_BLIND_TYPE);
ret = CRYPT_RSA_ERR_BLIND_TYPE;
goto ERR;
}
blind = ctx->blindParam->para.bssa;
GOTO_ERR_IF(BN_Bin2Bn(z, input, inputLen), ret);
GOTO_ERR_IF(BN_ModMul(s, z, blind->rInv, n, opt), ret);
GOTO_ERR_IF(ResultToOut(bits, s, out, outLen), ret);
ERR:
BN_Destroy(z);
BN_Destroy(s);
BN_OptimizerDestroy(opt);
return ret;
}
int32_t CRYPT_RSA_UnBlind(const CRYPT_RSA_Ctx *ctx, const uint8_t *input, uint32_t inputLen,
uint8_t *out, uint32_t *outLen)
{
int32_t ret;
ret = BlindInputCheck(ctx, input, inputLen, out, outLen);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if ((ctx->flags & CRYPT_RSA_BSSA) != 0) {
ret = BssaUnBlind(ctx, input, inputLen, out, outLen);
} else {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_BLIND_TYPE);
ret = CRYPT_RSA_ERR_BLIND_TYPE;
}
return ret;
}
#endif // HITLS_CRYPTO_RSA_VERIFY
#endif // HITLS_CRYPTO_RSA_BSSA
#ifdef HITLS_CRYPTO_RSA_SIGN
static int32_t SignInputCheck(const CRYPT_RSA_Ctx *ctx, const uint8_t *input, uint32_t inputLen,
const uint8_t *out, const uint32_t *outLen)
{
if (ctx == NULL || input == NULL || out == NULL || outLen == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->prvKey == NULL) {
// Check whether the private key information exists.
BSL_ERR_PUSH_ERROR(CRYPT_RSA_NO_KEY_INFO);
return CRYPT_RSA_NO_KEY_INFO;
}
// Check whether the length of the out is sufficient to place the signature information.
uint32_t bits = CRYPT_RSA_GetBits(ctx);
if ((*outLen) < BN_BITS_TO_BYTES(bits)) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_BUFF_LEN_NOT_ENOUGH);
return CRYPT_RSA_BUFF_LEN_NOT_ENOUGH;
}
if (ctx->pad.type != EMSA_PKCSV15 && ctx->pad.type != EMSA_PSS) {
// No padding type is set.
BSL_ERR_PUSH_ERROR(CRYPT_RSA_PAD_NO_SET_ERROR);
return CRYPT_RSA_PAD_NO_SET_ERROR;
}
#ifdef HITLS_CRYPTO_RSA_BSSA
if ((ctx->flags & CRYPT_RSA_BSSA) != 0) {
if (BN_BITS_TO_BYTES(bits) != inputLen) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_INPUT_VALUE);
return CRYPT_RSA_ERR_INPUT_VALUE;
}
return CRYPT_SUCCESS;
}
#endif
if (GetHashLen(ctx) != inputLen) {
return CheckHashLen(inputLen);
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_RSA_SignData(CRYPT_RSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen,
uint8_t *sign, uint32_t *signLen)
{
int32_t ret = SignInputCheck(ctx, data, dataLen, sign, signLen);
if (ret != CRYPT_SUCCESS) {
return ret;
}
#ifdef HITLS_CRYPTO_RSA_BSSA
if ((ctx->flags & CRYPT_RSA_BSSA) != 0) {
return BlindSign(ctx, data, dataLen, sign, signLen);
}
#endif
uint32_t bits = CRYPT_RSA_GetBits(ctx);
uint32_t padLen = BN_BITS_TO_BYTES(bits);
uint8_t *pad = BSL_SAL_Malloc(padLen);
if (pad == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
switch (ctx->pad.type) {
#ifdef HITLS_CRYPTO_RSA_EMSA_PKCSV15
case EMSA_PKCSV15:
ret = CRYPT_RSA_SetPkcsV15Type1(ctx->pad.para.pkcsv15.mdId, data,
dataLen, pad, padLen);
break;
#endif
#ifdef HITLS_CRYPTO_RSA_EMSA_PSS
case EMSA_PSS:
ret = PssPad(ctx, data, dataLen, pad, padLen);
break;
#endif
default: // This branch cannot be entered because it's been verified before.
ret = CRYPT_RSA_PAD_NO_SET_ERROR;
break;
}
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = CRYPT_RSA_PrvDec(ctx, pad, padLen, sign, signLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
EXIT:
(void)memset_s(pad, padLen, 0, padLen);
BSL_SAL_FREE(pad);
return ret;
}
int32_t CRYPT_RSA_Sign(CRYPT_RSA_Ctx *ctx, int32_t algId, const uint8_t *data, uint32_t dataLen,
uint8_t *sign, uint32_t *signLen)
{
uint8_t hash[64]; // 64 is max hash len
uint32_t hashLen = sizeof(hash) / sizeof(hash[0]);
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret = EAL_Md(algId, LIBCTX_FROM_RSA_CTX(ctx), MDATTR_FROM_RSA_CTX(ctx), data, dataLen, hash, &hashLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
return CRYPT_RSA_SignData(ctx, hash, hashLen, sign, signLen);
}
#endif // HITLS_CRYPTO_RSA_SIGN
#ifdef HITLS_CRYPTO_RSA_VERIFY
static int32_t VerifyInputCheck(const CRYPT_RSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen,
const uint8_t *sign)
{
if (ctx == NULL || data == NULL || sign == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->pubKey == NULL) {
// Check whether the private key information exists.
BSL_ERR_PUSH_ERROR(CRYPT_RSA_NO_KEY_INFO);
return CRYPT_RSA_NO_KEY_INFO;
}
if (ctx->pad.type != EMSA_PKCSV15 && ctx->pad.type != EMSA_PSS) {
// No padding type is set.
BSL_ERR_PUSH_ERROR(CRYPT_RSA_PAD_NO_SET_ERROR);
return CRYPT_RSA_PAD_NO_SET_ERROR;
}
if (GetHashLen(ctx) != dataLen) {
return CheckHashLen(dataLen);
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_RSA_VerifyData(CRYPT_RSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen,
const uint8_t *sign, uint32_t signLen)
{
uint8_t *pad = NULL;
#ifdef HITLS_CRYPTO_RSA_EMSA_PSS
uint32_t saltLen = 0;
#endif
int32_t ret = VerifyInputCheck(ctx, data, dataLen, sign);
if (ret != CRYPT_SUCCESS) {
return ret;
}
uint32_t bits = CRYPT_RSA_GetBits(ctx);
uint32_t padLen = BN_BITS_TO_BYTES(bits);
pad = BSL_SAL_Malloc(padLen);
if (pad == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
ret = CRYPT_RSA_PubEnc(ctx, sign, signLen, pad, &padLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
switch (ctx->pad.type) {
#ifdef HITLS_CRYPTO_RSA_EMSA_PKCSV15
case EMSA_PKCSV15:
ret = CRYPT_RSA_VerifyPkcsV15Type1(ctx->pad.para.pkcsv15.mdId, pad, padLen,
data, dataLen);
break;
#endif
#ifdef HITLS_CRYPTO_RSA_EMSA_PSS
case EMSA_PSS:
saltLen = (uint32_t)ctx->pad.para.pss.saltLen;
if (ctx->pad.para.pss.mdMeth.id == 0) {
ret = CRYPT_NULL_INPUT;
goto EXIT;
}
ret = CRYPT_RSA_VerifyPss(ctx, &ctx->pad.para.pss.mdMeth, &ctx->pad.para.pss.mgfMeth,
saltLen, data, dataLen, pad, padLen);
break;
#endif
default: // This branch cannot be entered because it's been verified before.
ret = CRYPT_RSA_PAD_NO_SET_ERROR;
BSL_ERR_PUSH_ERROR(ret);
}
EXIT:
(void)memset_s(pad, padLen, 0, padLen);
BSL_SAL_FREE(pad);
return ret;
}
int32_t CRYPT_RSA_Verify(CRYPT_RSA_Ctx *ctx, int32_t algId, const uint8_t *data, uint32_t dataLen,
const uint8_t *sign, uint32_t signLen)
{
uint8_t hash[64]; // 64 is max hash len
uint32_t hashLen = sizeof(hash) / sizeof(hash[0]);
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret = EAL_Md(algId, LIBCTX_FROM_RSA_CTX(ctx), MDATTR_FROM_RSA_CTX(ctx), data, dataLen, hash, &hashLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
return CRYPT_RSA_VerifyData(ctx, hash, hashLen, sign, signLen);
}
#endif // HITLS_CRYPTO_RSA_VERIFY
#if defined(HITLS_CRYPTO_RSA_ENCRYPT) || defined(HITLS_CRYPTO_RSA_VERIFY)
static int32_t EncryptInputCheck(const CRYPT_RSA_Ctx *ctx, const uint8_t *input, uint32_t inputLen,
const uint8_t *out, const uint32_t *outLen)
{
if (ctx == NULL || (input == NULL && inputLen != 0) || out == NULL || outLen == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->pubKey == NULL) {
// Check whether the public key information exists.
BSL_ERR_PUSH_ERROR(CRYPT_RSA_NO_KEY_INFO);
return CRYPT_RSA_NO_KEY_INFO;
}
// Check whether the length of the out is sufficient to place the encryption information.
uint32_t bits = CRYPT_RSA_GetBits(ctx);
if ((*outLen) < BN_BITS_TO_BYTES(bits)) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_BUFF_LEN_NOT_ENOUGH);
return CRYPT_RSA_BUFF_LEN_NOT_ENOUGH;
}
if (inputLen > BN_BITS_TO_BYTES(bits)) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_ENC_BITS);
return CRYPT_RSA_ERR_ENC_BITS;
}
return CRYPT_SUCCESS;
}
#endif
#ifdef HITLS_CRYPTO_RSA_ENCRYPT
int32_t CRYPT_RSA_Encrypt(CRYPT_RSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen,
uint8_t *out, uint32_t *outLen)
{
uint32_t bits, padLen;
uint8_t *pad = NULL;
int32_t ret = EncryptInputCheck(ctx, data, dataLen, out, outLen);
// The static function has pushed an error. The push error is not repeated here.
if (ret != CRYPT_SUCCESS) {
return ret;
}
bits = CRYPT_RSA_GetBits(ctx);
padLen = BN_BITS_TO_BYTES(bits);
pad = BSL_SAL_Malloc(padLen);
if (pad == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
switch (ctx->pad.type) {
#if defined(HITLS_CRYPTO_RSAES_PKCSV15_TLS) || defined(HITLS_CRYPTO_RSAES_PKCSV15)
case RSAES_PKCSV15_TLS:
case RSAES_PKCSV15:
ret = CRYPT_RSA_SetPkcsV15Type2(LIBCTX_FROM_RSA_CTX(ctx), data, dataLen, pad, padLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
break;
#endif
#ifdef HITLS_CRYPTO_RSAES_OAEP
case RSAES_OAEP:
ret = CRYPT_RSA_SetPkcs1Oaep(ctx, data, dataLen, pad, padLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
break;
#endif
#ifdef HITLS_CRYPTO_RSA_NO_PAD
case RSA_NO_PAD:
if (dataLen != padLen) {
ret = CRYPT_RSA_ERR_ENC_INPUT_NOT_ENOUGH;
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_ENC_INPUT_NOT_ENOUGH);
goto EXIT;
}
(void)memcpy_s(pad, padLen, data, dataLen);
break;
#endif
default:
ret = CRYPT_RSA_PAD_NO_SET_ERROR;
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = CRYPT_RSA_PubEnc(ctx, pad, padLen, out, outLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
EXIT:
(void)memset_s(pad, padLen, 0, padLen);
BSL_SAL_FREE(pad);
return ret;
}
#endif // HITLS_CRYPTO_RSA_ENCRYPT
#ifdef HITLS_CRYPTO_RSA_DECRYPT
static int32_t DecryptInputCheck(const CRYPT_RSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen,
const uint8_t *out, const uint32_t *outLen)
{
if (ctx == NULL || data == NULL || out == NULL || outLen == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->prvKey == NULL) {
// Check whether the private key information exists.
BSL_ERR_PUSH_ERROR(CRYPT_RSA_NO_KEY_INFO);
return CRYPT_RSA_NO_KEY_INFO;
}
uint32_t bits = CRYPT_RSA_GetBits(ctx);
if (dataLen != BN_BITS_TO_BYTES(bits)) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_DEC_BITS);
return CRYPT_RSA_ERR_DEC_BITS;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_RSA_Decrypt(CRYPT_RSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint8_t *out, uint32_t *outLen)
{
uint8_t *pad = NULL;
int32_t ret = DecryptInputCheck(ctx, data, dataLen, out, outLen);
// The static function has pushed an error. The push error is not repeated here.
if (ret != CRYPT_SUCCESS) {
return ret;
}
uint32_t bits = CRYPT_RSA_GetBits(ctx);
uint32_t padLen = BN_BITS_TO_BYTES(bits);
pad = BSL_SAL_Malloc(padLen);
if (pad == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
ret = CRYPT_RSA_PrvDec(ctx, data, dataLen, pad, &padLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
switch (ctx->pad.type) {
#ifdef HITLS_CRYPTO_RSAES_OAEP
case RSAES_OAEP:
ret = CRYPT_RSA_VerifyPkcs1Oaep(&ctx->pad.para.oaep, pad, padLen, ctx->label.data, ctx->label.len,
out, outLen);
break;
#endif
#ifdef HITLS_CRYPTO_RSAES_PKCSV15
case RSAES_PKCSV15:
ret = CRYPT_RSA_VerifyPkcsV15Type2(pad, padLen, out, outLen);
break;
#endif
#ifdef HITLS_CRYPTO_RSAES_PKCSV15_TLS
case RSAES_PKCSV15_TLS:
ret = CRYPT_RSA_VerifyPkcsV15Type2TLS(pad, padLen, out, outLen);
break;
#endif
#ifdef HITLS_CRYPTO_RSA_NO_PAD
case RSA_NO_PAD:
if (memcpy_s(out, *outLen, pad, padLen) != EOK) {
ret = CRYPT_RSA_BUFF_LEN_NOT_ENOUGH;
BSL_ERR_PUSH_ERROR(CRYPT_RSA_BUFF_LEN_NOT_ENOUGH);
goto EXIT;
}
*outLen = padLen;
break;
#endif
default:
ret = CRYPT_RSA_PAD_NO_SET_ERROR;
BSL_ERR_PUSH_ERROR(ret);
break;
}
EXIT:
BSL_SAL_CleanseData(pad, padLen);
BSL_SAL_FREE(pad);
return ret;
}
#endif // HITLS_CRYPTO_RSA_DECRYPT
#ifdef HITLS_CRYPTO_RSA_VERIFY
int32_t CRYPT_RSA_Recover(CRYPT_RSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint8_t *out, uint32_t *outLen)
{
int32_t ret = EncryptInputCheck(ctx, data, dataLen, out, outLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (data == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
uint8_t *emMsg = NULL;
uint32_t bits = CRYPT_RSA_GetBits(ctx);
uint32_t emLen = BN_BITS_TO_BYTES(bits);
emMsg = BSL_SAL_Malloc(emLen);
if (emMsg == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
ret = CRYPT_RSA_PubEnc(ctx, data, dataLen, emMsg, &emLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
switch (ctx->pad.type) { // Remove padding based on the padding type to obtain the plaintext.
#ifdef HITLS_CRYPTO_RSA_EMSA_PKCSV15
case RSAES_PKCSV15:
ret = CRYPT_RSA_UnPackPkcsV15Type1(emMsg, emLen, out, outLen);
break;
#endif
#ifdef HITLS_CRYPTO_RSA_NO_PAD
case RSA_NO_PAD:
if (memcpy_s(out, *outLen, emMsg, emLen) != EOK) {
BSL_ERR_PUSH_ERROR(CRYPT_SECUREC_FAIL);
ret = CRYPT_SECUREC_FAIL;
goto ERR;
}
*outLen = emLen;
break;
#endif
default:
ret = CRYPT_RSA_PAD_NO_SET_ERROR;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
ERR:
(void)memset_s(emMsg, emLen, 0, emLen);
BSL_SAL_FREE(emMsg);
return ret;
}
#endif // HITLS_CRYPTO_RSA_VERIFY
#endif /* HITLS_CRYPTO_RSA */ | 2302_82127028/openHiTLS-examples_1508 | crypto/rsa/src/rsa_encdec.c | C | unknown | 38,586 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_RSA
#include "crypt_rsa.h"
#include "rsa_local.h"
#include "crypt_errno.h"
#include "crypt_utils.h"
#include "securec.h"
#include "bsl_sal.h"
#include "bsl_err_internal.h"
CRYPT_RSA_Ctx *CRYPT_RSA_NewCtx(void)
{
CRYPT_RSA_Ctx *keyCtx = NULL;
keyCtx = BSL_SAL_Malloc(sizeof(CRYPT_RSA_Ctx));
if (keyCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
(void)memset_s(keyCtx, sizeof(CRYPT_RSA_Ctx), 0, sizeof(CRYPT_RSA_Ctx));
BSL_SAL_ReferencesInit(&(keyCtx->references));
return keyCtx;
}
CRYPT_RSA_Ctx *CRYPT_RSA_NewCtxEx(void *libCtx)
{
CRYPT_RSA_Ctx *keyCtx = CRYPT_RSA_NewCtx();
if (keyCtx == NULL) {
return NULL;
}
keyCtx->libCtx = libCtx;
return keyCtx;
}
static CRYPT_RSA_PubKey *RSAPubKeyDupCtx(CRYPT_RSA_PubKey *pubKey)
{
CRYPT_RSA_PubKey *newPubKey = BSL_SAL_Malloc(sizeof(CRYPT_RSA_PubKey));
if (newPubKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
(void)memset_s(newPubKey, sizeof(CRYPT_RSA_PubKey), 0, sizeof(CRYPT_RSA_PubKey));
GOTO_ERR_IF_SRC_NOT_NULL(newPubKey->e, pubKey->e, BN_Dup(pubKey->e), CRYPT_MEM_ALLOC_FAIL);
GOTO_ERR_IF_SRC_NOT_NULL(newPubKey->n, pubKey->n, BN_Dup(pubKey->n), CRYPT_MEM_ALLOC_FAIL);
newPubKey->mont = BN_MontCreate(pubKey->n);
if (newPubKey->mont == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
goto ERR;
}
return newPubKey;
ERR:
RSA_FREE_PUB_KEY(newPubKey);
return NULL;
}
static CRYPT_RSA_PrvKey *RSAPriKeyDupCtx(CRYPT_RSA_PrvKey *prvKey)
{
CRYPT_RSA_PrvKey *newPriKey = BSL_SAL_Malloc(sizeof(CRYPT_RSA_PrvKey));
if (newPriKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
(void)memset_s(newPriKey, sizeof(CRYPT_RSA_PrvKey), 0, sizeof(CRYPT_RSA_PrvKey));
GOTO_ERR_IF_SRC_NOT_NULL(newPriKey->n, prvKey->n, BN_Dup(prvKey->n), CRYPT_MEM_ALLOC_FAIL);
GOTO_ERR_IF_SRC_NOT_NULL(newPriKey->d, prvKey->d, BN_Dup(prvKey->d), CRYPT_MEM_ALLOC_FAIL);
GOTO_ERR_IF_SRC_NOT_NULL(newPriKey->p, prvKey->p, BN_Dup(prvKey->p), CRYPT_MEM_ALLOC_FAIL);
GOTO_ERR_IF_SRC_NOT_NULL(newPriKey->q, prvKey->q, BN_Dup(prvKey->q), CRYPT_MEM_ALLOC_FAIL);
GOTO_ERR_IF_SRC_NOT_NULL(newPriKey->dP, prvKey->dP, BN_Dup(prvKey->dP), CRYPT_MEM_ALLOC_FAIL);
GOTO_ERR_IF_SRC_NOT_NULL(newPriKey->dQ, prvKey->dQ, BN_Dup(prvKey->dQ), CRYPT_MEM_ALLOC_FAIL);
GOTO_ERR_IF_SRC_NOT_NULL(newPriKey->qInv, prvKey->qInv, BN_Dup(prvKey->qInv), CRYPT_MEM_ALLOC_FAIL);
GOTO_ERR_IF_SRC_NOT_NULL(newPriKey->e, prvKey->e, BN_Dup(prvKey->e), CRYPT_MEM_ALLOC_FAIL);
return newPriKey;
ERR:
RSA_FREE_PRV_KEY(newPriKey);
return NULL;
}
static CRYPT_RSA_Para *RSAParaDupCtx(CRYPT_RSA_Para *para)
{
CRYPT_RSA_Para *newPara = BSL_SAL_Malloc(sizeof(CRYPT_RSA_Para));
if (newPara == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
(void)memset_s(newPara, sizeof(CRYPT_RSA_Para), 0, sizeof(CRYPT_RSA_Para));
newPara->bits = para->bits;
GOTO_ERR_IF_SRC_NOT_NULL(newPara->e, para->e, BN_Dup(para->e), CRYPT_MEM_ALLOC_FAIL);
GOTO_ERR_IF_SRC_NOT_NULL(newPara->p, para->p, BN_Dup(para->p), CRYPT_MEM_ALLOC_FAIL);
GOTO_ERR_IF_SRC_NOT_NULL(newPara->q, para->q, BN_Dup(para->q), CRYPT_MEM_ALLOC_FAIL);
return newPara;
ERR:
RSA_FREE_PARA(newPara);
return NULL;
}
#if defined(HITLS_CRYPTO_RSA_BLINDING) || defined(HITLS_CRYPTO_RSA_BSSA)
static RSA_Blind *RSABlindDupCtx(RSA_Blind *blind)
{
RSA_Blind *newBlind = BSL_SAL_Malloc(sizeof(RSA_Blind));
if (newBlind == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
(void)memset_s(newBlind, sizeof(RSA_Blind), 0, sizeof(RSA_Blind));
GOTO_ERR_IF_SRC_NOT_NULL(newBlind->r, blind->r, BN_Dup(blind->r), CRYPT_MEM_ALLOC_FAIL);
GOTO_ERR_IF_SRC_NOT_NULL(newBlind->rInv, blind->rInv, BN_Dup(blind->rInv), CRYPT_MEM_ALLOC_FAIL);
return newBlind;
ERR:
RSA_BlindFreeCtx(newBlind);
return NULL;
}
#endif
#ifdef HITLS_CRYPTO_RSA_BSSA
static RSA_BlindParam *RSABssADupCtx(RSA_BlindParam *blind)
{
RSA_BlindParam *newBlind = BSL_SAL_Calloc(1u, sizeof(RSA_BlindParam));
if (newBlind == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
if (blind->type == RSABSSA) {
GOTO_ERR_IF_SRC_NOT_NULL(newBlind->para.bssa, blind->para.bssa,
RSABlindDupCtx(blind->para.bssa), CRYPT_MEM_ALLOC_FAIL);
newBlind->type = RSABSSA;
return newBlind;
}
ERR:
BSL_SAL_FREE(newBlind);
return NULL;
}
#endif
CRYPT_RSA_Ctx *CRYPT_RSA_DupCtx(CRYPT_RSA_Ctx *keyCtx)
{
if (keyCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return NULL;
}
CRYPT_RSA_Ctx *newKeyCtx = NULL;
newKeyCtx = BSL_SAL_Malloc(sizeof(CRYPT_RSA_Ctx));
if (newKeyCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
(void)memset_s(newKeyCtx, sizeof(CRYPT_RSA_Ctx), 0, sizeof(CRYPT_RSA_Ctx));
newKeyCtx->flags = keyCtx->flags;
(void)memcpy_s(&(newKeyCtx->pad), sizeof(RSAPad), &(keyCtx->pad), sizeof(RSAPad));
GOTO_ERR_IF_SRC_NOT_NULL(newKeyCtx->prvKey, keyCtx->prvKey, RSAPriKeyDupCtx(keyCtx->prvKey), CRYPT_MEM_ALLOC_FAIL);
GOTO_ERR_IF_SRC_NOT_NULL(newKeyCtx->pubKey, keyCtx->pubKey, RSAPubKeyDupCtx(keyCtx->pubKey), CRYPT_MEM_ALLOC_FAIL);
#ifdef HITLS_CRYPTO_RSA_BLINDING
GOTO_ERR_IF_SRC_NOT_NULL(newKeyCtx->scBlind, keyCtx->scBlind, RSABlindDupCtx(keyCtx->scBlind),
CRYPT_MEM_ALLOC_FAIL);
#endif
#ifdef HITLS_CRYPTO_RSA_BSSA
if (keyCtx->blindParam != NULL) {
GOTO_ERR_IF_SRC_NOT_NULL(newKeyCtx->blindParam, keyCtx->blindParam,
RSABssADupCtx(keyCtx->blindParam), CRYPT_MEM_ALLOC_FAIL);
}
#endif
GOTO_ERR_IF_SRC_NOT_NULL(newKeyCtx->para, keyCtx->para, RSAParaDupCtx(keyCtx->para), CRYPT_MEM_ALLOC_FAIL);
GOTO_ERR_IF_SRC_NOT_NULL(newKeyCtx->mdAttr, keyCtx->mdAttr, BSL_SAL_Dump(keyCtx->mdAttr,
strlen(keyCtx->mdAttr) + 1), CRYPT_MEM_ALLOC_FAIL);
newKeyCtx->libCtx = keyCtx->libCtx;
BSL_SAL_ReferencesInit(&(newKeyCtx->references));
return newKeyCtx;
ERR:
CRYPT_RSA_FreeCtx(newKeyCtx);
return NULL;
}
static int32_t GetRsaParam(const BSL_Param *params, int32_t type, const uint8_t **value, uint32_t *valueLen)
{
const BSL_Param *temp = BSL_PARAM_FindConstParam(params, type);
if (temp == NULL || temp->valueLen == 0 || temp->value == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
*value = temp->value;
*valueLen = temp->valueLen;
return CRYPT_SUCCESS;
}
static int32_t GetRsaBits(const BSL_Param *params, uint32_t *bits)
{
uint32_t bitsLen = sizeof(*bits);
const BSL_Param *temp = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_BITS);
if (temp == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
int32_t ret = BSL_PARAM_GetValue(temp, CRYPT_PARAM_RSA_BITS, BSL_PARAM_TYPE_UINT32, bits, &bitsLen);
if (ret != BSL_SUCCESS || *bits < RSA_MIN_MODULUS_BITS || *bits > RSA_MAX_MODULUS_BITS) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
return CRYPT_SUCCESS;
}
static int32_t ValidateRsaParams(uint32_t eLen, uint32_t bits)
{
/* the length of e cannot be greater than bits */
if (eLen > BN_BITS_TO_BYTES(bits)) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_KEY_BITS);
return CRYPT_RSA_ERR_KEY_BITS;
}
return CRYPT_SUCCESS;
}
#ifdef HITLS_CRYPTO_ACVP_TESTS
static int32_t ProcessRsaPrimeSeeds(const BSL_Param *para, CRYPT_RSA_Para *retPara, uint32_t bits)
{
const BSL_Param *sp = BSL_PARAM_FindConstParam(para, CRYPT_PARAM_RSA_XP);
if (sp != NULL && sp->valueLen > 0) {
if ((retPara->acvpTests.primeSeed.fipsPrimeSeeds.xp = BN_Create(bits)) == NULL ||
(BN_Bin2Bn(retPara->acvpTests.primeSeed.fipsPrimeSeeds.xp, sp->value, sp->valueLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
}
sp = BSL_PARAM_FindConstParam(para, CRYPT_PARAM_RSA_XP1);
if (sp != NULL && sp->valueLen > 0) {
if ((retPara->acvpTests.primeSeed.fipsPrimeSeeds.xp1 = BN_Create(bits)) == NULL ||
(BN_Bin2Bn(retPara->acvpTests.primeSeed.fipsPrimeSeeds.xp1, sp->value, sp->valueLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
}
sp = BSL_PARAM_FindConstParam(para, CRYPT_PARAM_RSA_XP2);
if (sp != NULL && sp->valueLen > 0) {
if ((retPara->acvpTests.primeSeed.fipsPrimeSeeds.xp2 = BN_Create(bits)) == NULL ||
(BN_Bin2Bn(retPara->acvpTests.primeSeed.fipsPrimeSeeds.xp2, sp->value, sp->valueLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
}
sp = BSL_PARAM_FindConstParam(para, CRYPT_PARAM_RSA_XQ);
if (sp != NULL && sp->valueLen > 0) {
if ((retPara->acvpTests.primeSeed.fipsPrimeSeeds.xq = BN_Create(bits)) == NULL ||
(BN_Bin2Bn(retPara->acvpTests.primeSeed.fipsPrimeSeeds.xq, sp->value, sp->valueLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
}
sp = BSL_PARAM_FindConstParam(para, CRYPT_PARAM_RSA_XQ1);
if (sp != NULL && sp->valueLen > 0) {
if ((retPara->acvpTests.primeSeed.fipsPrimeSeeds.xq1 = BN_Create(bits)) == NULL ||
(BN_Bin2Bn(retPara->acvpTests.primeSeed.fipsPrimeSeeds.xq1, sp->value, sp->valueLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
}
sp = BSL_PARAM_FindConstParam(para, CRYPT_PARAM_RSA_XQ2);
if (sp != NULL && sp->valueLen > 0) {
if ((retPara->acvpTests.primeSeed.fipsPrimeSeeds.xq2 = BN_Create(bits)) == NULL ||
(BN_Bin2Bn(retPara->acvpTests.primeSeed.fipsPrimeSeeds.xq2, sp->value, sp->valueLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
}
return CRYPT_SUCCESS;
}
#endif
static int32_t RsaNewParaBasicCheck(const CRYPT_RsaPara *para)
{
if (para == NULL || para->e == NULL || para->eLen == 0 ||
para->bits > RSA_MAX_MODULUS_BITS || para->bits < RSA_MIN_MODULUS_BITS) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
/* the length of e cannot be greater than bits */
if (para->eLen > BN_BITS_TO_BYTES(para->bits)) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_KEY_BITS);
return CRYPT_RSA_ERR_KEY_BITS;
}
return CRYPT_SUCCESS;
}
CRYPT_RSA_Para *CRYPT_RSA_NewPara(const CRYPT_RsaPara *para)
{
if (RsaNewParaBasicCheck(para) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return NULL;
}
CRYPT_RSA_Para *retPara = BSL_SAL_Calloc(1, sizeof(CRYPT_RSA_Para));
if (retPara == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
retPara->bits = para->bits;
retPara->e = BN_Create(para->bits);
retPara->p = BN_Create(para->bits);
retPara->q = BN_Create(para->bits);
if (retPara->e == NULL || retPara->p == NULL || retPara->q == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
goto ERR;
}
int32_t ret;
ret = BN_Bin2Bn(retPara->e, para->e, para->eLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
if (BN_BITS_TO_BYTES(para->bits) > RSA_SMALL_MODULUS_BYTES && BN_Bytes(retPara->e) > RSA_MAX_PUBEXP_BYTES) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_KEY_BITS);
goto ERR;
}
return retPara;
ERR:
CRYPT_RSA_FreePara(retPara);
return NULL;
}
void CRYPT_RSA_FreePara(CRYPT_RSA_Para *para)
{
if (para == NULL) {
return;
}
#ifdef HITLS_CRYPTO_ACVP_TESTS
BN_Destroy(para->acvpTests.primeSeed.fipsPrimeSeeds.xp);
BN_Destroy(para->acvpTests.primeSeed.fipsPrimeSeeds.xp1);
BN_Destroy(para->acvpTests.primeSeed.fipsPrimeSeeds.xp2);
BN_Destroy(para->acvpTests.primeSeed.fipsPrimeSeeds.xq);
BN_Destroy(para->acvpTests.primeSeed.fipsPrimeSeeds.xq1);
BN_Destroy(para->acvpTests.primeSeed.fipsPrimeSeeds.xq2);
#endif
BN_Destroy(para->e);
BN_Destroy(para->p);
BN_Destroy(para->q);
BSL_SAL_FREE(para);
}
void RSA_FreePrvKey(CRYPT_RSA_PrvKey *prvKey)
{
if (prvKey == NULL) {
return;
}
BN_Destroy(prvKey->n);
BN_Destroy(prvKey->d);
BN_Destroy(prvKey->p);
BN_Destroy(prvKey->q);
BN_Destroy(prvKey->e);
BN_Destroy(prvKey->dP);
BN_Destroy(prvKey->dQ);
BN_Destroy(prvKey->qInv);
BSL_SAL_FREE(prvKey);
}
void RSA_FreePubKey(CRYPT_RSA_PubKey *pubKey)
{
if (pubKey == NULL) {
return;
}
BN_Destroy(pubKey->n);
BN_Destroy(pubKey->e);
BN_MontDestroy(pubKey->mont);
BSL_SAL_FREE(pubKey);
}
void CRYPT_RSA_FreeCtx(CRYPT_RSA_Ctx *ctx)
{
if (ctx == NULL) {
return;
}
int i = 0;
BSL_SAL_AtomicDownReferences(&(ctx->references), &i);
if (i > 0) {
return;
}
BSL_SAL_ReferencesFree(&(ctx->references));
RSA_FREE_PARA(ctx->para);
RSA_FREE_PRV_KEY(ctx->prvKey);
RSA_FREE_PUB_KEY(ctx->pubKey);
#ifdef HITLS_CRYPTO_RSA_BLINDING
RSA_BlindFreeCtx(ctx->scBlind);
ctx->scBlind = NULL;
#endif
#ifdef HITLS_CRYPTO_RSA_BSSA
if (ctx->blindParam != NULL) {
if (ctx->blindParam->type == RSABSSA) {
RSA_BlindFreeCtx(ctx->blindParam->para.bssa);
}
BSL_SAL_FREE(ctx->blindParam);
}
#endif
BSL_SAL_CleanseData((void *)(&(ctx->pad)), sizeof(RSAPad));
BSL_SAL_FREE(ctx->label.data);
BSL_SAL_FREE(ctx->mdAttr);
BSL_SAL_FREE(ctx);
}
static int32_t IsRSASetParamValid(const CRYPT_RSA_Ctx *ctx, const CRYPT_RSA_Para *para)
{
if (ctx == NULL || para == NULL || para->e == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (para->bits > RSA_MAX_MODULUS_BITS || para->bits < RSA_MIN_MODULUS_BITS) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_KEY_BITS);
return CRYPT_RSA_ERR_KEY_BITS;
}
if (BN_GetBit(para->e, 0) != true || BN_IsLimb(para->e, 1) == true) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_E_VALUE);
return CRYPT_RSA_ERR_E_VALUE;
}
return CRYPT_SUCCESS;
}
#ifdef HITLS_CRYPTO_ACVP_TESTS
static int32_t DupRsaPrimeSeeds(const CRYPT_RSA_Para *para, CRYPT_RSA_Para *paraCopy)
{
if (para->acvpTests.primeSeed.fipsPrimeSeeds.xp != NULL &&
(paraCopy->acvpTests.primeSeed.fipsPrimeSeeds.xp =
BN_Dup(para->acvpTests.primeSeed.fipsPrimeSeeds.xp)) == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
if (para->acvpTests.primeSeed.fipsPrimeSeeds.xp1 != NULL &&
(paraCopy->acvpTests.primeSeed.fipsPrimeSeeds.xp1 =
BN_Dup(para->acvpTests.primeSeed.fipsPrimeSeeds.xp1)) == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
if (para->acvpTests.primeSeed.fipsPrimeSeeds.xp2 != NULL &&
(paraCopy->acvpTests.primeSeed.fipsPrimeSeeds.xp2 =
BN_Dup(para->acvpTests.primeSeed.fipsPrimeSeeds.xp2)) == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
if (para->acvpTests.primeSeed.fipsPrimeSeeds.xq != NULL &&
(paraCopy->acvpTests.primeSeed.fipsPrimeSeeds.xq =
BN_Dup(para->acvpTests.primeSeed.fipsPrimeSeeds.xq)) == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
if (para->acvpTests.primeSeed.fipsPrimeSeeds.xq1 != NULL &&
(paraCopy->acvpTests.primeSeed.fipsPrimeSeeds.xq1 =
BN_Dup(para->acvpTests.primeSeed.fipsPrimeSeeds.xq1)) == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
if (para->acvpTests.primeSeed.fipsPrimeSeeds.xq2 != NULL &&
(paraCopy->acvpTests.primeSeed.fipsPrimeSeeds.xq2 =
BN_Dup(para->acvpTests.primeSeed.fipsPrimeSeeds.xq2)) == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
return CRYPT_SUCCESS;
}
#endif
CRYPT_RSA_Para *CRYPT_RSA_DupPara(const CRYPT_RSA_Para *para)
{
CRYPT_RSA_Para *paraCopy = BSL_SAL_Calloc(1, sizeof(CRYPT_RSA_Para));
if (paraCopy == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
paraCopy->bits = para->bits;
paraCopy->e = BN_Dup(para->e);
paraCopy->p = BN_Dup(para->p);
paraCopy->q = BN_Dup(para->q);
if (paraCopy->e == NULL || paraCopy->p == NULL || paraCopy->q == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
goto ERR;
}
#ifdef HITLS_CRYPTO_ACVP_TESTS
int32_t ret = DupRsaPrimeSeeds(para, paraCopy);
if (ret != CRYPT_SUCCESS) {
goto ERR;
}
#endif
return paraCopy;
ERR:
RSA_FREE_PARA(paraCopy);
return NULL;
}
int32_t CRYPT_RSA_SetPara(CRYPT_RSA_Ctx *ctx, const CRYPT_RsaPara *para)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_RSA_Para *rsaPara = CRYPT_RSA_NewPara(para);
if (rsaPara == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_NEW_PARA_FAIL);
return CRYPT_EAL_ERR_NEW_PARA_FAIL;
}
int32_t ret = IsRSASetParamValid(ctx, rsaPara);
if (ret != CRYPT_SUCCESS) {
RSA_FREE_PARA(rsaPara);
return ret;
}
(void)memset_s(&(ctx->pad), sizeof(RSAPad), 0, sizeof(RSAPad));
RSA_FREE_PARA(ctx->para);
RSA_FREE_PRV_KEY(ctx->prvKey);
RSA_FREE_PUB_KEY(ctx->pubKey);
ctx->para = rsaPara;
return CRYPT_SUCCESS;
}
#ifdef HITLS_BSL_PARAMS
CRYPT_RSA_Para *CRYPT_RSA_NewParaEx(const BSL_Param *para)
{
const uint8_t *e = NULL;
uint32_t eLen = 0;
int32_t ret = GetRsaParam(para, CRYPT_PARAM_RSA_E, &e, &eLen);
if (ret != CRYPT_SUCCESS) {
return NULL;
}
uint32_t bits = 0;
ret = GetRsaBits(para, &bits);
if (ret != CRYPT_SUCCESS) {
return NULL;
}
ret = ValidateRsaParams(eLen, bits);
if (ret != CRYPT_SUCCESS) {
return NULL;
}
CRYPT_RSA_Para *retPara = BSL_SAL_Calloc(1, sizeof(CRYPT_RSA_Para));
if (retPara == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
retPara->bits = bits;
retPara->e = BN_Create(bits);
retPara->p = BN_Create(bits);
retPara->q = BN_Create(bits);
if (retPara->e == NULL || retPara->p == NULL || retPara->q == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
goto ERR;
}
ret = BN_Bin2Bn(retPara->e, e, eLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
if (BN_BITS_TO_BYTES(bits) > RSA_SMALL_MODULUS_BYTES && BN_Bytes(retPara->e) > RSA_MAX_PUBEXP_BYTES) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_KEY_BITS);
goto ERR;
}
#ifdef HITLS_CRYPTO_ACVP_TESTS
ret = ProcessRsaPrimeSeeds(para, retPara, bits);
if (ret != CRYPT_SUCCESS) {
goto ERR;
}
#endif
return retPara;
ERR:
CRYPT_RSA_FreePara(retPara);
return NULL;
}
static int32_t IsRSASetParamValidEx(const CRYPT_RSA_Para *para)
{
if (para == NULL || para->e == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (para->bits > RSA_MAX_MODULUS_BITS || para->bits < RSA_MIN_MODULUS_BITS) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_KEY_BITS);
return CRYPT_RSA_ERR_KEY_BITS;
}
if (BN_GetBit(para->e, 0) != true || BN_IsLimb(para->e, 1) == true) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_E_VALUE);
return CRYPT_RSA_ERR_E_VALUE;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_RSA_SetParaEx(CRYPT_RSA_Ctx *ctx, const BSL_Param *para)
{
if (ctx == NULL || para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret;
#ifdef HITLS_CRYPTO_PROVIDER
const BSL_Param *temp = NULL;
if ((temp = BSL_PARAM_FindConstParam(para, CRYPT_PARAM_MD_ATTR)) != NULL) {
ret = CRYPT_PkeySetMdAttr((const char *)(temp->value), temp->valueLen, &(ctx->mdAttr));
if (ret != CRYPT_SUCCESS) {
return ret;
}
}
#endif
if (BSL_PARAM_FindConstParam(para, CRYPT_PARAM_RSA_E) == NULL) {
return CRYPT_SUCCESS;
}
CRYPT_RSA_Para *rsaPara = CRYPT_RSA_NewParaEx(para);
if (rsaPara == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_NEW_PARA_FAIL);
return CRYPT_EAL_ERR_NEW_PARA_FAIL;
}
ret = IsRSASetParamValidEx(rsaPara);
if (ret != CRYPT_SUCCESS) {
RSA_FREE_PARA(rsaPara);
return ret;
}
(void)memset_s(&(ctx->pad), sizeof(RSAPad), 0, sizeof(RSAPad));
RSA_FREE_PARA(ctx->para);
RSA_FREE_PRV_KEY(ctx->prvKey);
RSA_FREE_PUB_KEY(ctx->pubKey);
ctx->para = rsaPara;
return CRYPT_SUCCESS;
}
#endif
CRYPT_RSA_PrvKey *RSA_NewPrvKey(uint32_t bits)
{
CRYPT_RSA_PrvKey *priKey = BSL_SAL_Malloc(sizeof(CRYPT_RSA_PrvKey));
if (priKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
priKey->n = BN_Create(bits);
priKey->d = BN_Create(bits);
priKey->p = BN_Create(bits >> 1);
priKey->q = BN_Create(bits >> 1);
priKey->e = BN_Create(bits >> 1);
priKey->dP = BN_Create(bits >> 1);
priKey->dQ = BN_Create(bits >> 1);
priKey->qInv = BN_Create(bits >> 1);
bool creatFailed = (priKey->n == NULL || priKey->d == NULL || priKey->e == NULL || priKey->p == NULL ||
priKey->q == NULL || priKey->dP == NULL || priKey->dQ == NULL || priKey->qInv == NULL);
if (creatFailed) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
RSA_FREE_PRV_KEY(priKey);
}
return priKey;
}
CRYPT_RSA_PubKey *RSA_NewPubKey(uint32_t bits)
{
CRYPT_RSA_PubKey *pubKey = BSL_SAL_Malloc(sizeof(CRYPT_RSA_PubKey));
if (pubKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
pubKey->n = BN_Create(bits);
pubKey->e = BN_Create(bits);
pubKey->mont = NULL;
if (pubKey->n == NULL || pubKey->e == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
RSA_FREE_PUB_KEY(pubKey);
}
return pubKey;
}
uint32_t CRYPT_RSA_GetBits(const CRYPT_RSA_Ctx *ctx)
{
if (ctx == NULL) {
return 0;
}
if (ctx->para != NULL) {
return ctx->para->bits;
}
if (ctx->prvKey != NULL) {
return BN_Bits(ctx->prvKey->n);
}
if (ctx->pubKey != NULL) {
return BN_Bits(ctx->pubKey->n);
}
return 0;
}
#if defined(HITLS_CRYPTO_RSA_SIGN) || defined(HITLS_CRYPTO_RSA_VERIFY)
uint32_t CRYPT_RSA_GetSignLen(const CRYPT_RSA_Ctx *ctx)
{
return BN_BITS_TO_BYTES(CRYPT_RSA_GetBits(ctx));
}
#endif
#ifdef HITLS_CRYPTO_RSA_GEN
static int32_t GetRandomX(void *libCtx, BN_BigNum *X, uint32_t nlen, bool isP)
{
/*
* The FIPS 185-5 Appendix B.9 required √2(2 ^(nlen/2 - 1)) <= x <= ((2 ^(nlen/2) - 1))
* hence we can limit it as follows:
* √2 ~= 1.41421 < 1.5 -->
* √2(2 ^(nlen/2 - 1)) < 1.5 * (2 ^(nlen/2 - 1))
* next, we need to prove 1.5 * (2 ^(nlen/2 - 1)) <= ((2 ^(nlen/2) - 1))
* --> let x = 2 ^(nlen/2), 1.5 * (x/2) ≤ x - 1
* --> (3/4) x ≤ x - 1
* --> x >= 4, obviously correct.
* And, 1.5 * 2 ^(nlen/2 - 1) = 2 ^ (nlen/2 - 1) + 2 ^ (nlen/2 - 2);
* If we follow these steps to construct the bigNum:
* i. Randomly generate a random number, the most significant bit is (nlen / 2).
* ii. Set the (nlen/2 - 1) bits.
* We can obtain the x, satisfied [ 1.5 * 2 ^(nlen/2 - 1), ((2 ^(nlen/2) - 1) ].
*/
if ((nlen % 2) == 0) {
return BN_RandEx(libCtx, X, nlen >> 1, BN_RAND_TOP_TWOBIT, BN_RAND_BOTTOM_NOBIT);
}
/*
* Meanwhile, if nlen is odd, We need to consider p, q separately.
*/
if (isP) {
/*
* left : √2(2 ^(nlen/2 - 1)) < 2 ^ ⌊ (nlen / 2) ⌋
* right: if nlen is odd, 2 ^ (nlen/2) - 1 == 2 ^ ( ⌊ (nlen)/2 ⌋ + 1/2) - 1 == √2 * 2 ^ (⌊ (nlen)/2 ⌋) - 1
* if we want left <= right:
* 2 ^ ⌊ (nlen / 2) ⌋ < √2 * 2 ^ (⌊ (nlen)/2 ⌋) - 1
* --> 2 ^ ⌊ (nlen / 2) ⌋ < 1.4 * 2 ^ (⌊ (nlen)/2 ⌋) - 1
* --> 1 < 0.4 * 2 ^ (⌊ (nlen)/2 ⌋)
* --> nlen >= 3, obviously correct.
* hence, We can obtain the x, set the (nlen)/2 + 1 bits.
*/
return BN_RandEx(libCtx, X, (nlen + 1) >> 1, BN_RAND_TOP_ONEBIT, BN_RAND_BOTTOM_NOBIT);
}
return BN_RandEx(libCtx, X, nlen >> 1, BN_RAND_TOP_TWOBIT, BN_RAND_BOTTOM_NOBIT);
}
/*
* Ref: FIPS 186-5: Table A.1
* Get the maximum lengths of p1, p2, q1, and q2.
*/
static uint32_t GetAuxiliaryPrimeBitLen(uint32_t nlen)
{
if (nlen <= 3071) {
return 141;
} else if (nlen <= 4095) {
return 171;
} else {
return 201;
}
}
/*
* Ref: FIPS 186-5: Table A.1
* Get the maximum lengths of p, q.
*/
static uint32_t GetProbableNoLimitedBitLen(uint32_t nlen)
{
if (nlen <= 3071) {
return 1007;
} else if (nlen <= 4095) {
return 1518;
} else {
return 2030;
}
}
/*
* Ref: FIPS 186-5: Table B.1
* Get minimum number of rounds of M-R testing when generating auxiliary primes.
*/
static uint32_t GetAuxPrimeMillerCheckTimes(uint32_t auxBits)
{
if (auxBits <= 170) {
return 38; // Error probability = 2 ^ (-112)
} else if (auxBits <= 200) {
return 41; // Error probability = 2 ^ (-128)
} else {
return 44; // Error probability = 2 ^ (-144)
}
}
/*
* Ref: FIPS 186-5: Table B.1
* Get minimum number of rounds of M-R testing when generating probable primes.
*/
static uint32_t GetProbPrimeMillerCheckTimes(uint32_t proBits)
{
if (proBits < 1536) {
return 5;
}
return 4;
}
static int32_t GenAuxPrime(BN_BigNum *Xp, uint32_t auxBits, BN_Optimizer *opt, bool isSeed)
{
int32_t ret = CRYPT_SUCCESS;
if (!isSeed) {
ret = BN_RandEx(BN_OptimizerGetLibCtx(opt), Xp, auxBits, BN_RAND_TOP_ONEBIT, BN_RAND_BOTTOM_ONEBIT);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
uint32_t auxPrimeCheck = GetAuxPrimeMillerCheckTimes(auxBits);
do {
ret = BN_PrimeCheck(Xp, auxPrimeCheck, opt, NULL);
if (ret == CRYPT_SUCCESS) {
return ret;
}
if (ret != CRYPT_BN_NOR_CHECK_PRIME) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = BN_AddLimb(Xp, Xp, 2); // Try with odd numbers every time.
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
} while (true);
}
/*
* Ref: FIPS 186-5 B.9 Compute a Probable Prime Factor Based on Auxiliary Primes.
* The standard specifies that the length of two small primes should meet
* len(r1) + len(r2) ≤ (nlen/2) – log2(nlen/2) – 7
* If nlen = 1024, r1, r2 is obtained by search from 141 bits data, the above inequality is still satisfied.
* Hence, it's a only performance consideration for us to use this standard for 1024-bit rsa key-Gen.
*/
static int32_t GenPrimeWithAuxiliaryPrime(uint32_t auxBits, uint32_t proBits, BN_BigNum *Xp, BN_BigNum *Xp0,
BN_BigNum *Xp1, BN_BigNum *Xp2, BN_BigNum *p, const CRYPT_RSA_Para *para, bool isP, BN_Optimizer *opt)
{
BN_BigNum *r1;
BN_BigNum *r2;
uint32_t auxRoom = BITS_TO_BN_UNIT(auxBits);
int32_t ret = OptimizerStart(opt); // use the optimizer
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
uint32_t probPrimeCheck = GetProbPrimeMillerCheckTimes(proBits);
r1 = (Xp1 != NULL) ? Xp1 : OptimizerGetBn(opt, auxRoom);
r2 = (Xp2 != NULL) ? Xp2 : OptimizerGetBn(opt, auxRoom);
BN_BigNum *r1Double = OptimizerGetBn(opt, auxRoom);
BN_BigNum *primeCheck = OptimizerGetBn(opt, auxRoom);
BN_BigNum *r2Inv = OptimizerGetBn(opt, auxRoom);
BN_BigNum *r1DoubleInv = OptimizerGetBn(opt, auxRoom);
BN_BigNum *R = OptimizerGetBn(opt, auxRoom);
BN_BigNum *pMinusOne = OptimizerGetBn(opt, BITS_TO_BN_UNIT(proBits));
uint32_t bits = isP ? (para->bits + 1) >> 1 : (para->bits >> 1); // Avoid the bit is odd.
uint32_t iterRound = 20 * bits; // Step 9 specifies that the iteration round is 20 * (nlen/2);
if (r1 == NULL || r2 == NULL || r1Double == NULL || primeCheck == NULL || r2Inv == NULL ||
r1DoubleInv == NULL || R == NULL || pMinusOne == NULL) {
ret = CRYPT_BN_OPTIMIZER_GET_FAIL;
OptimizerEnd(opt);
return ret;
}
// Choose auxiliary prime r1, either from seed or generate randomly
ret = GenAuxPrime(r1, auxBits, opt, (Xp1 != NULL));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
OptimizerEnd(opt);
return ret;
}
GOTO_ERR_IF(GenAuxPrime(r2, auxBits, opt, (Xp2 != NULL)), ret);
GOTO_ERR_IF(BN_Lshift(r1Double, r1, 1), ret);
// Step 1: check 2r1, r2 are coprime.
GOTO_ERR_IF(BN_Gcd(primeCheck, r1Double, r2, opt), ret);
if (!BN_IsOne(primeCheck)) {
ret = CRYPT_RSA_NOR_KEYGEN_FAIL;
BSL_ERR_PUSH_ERROR(CRYPT_RSA_NOR_KEYGEN_FAIL);
goto ERR;
}
// Step 2: cal R = (r2^-1 mod 2r1) * r2 - ((2 * r1)^-1 mod r2) * (2 * r1)
GOTO_ERR_IF(BN_ModInv(r2Inv, r2, r1Double, opt), ret); // (r2^-1 mod 2r1) * r2
GOTO_ERR_IF(BN_Mul(r2Inv, r2, r2Inv, opt), ret);
// ((2 * r1)^-1 mod r2) * (2 * r1)
GOTO_ERR_IF(BN_ModInv(r1DoubleInv, r1Double, r2, opt), ret);
GOTO_ERR_IF(BN_Mul(r1DoubleInv, r1Double, r1DoubleInv, opt), ret);
// get R.
GOTO_ERR_IF(BN_Sub(R, r2Inv, r1DoubleInv), ret);
do {
// Step 3: get x via seed xp/xq or random
if (Xp0 == NULL) {
GOTO_ERR_IF(GetRandomX(BN_OptimizerGetLibCtx(opt), Xp, para->bits, isP), ret);
}
// Step 4: Y = X + ((R – X) mod 2r1r2
GOTO_ERR_IF(BN_Mul(r1, r1Double, r2, opt), ret); // 2r1r2
GOTO_ERR_IF(BN_ModSub(R, R, Xp, r1, opt), ret);
GOTO_ERR_IF(BN_Add(p, Xp, R), ret);
uint32_t i = 0;
for (; i < iterRound; i++) {
// Step 6: Check p ≥ 2 ^ (nlen/2)
if (BN_Bits(p) > bits) {
break;
}
// Step 7: Check the p - 1 and e are corprime.
GOTO_ERR_IF(BN_SubLimb(pMinusOne, p, 1), ret);
GOTO_ERR_IF(BN_Gcd(pMinusOne, pMinusOne, para->e, opt), ret);
if (BN_IsOne(pMinusOne)) {
// Step 7.1: Check the primality of p.
ret = BN_PrimeCheck(p, probPrimeCheck, opt, NULL);
if (ret == CRYPT_SUCCESS) { // We find a primes successfully.
goto ERR;
}
if (ret != CRYPT_BN_NOR_CHECK_PRIME) { // Another exception has occurred.
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
}
// Step 10: Update p.
GOTO_ERR_IF(BN_Add(p, p, r1), ret);
}
// Step 9: check i ≥ 20 * (nlen/2).
if (i == iterRound) {
ret = CRYPT_RSA_NOR_KEYGEN_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
} while (true);
ERR:
if (Xp1 == NULL) {
BN_Zeroize(r1);
}
if (Xp2 == NULL) {
BN_Zeroize(r2);
}
OptimizerEnd(opt);
return ret;
}
// ref: FIPS 186-5, A.1.6 & B.9
static int32_t GenPQBasedOnProbPrimes(const CRYPT_RSA_Para *para, CRYPT_RSA_PrvKey *priKey, BN_Optimizer *opt)
{
BN_BigNum *Xp = NULL, *Xq = NULL, *Xp0 = NULL, *Xp1 = NULL, *Xp2 = NULL, *Xq0 = NULL, *Xq1 = NULL, *Xq2 = NULL;
uint32_t proBits = GetProbableNoLimitedBitLen(para->bits);
uint32_t auxBits = GetAuxiliaryPrimeBitLen(para->bits);
// Used in check |Xp – Xq| ≤ 2^(nlen/2) – 100 or |p – q| ≤ 2^(nlen/2) – 100.
uint32_t secBits = ((para->bits + 1) >> 1) - 100;
uint32_t proRoom = BITS_TO_BN_UNIT(proBits);
int32_t ret = OptimizerStart(opt); // use the optimizer
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
#ifdef HITLS_CRYPTO_ACVP_TESTS
Xp0 = para->acvpTests.primeSeed.fipsPrimeSeeds.xp;
Xp1 = para->acvpTests.primeSeed.fipsPrimeSeeds.xp1;
Xp2 = para->acvpTests.primeSeed.fipsPrimeSeeds.xp2;
Xq0 = para->acvpTests.primeSeed.fipsPrimeSeeds.xq;
Xq1 = para->acvpTests.primeSeed.fipsPrimeSeeds.xq1;
Xq2 = para->acvpTests.primeSeed.fipsPrimeSeeds.xq2;
#endif
Xp = (Xp0 != NULL) ? Xp0 : OptimizerGetBn(opt, proRoom);
Xq = (Xq0 != NULL) ? Xq0 : OptimizerGetBn(opt, proRoom);
if (Xp == NULL || Xq == NULL) {
ret = CRYPT_BN_OPTIMIZER_GET_FAIL;
BSL_ERR_PUSH_ERROR(ret);
OptimizerEnd(opt);
return ret;
}
// Step 4: get p
ret = GenPrimeWithAuxiliaryPrime(auxBits, proBits, Xp, Xp0, Xp1, Xp2, priKey->p, para, true, opt);
if (ret != CRYPT_SUCCESS) {
BN_Zeroize(Xp);
BSL_ERR_PUSH_ERROR(ret);
OptimizerEnd(opt);
return ret;
}
/*
* If |Xp – Xq| ≤ 2 ^ (2nlen/2 – 100) or |p – q| ≤ 2 ^ (2nlen/2 – 100), need to try again.
* We think there can ever be repeated many times here unless the 'random' is stuck.
* For example, nlen = 2048 and |Xp – Xq| ≤ 2 ^ (1024 – 100), it means that the most significant
* 99 bits of our Xq and Xp randomly generated are all identical. It's a low-probability event.
*/
do {
// Step 5: get q
ret = GenPrimeWithAuxiliaryPrime(auxBits, proBits, Xq, Xq0, Xq1, Xq2, priKey->q, para, false, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
// Step 6: Check (|Xp – Xq| ≤ 2^(nlen/2) – 100) and (|p – q| ≤ 2^(nlen/2) – 100)
ret = BN_Sub(Xq, Xp, Xq); // Xq dont needs anymore, but Xp may be used.
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
// |Xp – Xq| ≤ 2 ^ (2nlen/2 – 100) -> BN_Bits(Xp) <= secBits + 1 -> BN_Bits(Xp) < secBits
if (BN_Bits(Xq) < secBits) {
if (Xq0 != NULL && Xq1 != NULL && Xq2 != NULL) {
ret = CRYPT_RSA_NOR_KEYGEN_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
continue;
}
ret = BN_Sub(Xq, priKey->p, priKey->q);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
// |p – q| ≤ 2 ^ (2nlen/2 – 100)
if (BN_Bits(Xq) < secBits) {
if (Xq0 != NULL && Xq1 != NULL && Xq2 != NULL) {
ret = CRYPT_RSA_NOR_KEYGEN_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
continue;
}
break;
} while (true);
ERR:
if (Xp0 == NULL) {
BN_Zeroize(Xp);
}
if (Xq0 == NULL) {
BN_Zeroize(Xq);
}
OptimizerEnd(opt);
return ret;
}
#endif
static int32_t RsaPrvKeyCalcND(
const CRYPT_RSA_Para *para, CRYPT_RSA_Ctx *ctx, BN_BigNum *pMinusOne, BN_BigNum *qMinusOne, BN_Optimizer *optimizer)
{
int32_t ret;
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
ret = OptimizerStart(optimizer);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
CRYPT_RSA_PrvKey *prvKey = ctx->prvKey;
BN_BigNum *l = OptimizerGetBn(optimizer, BITS_TO_BN_UNIT(para->bits));
BN_BigNum *u = OptimizerGetBn(optimizer, BITS_TO_BN_UNIT(para->bits));
if (l == NULL || u == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
ret = CRYPT_BN_OPTIMIZER_GET_FAIL;
goto EXIT;
}
ret = BN_Mul(prvKey->n, prvKey->p, prvKey->q, optimizer);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BN_Mul(l, pMinusOne, qMinusOne, optimizer);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BN_Gcd(u, pMinusOne, qMinusOne, optimizer);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BN_Div(l, NULL, l, u, optimizer);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BN_ModInv(prvKey->d, para->e, l, optimizer);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
EXIT:
OptimizerEnd(optimizer);
return ret;
}
// p, q [ => n, d] => dP dQ qInv
// ctx->para may be NULL when setting key
int32_t RSA_CalcPrvKey(const CRYPT_RSA_Para *para, CRYPT_RSA_Ctx *ctx, BN_Optimizer *optimizer)
{
int32_t ret;
CRYPT_RSA_PrvKey *prvKey = ctx->prvKey;
uint32_t needRoom = BITS_TO_BN_UNIT(BN_Bits(prvKey->p));
ret = OptimizerStart(optimizer);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BN_BigNum *pMinusOne = OptimizerGetBn(optimizer, needRoom);
BN_BigNum *qMinusOne = OptimizerGetBn(optimizer, needRoom);
if (pMinusOne == NULL || qMinusOne == NULL) {
ret = CRYPT_BN_OPTIMIZER_GET_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BN_SubLimb(pMinusOne, prvKey->p, 1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BN_SubLimb(qMinusOne, prvKey->q, 1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
if (BN_IsZero(prvKey->n)) { // when generating key
ret = RsaPrvKeyCalcND(para, ctx, pMinusOne, qMinusOne, optimizer);
if (ret != CRYPT_SUCCESS) {
goto EXIT;
}
}
ret = BN_ModInv(prvKey->qInv, prvKey->q, prvKey->p, optimizer);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BN_Div(NULL, prvKey->dP, prvKey->d, pMinusOne, optimizer);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BN_Div(NULL, prvKey->dQ, prvKey->d, qMinusOne, optimizer);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
EXIT:
OptimizerEnd(optimizer);
return ret;
}
#ifdef HITLS_CRYPTO_RSA_GEN
/*
* In NIST SP 800-56B, Section 6.4.1.1, requiring we should perform a successful key-pair validation
* while generating the key pair.
*/
static int32_t RSA_KeyValidationCheck(CRYPT_RSA_Ctx *ctx, uint32_t bits)
{
int32_t ret;
BN_BigNum *val = BN_Create(1);
BN_BigNum *expect = BN_Create(bits);
if (val == NULL || expect == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
goto ERR;
}
// for performance reasons, we choose test num = 2.
(void)BN_SetLimb(val, 2); // val is not null, and the val-memory must be sufficient.
GOTO_ERR_IF(BN_MontExp(expect, val, ctx->prvKey->e, ctx->pubKey->mont, NULL), ret);
GOTO_ERR_IF(BN_MontExpConsttime(expect, expect, ctx->prvKey->d, ctx->pubKey->mont, NULL), ret);
if (BN_Cmp(val, expect) != 0) {
ret = CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE;
BSL_ERR_PUSH_ERROR(CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE);
goto ERR;
}
ERR:
BN_Destroy(val);
BN_Destroy(expect);
return ret;
}
int32_t CRYPT_RSA_Gen(CRYPT_RSA_Ctx *ctx)
{
if (ctx == NULL || ctx->para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret = CRYPT_MEM_ALLOC_FAIL;
BN_Optimizer *optimizer = NULL;
CRYPT_RSA_Ctx *newCtx = CRYPT_RSA_NewCtx();
if (newCtx == NULL) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
newCtx->prvKey = RSA_NewPrvKey(ctx->para->bits);
newCtx->pubKey = RSA_NewPubKey(ctx->para->bits);
optimizer = BN_OptimizerCreate();
if (optimizer == NULL || newCtx->prvKey == NULL || newCtx->pubKey == NULL) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
/*
* Currently, although the FIPS 186-5 standard does not support key generation of 1024 bits
* due to its low security, our interface does not lift this restriction.
* Meanwhile, the check of e is not added to ensure compatibility.
*/
BN_OptimizerSetLibCtx(ctx->libCtx, optimizer);
ret = GenPQBasedOnProbPrimes(ctx->para, newCtx->prvKey, optimizer);
if (ret != CRYPT_SUCCESS) {
BN_OptimizerDestroy(optimizer);
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
ret = RSA_CalcPrvKey(ctx->para, newCtx, optimizer);
BN_OptimizerDestroy(optimizer);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
GOTO_ERR_IF(BN_Copy(newCtx->pubKey->n, newCtx->prvKey->n), ret);
GOTO_ERR_IF(BN_Copy(newCtx->pubKey->e, ctx->para->e), ret);
GOTO_ERR_IF(BN_Copy(newCtx->prvKey->e, ctx->para->e), ret);
if ((newCtx->pubKey->mont = BN_MontCreate(newCtx->pubKey->n)) == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
ret = RSA_KeyValidationCheck(newCtx, ctx->para->bits);
if (ret != CRYPT_SUCCESS) {
goto ERR; // dont't push the stack repeatedly.
}
ShallowCopyCtx(ctx, newCtx);
BSL_SAL_FREE(newCtx);
return ret;
ERR:
CRYPT_RSA_FreeCtx(newCtx);
return ret;
}
void ShallowCopyCtx(CRYPT_RSA_Ctx *ctx, CRYPT_RSA_Ctx *newCtx)
{
RSA_FREE_PRV_KEY(ctx->prvKey);
RSA_FREE_PUB_KEY(ctx->pubKey);
#ifdef HITLS_CRYPTO_RSA_BLINDING
RSA_BlindFreeCtx(ctx->scBlind);
#endif
BSL_SAL_ReferencesFree(&(newCtx->references));
ctx->prvKey = newCtx->prvKey;
ctx->pubKey = newCtx->pubKey;
#ifdef HITLS_CRYPTO_RSA_BLINDING
ctx->scBlind = newCtx->scBlind;
#endif
ctx->pad = newCtx->pad;
ctx->flags = newCtx->flags;
}
#endif // HITLS_CRYPTO_RSA_GEN
#ifdef HITLS_CRYPTO_PROVIDER
static bool IsExistPrvKeyParams(const BSL_Param *params)
{
const BSL_Param *d = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_D);
const BSL_Param *n = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_N);
const BSL_Param *p = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_P);
const BSL_Param *q = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_Q);
const BSL_Param *dp = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_DP);
const BSL_Param *dq = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_DQ);
const BSL_Param *qInv = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_QINV);
return n != NULL && d != NULL && (PARAMISNULL(p) == PARAMISNULL(q)) &&
(PARAMISNULL(dp) == PARAMISNULL(dq)) && PARAMISNULL(dq) == PARAMISNULL(qInv);
}
static bool IsExistPubKeyParams(const BSL_Param *params)
{
const BSL_Param *e = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_E);
const BSL_Param *n = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_N);
return e != NULL && n != NULL;
}
static bool IsExistRsaParam(const BSL_Param *params)
{
const BSL_Param *bits = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_BITS);
const BSL_Param *e = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_E);
return bits != NULL && e != NULL;
}
int32_t CRYPT_RSA_Import(CRYPT_RSA_Ctx *ctx, const BSL_Param *params)
{
int32_t ret = CRYPT_SUCCESS;
if (IsExistPrvKeyParams(params)) {
ret = CRYPT_RSA_SetPrvKeyEx(ctx, params);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
if (IsExistPubKeyParams(params)) {
ret = CRYPT_RSA_SetPubKeyEx(ctx, params);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
if (IsExistRsaParam(params)) {
ret = CRYPT_RSA_SetParaEx(ctx, params);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
const BSL_Param *mdIdParam = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_MD_ID);
const BSL_Param *mgf1IdParam = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_MGF1_ID);
const BSL_Param *saltLenParam = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_SALTLEN);
if (mdIdParam != NULL && mgf1IdParam != NULL && saltLenParam != NULL) {
ret = CRYPT_RSA_Ctrl(ctx, CRYPT_CTRL_SET_RSA_EMSA_PSS, (void *)(uintptr_t)params, 0);
} else if (mdIdParam != NULL && mdIdParam->valueType == BSL_PARAM_TYPE_INT32 && mdIdParam->value != NULL) {
int32_t mdId = *(int32_t *)mdIdParam->value;
ret = CRYPT_RSA_Ctrl(ctx, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &mdId, sizeof(mdId));
}
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
static void InitRsaPubKeyParams(BSL_Param *params, uint32_t *index, uint8_t *buffer, uint32_t len)
{
(void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_E,
BSL_PARAM_TYPE_OCTETS, buffer + ((*index) * len), len);
(*index)++;
(void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_N,
BSL_PARAM_TYPE_OCTETS, buffer + ((*index) * len), len);
(*index)++;
}
static void InitRsaPrvKeyParams(BSL_Param *params, uint32_t *index, uint8_t *buffer, uint32_t len)
{
(void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_D,
BSL_PARAM_TYPE_OCTETS, buffer + ((*index) * len), len);
(*index)++;
(void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_P,
BSL_PARAM_TYPE_OCTETS, buffer + ((*index) * len), len);
(*index)++;
(void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_Q,
BSL_PARAM_TYPE_OCTETS, buffer + ((*index) * len), len);
(*index)++;
(void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_DP,
BSL_PARAM_TYPE_OCTETS, buffer + ((*index) * len), len);
(*index)++;
(void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_DQ,
BSL_PARAM_TYPE_OCTETS, buffer + ((*index) * len), len);
(*index)++;
(void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_QINV,
BSL_PARAM_TYPE_OCTETS, buffer + ((*index) * len), len);
(*index)++;
}
static void ExportRsaPssParams(const CRYPT_RSA_Ctx *ctx, BSL_Param *params, uint32_t *index)
{
(void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_MD_ID,
BSL_PARAM_TYPE_UINT32, (void *)(uintptr_t)&ctx->pad.para.pss.mdId, sizeof(uint32_t));
params[(*index)++].useLen = sizeof(uint32_t);
(void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_MGF1_ID,
BSL_PARAM_TYPE_UINT32, (void *)(uintptr_t)&ctx->pad.para.pss.mgfId, sizeof(uint32_t));
params[(*index)++].useLen = sizeof(uint32_t);
(void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_SALTLEN,
BSL_PARAM_TYPE_UINT32, (void *)(uintptr_t)&ctx->pad.para.pss.saltLen, sizeof(uint32_t));
params[(*index)++].useLen = sizeof(uint32_t);
}
static void ExportRsaPkcsParams(const CRYPT_RSA_Ctx *ctx, BSL_Param *params, uint32_t *index)
{
(void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_MD_ID,
BSL_PARAM_TYPE_UINT32, (void *)(uintptr_t)&ctx->pad.para.pkcsv15.mdId, sizeof(uint32_t));
params[(*index)++].useLen = sizeof(uint32_t);
}
int32_t CRYPT_RSA_Export(const CRYPT_RSA_Ctx *ctx, BSL_Param *params)
{
if (ctx == NULL || params == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
uint32_t index = 1;
void *args = NULL;
CRYPT_EAL_ProcessFuncCb processCb = NULL;
uint32_t keyBits = CRYPT_RSA_GetBits(ctx);
if (keyBits == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_NO_KEY_INFO);
return CRYPT_RSA_NO_KEY_INFO;
}
uint32_t bytes = BN_BITS_TO_BYTES(keyBits);
BSL_Param rsaParams[13] = {
{CRYPT_PARAM_RSA_BITS, BSL_PARAM_TYPE_UINT32, &keyBits, sizeof(uint32_t), sizeof(uint32_t)},
{0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, BSL_PARAM_END};
int32_t ret = CRYPT_GetPkeyProcessParams(params, &processCb, &args);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
uint8_t *buffer = BSL_SAL_Calloc(1, keyBits * 8);
if (buffer == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
if (ctx->pubKey != NULL) {
InitRsaPubKeyParams(rsaParams, &index, buffer, bytes);
ret = CRYPT_RSA_GetPubKeyEx(ctx, rsaParams);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_Free(buffer);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
if (ctx->prvKey != NULL) {
InitRsaPrvKeyParams(rsaParams, &index, buffer, bytes);
ret = CRYPT_RSA_GetPrvKeyEx(ctx, rsaParams);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_Free(buffer);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
if (ctx->pad.type == EMSA_PSS) {
ExportRsaPssParams(ctx, rsaParams, &index);
} else if (ctx->pad.type == EMSA_PKCSV15) {
ExportRsaPkcsParams(ctx, rsaParams, &index);
}
for (uint32_t i = 0; i < index; i++) {
rsaParams[i].valueLen = rsaParams[i].useLen;
}
ret = processCb(rsaParams, args);
BSL_SAL_Free(buffer);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
#endif // HITLS_CRYPTO_PROVIDER
#endif /* HITLS_CRYPTO_RSA */
| 2302_82127028/openHiTLS-examples_1508 | crypto/rsa/src/rsa_keygen.c | C | unknown | 50,299 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_RSA
#include "crypt_types.h"
#include "crypt_rsa.h"
#include "crypt_utils.h"
#include "bsl_err_internal.h"
#include "rsa_local.h"
#include "crypt_errno.h"
#include "securec.h"
#include "bsl_sal.h"
#include "crypt_params_key.h"
static int32_t SetPrvPara(const CRYPT_RSA_PrvKey *prvKey, const CRYPT_RsaPrv *prv)
{
int32_t ret = BN_Bin2Bn(prvKey->n, prv->n, prv->nLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
uint32_t bnBits = BN_Bits(prvKey->n);
if (bnBits > RSA_MAX_MODULUS_BITS || bnBits < RSA_MIN_MODULUS_BITS) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_KEY_BITS);
return CRYPT_RSA_ERR_KEY_BITS;
}
ret = BN_Bin2Bn(prvKey->d, prv->d, prv->dLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// d cannot be 0 or 1. The mathematical logic of e and d is that
// d and e are reciprocal in mod((p-1) * (q-1)); When d is 1, e and d must be 1. When d is 0, e doesn't exist.
if (BN_IsZero(prvKey->d) || BN_IsOne(prvKey->d)) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_INPUT_VALUE);
return CRYPT_RSA_ERR_INPUT_VALUE;
}
if (BN_Cmp(prvKey->n, prvKey->d) <= 0) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_INPUT_VALUE);
return CRYPT_RSA_ERR_INPUT_VALUE;
}
if (prv->e != NULL) {
ret = BN_Bin2Bn(prvKey->e, prv->e, prv->eLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (BN_Cmp(prvKey->n, prvKey->e) <= 0) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_INPUT_VALUE);
return CRYPT_RSA_ERR_INPUT_VALUE;
}
}
if (prv->p != NULL) {
GOTO_ERR_IF_EX(BN_Bin2Bn(prvKey->p, prv->p, prv->pLen), ret);
GOTO_ERR_IF_EX(BN_Bin2Bn(prvKey->q, prv->q, prv->qLen), ret);
if (BN_IsZero(prvKey->p) == true || BN_IsZero(prvKey->q) == true) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_INPUT_VALUE);
return CRYPT_RSA_ERR_INPUT_VALUE;
}
if (prv->dP != NULL) {
GOTO_ERR_IF_EX(BN_Bin2Bn(prvKey->dP, prv->dP, prv->dPLen), ret);
GOTO_ERR_IF_EX(BN_Bin2Bn(prvKey->dQ, prv->dQ, prv->dQLen), ret);
GOTO_ERR_IF_EX(BN_Bin2Bn(prvKey->qInv, prv->qInv, prv->qInvLen), ret);
}
}
ERR:
return ret;
}
// If n and d are not NULL, p and q are optional. If p and q exist, qInv, dP, and dQ need to be calculated.
static int32_t SetPrvBasicCheck(const CRYPT_RSA_Ctx *ctx, const CRYPT_RsaPrv *prv)
{
if (ctx == NULL || prv == NULL || prv->n == NULL || prv->d == NULL || prv->nLen == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (prv->nLen > RSA_MAX_MODULUS_LEN) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_KEY_BITS);
return CRYPT_RSA_ERR_KEY_BITS;
}
// prv->p\q and prv->dP\dQ\qInv must be both empty or not.
// If prv->p is empty, prv->dP must be empty.
if ((prv->p == NULL) != (prv->q == NULL) || (prv->p == NULL && prv->dP != NULL) ||
((prv->dP == NULL || prv->dQ == NULL || prv->qInv == NULL) && (prv->dP || prv->dQ || prv->qInv))) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_NO_KEY_INFO);
return CRYPT_RSA_NO_KEY_INFO;
}
return CRYPT_SUCCESS;
}
static int32_t SetPrvBnLenCheck(const CRYPT_RsaPrv *prv)
{
/* The length of n is used as the length of a BigNum. The lengths of d, p, and q are not greater than n. */
uint32_t bnBytes = prv->nLen;
if (prv->dLen > bnBytes || prv->pLen > bnBytes || prv->qLen > bnBytes) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_KEY_BITS);
return CRYPT_RSA_ERR_KEY_BITS;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_RSA_SetPrvKey(CRYPT_RSA_Ctx *ctx, const CRYPT_RsaPrv *prv)
{
int32_t ret = SetPrvBasicCheck(ctx, prv);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = SetPrvBnLenCheck(prv);
if (ret != CRYPT_SUCCESS) {
return ret;
}
CRYPT_RSA_Ctx *newCtx = CRYPT_RSA_NewCtx();
if (newCtx == NULL) {
return CRYPT_MEM_ALLOC_FAIL;
}
newCtx->prvKey = RSA_NewPrvKey(prv->nLen * 8); // Bit length is obtained by multiplying byte length by 8.
if (newCtx->prvKey == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
GOTO_ERR_IF(SetPrvPara(newCtx->prvKey, prv), ret);
if (prv->p != NULL && prv->dP == NULL) {
BN_Optimizer *optimizer = BN_OptimizerCreate();
if (optimizer == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
ret = RSA_CalcPrvKey(newCtx->para, newCtx, optimizer);
BN_OptimizerDestroy(optimizer);
if (ret != CRYPT_SUCCESS) {
goto ERR;
}
}
RSA_FREE_PRV_KEY(ctx->prvKey);
#ifdef HITLS_CRYPTO_RSA_BLINDING
RSA_BlindFreeCtx(ctx->scBlind);
ctx->scBlind = newCtx->scBlind;
#endif
ctx->prvKey = newCtx->prvKey;
ctx->pad = newCtx->pad;
BSL_SAL_ReferencesFree(&(newCtx->references));
BSL_SAL_FREE(newCtx);
return ret;
ERR:
CRYPT_RSA_FreeCtx(newCtx);
return ret;
}
static int32_t SetPubBasicCheck(const CRYPT_RSA_Ctx *ctx, const CRYPT_RsaPub *pub)
{
if (ctx == NULL || pub == NULL || pub->n == NULL || pub->e == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (pub->nLen > RSA_MAX_MODULUS_LEN) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_KEY_BITS);
return CRYPT_RSA_ERR_KEY_BITS;
}
/* The length of n is used as the length of a BigNum, and the length of e is not greater than n. */
if (pub->eLen > pub->nLen) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_KEY_BITS);
return CRYPT_RSA_ERR_KEY_BITS;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_RSA_SetPubKey(CRYPT_RSA_Ctx *ctx, const CRYPT_RsaPub *pub)
{
int32_t ret = SetPubBasicCheck(ctx, pub);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
uint32_t bnBits;
CRYPT_RSA_PubKey *newPub = NULL;
(void)memset_s(&(ctx->pad), sizeof(RSAPad), 0, sizeof(RSAPad));
/* Bit length is obtained by multiplying byte length by 8. */
newPub = RSA_NewPubKey(pub->nLen * 8);
if (newPub == NULL) {
return CRYPT_MEM_ALLOC_FAIL;
}
GOTO_ERR_IF(BN_Bin2Bn(newPub->n, pub->n, pub->nLen), ret);
bnBits = BN_Bits(newPub->n);
if (bnBits > RSA_MAX_MODULUS_BITS || bnBits < RSA_MIN_MODULUS_BITS) {
ret = CRYPT_RSA_ERR_KEY_BITS;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
GOTO_ERR_IF(BN_Bin2Bn(newPub->e, pub->e, pub->eLen), ret);
if (pub->nLen > RSA_SMALL_MODULUS_BYTES && BN_Bytes(newPub->e) > RSA_MAX_PUBEXP_BYTES) {
ret = CRYPT_RSA_ERR_KEY_BITS;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
/**
* n > e
* e cannot be 0 or 1; The mathematical logic of e and d is that
* d and e are reciprocal in mod((p - 1) * (q - 1));
* When e is 1, both e and d must be 1. When e is 0, d does not exist.
*/
if (BN_Cmp(newPub->n, newPub->e) <= 0 || BN_IsZero(newPub->e) || BN_IsOne(newPub->e)) {
ret = CRYPT_RSA_ERR_INPUT_VALUE;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
newPub->mont = BN_MontCreate(newPub->n);
if (newPub->mont == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
RSA_FREE_PUB_KEY(ctx->pubKey);
ctx->pubKey = newPub;
return ret;
ERR:
RSA_FREE_PUB_KEY(newPub);
return ret;
}
static int32_t GetPrvBasicCheck(const CRYPT_RSA_Ctx *ctx, const CRYPT_RsaPrv *prv)
{
// ctx\ctx->prvKey\prv is not empty.
// prv->p\q and prv->dP\dQ\qInv are both null or non-null.
// If prv->p is empty, prv->dP is empty.
if (ctx == NULL || ctx->prvKey == NULL || prv == NULL || ((prv->p == NULL) != (prv->q == NULL)) ||
((prv->dP == NULL || prv->dQ == NULL || prv->qInv == NULL) && (prv->dP || prv->dQ || prv->qInv)) ||
(prv->p == NULL && prv->dP != NULL)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_RSA_GetPrvKey(const CRYPT_RSA_Ctx *ctx, CRYPT_RsaPrv *prv)
{
int32_t ret = GetPrvBasicCheck(ctx, prv);
if (ret != CRYPT_SUCCESS) {
return ret;
}
GOTO_ERR_IF(BN_Bn2Bin(ctx->prvKey->n, prv->n, &prv->nLen), ret);
GOTO_ERR_IF(BN_Bn2Bin(ctx->prvKey->d, prv->d, &prv->dLen), ret);
if (prv->e != NULL) {
GOTO_ERR_IF(BN_Bn2Bin(ctx->prvKey->e, prv->e, &prv->eLen), ret);
}
if (prv->p != NULL) {
GOTO_ERR_IF(BN_Bn2Bin(ctx->prvKey->p, prv->p, &prv->pLen), ret);
GOTO_ERR_IF(BN_Bn2Bin(ctx->prvKey->q, prv->q, &prv->qLen), ret);
}
if (prv->dQ != NULL) {
GOTO_ERR_IF(BN_Bn2Bin(ctx->prvKey->dQ, prv->dQ, &prv->dQLen), ret);
GOTO_ERR_IF(BN_Bn2Bin(ctx->prvKey->dP, prv->dP, &prv->dPLen), ret);
GOTO_ERR_IF(BN_Bn2Bin(ctx->prvKey->qInv, prv->qInv, &prv->qInvLen), ret);
}
return CRYPT_SUCCESS;
ERR:
if (prv->d != NULL && prv->dLen != 0) {
BSL_SAL_CleanseData(prv->d, prv->dLen);
}
if (prv->p != NULL && prv->pLen != 0) {
BSL_SAL_CleanseData(prv->p, prv->pLen);
}
if (prv->q != NULL && prv->qLen != 0) {
BSL_SAL_CleanseData(prv->q, prv->qLen);
}
if (prv->dQ != NULL && prv->dQLen != 0) {
BSL_SAL_CleanseData(prv->dQ, prv->dQLen);
}
if (prv->dP != NULL && prv->dPLen != 0) {
BSL_SAL_CleanseData(prv->dP, prv->dPLen);
}
if (prv->qInv != NULL && prv->qInvLen != 0) {
BSL_SAL_CleanseData(prv->qInv, prv->qInvLen);
}
return ret;
}
int32_t CRYPT_RSA_GetPubKey(const CRYPT_RSA_Ctx *ctx, CRYPT_RsaPub *pub)
{
if (ctx == NULL || ctx->pubKey == NULL || pub == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret = BN_Bn2Bin(ctx->pubKey->e, pub->e, &pub->eLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = BN_Bn2Bin(ctx->pubKey->n, pub->n, &pub->nLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
#ifdef HITLS_BSL_PARAMS
int32_t CRYPT_RSA_SetPrvKeyEx(CRYPT_RSA_Ctx *ctx, const BSL_Param *para)
{
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_RsaPrv prv = {0};
(void)GetConstParamValue(para, CRYPT_PARAM_RSA_N, &prv.n, &prv.nLen);
(void)GetConstParamValue(para, CRYPT_PARAM_RSA_D, &prv.d, &prv.dLen);
(void)GetConstParamValue(para, CRYPT_PARAM_RSA_E, &prv.e, &prv.eLen);
(void)GetConstParamValue(para, CRYPT_PARAM_RSA_P, &prv.p, &prv.pLen);
(void)GetConstParamValue(para, CRYPT_PARAM_RSA_Q, &prv.q, &prv.qLen);
(void)GetConstParamValue(para, CRYPT_PARAM_RSA_DP, &prv.dP, &prv.dPLen);
(void)GetConstParamValue(para, CRYPT_PARAM_RSA_DQ, &prv.dQ, &prv.dQLen);
(void)GetConstParamValue(para, CRYPT_PARAM_RSA_QINV, &prv.qInv, &prv.qInvLen);
return CRYPT_RSA_SetPrvKey(ctx, &prv);
}
int32_t CRYPT_RSA_SetPubKeyEx(CRYPT_RSA_Ctx *ctx, const BSL_Param *para)
{
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_RsaPub pub = {0};
(void)GetConstParamValue(para, CRYPT_PARAM_RSA_N, &pub.n, &pub.nLen);
(void)GetConstParamValue(para, CRYPT_PARAM_RSA_E, &pub.e, &pub.eLen);
return CRYPT_RSA_SetPubKey(ctx, &pub);
}
int32_t CRYPT_RSA_GetPrvKeyEx(const CRYPT_RSA_Ctx *ctx, BSL_Param *para)
{
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_RsaPrv prv = {0};
BSL_Param *paramN = GetParamValue(para, CRYPT_PARAM_RSA_N, &prv.n, &prv.nLen);
BSL_Param *paramD = GetParamValue(para, CRYPT_PARAM_RSA_D, &prv.d, &prv.dLen);
BSL_Param *paramE = GetParamValue(para, CRYPT_PARAM_RSA_E, &prv.e, &prv.eLen);
BSL_Param *paramP = GetParamValue(para, CRYPT_PARAM_RSA_P, &prv.p, &prv.pLen);
BSL_Param *paramQ = GetParamValue(para, CRYPT_PARAM_RSA_Q, &prv.q, &prv.qLen);
BSL_Param *paramDP = GetParamValue(para, CRYPT_PARAM_RSA_DP, &prv.dP, &prv.dPLen);
BSL_Param *paramDQ = GetParamValue(para, CRYPT_PARAM_RSA_DQ, &prv.dQ, &prv.dQLen);
BSL_Param *paramQInv = GetParamValue(para, CRYPT_PARAM_RSA_QINV, &prv.qInv, &prv.qInvLen);
int32_t ret = CRYPT_RSA_GetPrvKey(ctx, &prv);
if (ret != CRYPT_SUCCESS) {
return ret;
}
paramN->useLen = prv.nLen;
paramD->useLen = prv.dLen;
if (paramE != NULL) {
paramE->useLen = prv.eLen;
}
if (paramP != NULL) {
paramP->useLen = prv.pLen;
}
if (paramQ != NULL) {
paramQ->useLen = prv.qLen;
}
if (paramDP != NULL) {
paramDP->useLen = prv.dPLen;
}
if (paramDQ != NULL) {
paramDQ->useLen = prv.dQLen;
}
if (paramQInv != NULL) {
paramQInv->useLen = prv.qInvLen;
}
return ret;
}
int32_t CRYPT_RSA_GetPubKeyEx(const CRYPT_RSA_Ctx *ctx, BSL_Param *para)
{
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_RsaPub pub = {0};
BSL_Param *paramN = GetParamValue(para, CRYPT_PARAM_RSA_N, &pub.n, &pub.nLen);
BSL_Param *paramE = GetParamValue(para, CRYPT_PARAM_RSA_E, &pub.e, &pub.eLen);
int32_t ret = CRYPT_RSA_GetPubKey(ctx, &pub);
if (ret != CRYPT_SUCCESS) {
return ret;
}
paramN->useLen = pub.nLen;
paramE->useLen = pub.eLen;
return ret;
}
#endif
int32_t CRYPT_RSA_Cmp(const CRYPT_RSA_Ctx *a, const CRYPT_RSA_Ctx *b)
{
RETURN_RET_IF(a == NULL || b == NULL, CRYPT_NULL_INPUT);
RETURN_RET_IF(a->pubKey == NULL || b->pubKey == NULL, CRYPT_RSA_NO_KEY_INFO);
RETURN_RET_IF(BN_Cmp(a->pubKey->n, b->pubKey->n) != 0 ||
BN_Cmp(a->pubKey->e, b->pubKey->e) != 0,
CRYPT_RSA_PUBKEY_NOT_EQUAL);
return CRYPT_SUCCESS;
}
int32_t CRYPT_RSA_GetSecBits(const CRYPT_RSA_Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return 0;
}
int32_t bits = (int32_t)CRYPT_RSA_GetBits(ctx);
return BN_SecBits(bits, -1);
}
#ifdef HITLS_CRYPTO_RSA_CHECK
#define RSA_CHECK_PQ_RECOVER 1 // recover p q and check.
#define RSA_CHECK_PQD_CHECK 2 // check prime p q
#define RSA_CHECK_CRT_CHECK 3 // check crt
// m = 2^t * r, m != 0. cal Max(t) and bn = m / 2^t.
static void CalMaxT(BN_BigNum *bn, uint32_t *res)
{
uint32_t t = 0;
while (BN_GetBit(bn, t) == false) {
t++;
}
*res = t;
(void)BN_Rshift(bn, bn, t); // bn will decrease, and the memory will definitely be sufficient
return;
}
static int32_t BasicKeypairCheck(const CRYPT_RSA_PubKey *pubKey, const CRYPT_RSA_PrvKey *prvKey)
{
if (pubKey->n == NULL || pubKey->e == NULL) {
return CRYPT_RSA_ERR_NO_PUBKEY_INFO;
}
// Currently, the check for p and q being null is not supported.
if (prvKey->n == NULL || prvKey->d == NULL) {
return CRYPT_RSA_ERR_NO_PRVKEY_INFO;
}
uint32_t eBits1 = BN_Bits(pubKey->e); // not check e == NULL repeatedly.
uint32_t eBits2 = BN_Bits(prvKey->e); // prvKey->e can be empty, unless in crt mode
// e <= 2^16 or e >= 2^256 -> e shoule be [17, 256].
if ((eBits2 != 0 && eBits2 != eBits1) || eBits1 < 17 || eBits1 > 256 || !BN_IsOdd(pubKey->e)) {
return CRYPT_RSA_ERR_E_VALUE;
}
uint32_t nBbits = BN_Bits(pubKey->n);
if (nBbits % 2 != 0) { // mod 2 to check nBits is a positive even integer or not.
return CRYPT_RSA_ERR_KEY_BITS;
}
int32_t ret = BN_Cmp(pubKey->n, prvKey->n); // If n_pub != n_priv
if (ret != 0) { // not equal
return CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE;
}
ret = BN_SecBits((int32_t)nBbits, -1); // no need to consider prvLen.
/* SP800-56B requires that its should in the interval [112, 256]
* Because the current rsa specification supports 1024 bits, so the lower limit is 80. */
if (ret < 80 || ret > 256) {
return CRYPT_RSA_ERR_KEY_BITS;
}
return CRYPT_SUCCESS;
}
/*
* if lower < p < upper, return success, otherwise return error.
*/
static int32_t RangeCheck(const BN_BigNum *lower, const BN_BigNum *p, const BN_BigNum *upper)
{
int32_t ret = BN_Cmp(lower, p);
if (ret >= 0) {
return CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE;
}
ret = BN_Cmp(p, upper);
if (ret >= 0) {
return CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE;
}
return CRYPT_SUCCESS;
}
#ifdef HITLS_CRYPTO_SP800_STRICT_CHECK
/*
* if (p < √2)(2nBits/2−1)) or (p > 2nBits/2 – 1), return error.
*/
static int32_t FactorPQcheck(const BN_BigNum *e, const BN_BigNum *p, const BN_BigNum *n1, const BN_BigNum *n2,
BN_Optimizer *opt)
{
int32_t ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BN_BigNum *pSqr = OptimizerGetBn(opt, p->size);
BN_BigNum *tmp = OptimizerGetBn(opt, p->size);
if (tmp == NULL || pSqr == NULL) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
GOTO_ERR_IF(BN_Sqr(pSqr, p, opt), ret);
if (BN_Cmp(pSqr, n1) < 0) { // check (p < (√2)(2^(nBits/2−1))
ret = CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
if (BN_Cmp(p, n2) > 0) { // check (p > (2^(nBits - 1)))
ret = CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
GOTO_ERR_IF(BN_SubLimb(tmp, p, 1), ret);
GOTO_ERR_IF(BN_Gcd(tmp, e, tmp, opt), ret); // check gcd(p-1, e_pub) != 1
if (!BN_IsOne(tmp)) {
ret = CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE;
BSL_ERR_PUSH_ERROR(ret);
}
ERR:
OptimizerEnd(opt);
return ret;
}
#endif
static int32_t FactorPrimeCheck(const BN_BigNum *n, const BN_BigNum *e, const BN_BigNum *p, const BN_BigNum *q,
BN_Optimizer *opt)
{
int32_t ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
uint32_t nBits = BN_Bits(n);
uint32_t checkTimes = nBits < 1536 ? 5 : 4; // ref. FIPS 186-5, Table B.1
uint32_t needRoom = nBits / BN_UINT_BITS;
BN_BigNum *tmp1 = OptimizerGetBn(opt, needRoom);
BN_BigNum *tmp2 = OptimizerGetBn(opt, needRoom);
if (tmp1 == NULL || tmp2 == NULL) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
GOTO_ERR_IF(BN_Mul(tmp1, p, q, opt), ret);
if (BN_Cmp(tmp1, n) != 0) { // if n_pub != p * q.
ret = CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE;
BSL_ERR_PUSH_ERROR(CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE);
goto ERR;
}
#ifdef HITLS_CRYPTO_SP800_STRICT_CHECK
// get ((√2)(2^(nBits/2 - 1)))^2
(void)BN_SetLimb(tmp1, 1);
GOTO_ERR_IF(BN_Lshift(tmp1, tmp1, nBits - 2), ret); // secLen can guarantee nBits > 2.
GOTO_ERR_IF(BN_Add(tmp1, tmp1, tmp1), ret);
// get 2^(nBits/2) - 1.
(void)BN_SetLimb(tmp2, 1);
GOTO_ERR_IF(BN_Lshift(tmp2, tmp2, nBits << 1), ret);
GOTO_ERR_IF(BN_SubLimb(tmp2, tmp2, 1), ret);
GOTO_ERR_IF(FactorPQcheck(e, p, tmp1, tmp2, opt), ret);
GOTO_ERR_IF(FactorPQcheck(e, q, tmp1, tmp2, opt), ret);
#else
(void)e;
#endif
GOTO_ERR_IF(BN_Sub(tmp1, p, q), ret);
(void)BN_SetSign(tmp1, false); // tmp1 = |p - q|
(void)BN_SetLimb(tmp2, 1);
GOTO_ERR_IF(BN_Lshift(tmp2, tmp2, (nBits >> 1) - 100), ret); // 2^(nBits/2 - 100)
if (BN_Cmp(tmp1, tmp2) <= 0) { // check |p - q| <= (2^(nBits/2 - 100))
ret = CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
ret = BN_PrimeCheck(p, checkTimes, opt, NULL);
if (ret != CRYPT_SUCCESS) {
if (ret == CRYPT_BN_NOR_CHECK_PRIME) {
ret = CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
}
ret = BN_PrimeCheck(q, checkTimes, opt, NULL);
if (ret != CRYPT_SUCCESS) {
if (ret == CRYPT_BN_NOR_CHECK_PRIME) {
ret = CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE;
BSL_ERR_PUSH_ERROR(ret);
}
}
ERR:
OptimizerEnd(opt);
return ret;
}
static int32_t FactorDCheck(const BN_BigNum *n, const BN_BigNum *e, const BN_BigNum *p, const BN_BigNum *q,
const BN_BigNum *d, BN_Optimizer *opt)
{
int32_t ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
uint32_t nBits = BN_Bits(n);
uint32_t needRoom = nBits / BN_UINT_BITS;
BN_BigNum *tmp0 = OptimizerGetBn(opt, needRoom);
BN_BigNum *tmp1 = OptimizerGetBn(opt, needRoom);
BN_BigNum *tmp2 = OptimizerGetBn(opt, needRoom);
if (tmp0 == NULL || tmp1 == NULL || tmp2 == NULL) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
// get 2^(nBits / 2)
(void)BN_SetLimb(tmp0, 1);
GOTO_ERR_IF(BN_Lshift(tmp0, tmp0, nBits >> 1), ret);
GOTO_ERR_IF(BN_SubLimb(tmp1, p, 1), ret);
GOTO_ERR_IF(BN_SubLimb(tmp2, q, 1), ret);
// tmp1 = LCM(p – 1, q – 1)
GOTO_ERR_IF(BN_Lcm(tmp1, tmp1, tmp2, opt), ret);
#ifdef HITLS_CRYPTO_SP800_STRICT_CHECK
// In the original RSA paper <A Method for Obtaining Digital Signatures and Public-Key Cryptosystems>,
// the Euler totient function is φ(n) = (p – 1)(q – 1), hence d < LCM(p – 1, q – 1) will be incompatible.
// check 2^(nBits / 2) < d < LCM(p – 1, q – 1).
GOTO_ERR_IF(RangeCheck(tmp0, d, tmp1), ret);
#endif
GOTO_ERR_IF(BN_Mul(tmp0, e, d, opt), ret);
GOTO_ERR_IF(BN_Mod(tmp2, tmp0, tmp1, opt), ret);
// check. 1 = (d * epub) mod LCM(p – 1, q – 1).
if (!BN_IsOne(tmp2)) {
ret = CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE;
BSL_ERR_PUSH_ERROR(ret);
}
ERR:
OptimizerEnd(opt);
return ret;
}
/*
* Recover prime factors p and q from n, e, and d.
* ref SP800.56b Appendix C
*/
static int32_t RecoverPrimeFactorsAndCheck(const CRYPT_RSA_Ctx *pubKey, const CRYPT_RSA_Ctx *prvKey,
BN_Optimizer *opt)
{
int ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
bool flag = false;
uint32_t tFactor;
uint32_t nBits = BN_Bits(pubKey->pubKey->n);
uint32_t needRoom = nBits / BN_UINT_BITS;
BN_BigNum *g = OptimizerGetBn(opt, needRoom);
BN_BigNum *x = OptimizerGetBn(opt, needRoom);
BN_BigNum *y = OptimizerGetBn(opt, needRoom);
BN_BigNum *nSubOne = OptimizerGetBn(opt, needRoom);
BN_BigNum *p = OptimizerGetBn(opt, needRoom);
BN_BigNum *q = OptimizerGetBn(opt, needRoom);
BN_BigNum *r = OptimizerGetBn(opt, needRoom);
if (g == NULL || x == NULL || y == NULL || nSubOne == NULL || p == NULL || q == NULL || r == NULL) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
GOTO_ERR_IF(BN_SubLimb(nSubOne, pubKey->pubKey->n, 1), ret); // n - 1
// step 1: compute r = d * e - 1
GOTO_ERR_IF(BN_Mul(r, prvKey->prvKey->d, pubKey->pubKey->e, opt), ret); // d * e
GOTO_ERR_IF(BN_SubLimb(r, r, 1), ret); // d * e - 1
if (BN_IsOdd(r)) {
ret = CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
// step 2: find t and m = (2^t) * r, r is the largest odd integer.
CalMaxT(r, &tFactor); // r = m / 2^t
// step 3: find prime factors p and q.
for (uint32_t i = 0; i < 100; i++) { // try 100 times
GOTO_ERR_IF(BN_RandRangeEx(LIBCTX_FROM_RSA_CTX(pubKey), g, pubKey->pubKey->n), ret); // rand(0, n)
GOTO_ERR_IF(BN_ModExp(y, g, r, pubKey->pubKey->n, opt), ret); // y = g ^ r % n
if (BN_IsOne(y) == true || BN_Cmp(y, nSubOne) == 0) { // y == 1 or y == n - 1
continue;
}
for (uint32_t j = 1; j < tFactor; j++) { // 1 -> t - 1
GOTO_ERR_IF(BN_ModSqr(x, y, pubKey->pubKey->n, opt), ret); // y ^ 2 mod n
if (BN_IsOne(x) == true) {
flag = true;
break;
}
if (BN_Cmp(x, nSubOne) == 0) {
continue;
}
GOTO_ERR_IF(BN_Copy(y, x), ret); // update y.
}
GOTO_ERR_IF(BN_ModSqr(x, y, pubKey->pubKey->n, opt), ret); // y ^ 2 mod n
if (BN_IsOne(x) == true) {
flag = true;
break;
}
}
// step 4: check if flag is true.
if (!flag) {
ret = CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
GOTO_ERR_IF(BN_SubLimb(y, y, 1), ret); // y - 1
// step 5: compute p = gcd(y, n) and q = n / p.
GOTO_ERR_IF(BN_Gcd(p, y, pubKey->pubKey->n, opt), ret); // p = gcd(y, n)
GOTO_ERR_IF(BN_Div(q, NULL, pubKey->pubKey->n, p, opt), ret); // q = n / p
GOTO_ERR_IF(FactorPrimeCheck(pubKey->pubKey->n, pubKey->pubKey->e, p, q, opt), ret);
GOTO_ERR_IF(FactorDCheck(pubKey->pubKey->n, pubKey->pubKey->e, p, q, prvKey->prvKey->d, opt), ret);
ERR:
OptimizerEnd(opt);
return ret;
}
static int32_t FactorCRTCheck(const CRYPT_RSA_PrvKey *prvKey, BN_Optimizer *opt)
{
int32_t ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
uint32_t nBits = BN_Bits(prvKey->n);
uint32_t needRoom = nBits / BN_UINT_BITS;
BN_BigNum *pMinusOne = OptimizerGetBn(opt, needRoom);
BN_BigNum *qMinusOne = OptimizerGetBn(opt, needRoom);
BN_BigNum *one = OptimizerGetBn(opt, needRoom);
if (pMinusOne == NULL || qMinusOne == NULL || one == NULL) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
GOTO_ERR_IF(BN_SubLimb(pMinusOne, prvKey->p, 1), ret); // p - 1
GOTO_ERR_IF(BN_SubLimb(qMinusOne, prvKey->q, 1), ret); // q - 1
(void)BN_SetLimb(one, 1);
GOTO_ERR_IF(RangeCheck(one, prvKey->dP, pMinusOne), ret); // 1 < dP < (p – 1).
GOTO_ERR_IF(RangeCheck(one, prvKey->dQ, qMinusOne), ret); // 1 < dQ < (q – 1).
GOTO_ERR_IF(RangeCheck(one, prvKey->qInv, prvKey->p), ret); // 1 < qInv < p.
GOTO_ERR_IF(BN_ModMul(pMinusOne, prvKey->dP, prvKey->e, pMinusOne, opt), ret); // (dP * e) mod (p - 1)
GOTO_ERR_IF(BN_ModMul(qMinusOne, prvKey->dQ, prvKey->e, qMinusOne, opt), ret); // (dQ * e) mod (q - 1)
GOTO_ERR_IF(BN_ModMul(one, prvKey->qInv, prvKey->q, prvKey->p, opt), ret); // (qInv * q) mod p
if (!BN_IsOne(pMinusOne) || !BN_IsOne(qMinusOne) || !BN_IsOne(one)) {
ret = CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE;
BSL_ERR_PUSH_ERROR(ret);
}
ERR:
OptimizerEnd(opt);
return ret;
}
static int32_t CheckLevel(const CRYPT_RSA_PrvKey *prvKey)
{
if (!BN_IsZero(prvKey->e) && !BN_IsZero(prvKey->dP) && !BN_IsZero(prvKey->dQ) && !BN_IsZero(prvKey->qInv)
&& !BN_IsZero(prvKey->p) && !BN_IsZero(prvKey->q)) {
return RSA_CHECK_CRT_CHECK; // check crt.
}
if (!BN_IsZero(prvKey->p) && !BN_IsZero(prvKey->q)) {
return RSA_CHECK_PQD_CHECK; // check prime p q.
}
return RSA_CHECK_PQ_RECOVER; // recover p q and check.
}
/*
* ref. SP800-56B 6.4.3.1 RSA Key-Pair Validation (Random Public Exponent)
*/
static int32_t RsaKeyPairCheck(const CRYPT_RSA_Ctx *pubKey, const CRYPT_RSA_Ctx *prvKey)
{
if (pubKey == NULL || prvKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (pubKey->pubKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_NO_PUBKEY_INFO);
return CRYPT_RSA_ERR_NO_PUBKEY_INFO;
}
if (prvKey->prvKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_NO_PRVKEY_INFO);
return CRYPT_RSA_ERR_NO_PRVKEY_INFO;
}
/* basic check */
int32_t ret = BasicKeypairCheck(pubKey->pubKey, prvKey->prvKey);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BN_Optimizer *opt = BN_OptimizerCreate();
if (opt == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
switch (CheckLevel(prvKey->prvKey)) {
case RSA_CHECK_PQ_RECOVER:
ret = RecoverPrimeFactorsAndCheck(pubKey, prvKey, opt);
break;
case RSA_CHECK_PQD_CHECK:
/* prime p q check */
ret = FactorPrimeCheck(pubKey->pubKey->n, pubKey->pubKey->e, prvKey->prvKey->p, prvKey->prvKey->q, opt);
if (ret != CRYPT_SUCCESS) {
goto ERR;
}
/* factor d check */
ret = FactorDCheck(pubKey->pubKey->n, pubKey->pubKey->e, prvKey->prvKey->p, prvKey->prvKey->q,
prvKey->prvKey->d, opt);
break;
default:
/* prime p q check */
ret = FactorPrimeCheck(pubKey->pubKey->n, pubKey->pubKey->e, prvKey->prvKey->p, prvKey->prvKey->q, opt);
if (ret != CRYPT_SUCCESS) {
goto ERR;
}
/* factor d check */
ret = FactorDCheck(pubKey->pubKey->n, pubKey->pubKey->e, prvKey->prvKey->p, prvKey->prvKey->q,
prvKey->prvKey->d, opt);
if (ret != CRYPT_SUCCESS) {
goto ERR;
}
ret = FactorCRTCheck(prvKey->prvKey, opt); /* factor crt check */
break;
}
ERR:
BN_OptimizerDestroy(opt);
return ret;
}
static int32_t RsaPrvKeyCheck(const CRYPT_RSA_Ctx *pkey)
{
if (pkey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (pkey->prvKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_NO_PRVKEY_INFO);
return CRYPT_RSA_ERR_NO_PRVKEY_INFO;
}
if (pkey->prvKey->n == NULL || pkey->prvKey->d == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_NO_PRVKEY_INFO);
return CRYPT_RSA_ERR_NO_PRVKEY_INFO;
}
if (BN_IsZero(pkey->prvKey->n) || BN_IsZero(pkey->prvKey->d)) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_INVALID_PRVKEY);
return CRYPT_RSA_ERR_INVALID_PRVKEY;
}
if (BN_Cmp(pkey->prvKey->n, pkey->prvKey->d) <= 0) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_INVALID_PRVKEY);
return CRYPT_RSA_ERR_INVALID_PRVKEY;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_RSA_Check(uint32_t checkType, const CRYPT_RSA_Ctx *pkey1, const CRYPT_RSA_Ctx *pkey2)
{
switch (checkType) {
case CRYPT_PKEY_CHECK_KEYPAIR:
return RsaKeyPairCheck(pkey1, pkey2);
case CRYPT_PKEY_CHECK_PRVKEY:
return RsaPrvKeyCheck(pkey1);
default:
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
}
#endif // HITLS_CRYPTO_RSA_CHECK
#endif // HITLS_CRYPTO_RSA
| 2302_82127028/openHiTLS-examples_1508 | crypto/rsa/src/rsa_keyop.c | C | unknown | 31,572 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef RSA_LOCAL_H
#define RSA_LOCAL_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_RSA
#include "crypt_rsa.h"
#include "crypt_bn.h"
#include "crypt_local_types.h"
#include "crypt_types.h"
#include "sal_atomic.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
#define HASH_MAX_MDSIZE (64)
#define PARAMISNULL(a) ((a) == NULL || (a)->value == NULL)
typedef struct RSA_BlindSt {
BN_BigNum *r;
BN_BigNum *rInv;
} RSA_Blind;
typedef struct {
BN_BigNum *n; // pub key n needed for no padding
BN_BigNum *d; // private key d needed for asn encoding
BN_BigNum *p; // prime factor p
BN_BigNum *q; // prime factor q
BN_BigNum *dP; // exponent dP for CRT
BN_BigNum *dQ; // exponent dQ for CRT
BN_BigNum *qInv; // CRT coefficient qInv
BN_BigNum *e; // public key e
} CRYPT_RSA_PrvKey;
typedef struct {
BN_BigNum *n; // modulo Value - converted.Not in char
BN_BigNum *e; // Exponent Value -converted.Not in char
// Montgomery pre-calculation cache
BN_Mont *mont;
} CRYPT_RSA_PubKey;
#ifdef HITLS_CRYPTO_ACVP_TESTS
typedef struct {
BN_BigNum *xp; // main seed for prime p
BN_BigNum *xp1; // auxiliary seed1 for prime p
BN_BigNum *xp2; // auxiliary seed2 for prime p
BN_BigNum *xq; // main seed for prime q
BN_BigNum *xq1; // auxiliary seed1 for prime q
BN_BigNum *xq2; // auxiliary seed2 for prime q
} RSA_FIPS_AUX_PRIME_SEEDS;
typedef struct {
union {
RSA_FIPS_AUX_PRIME_SEEDS fipsPrimeSeeds;
} primeSeed;
} RSA_ACVP_TESTS;
#endif
struct RSA_Para {
BN_BigNum *e; // Exponent Value -converted.Not in char
uint32_t bits; // length in bits of modulus
BN_BigNum *p; // prime factor p
BN_BigNum *q; // prime factor q
#ifdef HITLS_CRYPTO_ACVP_TESTS
RSA_ACVP_TESTS acvpTests;
#endif
};
#ifdef HITLS_CRYPTO_RSA_BSSA
typedef enum {
RSABSSA = 1, /**< RSA Blind Signature with Appendix, ref RFC9474 */
} RSA_BlindType;
typedef struct {
RSA_BlindType type; /**< padding id */
union {
RSA_Blind *bssa;
} para;
} RSA_BlindParam;
#endif
/**
* @ingroup crypt_eal_pkey
*
* (For internal use)Set the padding mode of the RSA. The value 0 indicates that the padding mode is not set.
*/
typedef enum {
EMSA_PKCSV15 = 1, /**< PKCS1-v1_5 complies with RFC8017 */
EMSA_PSS, /**< PSS complies with RFC8017 */
RSAES_OAEP, /**< OAEP complies with RFC8017 */
RSAES_PKCSV15, /**< RSAES_PKCSV15 complies with RFC8017 */
RSA_NO_PAD,
RSAES_PKCSV15_TLS, /* Specific RSA pkcs1.5 padding verification process
to prevent possible Bleichenbacher attacks */
} RSA_PadType;
/**
* @ingroup crypt_types
*
* Pkcsv15 padding mode, when RSA is used for signature.
*/
typedef struct {
CRYPT_MD_AlgId mdId; /**< ID of the hash algorithm during pkcsv15 padding */
} RSA_PkcsV15Para;
typedef struct {
RSA_PadType type; /**< padding id */
union {
RSA_PkcsV15Para pkcsv15; /**< pkcsv15 padding mode */
RSA_PadingPara pss; /**< pss padding mode */
RSA_PadingPara oaep; /**< oaep padding mode */
} para; /**< padding mode combination, including pss and pkcsv15 */
CRYPT_Data salt; // Used for the KAT test.
} RSAPad;
struct RSA_Ctx {
CRYPT_RSA_PrvKey *prvKey;
CRYPT_RSA_PubKey *pubKey;
CRYPT_RSA_Para *para;
#ifdef HITLS_CRYPTO_RSA_BLINDING
RSA_Blind *scBlind; // Preventing side channel attacks
#endif
RSAPad pad;
uint32_t flags;
CRYPT_Data label; // Used for oaep padding
BSL_SAL_RefCount references;
#ifdef HITLS_CRYPTO_RSA_BSSA
RSA_BlindParam *blindParam;
#endif
void *libCtx;
char *mdAttr;
};
#define LIBCTX_FROM_RSA_CTX(ctx) ((ctx) == NULL ? NULL : (ctx)->libCtx)
#define MDATTR_FROM_RSA_CTX(ctx) ((ctx) == NULL ? NULL : (ctx)->mdAttr)
CRYPT_RSA_PrvKey *RSA_NewPrvKey(uint32_t bits);
CRYPT_RSA_PubKey *RSA_NewPubKey(uint32_t bits);
void RSA_FreePrvKey(CRYPT_RSA_PrvKey *prvKey);
void RSA_FreePubKey(CRYPT_RSA_PubKey *pubKey);
int32_t RSA_CalcPrvKey(const CRYPT_RSA_Para *para, CRYPT_RSA_Ctx *ctx, BN_Optimizer *optimizer);
void ShallowCopyCtx(CRYPT_RSA_Ctx *ctx, CRYPT_RSA_Ctx *newCtx);
CRYPT_RSA_Para *CRYPT_RSA_DupPara(const CRYPT_RSA_Para *para);
#ifdef HITLS_CRYPTO_RSA_EMSA_PKCSV15
int32_t CRYPT_RSA_UnPackPkcsV15Type1(uint8_t *data, uint32_t dataLen, uint8_t *out, uint32_t *outLen);
#endif
#if defined(HITLS_CRYPTO_RSA_BLINDING) || defined(HITLS_CRYPTO_RSA_BSSA)
/**
* @ingroup rsa
* @brief Create a blinding handle.
*
* @retval Return the blinding handle.
*/
RSA_Blind *RSA_BlindNewCtx(void);
/**
* @ingroup rsa
* @brief Release the blinding handle.
*
* @param b [IN] blinding Handle. b is set NULL by the invoker.
*
* @retval none
*/
void RSA_BlindFreeCtx(RSA_Blind *b);
/**
* @ingroup rsa
* @brief Multiply n by blinding factor A
*
* @param b [IN] Blinding Handle
* @param data [IN] Input data
* @param n [IN] n in the public key (n, e)
* @param opt [IN] BigNum optimizer
*
* @retval Return the error code.
*/
int32_t RSA_BlindCovert(RSA_Blind *b, BN_BigNum *data, BN_BigNum *n, BN_Optimizer *opt);
/**
* @ingroup rsa
* @brief Multiply n by the reverse blinding factor Ai
*
* @param b [IN] Blinding Handle
* @param data [IN] Input data
* @param n [IN] n in the public key (n, e)
* @param opt [IN] BigNum optimizer
*
* @retval Return the error code.
*/
int32_t RSA_BlindInvert(RSA_Blind *b, BN_BigNum *data, BN_BigNum *n, BN_Optimizer *opt);
/**
* @ingroup rsa
* @brief Create a new Blind parameter with the parameters e and m,
* e in the public key (n, e), n in the public key (n, e)
*
* @param libCtx [IN] libctx
* @param b [IN] Blinding Handle
* @param e [IN] e in the public key (n, e)
* @param n [IN] n in the public key (n, e)
* @param bits [IN] bits of n
*
* @retval Return the error code.
*/
int32_t RSA_BlindCreateParam(void *libCtx, RSA_Blind *b, BN_BigNum *e, BN_BigNum *n, uint32_t bits, BN_Optimizer *opt);
int32_t RSA_CreateBlind(RSA_Blind *b, uint32_t bits);
#endif
#define RSA_FREE_PRV_KEY(prvKey_) \
do { \
RSA_FreePrvKey((prvKey_)); \
(prvKey_) = NULL; \
} while (0)
#define RSA_FREE_PUB_KEY(pubKey_) \
do { \
RSA_FreePubKey((pubKey_)); \
(pubKey_) = NULL; \
} while (0)
#define RSA_FREE_PARA(para_) \
do { \
CRYPT_RSA_FreePara((para_)); \
(para_) = NULL; \
} while (0)
#ifdef __cplusplus
}
#endif
#endif // HITLS_CRYPTO_RSA
#endif | 2302_82127028/openHiTLS-examples_1508 | crypto/rsa/src/rsa_local.h | C | unknown | 7,366 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_RSA
#include "crypt_rsa.h"
#include "rsa_local.h"
#include "crypt_errno.h"
#include "crypt_types.h"
#include "crypt_utils.h"
#include "crypt_util_rand.h"
#include "securec.h"
#include "bsl_sal.h"
#include "bsl_bytes.h"
#include "bsl_err_internal.h"
#define UINT32_SIZE 4
#ifdef HITLS_CRYPTO_RSA_EMSA_PSS
// maskedDB: [in] maskDB from MGF
// [out] maskedDB = DB xor maskDB
// DB: PS || 0x01 || salt;
// msBit: indicates the number of valid bits in the most significant bytes of the EM,
// value 0 indicates that all bits are valid.
static void MaskDB(uint8_t *maskedDB, uint32_t len, const uint8_t *salt, uint32_t saltLen, uint32_t msBit)
{
uint8_t *tmp = maskedDB + (len - saltLen) - 1; // init point to pos of 0x01
*tmp ^= 0x01;
tmp++;
uint32_t i;
for (i = 0; i < saltLen; i++) {
tmp[i] ^= salt[i];
}
if (msBit != 0) {
// Set the leftmost 8emLen - emBits bits of the leftmost octet in maskedDB to zero
maskedDB[0] &= ((uint8_t)(0xFF >> (8 - msBit)));
}
}
static int32_t PssEncodeLengthCheck(uint32_t modBits, uint32_t hLen,
uint32_t saltLen, uint32_t dataLen, uint32_t padLen)
{
if (modBits < RSA_MIN_MODULUS_BITS || modBits > RSA_MAX_MODULUS_BITS) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_KEY_BITS);
return CRYPT_RSA_ERR_KEY_BITS;
}
if (hLen > RSA_MAX_MODULUS_LEN || dataLen != hLen) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_INPUT_VALUE);
return CRYPT_RSA_ERR_INPUT_VALUE;
}
uint32_t keyBytes = BN_BITS_TO_BYTES(modBits);
if (keyBytes != padLen) { // The length required for padding does not match the key module length (API convention).
BSL_ERR_PUSH_ERROR(CRYPT_RSA_BUFF_LEN_NOT_ENOUGH);
return CRYPT_RSA_BUFF_LEN_NOT_ENOUGH;
}
if (saltLen == (uint32_t)CRYPT_RSA_SALTLEN_TYPE_AUTOLEN) {
return CRYPT_SUCCESS;
}
if (saltLen > RSA_MAX_MODULUS_LEN) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_PSS_SALT_LEN);
return CRYPT_RSA_ERR_PSS_SALT_LEN;
}
uint32_t emLen = keyBytes;
// the octet length of EM will be one less than k if modBits - 1 is divisible by 8 and equal to k otherwise
if (((modBits - 1) & 0x7) == 0) {
emLen--;
}
if (emLen < hLen + saltLen + 2) { // RFC: If emLen < hLen + sLen + 2, output "encoding error" and stop.
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_PSS_SALT_LEN);
return CRYPT_RSA_ERR_PSS_SALT_LEN;
}
return CRYPT_SUCCESS;
}
#if defined(HITLS_CRYPTO_RSA_SIGN) || defined(HITLS_CRYPTO_RSA_BSSA)
static int32_t GenPssSalt(void *libCtx, CRYPT_Data *salt,
const EAL_MdMethod *mdMethod, int32_t saltLen, uint32_t padBuffLen)
{
uint32_t hashLen = mdMethod->mdSize;
if (saltLen == CRYPT_RSA_SALTLEN_TYPE_HASHLEN) { // saltLen is -1
salt->len = hashLen;
} else if (saltLen == CRYPT_RSA_SALTLEN_TYPE_MAXLEN ||
saltLen == CRYPT_RSA_SALTLEN_TYPE_AUTOLEN) { // saltLen is -2 or -3
salt->len = padBuffLen - hashLen - 2; // salt, obtains from the DRBG
} else {
salt->len = (uint32_t)saltLen;
}
salt->data = BSL_SAL_Malloc(salt->len);
if (salt->data == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
// Obtain the salt through the public random number.
int32_t ret = CRYPT_RandEx(libCtx, salt->data, salt->len);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_FREE(salt->data);
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
/**
* EMSA-PSS Encoding Operation
* +-----------+
* | M |
* +-----------+
* |
* V
* Hash
* |
* V
* +--------+----------+----------+
* M' = |Padding1| mHash | salt |
* +--------+----------+----------+
* |
* +--------+----------+ V
* DB = |Padding2| salt | Hash
* +--------+----------+ |
* | |
* V |
* xor <--- MGF <---| maskDB = MGF(H, emLen - hLen - 1).
* | |
* | |
* V V
* +-------------------+----------+--+
* EM = | maskedDB | H |bc|
* +-------------------+----------+--+
* Output EM data with a fixed length (keyBytes) to the pad buffer.
* Add 0s to the first byte, if the EM length + 1 = keyBytes.
* Of which:
* The data is the mHash in the preceding figure.
* M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt
* DB = PS || 0x01 || salt; DB is an octet string of length emLen - hLen - 1
* PS consisting of emLen - sLen - hLen - 2 zero octets, The length of PS may be 0.
*/
int32_t CRYPT_RSA_SetPss(CRYPT_RSA_Ctx *ctx, const EAL_MdMethod *hashMethod, const EAL_MdMethod *mgfMethod,
uint32_t saltLen, const uint8_t *data, uint32_t dataLen, uint8_t *pad, uint32_t padLen)
{
int32_t ret;
if (ctx == NULL || hashMethod == NULL || mgfMethod == NULL || pad == NULL || data == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_Data salt = {0};
bool kat = false; // mark
if (ctx->pad.salt.data != NULL) {
kat = true;
salt.data = ctx->pad.salt.data;
salt.len = ctx->pad.salt.len;
ctx->pad.salt.data = NULL;
ctx->pad.salt.len = 0;
} else if (saltLen != 0) {
// Generate a salt information to the salt.
ret = GenPssSalt(LIBCTX_FROM_RSA_CTX(ctx), &salt, hashMethod, (int32_t)saltLen, padLen);
RETURN_RET_IF((ret != CRYPT_SUCCESS), CRYPT_RSA_ERR_GEN_SALT);
}
RETURN_RET_IF((salt.data == NULL && salt.len != 0), CRYPT_RSA_ERR_PSS_SALT_DATA);
uint32_t keyBits = CRYPT_RSA_GetBits(ctx);
uint32_t hLen = hashMethod->mdSize;
ret = PssEncodeLengthCheck(keyBits, hLen, salt.len, dataLen, padLen);
if (ret != CRYPT_SUCCESS) {
if ((kat != true) && (saltLen != 0)) {
BSL_SAL_ClearFree(salt.data, salt.len);
}
return ret;
}
uint8_t *em = pad;
uint32_t emLen = BN_BITS_TO_BYTES(keyBits);
// the octet length of EM will be one less than k if modBits - 1 is divisible by 8 and equal to k otherwise
uint32_t msBit = ((keyBits - 1) & 0x7);
if (msBit == 0) {
emLen--;
*em = 0;
em++;
}
em[emLen - 1] = 0xbc; // EM = maskedDB || H || 0xbc.
// set H
static const uint8_t zeros8[8] = {0};
const CRYPT_ConstData hashData[] = {{zeros8, sizeof(zeros8)}, {data, dataLen}, {salt.data, salt.len}};
const uint32_t maskedDBLen = emLen - hLen - 1;
uint8_t *h = em + maskedDBLen;
GOTO_ERR_IF(CRYPT_CalcHash(ctx->pad.para.pss.mdProvCtx, hashMethod, hashData,
sizeof(hashData) / sizeof(hashData[0]), h, &hLen), ret);
// set maskedDB
GOTO_ERR_IF(CRYPT_Mgf1(ctx->pad.para.pss.mgfProvCtx, mgfMethod, h, hLen, em, maskedDBLen), ret);
MaskDB(em, maskedDBLen, salt.data, salt.len, msBit);
ERR:
if ((kat != true) && (saltLen != 0)) {
BSL_SAL_ClearFree(salt.data, salt.len);
}
return ret;
}
#endif // HITLS_CRYPTO_RSA_SIGN || HITLS_CRYPTO_RSA_BSSA
#ifdef HITLS_CRYPTO_RSA_VERIFY
static int32_t GetVerifySaltLen(const uint8_t *emData, const uint8_t *dbBuff, uint32_t maskedDBLen, uint32_t msBit,
uint32_t *saltLen)
{
uint32_t i = 0;
uint8_t *tmpBuff = (uint8_t *)BSL_SAL_Malloc(maskedDBLen);
if (tmpBuff == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
(void)memcpy_s(tmpBuff, maskedDBLen, dbBuff, maskedDBLen);
if (msBit != 0) {
tmpBuff[0] &= ((uint8_t)(0xFF >> (8 - msBit))); // Set the leftmost 8emLen - emBits bits to zero
}
for (i = 0; i < maskedDBLen; i++) {
tmpBuff[i] ^= emData[i];
if (tmpBuff[i] != 0) {
break;
}
}
if (i == maskedDBLen || tmpBuff[i] != 0x01) {
BSL_SAL_FREE(tmpBuff);
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_PSS_SALT_LEN);
return CRYPT_RSA_ERR_PSS_SALT_LEN;
}
i++;
BSL_SAL_FREE(tmpBuff);
*saltLen = maskedDBLen - i;
return CRYPT_SUCCESS;
}
static int32_t GetAndVerifyDB(void *provCtx, const EAL_MdMethod *mgfMethod, const CRYPT_Data *emData,
const CRYPT_Data *dbBuff, uint32_t *saltLen, uint32_t msBit)
{
uint32_t maskedDBLen = dbBuff->len;
uint32_t hLen = emData->len - maskedDBLen - 1;
uint32_t tmpSaltLen = *saltLen;
const uint8_t *h = emData->data + maskedDBLen;
int32_t ret = CRYPT_Mgf1(provCtx, mgfMethod, h, hLen, dbBuff->data, dbBuff->len);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (tmpSaltLen == (uint32_t)CRYPT_RSA_SALTLEN_TYPE_AUTOLEN) {
ret = GetVerifySaltLen(emData->data, dbBuff->data, maskedDBLen, msBit, &tmpSaltLen);
if (ret != CRYPT_SUCCESS) {
return ret;
}
}
// A ^ B == C => A ^ C == B
MaskDB(dbBuff->data, dbBuff->len, h - tmpSaltLen, tmpSaltLen, msBit);
if (memcmp(dbBuff->data, emData->data, maskedDBLen - tmpSaltLen) != 0) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_NOR_VERIFY_FAIL);
return CRYPT_RSA_NOR_VERIFY_FAIL;
}
*saltLen = tmpSaltLen;
return CRYPT_SUCCESS;
}
static int32_t VerifyH(void *provCtx, const EAL_MdMethod *hashMethod, const CRYPT_Data *mHash, const CRYPT_Data *salt,
const CRYPT_Data *h, const CRYPT_Data *hBuff)
{
static const uint8_t zeros8[8] = {0};
const CRYPT_ConstData hashData[] = {
{zeros8, sizeof(zeros8)},
{mHash->data, mHash->len},
{salt->data, salt->len}
};
uint32_t hLen = hBuff->len;
int32_t ret = CRYPT_CalcHash(provCtx, hashMethod, hashData, sizeof(hashData) / sizeof(hashData[0]), hBuff->data, &hLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (memcmp(h->data, hBuff->data, hLen) != 0) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_NOR_VERIFY_FAIL);
return CRYPT_RSA_NOR_VERIFY_FAIL;
}
return CRYPT_SUCCESS;
}
// Reverse verification process of EMSA-PSS Encoding Operation:
// MGF(H,maskedDBLen) ^ MaskedDB => DB' (PS||0x01||salt'), H' = Hash(padding1 || mHash || salt') == H ?
int32_t CRYPT_RSA_VerifyPss(CRYPT_RSA_Ctx *ctx, const EAL_MdMethod *hashMethod, const EAL_MdMethod *mgfMethod,
uint32_t saltLen, const uint8_t *data, uint32_t dataLen, const uint8_t *pad, uint32_t padLen)
{
if (ctx == NULL || hashMethod == NULL || mgfMethod == NULL || pad == NULL || data == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret;
uint32_t keyBits = CRYPT_RSA_GetBits(ctx);
uint32_t hLen = hashMethod->mdSize;
uint32_t saltLength = saltLen;
if (saltLength == (uint32_t)CRYPT_RSA_SALTLEN_TYPE_HASHLEN) { // saltLength is -1
saltLength = (uint32_t)ctx->pad.para.pss.mdMeth.mdSize;
} else if (saltLength == (uint32_t)CRYPT_RSA_SALTLEN_TYPE_MAXLEN) { // saltLength is -2
saltLength = (uint32_t)(padLen - ctx->pad.para.pss.mdMeth.mdSize - 2); // salt, obtains DRBG
}
RETURN_RET_IF_ERR(PssEncodeLengthCheck(keyBits, hLen, saltLength, dataLen, padLen), ret);
// EM = maskedDB || H || 0xbc
RETURN_RET_IF((pad[padLen - 1] != 0xbc), CRYPT_RSA_NOR_VERIFY_FAIL);
const uint8_t *em = pad;
uint32_t emLen = BN_BITS_TO_BYTES(keyBits);
// the octet length of EM will be one less than k if modBits - 1 is divisible by 8 and equal to k otherwise
uint32_t msBit = ((keyBits - 1) & 0x7);
if (msBit == 0) {
emLen--;
em++;
}
// if msBit == 0, 8emLen == emBits, pad[0] should be 0
// the leftmost 8emLen - emBits bits of the leftmost octet in maskedDB should be 0
RETURN_RET_IF(((pad[0] >> msBit) != 0), CRYPT_RSA_NOR_VERIFY_FAIL);
uint8_t *tmpBuff = BSL_SAL_Malloc(emLen); // for maskDB' / DB' and H'
RETURN_RET_IF((tmpBuff == NULL), CRYPT_MEM_ALLOC_FAIL);
const uint32_t maskedDBLen = emLen - hLen - 1;
const CRYPT_Data dbBuff = {tmpBuff, maskedDBLen};
const CRYPT_Data emData = {(uint8_t *)(uintptr_t)em, emLen};
const CRYPT_Data mHash = {(uint8_t *)(uintptr_t)data, dataLen};
const CRYPT_Data h = {(uint8_t *)(uintptr_t)&em[maskedDBLen], hLen};
const CRYPT_Data hBuff = {&tmpBuff[maskedDBLen], hLen};
ret = GetAndVerifyDB(ctx->pad.para.pss.mgfProvCtx, mgfMethod, &emData, &dbBuff, &saltLength, msBit);
if (ret != CRYPT_SUCCESS) {
(void)memset_s(tmpBuff, emLen, 0, emLen);
BSL_SAL_FREE(tmpBuff);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
const CRYPT_Data salt = {&tmpBuff[maskedDBLen - saltLength], saltLength};
ret = VerifyH(ctx->pad.para.pss.mdProvCtx, hashMethod, &mHash, &salt, &h, &hBuff);
(void)memset_s(tmpBuff, emLen, 0, emLen);
BSL_SAL_FREE(tmpBuff);
return ret;
}
#endif // HITLS_CRYPTO_RSA_VERIFY
#endif // HITLS_CRYPTO_RSA_EMSA_PSS
#ifdef HITLS_CRYPTO_RSA_EMSA_PKCSV15
static int32_t PkcsSetLengthCheck(uint32_t emLen, uint32_t hashLen, uint32_t algIdentLen)
{
if (emLen > RSA_MAX_MODULUS_LEN || hashLen > RSA_MAX_MODULUS_LEN) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_INPUT_VALUE);
return CRYPT_RSA_ERR_INPUT_VALUE;
}
if (hashLen == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_INPUT_VALUE);
return CRYPT_RSA_ERR_INPUT_VALUE;
}
/* The length of the pad must exceed 11 bytes at least. tLen = hashLen + algIdentLen */
if (emLen < hashLen + algIdentLen + 11) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_BUFF_LEN_NOT_ENOUGH);
return CRYPT_RSA_BUFF_LEN_NOT_ENOUGH;
}
return CRYPT_SUCCESS;
}
static int32_t PkcsGetIdentifier(CRYPT_MD_AlgId hashId, CRYPT_Data *algIdentifier)
{
static uint8_t sha1TInfo[] = {0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05,
0x00, 0x04, 0x14};
static uint8_t sha224TInfo[] = {0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1c};
static uint8_t sha256TInfo[] = {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20};
static uint8_t sha384TInfo[] = {0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30};
static uint8_t sha512TInfo[] = {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40};
static uint8_t md5TInfo[] = {0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
0x02, 0x05, 0x05, 0x00, 0x04, 0x10};
static uint8_t sm3TInfo[] = {0x30, 0x30, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x81, 0x1c, 0xcf, 0x55, 0x01,
0x83, 0x11, 0x05, 0x00, 0x04, 0x20};
algIdentifier->data = NULL;
algIdentifier->len = 0;
if (hashId == CRYPT_MD_SHA1) {
algIdentifier->data = (uint8_t *)sha1TInfo;
algIdentifier->len = sizeof(sha1TInfo);
} else if (hashId == CRYPT_MD_SHA224) {
algIdentifier->data = (uint8_t *)sha224TInfo;
algIdentifier->len = sizeof(sha224TInfo);
} else if (hashId == CRYPT_MD_SHA256) {
algIdentifier->data = (uint8_t *)sha256TInfo;
algIdentifier->len = sizeof(sha256TInfo);
} else if (hashId == CRYPT_MD_SHA384) {
algIdentifier->data = (uint8_t *)sha384TInfo;
algIdentifier->len = sizeof(sha384TInfo);
} else if (hashId == CRYPT_MD_SHA512) {
algIdentifier->data = (uint8_t *)sha512TInfo;
algIdentifier->len = sizeof(sha512TInfo);
} else if (hashId == CRYPT_MD_MD5) {
algIdentifier->data = (uint8_t *)md5TInfo;
algIdentifier->len = sizeof(md5TInfo);
} else if (hashId == CRYPT_MD_SM3) {
algIdentifier->data = (uint8_t *)sm3TInfo;
algIdentifier->len = sizeof(sm3TInfo);
} else {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_MD_ALGID);
return CRYPT_RSA_ERR_MD_ALGID;
}
return CRYPT_SUCCESS;
}
// Pad output format:EM = 00 || 01 || PS || 00 || T; where T = algIdentifier || hash(M);
// hash(M) is the input parameter data of this function.
int32_t CRYPT_RSA_SetPkcsV15Type1(CRYPT_MD_AlgId hashId, const uint8_t *data, uint32_t dataLen,
uint8_t *pad, uint32_t padLen)
{
int32_t ret;
uint32_t padSize;
uint8_t *tmp = pad;
uint32_t tmpLen = padLen;
if (pad == NULL || data == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_Data algIdentifier = {NULL, 0};
ret = PkcsGetIdentifier(hashId, &algIdentifier);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = PkcsSetLengthCheck(padLen, dataLen, algIdentifier.len);
if (ret != CRYPT_SUCCESS) {
return ret;
}
// Considering that the data space and pad space may overlap,
// move the data to the specified position(the end of the pad).
if (memmove_s(pad + (padLen - dataLen), dataLen, data, dataLen) != EOK) {
BSL_ERR_PUSH_ERROR(CRYPT_SECUREC_FAIL);
return CRYPT_SECUREC_FAIL;
}
*tmp = 0x0;
tmp++;
*tmp = 0x1;
tmp++;
tmpLen -= 2; // Skip the first 2 bytes.
// PS length: padSize = padLen - dataLen - algIdentifier.len - 3
padSize = padLen - dataLen - algIdentifier.len - 3;
if (memset_s(tmp, tmpLen, 0xff, padSize) != EOK) { // 0xff padded in PS
BSL_ERR_PUSH_ERROR(CRYPT_SECUREC_FAIL);
return CRYPT_SECUREC_FAIL;
}
tmp += padSize;
tmpLen -= padSize;
*tmp = 0x0;
tmp++;
tmpLen--;
if ((algIdentifier.len > 0) && memcpy_s(tmp, tmpLen, algIdentifier.data, algIdentifier.len) != EOK) {
// padding when identifier exit
BSL_ERR_PUSH_ERROR(CRYPT_SECUREC_FAIL);
return CRYPT_SECUREC_FAIL;
}
return CRYPT_SUCCESS;
}
#ifdef HITLS_CRYPTO_RSA_VERIFY
int32_t CRYPT_RSA_VerifyPkcsV15Type1(CRYPT_MD_AlgId hashId, const uint8_t *pad, uint32_t padLen,
const uint8_t *data, uint32_t dataLen)
{
if (pad == NULL || data == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (padLen == 0 || dataLen == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_INPUT_VALUE);
return CRYPT_RSA_ERR_INPUT_VALUE;
}
uint8_t *padBuff = BSL_SAL_Malloc(padLen);
if (padBuff == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
int32_t ret = CRYPT_RSA_SetPkcsV15Type1(hashId, data, dataLen, padBuff, padLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
BSL_SAL_FREE(padBuff);
return ret;
}
if (memcmp(pad, padBuff, padLen) != 0) {
BSL_SAL_FREE(padBuff);
BSL_ERR_PUSH_ERROR(CRYPT_RSA_NOR_VERIFY_FAIL);
return CRYPT_RSA_NOR_VERIFY_FAIL;
}
BSL_SAL_FREE(padBuff);
return CRYPT_SUCCESS;
}
#endif // HITLS_CRYPTO_RSA_VERIFY
int32_t CRYPT_RSA_UnPackPkcsV15Type1(uint8_t *data, uint32_t dataLen, uint8_t *out, uint32_t *outLen)
{
uint8_t *index = data;
uint32_t tmpLen = dataLen;
// Format of the data to be decrypted is EB = 00 || 01 || PS || 00 || T.
// The PS padding is at least 8. Therefore, the length of the data to be decrypted is at least 11.
if (dataLen < 11) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_BUFF_LEN_NOT_ENOUGH);
return CRYPT_RSA_BUFF_LEN_NOT_ENOUGH;
}
if (*index != 0x0 || *(index + 1) != 0x01) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_INPUT_VALUE);
return CRYPT_RSA_ERR_INPUT_VALUE;
}
index += 2; // Skip first 2 bytes.
tmpLen -= 2; // Skip first 2 bytes.
uint32_t padNum = 0;
while (*index == 0xff) {
index++;
tmpLen--;
padNum++;
}
if (padNum < 8) { // The PS padding is at least 8.
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_PAD_NUM);
return CRYPT_RSA_ERR_PAD_NUM;
}
if (tmpLen == 0 || *index != 0x0) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_INPUT_VALUE);
return CRYPT_RSA_ERR_INPUT_VALUE;
}
index++;
tmpLen--;
if (memcpy_s(out, *outLen, index, tmpLen) != EOK) {
BSL_ERR_PUSH_ERROR(CRYPT_SECUREC_FAIL);
return CRYPT_SECUREC_FAIL;
}
*outLen = tmpLen;
return CRYPT_SUCCESS;
}
#endif // HITLS_CRYPTO_RSA_EMSA_PKCSV15
#ifdef HITLS_CRYPTO_RSAES_OAEP
#ifdef HITLS_CRYPTO_RSA_ENCRYPT
static int32_t OaepSetLengthCheck(uint32_t outLen, uint32_t inLen, uint32_t hashLen)
{
if (outLen > RSA_MAX_MODULUS_LEN || inLen > RSA_MAX_MODULUS_LEN || hashLen > HASH_MAX_MDSIZE) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_INPUT_VALUE);
return CRYPT_RSA_ERR_INPUT_VALUE;
}
if (outLen == 0 || hashLen == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_INPUT_VALUE);
return CRYPT_RSA_ERR_INPUT_VALUE;
}
// If mLen > k - 2hLen - 2, output "message too long" and stop.
if (inLen + 2 * hashLen + 2 > outLen) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_ENC_BITS);
return CRYPT_RSA_ERR_ENC_BITS;
}
return CRYPT_SUCCESS;
}
static int32_t OaepSetPs(const uint8_t *in, uint32_t inLen, uint8_t *db, uint32_t padLen, uint32_t hashLen)
{
uint8_t *ps = db + hashLen;
// Generate a padding string PS consisting of k - mLen - 2hLen - 2 zero octets. The length of PS may be zero
// This operation cannot be reversed because the OaepSetLengthCheck has checked the validity of the data.
uint32_t psLen = padLen - inLen - 2 * hashLen - 2;
// padding 0x00
(void)memset_s(ps, psLen, 0, psLen);
ps += psLen;
*ps = 0x01;
ps++;
/**
* padLen minus twice hashLen, then subtract 2 bytes of fixed data, and subtract the padding length.
* The remaining length is the plaintext length.
*/
if (inLen != 0 && memcpy_s(ps, padLen - 2 * hashLen - 2 - psLen, in, inLen) != EOK) {
BSL_ERR_PUSH_ERROR(CRYPT_SECUREC_FAIL);
return CRYPT_SECUREC_FAIL;
}
return CRYPT_SUCCESS;
}
static int32_t OaepSetMaskedDB(void *provCtx, const EAL_MdMethod *mgfMethod, uint8_t *db, uint8_t *seed, uint32_t padLen,
uint32_t hashLen)
{
int32_t ret;
uint32_t i;
uint32_t maskedDBLen = padLen - hashLen - 1;
uint8_t *maskedDB = (uint8_t *)BSL_SAL_Malloc(maskedDBLen);
if (maskedDB == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
ret = CRYPT_Mgf1(provCtx, mgfMethod, seed, hashLen, maskedDB, maskedDBLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
for (i = 0; i < maskedDBLen; i++) {
db[i] ^= maskedDB[i];
}
EXIT:
BSL_SAL_CleanseData(maskedDB, maskedDBLen);
BSL_SAL_FREE(maskedDB);
return ret;
}
static int32_t OaepSetSeedMask(void *provCtx, const EAL_MdMethod *mgfMethod, uint8_t *db, uint8_t *seed, uint32_t padLen,
uint32_t hashLen)
{
uint32_t i;
int32_t ret;
uint8_t seedmask[HASH_MAX_MDSIZE];
uint32_t maskedDBLen = padLen - hashLen - 1;
ret = CRYPT_Mgf1(provCtx, mgfMethod, db, maskedDBLen, seedmask, hashLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
for (i = 0; i < hashLen; i++) {
seed[i] ^= seedmask[i];
}
EXIT:
BSL_SAL_CleanseData(seedmask, hashLen);
return ret;
}
/**
* _________________________________________________________________
*
* +----------+------+--+-------+
* DB = | lHash | PS |01| M |
* +----------+------+--+-------+
* |
* +----------+ |
* | seed | |
* +----------+ |
* | |
* |-------> MGF ---> xor
* | |
* +--+ V |
* |00| xor <----- MGF <-----|
* +--+ | |
* | | |
* V V V
* +--+----------+----------------------------+
* EM = |00|maskedSeed| maskedDB |
* +--+----------+----------------------------+
* _________________________________________________________________
*
* Figure 1: EME-OAEP Encoding Operation <rfc8017>
*/
int32_t CRYPT_RSA_SetPkcs1Oaep(CRYPT_RSA_Ctx *ctx, const uint8_t *in, uint32_t inLen, uint8_t *pad, uint32_t padLen)
{
int32_t ret;
const EAL_MdMethod *hashMethod = &ctx->pad.para.oaep.mdMeth;
const EAL_MdMethod *mgfMethod = &ctx->pad.para.oaep.mgfMeth;
if ((in == NULL && inLen != 0) || pad == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
uint32_t hashLen = hashMethod->mdSize;
/* If mLen > k - 2hLen - 2, output "message too long" and stop<rfc8017>
k is output len, hLen is hashLen, mLen is inLen
*/
ret = OaepSetLengthCheck(padLen, inLen, hashLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
*pad = 0x00;
uint8_t *seed = pad + 1;
// Generate a random octet string seed of length hLen<rfc8017>
ret = CRYPT_RandEx(LIBCTX_FROM_RSA_CTX(ctx), seed, hashLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
uint8_t *db = seed + hashLen;
// Calculate hash
const CRYPT_ConstData data = {ctx->label.data, ctx->label.len};
ret = CRYPT_CalcHash(ctx->pad.para.oaep.mdProvCtx, hashMethod, &data, 1, db, &hashLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = OaepSetPs(in, inLen, db, padLen, hashLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// set maskedDB
ret = OaepSetMaskedDB(ctx->pad.para.oaep.mgfProvCtx, mgfMethod, db, seed, padLen, hashLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// set seedmask
ret = OaepSetSeedMask(ctx->pad.para.oaep.mgfProvCtx, mgfMethod, db, seed, padLen, hashLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
#endif // HITLS_CRYPTO_RSA_ENCRYPT
#ifdef HITLS_CRYPTO_RSA_DECRYPT
static int32_t OaepVerifyLengthCheck(uint32_t outLen, uint32_t inLen, uint32_t hashLen)
{
if (outLen > RSA_MAX_MODULUS_LEN || inLen > RSA_MAX_MODULUS_LEN || hashLen > HASH_MAX_MDSIZE) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_INPUT_VALUE);
return CRYPT_RSA_ERR_INPUT_VALUE;
}
if (outLen == 0 || hashLen == 0 || inLen == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_INPUT_VALUE);
return CRYPT_RSA_ERR_INPUT_VALUE;
}
// If k < 2hLen + 2, output "decryption error" and stop
if (inLen < 2 * hashLen + 2) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_BUFF_LEN_NOT_ENOUGH);
return CRYPT_RSA_BUFF_LEN_NOT_ENOUGH;
}
return CRYPT_SUCCESS;
}
static int32_t OaepDecodeSeedMask(void *provCtx, const EAL_MdMethod *mgfMethod, const uint8_t *in, uint32_t inLen,
CRYPT_Data *seedMask, uint32_t hashLen)
{
uint32_t i;
int32_t ret;
const uint8_t *maskedSeed = in + 1;
uint32_t maskedDBLen = inLen - hashLen - 1;
const uint8_t *maskedDB = maskedSeed + hashLen;
ret = CRYPT_Mgf1(provCtx, mgfMethod, maskedDB, maskedDBLen, seedMask->data, hashLen);
if (ret != CRYPT_SUCCESS) {
return ret;
}
for (i = 0; i < hashLen; i++) {
seedMask->data[i] ^= maskedSeed[i];
}
return CRYPT_SUCCESS;
}
static int32_t OaepDecodeMaskedDB(void *provCtx, const EAL_MdMethod *mgfMethod, const CRYPT_Data *in, const uint8_t *seedMask,
uint32_t hashLen, const CRYPT_Data *dbMaskData)
{
int32_t ret;
uint32_t i;
const uint8_t *maskedDB = in->data + 1 + hashLen;
uint32_t maskedDBLen = in->len - hashLen - 1;
ret = CRYPT_Mgf1(provCtx, mgfMethod, seedMask, hashLen, dbMaskData->data, maskedDBLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
for (i = 0; i < maskedDBLen; i++) {
dbMaskData->data[i] ^= maskedDB[i];
}
return ret;
}
static int32_t OaepVerifyHashMaskDB(void *provCtx, const EAL_MdMethod *hashMethod, CRYPT_Data *paramData, CRYPT_Data *dbMaskData,
uint32_t hashLen, uint32_t *offset)
{
int32_t ret;
uint8_t hashVal[HASH_MAX_MDSIZE];
CRYPT_ConstData data = {paramData->data, paramData->len};
ret = CRYPT_CalcHash(provCtx, hashMethod, &data, 1, hashVal, &hashLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (memcmp(dbMaskData->data, hashVal, hashLen) != 0) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_NOR_VERIFY_FAIL);
return CRYPT_RSA_NOR_VERIFY_FAIL;
}
*offset = hashLen;
while ((*offset) < dbMaskData->len && dbMaskData->data[(*offset)] == 0) {
(*offset)++;
}
if ((*offset) >= dbMaskData->len) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_NOR_VERIFY_FAIL);
return CRYPT_RSA_NOR_VERIFY_FAIL;
}
if (dbMaskData->data[(*offset)] != 0x01) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_NOR_VERIFY_FAIL);
return CRYPT_RSA_NOR_VERIFY_FAIL;
}
(*offset)++;
return ret;
}
int32_t CRYPT_RSA_VerifyPkcs1Oaep(RSA_PadingPara *pad, const uint8_t *in, uint32_t inLen, const uint8_t *param,
uint32_t paramLen, uint8_t *msg, uint32_t *msgLen)
{
if (pad == NULL || in == NULL || msg == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
uint32_t hashLen = pad->mdMeth.mdSize;
if (inLen <= (hashLen + 1)) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_INPUT_VALUE);
return CRYPT_RSA_ERR_INPUT_VALUE;
}
uint32_t maskedDBLen = inLen - hashLen - 1;
int32_t ret;
uint32_t offset;
uint8_t seedMask[HASH_MAX_MDSIZE];
CRYPT_Data seedData = { (uint8_t *)(uintptr_t)seedMask, HASH_MAX_MDSIZE };
CRYPT_Data paramData = { (uint8_t *)(uintptr_t)param, paramLen };
CRYPT_Data inData = { (uint8_t *)(uintptr_t)in, inLen };
uint8_t *maskDB = (uint8_t *)BSL_SAL_Malloc(maskedDBLen);
if (maskDB == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
CRYPT_Data dbMaskData = { maskDB, maskedDBLen };
/* If k < 2hLen + 2, output "decryption error" and stop.<rfc8017>
k is intLen , hLen is hashLen
*/
GOTO_ERR_IF_EX(OaepVerifyLengthCheck(*msgLen, inLen, hashLen), ret);
GOTO_ERR_IF_EX(OaepDecodeSeedMask(pad->mgfProvCtx, &pad->mgfMeth, in, inLen, &seedData, hashLen), ret);
GOTO_ERR_IF_EX(OaepDecodeMaskedDB(pad->mgfProvCtx, &pad->mgfMeth, &inData, seedMask, hashLen, &dbMaskData), ret);
GOTO_ERR_IF_EX(OaepVerifyHashMaskDB(pad->mdProvCtx, &pad->mdMeth, ¶mData, &dbMaskData, hashLen, &offset), ret);
if (memcpy_s(msg, *msgLen, maskDB + offset, maskedDBLen - offset) != EOK) {
ret = CRYPT_RSA_NOR_VERIFY_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
*msgLen = maskedDBLen - offset;
ERR:
BSL_SAL_CleanseData(maskDB, maskedDBLen);
BSL_SAL_FREE(maskDB);
return ret;
}
#endif // HITLS_CRYPTO_RSA_DECRYPT
#endif // HITLS_CRYPTO_RSAES_OAEP
#if defined(HITLS_CRYPTO_RSA_ENCRYPT) && \
(defined(HITLS_CRYPTO_RSAES_PKCSV15_TLS) || defined(HITLS_CRYPTO_RSAES_PKCSV15))
// Pad output format: EM = 00 || 02 || PS || 00 || M; where M indicates message.
int32_t CRYPT_RSA_SetPkcsV15Type2(void *libCtx, const uint8_t *in, uint32_t inLen,
uint8_t *out, uint32_t outLen)
{
// If mLen > k - 11, output "message too long" and stop.<rfc8017>
if (inLen + 11 > outLen) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_BUFF_LEN_NOT_ENOUGH);
return CRYPT_RSA_BUFF_LEN_NOT_ENOUGH;
}
int32_t ret;
uint32_t i;
uint8_t *ps = out + 2;
uint32_t psLen = outLen - inLen - 3;
uint8_t *msg = out + psLen + 3;
*out = 0x00;
*(out + 1) = 0x02;
*(out + outLen - inLen - 2) = 0x00;
// msg padding, outLen minus the 3-byte constant, ps length, and start padding.
if (inLen != 0 && memcpy_s(msg, outLen - (psLen + 3), in, inLen) != EOK) {
BSL_ERR_PUSH_ERROR(CRYPT_SECUREC_FAIL);
return CRYPT_SECUREC_FAIL;
}
// cal ps
ret = CRYPT_RandEx(libCtx, ps, psLen);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ps[psLen] = 0;
for (i = 0; i < psLen; i++) {
if (*(ps + i) != 0) {
continue;
}
do {
// no zero
ret = CRYPT_RandEx(libCtx, ps + i, 1);
if (ret != CRYPT_SUCCESS) {
return ret;
}
} while (*(ps + i) == 0);
}
return CRYPT_SUCCESS;
}
#endif // HITLS_CRYPTO_RSA_ENCRYPT && (EC_PKCSV15_TLS || EC_PKCSV15)
#ifdef HITLS_CRYPTO_RSA_DECRYPT
#ifdef HITLS_CRYPTO_RSAES_PKCSV15
int32_t CRYPT_RSA_VerifyPkcsV15Type2(const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen)
{
uint32_t zeroIndex = 0;
uint32_t index = ~(0);
uint32_t firstZero = Uint32ConstTimeEqual(in[0], 0x00);
uint32_t firstTwo = Uint32ConstTimeEqual(in[1], 0x02);
// Check the ps starting from subscript 2.
for (uint32_t i = 2; i < inLen; i++) {
uint32_t equals0 = Uint32ConstTimeIsZero(in[i]);
zeroIndex = Uint32ConstTimeSelect(index & equals0, i, zeroIndex);
index = Uint32ConstTimeSelect(equals0, 0, index);
}
uint32_t valid = firstZero & firstTwo & (~index);
// Pad output format: EM = 00 || 02 || PS || 00 || M; where M is a message, and PS must be >= 8.
// Therefore, the subscript of the second 0 must be greater than or equal to 10.
valid &= Uint32ConstTimeGe(zeroIndex, 10);
zeroIndex++;
if (valid == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_NOR_VERIFY_FAIL);
return CRYPT_RSA_NOR_VERIFY_FAIL;
}
if (inLen - zeroIndex > *outLen) {
BSL_ERR_PUSH_ERROR(CRYPT_RSA_NOR_VERIFY_FAIL);
return CRYPT_RSA_NOR_VERIFY_FAIL;
}
(void)memcpy_s(out, *outLen, in + zeroIndex, inLen - zeroIndex);
*outLen = inLen - zeroIndex;
return CRYPT_SUCCESS;
}
#endif // HITLS_CRYPTO_RSAES_PKCSV15
#ifdef HITLS_CRYPTO_RSAES_PKCSV15_TLS
int32_t CRYPT_RSA_VerifyPkcsV15Type2TLS(const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen)
{
uint32_t masterSecretLen = *outLen;
uint32_t zeroIndex = 0;
uint32_t index = ~(0);
uint32_t fist = Uint32ConstTimeEqual(in[0], 0x00);
uint32_t second = Uint32ConstTimeEqual(in[1], 0x02);
for (uint32_t i = 2; i < inLen; i++) {
uint32_t equals0 = Uint32ConstTimeIsZero(in[i]);
zeroIndex = Uint32ConstTimeSelect(index & equals0, i, zeroIndex);
index = Uint32ConstTimeSelect(equals0, 0, index);
}
uint32_t valid = fist & second & (~index);
// Pad output format: EM = 00 || 02 || PS || 00 || M; where M is a message, and PS must be >= 8.
// Therefore, the subscript of the second 0 must be greater than or equal to 10.
valid &= Uint32ConstTimeGe(zeroIndex, 10);
zeroIndex++;
uint32_t secretLen = inLen - zeroIndex;
valid &= ~(Uint32ConstTimeGt(secretLen, *outLen));
for (uint32_t i = 0; i < masterSecretLen; i++) {
uint32_t mask = valid & Uint32ConstTimeLt(i, secretLen);
uint32_t inIndex = mask & zeroIndex;
out[i] = Uint8ConstTimeSelect(mask, *(in + inIndex + i), 0);
}
*outLen = secretLen;
// if the 'plaintext' is PKCS15 , the valid should be 0xffffffff, else should be 0
// so return 0 for success, else return 0xffffffff
return ~valid;
}
#endif // HITLS_CRYPTO_RSAES_PKCSV15_TLS
#endif // HITLS_CRYPTO_RSA_DECRYPT
#endif /* HITLS_CRYPTO_RSA */ | 2302_82127028/openHiTLS-examples_1508 | crypto/rsa/src/rsa_padding.c | C | unknown | 36,877 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef CRYPT_SCRYPT_H
#define CRYPT_SCRYPT_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SCRYPT
#include <stdint.h>
#include "crypt_local_types.h"
#include "bsl_params.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
typedef struct CryptScryptCtx CRYPT_SCRYPT_Ctx;
typedef int32_t (*PBKDF2_PRF)(void *libCtx, const EAL_MacMethod *macMeth, CRYPT_MAC_AlgId macId,
const EAL_MdMethod *mdMeth, const uint8_t *key, uint32_t keyLen,
const uint8_t *salt, uint32_t saltLen,
uint32_t iterCnt, uint8_t *out, uint32_t len);
#define CRYPT_SCRYPT_Ctrl NULL
/**
* @ingroup SCRYPT
* @brief Generate SCRYPT context.
*
* @retval Success: SCRYPT ctx.
* Fails: NULL.
*/
CRYPT_SCRYPT_Ctx *CRYPT_SCRYPT_NewCtx(void);
/**
* @ingroup SCRYPT
* @brief Generate SCRYPT context.
*
* @retval Success: SCRYPT ctx.
* Fails: NULL.
*/
CRYPT_SCRYPT_Ctx *CRYPT_SCRYPT_NewCtxEx(void *libCtx);
/**
* @ingroup SCRYPT
* @brief Set parameters for the SCRYPT context.
*
* @param ctx [in, out] Pointer to the SCRYPT context.
* @param param [in] Either a MAC algorithm ID, a seed, a password, or a label.
*
* @retval Success: CRYPT_SUCCESS
* For other error codes, see crypt_errno.h.
*/
int32_t CRYPT_SCRYPT_SetParam(CRYPT_SCRYPT_Ctx *ctx, const BSL_Param *param);
/**
* @ingroup SCRYPT
* @brief Obtain the derived key based on the passed SCRYPT context..
*
* @param ctx [in, out] Pointer to the SCRYPT context.
* @param out [out] Derived key buffer.
* @param len [in] Derived key buffer size.
*
* @retval Success: CRYPT_SUCCESS
* For other error codes, see crypt_errno.h.
*/
int32_t CRYPT_SCRYPT_Derive(CRYPT_SCRYPT_Ctx *ctx, uint8_t *out, uint32_t len);
/**
* @ingroup SCRYPT
* @brief SCRYPT deinitialization API
*
* @param ctx [in, out] Pointer to the SCRYPT context.
*
* @retval #CRYPT_SUCCESS Deinitialization succeeded.
* @retval #CRYPT_NULL_INPUT Pointer ctx is NULL
*/
int32_t CRYPT_SCRYPT_Deinit(CRYPT_SCRYPT_Ctx *ctx);
/**
* @ingroup SCRYPT
* @brief free SCRYPT context.
*
* @param ctx [IN] SCRYPT handle
*/
void CRYPT_SCRYPT_FreeCtx(CRYPT_SCRYPT_Ctx *ctx);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // HITLS_CRYPTO_SCRYPT
#endif // CRYPT_SCRYPT_H
| 2302_82127028/openHiTLS-examples_1508 | crypto/scrypt/include/crypt_scrypt.h | C | unknown | 2,802 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SCRYPT
#include <stdint.h>
#include "securec.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "crypt_local_types.h"
#include "crypt_errno.h"
#include "crypt_utils.h"
#include "crypt_types.h"
#include "crypt_scrypt.h"
#include "eal_mac_local.h"
#include "eal_md_local.h"
#include "pbkdf2_local.h"
#include "bsl_params.h"
#include "crypt_params_key.h"
#define SCRYPT_PR_MAX ((1 << 30) - 1)
// Convert the little-endian array to the host order.
#define SALSA_INPUT_TO_HOST(T, x) \
do { \
(x)[0] = CRYPT_LE32TOH((T)[0]); \
(x)[1] = CRYPT_LE32TOH((T)[1]); \
(x)[2] = CRYPT_LE32TOH((T)[2]); \
(x)[3] = CRYPT_LE32TOH((T)[3]); \
(x)[4] = CRYPT_LE32TOH((T)[4]); \
(x)[5] = CRYPT_LE32TOH((T)[5]); \
(x)[6] = CRYPT_LE32TOH((T)[6]); \
(x)[7] = CRYPT_LE32TOH((T)[7]); \
(x)[8] = CRYPT_LE32TOH((T)[8]); \
(x)[9] = CRYPT_LE32TOH((T)[9]); \
(x)[10] = CRYPT_LE32TOH((T)[10]); \
(x)[11] = CRYPT_LE32TOH((T)[11]); \
(x)[12] = CRYPT_LE32TOH((T)[12]); \
(x)[13] = CRYPT_LE32TOH((T)[13]); \
(x)[14] = CRYPT_LE32TOH((T)[14]); \
(x)[15] = CRYPT_LE32TOH((T)[15]); \
} while (0)
// Convert the host order to little endian order.
#define SALSA_OUTPUT_TO_LE32(T, x) \
do { \
(T)[0] = CRYPT_HTOLE32((x)[0] + CRYPT_LE32TOH((T)[0])); \
(T)[1] = CRYPT_HTOLE32((x)[1] + CRYPT_LE32TOH((T)[1])); \
(T)[2] = CRYPT_HTOLE32((x)[2] + CRYPT_LE32TOH((T)[2])); \
(T)[3] = CRYPT_HTOLE32((x)[3] + CRYPT_LE32TOH((T)[3])); \
(T)[4] = CRYPT_HTOLE32((x)[4] + CRYPT_LE32TOH((T)[4])); \
(T)[5] = CRYPT_HTOLE32((x)[5] + CRYPT_LE32TOH((T)[5])); \
(T)[6] = CRYPT_HTOLE32((x)[6] + CRYPT_LE32TOH((T)[6])); \
(T)[7] = CRYPT_HTOLE32((x)[7] + CRYPT_LE32TOH((T)[7])); \
(T)[8] = CRYPT_HTOLE32((x)[8] + CRYPT_LE32TOH((T)[8])); \
(T)[9] = CRYPT_HTOLE32((x)[9] + CRYPT_LE32TOH((T)[9])); \
(T)[10] = CRYPT_HTOLE32((x)[10] + CRYPT_LE32TOH((T)[10])); \
(T)[11] = CRYPT_HTOLE32((x)[11] + CRYPT_LE32TOH((T)[11])); \
(T)[12] = CRYPT_HTOLE32((x)[12] + CRYPT_LE32TOH((T)[12])); \
(T)[13] = CRYPT_HTOLE32((x)[13] + CRYPT_LE32TOH((T)[13])); \
(T)[14] = CRYPT_HTOLE32((x)[14] + CRYPT_LE32TOH((T)[14])); \
(T)[15] = CRYPT_HTOLE32((x)[15] + CRYPT_LE32TOH((T)[15])); \
} while (0)
#define SCRYPT_ELEMENTSIZE 64
struct CryptScryptCtx {
const EAL_MacMethod *macMeth;
const EAL_MdMethod *mdMeth;
PBKDF2_PRF pbkdf2Prf;
uint8_t *password;
uint32_t passLen;
uint8_t *salt;
uint32_t saltLen;
uint32_t n;
uint32_t r;
uint32_t p;
void *libCtx; // For provider usage, can be NULL if not used.
};
/* This function is implemented by referring to the RFC standard.
For details, see section 3 in https://www.rfc-editor.org/rfc/rfc7914.txt */
static void SCRYPT_Salsa20WordSpecification(uint32_t t[16])
{
uint32_t x[16];
SALSA_INPUT_TO_HOST(t, x);
for (int i = 0; i < 4; i++) {
x[4] ^= ROTL32(x[0] + x[12], 7);
x[8] ^= ROTL32(x[4] + x[0], 9);
x[12] ^= ROTL32(x[8] + x[4], 13);
x[0] ^= ROTL32(x[12] + x[8], 18);
x[9] ^= ROTL32(x[5] + x[1], 7);
x[13] ^= ROTL32(x[9] + x[5], 9);
x[1] ^= ROTL32(x[13] + x[9], 13);
x[5] ^= ROTL32(x[1] + x[13], 18);
x[14] ^= ROTL32(x[10] + x[6], 7);
x[2] ^= ROTL32(x[14] + x[10], 9);
x[6] ^= ROTL32(x[2] + x[14], 13);
x[10] ^= ROTL32(x[6] + x[2], 18);
x[3] ^= ROTL32(x[15] + x[11], 7);
x[7] ^= ROTL32(x[3] + x[15], 9);
x[11] ^= ROTL32(x[7] + x[3], 13);
x[15] ^= ROTL32(x[11] + x[7], 18);
x[1] ^= ROTL32(x[0] + x[3], 7);
x[2] ^= ROTL32(x[1] + x[0], 9);
x[3] ^= ROTL32(x[2] + x[1], 13);
x[0] ^= ROTL32(x[3] + x[2], 18);
x[6] ^= ROTL32(x[5] + x[4], 7);
x[7] ^= ROTL32(x[6] + x[5], 9);
x[4] ^= ROTL32(x[7] + x[6], 13);
x[5] ^= ROTL32(x[4] + x[7], 18);
x[11] ^= ROTL32(x[10] + x[9], 7);
x[8] ^= ROTL32(x[11] + x[10], 9);
x[9] ^= ROTL32(x[8] + x[11], 13);
x[10] ^= ROTL32(x[9] + x[8], 18);
x[12] ^= ROTL32(x[15] + x[14], 7);
x[13] ^= ROTL32(x[12] + x[15], 9);
x[14] ^= ROTL32(x[13] + x[12], 13);
x[15] ^= ROTL32(x[14] + x[13], 18);
}
SALSA_OUTPUT_TO_LE32(t, x);
}
static void SCRYPT_BlockMix(uint8_t *b, uint8_t *y, uint32_t r)
{
uint8_t *bTmp = b;
uint8_t *y0 = y;
uint8_t *y1 = y + (r << 6);
/* RFC7914 section 4
In this implementation, the output Y is split and processed separately based on the description in section 4.
The performance is slightly improved.
1. B' = Y, Y0 = Y, Y1 = Y[r], b=B,
The block size of each Y is 64 bytes. The processing unit in this function is 64 bytes.
2. Y0 = B[2 * r - 1] ^ B[0]
Salsa(Y0)
Y1 = Y0 ^ B[1]
Salsa(Y1)
3. for i = 1 to r -1 do
b += 2 // Two blocks have been processed in step 2.
Y0 += 1 // Process the next block of Y0.
Y0 = b[0] ^ Y1
Salsa(Y0)
Y1 += 1
Y1 = b[1] ^ Y0
Salsa(Y1)
4. B = Y // Copy Y to B.
*/
// r << 7 is equal to r * 128, where r * 128 is the block size of the algorithm.
DATA32_XOR(b + (r << 7) - SCRYPT_ELEMENTSIZE, bTmp, y0, SCRYPT_ELEMENTSIZE);
SCRYPT_Salsa20WordSpecification((uint32_t*)y0);
DATA32_XOR(y0, bTmp + SCRYPT_ELEMENTSIZE, y1, SCRYPT_ELEMENTSIZE);
SCRYPT_Salsa20WordSpecification((uint32_t*)y1);
for (uint32_t i = 1; i < r; i++) {
bTmp += 128; // Process two pieces of 64-bit(SCRYPT_ELEMENTSIZE) data in one cycle. 64 * 2 = 128
y0 += SCRYPT_ELEMENTSIZE;
DATA32_XOR(y1, bTmp, y0, SCRYPT_ELEMENTSIZE);
SCRYPT_Salsa20WordSpecification((uint32_t*)y0);
y1 += SCRYPT_ELEMENTSIZE;
DATA32_XOR(y0, bTmp + SCRYPT_ELEMENTSIZE, y1, SCRYPT_ELEMENTSIZE);
SCRYPT_Salsa20WordSpecification((uint32_t*)y1);
}
(void)memcpy_s(b, r << 7, y, r << 7); // Length bit r of B and y: r << 7
}
/* For details about this function, see section 5 in RFC7914 */
static void SCRYPT_ROMix(uint8_t *b, uint32_t n, uint32_t r, uint8_t *v, uint8_t *y)
{
uint32_t i;
uint8_t *tmp = NULL;
uint32_t blockSize = r << 7;
for (i = 0, tmp = v; i < n; i++, tmp += blockSize) {
(void)memcpy_s(tmp, blockSize, b, blockSize);
SCRYPT_BlockMix(b, y, r);
}
for (i = 0; i < n; i++) {
uint32_t j = GET_UINT32_LE(b, blockSize - 64) & (n - 1);
// X= B, X = X ^ Vj
DATA32_XOR(b, &v[j * blockSize], b, blockSize);
SCRYPT_BlockMix(b, y, r);
}
}
static int32_t SCRYPT_CheckParam(uint32_t n, uint32_t r, uint32_t p, const uint8_t *out, uint32_t len)
{
if (r == 0 || p == 0 || n <= 1 || ((n & (n - 1)) != 0)) {
BSL_ERR_PUSH_ERROR(CRYPT_SCRYPT_PARAM_ERROR);
return CRYPT_SCRYPT_PARAM_ERROR;
}
if (p > SCRYPT_PR_MAX / r) {
BSL_ERR_PUSH_ERROR(CRYPT_SCRYPT_PARAM_ERROR);
return CRYPT_SCRYPT_PARAM_ERROR;
}
/* r <= 3 indicates 16 * r < (sizeof(uint64_t) * 8 - 1) */
if ((r <= 3) && (n >= (((uint64_t)1) << (16 * r)))) {
BSL_ERR_PUSH_ERROR(CRYPT_SCRYPT_PARAM_ERROR);
return CRYPT_SCRYPT_PARAM_ERROR;
}
/* (p * 128 * r < UINT32_MAX) && (32 * r * n * sizeof(uint32_t)) */
if ((r > ((UINT32_MAX / 128) / p)) || (n > ((UINT32_MAX / 128) / r))) {
BSL_ERR_PUSH_ERROR(CRYPT_SCRYPT_PARAM_ERROR);
return CRYPT_SCRYPT_PARAM_ERROR;
}
/* malloc size:p * 128 * r + n * 128 * r + 128 *r */
if ((uint64_t)p * 128 * r + n * 128 * r + 128 * r > UINT32_MAX) {
BSL_ERR_PUSH_ERROR(CRYPT_SCRYPT_PARAM_ERROR);
return CRYPT_SCRYPT_PARAM_ERROR;
}
if (out == NULL || len == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_SCRYPT_PARAM_ERROR);
return CRYPT_SCRYPT_PARAM_ERROR;
}
return CRYPT_SUCCESS;
}
static int32_t SCRYPT_CheckPointer(PBKDF2_PRF pbkdf2Prf, const uint8_t *key, uint32_t keyLen,
const uint8_t *salt, uint32_t saltLen)
{
if (pbkdf2Prf == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (key == NULL && keyLen > 0) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (salt == NULL && saltLen > 0) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
return CRYPT_SUCCESS;
}
/* For details about this function, see section 6 in RFC7914. */
int32_t CRYPT_SCRYPT(PBKDF2_PRF pbkdf2Prf, const EAL_MacMethod *macMeth, CRYPT_MAC_AlgId macId,
const EAL_MdMethod *mdMeth, const uint8_t *key, uint32_t keyLen, const uint8_t *salt,
uint32_t saltLen, uint32_t n, uint32_t r, uint32_t p, uint8_t *out, uint32_t len)
{
int32_t ret;
// V in ROMix and BlockMix is allocated here, reducing memory application and release costs
uint8_t *b = NULL, *v = NULL, *bi = NULL, *y = NULL;
uint32_t bLen, blockSize, sumLen;
if ((ret = SCRYPT_CheckParam(n, r, p, out, len)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if ((ret = SCRYPT_CheckPointer(pbkdf2Prf, key, keyLen, salt, saltLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
blockSize = r << 7; // block length: r << 7 (r * 128)
bLen = blockSize * p;
sumLen = bLen + blockSize * n + blockSize;
b = BSL_SAL_Malloc(sumLen);
if (b == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
v = b + bLen;
y = v + blockSize * n;
GOTO_ERR_IF(pbkdf2Prf(NULL, macMeth, macId, mdMeth, key, keyLen, salt, saltLen, 1, b, bLen), ret);
bi = b;
for (uint32_t i = 0; i < p; i++, bi += blockSize) {
SCRYPT_ROMix(bi, n, r, v, y);
}
GOTO_ERR_IF(pbkdf2Prf(NULL, macMeth, macId, mdMeth, key, keyLen, b, bLen, 1, out, len), ret);
ERR:
BSL_SAL_FREE(b);
return ret;
}
int32_t CRYPT_SCRYPT_SetMacMethod(CRYPT_SCRYPT_Ctx *ctx)
{
ctx->macMeth = EAL_MacFindDefaultMethod(CRYPT_MAC_HMAC_SHA256);
if (ctx->macMeth == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_METH_NULL_MEMBER);
return CRYPT_EAL_ERR_METH_NULL_MEMBER;
}
ctx->mdMeth = EAL_MdFindDefaultMethod(CRYPT_MD_SHA256);
if (ctx->mdMeth == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_METH_NULL_MEMBER);
return CRYPT_EAL_ERR_METH_NULL_MEMBER;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_SCRYPT_InitCtx(CRYPT_SCRYPT_Ctx *ctx)
{
int32_t ret = CRYPT_SCRYPT_SetMacMethod(ctx);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ctx->pbkdf2Prf = CRYPT_PBKDF2_HMAC;
return CRYPT_SUCCESS;
}
CRYPT_SCRYPT_Ctx *CRYPT_SCRYPT_NewCtx(void)
{
CRYPT_SCRYPT_Ctx *ctx = BSL_SAL_Calloc(1, sizeof(CRYPT_SCRYPT_Ctx));
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
int32_t ret = CRYPT_SCRYPT_InitCtx(ctx);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
BSL_SAL_FREE(ctx);
return NULL;
}
return ctx;
}
#ifdef HITLS_CRYPTO_PROVIDER
CRYPT_SCRYPT_Ctx *CRYPT_SCRYPT_NewCtxEx(void *libCtx)
{
CRYPT_SCRYPT_Ctx *ctx = BSL_SAL_Calloc(1, sizeof(CRYPT_SCRYPT_Ctx));
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
int32_t ret = CRYPT_SCRYPT_InitCtx(ctx);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
BSL_SAL_FREE(ctx);
return NULL;
}
ctx->libCtx = libCtx;
return ctx;
}
#endif
int32_t CRYPT_SCRYPT_SetPassWord(CRYPT_SCRYPT_Ctx *ctx, const uint8_t *password, uint32_t passLen)
{
if (password == NULL && passLen > 0) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
BSL_SAL_ClearFree(ctx->password, ctx->passLen);
ctx->password = BSL_SAL_Dump(password, passLen);
if (ctx->password == NULL && passLen > 0) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
ctx->passLen = passLen;
return CRYPT_SUCCESS;
}
int32_t CRYPT_SCRYPT_SetSalt(CRYPT_SCRYPT_Ctx *ctx, const uint8_t *salt, uint32_t saltLen)
{
if (salt == NULL && saltLen > 0) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
BSL_SAL_FREE(ctx->salt);
ctx->salt = BSL_SAL_Dump(salt, saltLen);
if (ctx->salt == NULL && saltLen > 0) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
ctx->saltLen = saltLen;
return CRYPT_SUCCESS;
}
int32_t CRYPT_SCRYPT_SetN(CRYPT_SCRYPT_Ctx *ctx, const uint32_t n)
{
if (n <= 1 || (n & (n - 1)) != 0) {
BSL_ERR_PUSH_ERROR(CRYPT_SCRYPT_PARAM_ERROR);
return CRYPT_SCRYPT_PARAM_ERROR;
}
ctx->n = n;
return CRYPT_SUCCESS;
}
int32_t CRYPT_SCRYPT_SetR(CRYPT_SCRYPT_Ctx *ctx, const uint32_t r)
{
if (r == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_SCRYPT_PARAM_ERROR);
return CRYPT_SCRYPT_PARAM_ERROR;
}
ctx->r = r;
return CRYPT_SUCCESS;
}
int32_t CRYPT_SCRYPT_SetP(CRYPT_SCRYPT_Ctx *ctx, const uint32_t p)
{
if (p == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_SCRYPT_PARAM_ERROR);
return CRYPT_SCRYPT_PARAM_ERROR;
}
ctx->p = p;
return CRYPT_SUCCESS;
}
int32_t CRYPT_SCRYPT_SetParam(CRYPT_SCRYPT_Ctx *ctx, const BSL_Param *param)
{
uint32_t val = 0;
uint32_t len = 0;
const BSL_Param *temp = NULL;
int32_t ret = CRYPT_SCRYPT_PARAM_ERROR;
if (ctx == NULL || param == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_KDF_PASSWORD)) != NULL) {
GOTO_ERR_IF(CRYPT_SCRYPT_SetPassWord(ctx, temp->value, temp->valueLen), ret);
}
if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_KDF_SALT)) != NULL) {
GOTO_ERR_IF(CRYPT_SCRYPT_SetSalt(ctx, temp->value, temp->valueLen), ret);
}
if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_KDF_N)) != NULL) {
len = sizeof(val);
GOTO_ERR_IF(BSL_PARAM_GetValue(temp, CRYPT_PARAM_KDF_N,
BSL_PARAM_TYPE_UINT32, &val, &len), ret);
GOTO_ERR_IF(CRYPT_SCRYPT_SetN(ctx, val), ret);
}
if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_KDF_R)) != NULL) {
len = sizeof(val);
GOTO_ERR_IF(BSL_PARAM_GetValue(temp, CRYPT_PARAM_KDF_R,
BSL_PARAM_TYPE_UINT32, &val, &len), ret);
GOTO_ERR_IF(CRYPT_SCRYPT_SetR(ctx, val), ret);
}
if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_KDF_P)) != NULL) {
len = sizeof(val);
GOTO_ERR_IF(BSL_PARAM_GetValue(temp, CRYPT_PARAM_KDF_P,
BSL_PARAM_TYPE_UINT32, &val, &len), ret);
GOTO_ERR_IF(CRYPT_SCRYPT_SetP(ctx, val), ret);
}
ERR:
return ret;
}
int32_t CRYPT_SCRYPT_Derive(CRYPT_SCRYPT_Ctx *ctx, uint8_t *out, uint32_t len)
{
int32_t ret;
uint8_t *b = NULL, *v = NULL, *bi = NULL, *y = NULL;
uint32_t bLen, blockSize, sumLen;
const EAL_MacMethod *macMeth = ctx->macMeth;
const EAL_MdMethod *mdMeth = ctx->mdMeth;
PBKDF2_PRF pbkdf2Prf = ctx->pbkdf2Prf;
const uint8_t *password = ctx->password;
uint32_t passLen = ctx->passLen;
const uint8_t *salt = ctx->salt;
uint32_t saltLen = ctx->saltLen;
uint32_t n = ctx->n;
uint32_t r = ctx->r;
uint32_t p = ctx->p;
if ((ret = SCRYPT_CheckParam(n, r, p, out, len)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if ((ret = SCRYPT_CheckPointer(pbkdf2Prf, password, passLen, salt, saltLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
blockSize = r << 7;
bLen = blockSize * p;
sumLen = bLen + blockSize * n + blockSize;
if (sumLen < bLen) {
BSL_ERR_PUSH_ERROR(CRYPT_SCRYPT_DATA_TOO_MAX);
return CRYPT_SCRYPT_DATA_TOO_MAX;
}
b = BSL_SAL_Malloc(sumLen);
if (b == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
v = b + bLen;
y = v + blockSize * ctx->n;
GOTO_ERR_IF(pbkdf2Prf(ctx->libCtx, macMeth, CRYPT_MAC_HMAC_SHA256, mdMeth, password, passLen, salt, saltLen, 1,
b, bLen), ret);
bi = b;
for (uint32_t i = 0; i < p; i++, bi += blockSize) {
SCRYPT_ROMix(bi, n, r, v, y);
}
GOTO_ERR_IF(pbkdf2Prf(ctx->libCtx, macMeth, CRYPT_MAC_HMAC_SHA256, mdMeth, password, passLen, b, bLen, 1,
out, len), ret);
ERR:
BSL_SAL_FREE(b);
return ret;
}
int32_t CRYPT_SCRYPT_Deinit(CRYPT_SCRYPT_Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
BSL_SAL_ClearFree(ctx->password, ctx->passLen);
BSL_SAL_FREE(ctx->salt);
(void)memset_s(ctx, sizeof(CRYPT_SCRYPT_Ctx), 0, sizeof(CRYPT_SCRYPT_Ctx));
int32_t ret = CRYPT_SCRYPT_InitCtx(ctx);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
void CRYPT_SCRYPT_FreeCtx(CRYPT_SCRYPT_Ctx *ctx)
{
if (ctx == NULL) {
return;
}
BSL_SAL_ClearFree(ctx->password, ctx->passLen);
BSL_SAL_FREE(ctx->salt);
BSL_SAL_Free(ctx);
}
#endif /* HITLS_CRYPTO_SCRYPT */
| 2302_82127028/openHiTLS-examples_1508 | crypto/scrypt/src/scrypt.c | C | unknown | 17,935 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef CRYPT_SHA1_H
#define CRYPT_SHA1_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SHA1
#include <stdint.h>
#include <stdlib.h>
#include "crypt_types.h"
#include "bsl_params.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
/* Length of the message digest buffer. */
#define CRYPT_SHA1_DIGESTSIZE 20
/* Message processing block size */
#define CRYPT_SHA1_BLOCKSIZE 64
typedef struct CryptSha1Ctx CRYPT_SHA1_Ctx;
#define CRYPT_SHA1_Squeeze NULL
/**
* @ingroup SHA1
* @brief Generate md context.
*
* @retval Success: sha1 ctx.
* Fails: NULL.
*/
CRYPT_SHA1_Ctx *CRYPT_SHA1_NewCtx(void);
/**
* @ingroup SHA1
* @brief Generate md context.
*
* @param libCtx [IN] library context
* @param algId [IN] algorithm id
*
* @retval Success: sha1 ctx.
* Fails: NULL.
*/
CRYPT_SHA1_Ctx *CRYPT_SHA1_NewCtxEx(void *libCtx, int32_t algId);
/**
* @ingroup SHA1
* @brief free md context.
*
* @param ctx [IN] md handle
*/
void CRYPT_SHA1_FreeCtx(CRYPT_SHA1_Ctx *ctx);
/**
* @ingroup SHA1
* @brief This API is invoked to initialize the SHA-1 context.
*
* @param *ctx [in,out] Pointer to the SHA-1 context.
* @param *param [in] Pointer to the parameter.
*
* @retval #CRYPT_SUCCESS initialization succeeded.
* @retval #CRYPT_NULL_INPUT Pointer ctx is NULL
*/
int32_t CRYPT_SHA1_Init(CRYPT_SHA1_Ctx *ctx, BSL_Param *param);
/**
* @ingroup SHA1
* @brief Encode the input text and update the message digest.
*
* @param *ctx [in,out] Pointer to the SHA-1 context.
* @param *in [in] Pointer to the data to be calculated
* @param len [in] Length of the data to be calculated
*
* @retval #CRYPT_SUCCESS succeeded in updating the internal status of the digest.
* @retval #CRYPT_NULL_INPUT The input parameter is NULL.
* @retval #CRYPT_SHA1_ERR_OVERFLOW input data length exceeds the maximum (2^64 bits)
*/
int32_t CRYPT_SHA1_Update(CRYPT_SHA1_Ctx *ctx, const uint8_t *in, uint32_t len);
/**
* @ingroup SHA1
* @brief Obtain the message digest based on the passed SHA-1 text.
*
* @param *ctx [in,out] Pointer to the SHA-1 context.
* @param *out [in] Digest buffer
* @param *len [in,out] Digest buffer size
*
* @retval #CRYPT_SUCCESS succeeded in obtaining the computed digest.
* @retval #CRYPT_NULL_INPUT The input parameter is NULL.
* @retval #CRYPT_SHA1_ERR_OVERFLOW Input data length exceeds the maximum (2^64 bits).
* @retval #CRYPT_SHA1_OUT_BUFF_LEN_NOT_ENOUGH The output buffer is insufficient.
*/
int32_t CRYPT_SHA1_Final(CRYPT_SHA1_Ctx *ctx, uint8_t *out, uint32_t *len);
/**
* @ingroup SHA1
* @brief SHA1 deinitialization API
* @param *ctx [in,out] Pointer to the SHA-1 context.
*
* @retval #CRYPT_SUCCESS initialization succeeded.
* @retval #CRYPT_NULL_INPUT Pointer ctx is NULL
*/
int32_t CRYPT_SHA1_Deinit(CRYPT_SHA1_Ctx *ctx);
/**
* @ingroup SHA1
* @brief SHA1 copy CTX function
* @param dest [out] Pointer to the dest SHA1 context.
* @param src [in] Pointer to the original SHA1 context.
*
* @retval #CRYPT_SUCCESS initialization succeeded.
* @retval #CRYPT_NULL_INPUT Pointer ctx is NULL
*/
int32_t CRYPT_SHA1_CopyCtx(CRYPT_SHA1_Ctx *dst, const CRYPT_SHA1_Ctx *src);
/**
* @ingroup SHA1
* @brief SHA1 dup CTX function
* @param src [in] Pointer to the original SHA1 context.
*
* @retval Success: sha1 ctx.
* Fails: NULL.
*/
CRYPT_SHA1_Ctx *CRYPT_SHA1_DupCtx(const CRYPT_SHA1_Ctx *src);
#ifdef HITLS_CRYPTO_PROVIDER
/**
* @ingroup SHA1
* @brief SHA1 get param function
* @param ctx [in] Pointer to the SHA1 context.
* @param param [in] Pointer to the parameter.
*
* @retval #CRYPT_SUCCESS Success.
* @retval #CRYPT_NULL_INPUT Pointer param is NULL
* @retval #CRYPT_INVALID_ARG Pointer param is invalid
*/
int32_t CRYPT_SHA1_GetParam(CRYPT_SHA1_Ctx *ctx, BSL_Param *param);
#else
#define CRYPT_SHA1_GetParam NULL
#endif
#ifdef __cplusplus
}
#endif /* __cpluscplus */
#endif // HITLS_CRYPTO_SHA1
#endif // CRYPT_SHA1_H
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha1/include/crypt_sha1.h | C | unknown | 4,617 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SHA1
#include "crypt_arm.h"
.arch armv8-a+crypto
.extern g_cryptArmCpuInfo
.hidden g_cryptArmCpuInfo
/* SHA1 used constant value. For the data source, see the RFC3174 document.
* K(t) = 5A827999 ( 0 <= t <= 19)
* K(t) = 6ED9EBA1 (20 <= t <= 39)
* K(t) = 8F1BBCDC (40 <= t <= 59)
* K(t) = CA62C1D6 (60 <= t <= 79)
*/
.data
.balign 64 // Alignment based on the size of the read data block
.type g_k, %object
g_k:
.long 0x5a827999
.long 0x6ed9eba1
.long 0x8f1bbcdc
.long 0xca62c1d6
.size g_k, .-g_k
.balign 64 // Alignment based on the size of the read data block
.type g_kExt, %object
g_kExt:
.long 0x5a827999, 0x5a827999, 0x5a827999, 0x5a827999 //K_00_19
.long 0x6ed9eba1, 0x6ed9eba1, 0x6ed9eba1, 0x6ed9eba1 //K_20_39
.long 0x8f1bbcdc, 0x8f1bbcdc, 0x8f1bbcdc, 0x8f1bbcdc //K_40_59
.long 0xca62c1d6, 0xca62c1d6, 0xca62c1d6, 0xca62c1d6 //K_60_79
.size g_kExt, .-g_kExt
/**
* Macro Description: 32位Message block扩展Wi
* input register:
* wi_3: W[i-3]
* wi_8: W[i-8]
* wi_14: W[i-14]
* wi_16: W[i-16]
* temp1: temporary register
* temp2: temporary register
* Modify the register: wi_16 temp1 temp2
* Output register:
* wi_16: Latest W[i] value, W(i) = S^1(W(i-3) XOR W(i-8) XOR W(i-14) XOR W(i-16))
* Function/Macro Call: NONE
*/
.macro MESSAGE_EXPAND wi_16, wi_14, wi_8, wi_3, temp1, temp2
eor \temp1, \wi_14, \wi_16 // W(i-14) XOR W(i-16)
eor \temp2, \wi_3, \wi_8 // W(i-3) XOR W(i-8)
eor \wi_16, \temp1, \temp2 // W(i-3) XOR W(i-8) XOR W(i-14) XOR W(i-16)
ror \wi_16, \wi_16, #31 // Cyclic left shift 1 equals cyclic right shift 31
.endm
/**
* Macro Description: b、e Compute
* input register:
* k: Constant data
* wi: Message block
* a、b、e: Intermediate variable of hash value
* f: f(B, C, D)
* temp1-4: temporary register
* Modify the register: b e temp3-temp4
* Output register:
* b: Indicates the value after a cyclic update.
* e: Indicates the value after a cyclic update.
* Macro implementation:
* e = S^5(A) + f(B, C, D) + E + W(i) + K(i)
* b = S^30(B)
* Function/Macro Call: NONE
*/
.macro CAL_B_E a, b, e, wi, k, f, temp3, temp4
add \temp3, \wi, \k // W(i) + K(i)
ror \temp4, \a, #27 // S^5(A) Cyclic shift left 5 equal Cyclic shift right 27
ror \b, \b, #2 // b = S^30(B) Cyclic shift left 30 equal Cyclic shift right 2
add \temp4, \temp4, \temp3 // S^5(A) + W(i) + K(i)
add \e, \e, \f // f(B, C, D) + E
add \e, \e, \temp4 // f(B, C, D) + E + S^5(A) + W(i) + K(i)
.endm
/**
* Macro Description: Message compression,0~19round data compression
* input register:
* k: Constant data
* wi: Message block
* a - h: Intermediate variable of hash value
* temp1-4: temporary register
* Modify the register: b e temp1-temp4
* Output register:
* b: Indicates the value after a cyclic update.
* e: Indicates the value after a cyclic update.
* Macro implementation: f(B, C, D) = (B AND C) OR ((NOT B) AND D)
* e = S^5(A) + f(B, C, D) + E + W(i) + K(i)
* b = S^30(B)
* Function/Macro Call: CAL_B_E
*/
.macro DATA_COMPRE_0_19 a, b, c, d, e, wi, k, temp1, temp2, temp3, temp4
and \temp1, \b, \c // b&c
bic \temp2, \d, \b // d&(~b)
orr \temp1, \temp1, \temp2 // f(B, C, D)
CAL_B_E \a, \b, \e, \wi, \k, \temp1, \temp3, \temp4
.endm
/**
* Macro Description: Message compression,20~39、60~79round data compression
* input register:
* k: Constant data
* wi: Message block
* a - h: Intermediate variable of hash value
* temp1-4: temporary register
* Modify the register: b e temp1-temp4
* Output register:
* b: Indicates the value after a cyclic update.
* e: Indicates the value after a cyclic update.
* Macro implementation: f(B, C, D) = B XOR C XOR D
* e = S^5(A) + f(B, C, D) + E + W(i) + K(i)
* b = S^30(B)
* Function/Macro Call: CAL_B_E
*/
.macro DATA_COMPRE_20_39_60_79 a, b, c, d, e, wi, k, temp1, temp2, temp3, temp4
eor \temp2, \b, \c // b&c
eor \temp1, \temp2, \d // f(B, C, D) = b&c&d
CAL_B_E \a, \b, \e, \wi, \k, \temp1, \temp3, \temp4
.endm
/**
* Macro Description: Message compression,40~59round data compression
* input register:
* k: Constant data
* wi: Message block
* a - h: Intermediate variable of hash value
* temp1-4: temporary register
* Modify the register: b e temp1-temp4
* Output register:
* b: Indicates the value after a cyclic update.
* e: Indicates the value after a cyclic update.
* Macro implementation: f(B, C, D) = (B AND C) OR (B AND D) OR (C AND D)
* e = S^5(A) + f(B, C, D) + E + W(i) + K(i)
* b = S^30(B)
* Function/Macro Call: CAL_B_E
*/
.macro DATA_COMPRE_40_59 a, b, c, d, e, wi, k, temp1, temp2, temp3, temp4
and \temp1, \b, \c // b&c
and \temp2, \b, \d // b&d
and \temp3, \c, \d // c&d
orr \temp1, \temp1, \temp2 // (b&c) or (b&d)
orr \temp1, \temp1, \temp3 // f(B, C, D)
CAL_B_E \a, \b, \e, \wi, \k, \temp1, \temp3, \temp4
.endm
/**
* Function Description: Perform SHA1 compression calculation based on the input message and update the hash value.
* Function prototype: static const uint8_t *SHA1_Step(const uint8_t *input, uint32_t len, uint32_t *h)
* Input register:
* x0: Pointer to the input data address
* x1: Message length
* x2: Storage address of the hash value
* Register usage: w0–w15 store message blocks, x/w16, w17, w28, and w29 are temporary registers,
* and x30 stores the hash value address. a to e correspond to w20 to w24. w19 stores the k constant,
* x25 stores the message pointer, and x26 stores the remaining message length.
* Output register: x0 returns the address of the message for which sha1 calculation is not performed.
* Function/Macro Call: DATA_COMPRE_0_19、DATA_COMPRE_20_39_60_79、DATA_COMPRE_40_59、MESSAGE_EXPAND、SHA1CryptoExt
*/
.text
.balign 16
.global SHA1_Step
.type SHA1_Step, %function
SHA1_Step:
.inst 0xd503233f // paciasp
cmp x1, #64
b.lo .Lend_sha1
/* If the SHA1 cryptography extension instruction is supported, go to. */
adrp x5, g_cryptArmCpuInfo
add x5, x5, :lo12:g_cryptArmCpuInfo
ldr x6, [x5]
tst x6, #CRYPT_ARM_SHA1
bne SHA1CryptoExt
/* Extended instructions are not supported, Using Base Instructions, Open up stack space, push stack protection */
stp x29, x30, [sp, #-96]!
stp x19, x20, [sp, #8*2]
stp x21, x22, [sp, #8*4]
stp x23, x24, [sp, #8*6]
stp x25, x26, [sp, #8*8]
stp x27, x28, [sp, #8*10]
/* load a - e */
ldp w20, w21, [x2]
ldp w22, w23, [x2, #4*2]
ldr w24, [x2, #4*4]
mov x30, x2 // x30 address for storing hash values
mov x25, x0 // pointer to the x25 store message
mov x26, x1 // x26: stores the remaining message length.
.Lloop_sha1_compress:
adrp x16, g_k
add x16, x16, :lo12:g_k
ldr w19, [x16] // load k1
ldp w0, w1, [x25] // load input value, load 64 bytes at a time
ldp w2, w3, [x25, #4*2]
ldp w4, w5, [x25, #4*4]
ldp w6, w7, [x25, #4*6]
ldp w8, w9, [x25, #4*8]
ldp w10, w11, [x25, #4*10]
ldp w12, w13, [x25, #4*12]
ldp w14, w15, [x25, #4*14]
add x25, x25, #64 // address offset: 64 bytes
sub x26, x26, #64 // update the remaining address length.
#ifndef HITLS_BIG_ENDIAN
rev w0, w0
rev w1, w1
rev w2, w2
rev w3, w3
rev w4, w4
rev w5, w5
rev w6, w6
rev w7, w7
rev w8, w8
rev w9, w9
rev w10, w10
rev w11, w11
rev w12, w12
rev w13, w13
rev w14, w14
rev w15, w15
#endif
/* 0~19round data compression */
/* a, b, c, d, e, wi, k, temp1, temp2, temp3, temp4 */
DATA_COMPRE_0_19 w20, w21, w22, w23, w24, w0, w19, w16, w17, w28, w29
DATA_COMPRE_0_19 w24, w20, w21, w22, w23, w1, w19, w16, w17, w28, w29
DATA_COMPRE_0_19 w23, w24, w20, w21, w22, w2, w19, w16, w17, w28, w29
DATA_COMPRE_0_19 w22, w23, w24, w20, w21, w3, w19, w16, w17, w28, w29
DATA_COMPRE_0_19 w21, w22, w23, w24, w20, w4, w19, w16, w17, w28, w29
DATA_COMPRE_0_19 w20, w21, w22, w23, w24, w5, w19, w16, w17, w28, w29
DATA_COMPRE_0_19 w24, w20, w21, w22, w23, w6, w19, w16, w17, w28, w29
DATA_COMPRE_0_19 w23, w24, w20, w21, w22, w7, w19, w16, w17, w28, w29
DATA_COMPRE_0_19 w22, w23, w24, w20, w21, w8, w19, w16, w17, w28, w29
DATA_COMPRE_0_19 w21, w22, w23, w24, w20, w9, w19, w16, w17, w28, w29
DATA_COMPRE_0_19 w20, w21, w22, w23, w24, w10, w19, w16, w17, w28, w29
DATA_COMPRE_0_19 w24, w20, w21, w22, w23, w11, w19, w16, w17, w28, w29
DATA_COMPRE_0_19 w23, w24, w20, w21, w22, w12, w19, w16, w17, w28, w29
DATA_COMPRE_0_19 w22, w23, w24, w20, w21, w13, w19, w16, w17, w28, w29
DATA_COMPRE_0_19 w21, w22, w23, w24, w20, w14, w19, w16, w17, w28, w29
DATA_COMPRE_0_19 w20, w21, w22, w23, w24, w15, w19, w16, w17, w28, w29
/* Message block extension calculation wi_16, wi_14, wi_8, wi_3, temp1, temp2 */
MESSAGE_EXPAND w0, w2, w8, w13, w16, w17
DATA_COMPRE_0_19 w24, w20, w21, w22, w23, w0, w19, w16, w17, w28, w29
MESSAGE_EXPAND w1, w3, w9, w14, w16, w17
DATA_COMPRE_0_19 w23, w24, w20, w21, w22, w1, w19, w16, w17, w28, w29
MESSAGE_EXPAND w2, w4, w10, w15, w16, w17
DATA_COMPRE_0_19 w22, w23, w24, w20, w21, w2, w19, w16, w17, w28, w29
MESSAGE_EXPAND w3, w5, w11, w0, w16, w17
DATA_COMPRE_0_19 w21, w22, w23, w24, w20, w3, w19, w16, w17, w28, w29
/* 20~39 round data compression */
adrp x16, g_k
add x16, x16, :lo12:g_k
ldr w19, [x16, #4] // load k2
MESSAGE_EXPAND w4, w6, w12, w1, w16, w17
DATA_COMPRE_20_39_60_79 w20, w21, w22, w23, w24, w4, w19, w16, w17, w28, w29
MESSAGE_EXPAND w5, w7, w13, w2, w16, w17
DATA_COMPRE_20_39_60_79 w24, w20, w21, w22, w23, w5, w19, w16, w17, w28, w29
MESSAGE_EXPAND w6, w8, w14, w3, w16, w17
DATA_COMPRE_20_39_60_79 w23, w24, w20, w21, w22, w6, w19, w16, w17, w28, w29
MESSAGE_EXPAND w7, w9, w15, w4, w16, w17
DATA_COMPRE_20_39_60_79 w22, w23, w24, w20, w21, w7, w19, w16, w17, w28, w29
MESSAGE_EXPAND w8, w10, w0, w5, w16, w17
DATA_COMPRE_20_39_60_79 w21, w22, w23, w24, w20, w8, w19, w16, w17, w28, w29
MESSAGE_EXPAND w9, w11, w1, w6, w16, w17
DATA_COMPRE_20_39_60_79 w20, w21, w22, w23, w24, w9, w19, w16, w17, w28, w29
MESSAGE_EXPAND w10, w12, w2, w7, w16, w17
DATA_COMPRE_20_39_60_79 w24, w20, w21, w22, w23, w10, w19, w16, w17, w28, w29
MESSAGE_EXPAND w11, w13, w3, w8, w16, w17
DATA_COMPRE_20_39_60_79 w23, w24, w20, w21, w22, w11, w19, w16, w17, w28, w29
MESSAGE_EXPAND w12, w14, w4, w9, w16, w17
DATA_COMPRE_20_39_60_79 w22, w23, w24, w20, w21, w12, w19, w16, w17, w28, w29
MESSAGE_EXPAND w13, w15, w5, w10, w16, w17
DATA_COMPRE_20_39_60_79 w21, w22, w23, w24, w20, w13, w19, w16, w17, w28, w29
MESSAGE_EXPAND w14, w0, w6, w11, w16, w17
DATA_COMPRE_20_39_60_79 w20, w21, w22, w23, w24, w14, w19, w16, w17, w28, w29
MESSAGE_EXPAND w15, w1, w7, w12, w16, w17
DATA_COMPRE_20_39_60_79 w24, w20, w21, w22, w23, w15, w19, w16, w17, w28, w29
MESSAGE_EXPAND w0, w2, w8, w13, w16, w17
DATA_COMPRE_20_39_60_79 w23, w24, w20, w21, w22, w0, w19, w16, w17, w28, w29
MESSAGE_EXPAND w1, w3, w9, w14, w16, w17
DATA_COMPRE_20_39_60_79 w22, w23, w24, w20, w21, w1, w19, w16, w17, w28, w29
MESSAGE_EXPAND w2, w4, w10, w15, w16, w17
DATA_COMPRE_20_39_60_79 w21, w22, w23, w24, w20, w2, w19, w16, w17, w28, w29
MESSAGE_EXPAND w3, w5, w11, w0, w16, w17
DATA_COMPRE_20_39_60_79 w20, w21, w22, w23, w24, w3, w19, w16, w17, w28, w29
MESSAGE_EXPAND w4, w6, w12, w1, w16, w17
DATA_COMPRE_20_39_60_79 w24, w20, w21, w22, w23, w4, w19, w16, w17, w28, w29
MESSAGE_EXPAND w5, w7, w13, w2, w16, w17
DATA_COMPRE_20_39_60_79 w23, w24, w20, w21, w22, w5, w19, w16, w17, w28, w29
MESSAGE_EXPAND w6, w8, w14, w3, w16, w17
DATA_COMPRE_20_39_60_79 w22, w23, w24, w20, w21, w6, w19, w16, w17, w28, w29
MESSAGE_EXPAND w7, w9, w15, w4, w16, w17
DATA_COMPRE_20_39_60_79 w21, w22, w23, w24, w20, w7, w19, w16, w17, w28, w29
/* 40~59 round data compression */
adrp x16, g_k
add x16, x16, :lo12:g_k
ldr w19, [x16, #8] // load k3
MESSAGE_EXPAND w8, w10, w0, w5, w16, w17
DATA_COMPRE_40_59 w20, w21, w22, w23, w24, w8, w19, w16, w17, w28, w29
MESSAGE_EXPAND w9, w11, w1, w6, w16, w17
DATA_COMPRE_40_59 w24, w20, w21, w22, w23, w9, w19, w16, w17, w28, w29
MESSAGE_EXPAND w10, w12, w2, w7, w16, w17
DATA_COMPRE_40_59 w23, w24, w20, w21, w22, w10, w19, w16, w17, w28, w29
MESSAGE_EXPAND w11, w13, w3, w8, w16, w17
DATA_COMPRE_40_59 w22, w23, w24, w20, w21, w11, w19, w16, w17, w28, w29
MESSAGE_EXPAND w12, w14, w4, w9, w16, w17
DATA_COMPRE_40_59 w21, w22, w23, w24, w20, w12, w19, w16, w17, w28, w29
MESSAGE_EXPAND w13, w15, w5, w10, w16, w17
DATA_COMPRE_40_59 w20, w21, w22, w23, w24, w13, w19, w16, w17, w28, w29
MESSAGE_EXPAND w14, w0, w6, w11, w16, w17
DATA_COMPRE_40_59 w24, w20, w21, w22, w23, w14, w19, w16, w17, w28, w29
MESSAGE_EXPAND w15, w1, w7, w12, w16, w17
DATA_COMPRE_40_59 w23, w24, w20, w21, w22, w15, w19, w16, w17, w28, w29
MESSAGE_EXPAND w0, w2, w8, w13, w16, w17
DATA_COMPRE_40_59 w22, w23, w24, w20, w21, w0, w19, w16, w17, w28, w29
MESSAGE_EXPAND w1, w3, w9, w14, w16, w17
DATA_COMPRE_40_59 w21, w22, w23, w24, w20, w1, w19, w16, w17, w28, w29
MESSAGE_EXPAND w2, w4, w10, w15, w16, w17
DATA_COMPRE_40_59 w20, w21, w22, w23, w24, w2, w19, w16, w17, w28, w29
MESSAGE_EXPAND w3, w5, w11, w0, w16, w17
DATA_COMPRE_40_59 w24, w20, w21, w22, w23, w3, w19, w16, w17, w28, w29
MESSAGE_EXPAND w4, w6, w12, w1, w16, w17
DATA_COMPRE_40_59 w23, w24, w20, w21, w22, w4, w19, w16, w17, w28, w29
MESSAGE_EXPAND w5, w7, w13, w2, w16, w17
DATA_COMPRE_40_59 w22, w23, w24, w20, w21, w5, w19, w16, w17, w28, w29
MESSAGE_EXPAND w6, w8, w14, w3, w16, w17
DATA_COMPRE_40_59 w21, w22, w23, w24, w20, w6, w19, w16, w17, w28, w29
MESSAGE_EXPAND w7, w9, w15, w4, w16, w17
DATA_COMPRE_40_59 w20, w21, w22, w23, w24, w7, w19, w16, w17, w28, w29
MESSAGE_EXPAND w8, w10, w0, w5, w16, w17
DATA_COMPRE_40_59 w24, w20, w21, w22, w23, w8, w19, w16, w17, w28, w29
MESSAGE_EXPAND w9, w11, w1, w6, w16, w17
DATA_COMPRE_40_59 w23, w24, w20, w21, w22, w9, w19, w16, w17, w28, w29
MESSAGE_EXPAND w10, w12, w2, w7, w16, w17
DATA_COMPRE_40_59 w22, w23, w24, w20, w21, w10, w19, w16, w17, w28, w29
MESSAGE_EXPAND w11, w13, w3, w8, w16, w17
DATA_COMPRE_40_59 w21, w22, w23, w24, w20, w11, w19, w16, w17, w28, w29
/* 60~79 round data compression */
adrp x16, g_k
add x16, x16, :lo12:g_k
ldr w19, [x16, #12] // load k4
MESSAGE_EXPAND w12, w14, w4, w9, w16, w17
DATA_COMPRE_20_39_60_79 w20, w21, w22, w23, w24, w12, w19, w16, w17, w28, w29
MESSAGE_EXPAND w13, w15, w5, w10, w16, w17
DATA_COMPRE_20_39_60_79 w24, w20, w21, w22, w23, w13, w19, w16, w17, w28, w29
MESSAGE_EXPAND w14, w0, w6, w11, w16, w17
DATA_COMPRE_20_39_60_79 w23, w24, w20, w21, w22, w14, w19, w16, w17, w28, w29
MESSAGE_EXPAND w15, w1, w7, w12, w16, w17
DATA_COMPRE_20_39_60_79 w22, w23, w24, w20, w21, w15, w19, w16, w17, w28, w29
MESSAGE_EXPAND w0, w2, w8, w13, w16, w17
DATA_COMPRE_20_39_60_79 w21, w22, w23, w24, w20, w0, w19, w16, w17, w28, w29
MESSAGE_EXPAND w1, w3, w9, w14, w16, w17
DATA_COMPRE_20_39_60_79 w20, w21, w22, w23, w24, w1, w19, w16, w17, w28, w29
MESSAGE_EXPAND w2, w4, w10, w15, w16, w17
DATA_COMPRE_20_39_60_79 w24, w20, w21, w22, w23, w2, w19, w16, w17, w28, w29
MESSAGE_EXPAND w3, w5, w11, w0, w16, w17
DATA_COMPRE_20_39_60_79 w23, w24, w20, w21, w22, w3, w19, w16, w17, w28, w29
MESSAGE_EXPAND w4, w6, w12, w1, w16, w17
DATA_COMPRE_20_39_60_79 w22, w23, w24, w20, w21, w4, w19, w16, w17, w28, w29
MESSAGE_EXPAND w5, w7, w13, w2, w16, w17
DATA_COMPRE_20_39_60_79 w21, w22, w23, w24, w20, w5, w19, w16, w17, w28, w29
MESSAGE_EXPAND w6, w8, w14, w3, w16, w17
DATA_COMPRE_20_39_60_79 w20, w21, w22, w23, w24, w6, w19, w16, w17, w28, w29
MESSAGE_EXPAND w7, w9, w15, w4, w16, w17
DATA_COMPRE_20_39_60_79 w24, w20, w21, w22, w23, w7, w19, w16, w17, w28, w29
MESSAGE_EXPAND w8, w10, w0, w5, w16, w17
DATA_COMPRE_20_39_60_79 w23, w24, w20, w21, w22, w8, w19, w16, w17, w28, w29
MESSAGE_EXPAND w9, w11, w1, w6, w16, w17
DATA_COMPRE_20_39_60_79 w22, w23, w24, w20, w21, w9, w19, w16, w17, w28, w29
MESSAGE_EXPAND w10, w12, w2, w7, w16, w17
DATA_COMPRE_20_39_60_79 w21, w22, w23, w24, w20, w10, w19, w16, w17, w28, w29
MESSAGE_EXPAND w11, w13, w3, w8, w16, w17
DATA_COMPRE_20_39_60_79 w20, w21, w22, w23, w24, w11, w19, w16, w17, w28, w29
MESSAGE_EXPAND w12, w14, w4, w9, w16, w17
DATA_COMPRE_20_39_60_79 w24, w20, w21, w22, w23, w12, w19, w16, w17, w28, w29
MESSAGE_EXPAND w13, w15, w5, w10, w16, w17
DATA_COMPRE_20_39_60_79 w23, w24, w20, w21, w22, w13, w19, w16, w17, w28, w29
MESSAGE_EXPAND w14, w0, w6, w11, w16, w17
DATA_COMPRE_20_39_60_79 w22, w23, w24, w20, w21, w14, w19, w16, w17, w28, w29
MESSAGE_EXPAND w15, w1, w7, w12, w16, w17
DATA_COMPRE_20_39_60_79 w21, w22, w23, w24, w20, w15, w19, w16, w17, w28, w29
/* load a - e */
ldp w0, w1, [x30]
ldp w2, w3, [x30, #4*2]
ldr w4, [x30, #4*4]
/* H0 = H0 + A, H1 = H1 + B, H2 = H2 + C, H3 = H3 + D, H4 = H4 + E */
add w20, w20, w0
add w21, w21, w1
add w22, w22, w2
add w23, w23, w3
add w24, w24, w4
stp w20, w21, [x30]
stp w22, w23, [x30, #4*2]
str w24, [x30, #4*4]
cmp x26, #64
b.hs .Lloop_sha1_compress
/* returns the address of the message for which SHA1 calculation is not performed. */
mov x0, x25
/* pop-stack */
ldp x19, x20, [sp, #8*2]
ldp x21, x22, [sp, #8*4]
ldp x23, x24, [sp, #8*6]
ldp x25, x26, [sp, #8*8]
ldp x27, x28, [sp, #8*10]
ldp x29, x30, [sp], #96
.Lend_sha1:
.inst 0xd50323bf // autiasp
ret
.size SHA1_Step, .-SHA1_Step
/**
* Function Description: Based on the input message, compress the SHA1 dedicated instruction and
* update the hash value.
* Function prototype: static const uint8_t *SHA1CryptoExt(const uint8_t *input, uint32_t len, uint32_t *h)
* Input register:
* x0: Pointer to the input data address
* x1: Message length
* x2: Storage address of the hash value
* Register usage: v0–v3 stores k0–k3, s5 stores e temporarily, v6 stores abcd, and v7 stores e,
* V23–V26 stores w0–w15 and recycles w16–w79. V19–v22 stores w+k calculation results.
* V16 is used as the 0 register. v17 stores abcd and v18 stores e. v16 is used together with v6 and v7.
* Output register: x0 returns the address of the message for which sha1 calculation is not performed.
* Function/Macro Call: NONE
*/
.text
.balign 16
.type SHA1CryptoExt, %function
SHA1CryptoExt:
/* load k */
adrp x3, g_kExt
add x3, x3, :lo12:g_kExt
ld1 {v0.4s-v3.4s}, [x3]
/* load a - e */
ld1 {v17.4s}, [x2]
ld1 {v6.4s}, [x2], #16
ld1 {v18.s}[0], [x2]
ld1 {v7.s}[0], [x2]
sub x2, x2, #16
eor v16.16b, v16.16b, v16.16b
.Lloop_sha1_ext_compress:
/* load w */
ld1 {v23.4s-v26.4s}, [x0], #64
sub x1, x1, #64 // update the remaining address length.
/* little endian inversion */
#ifndef HITLS_BIG_ENDIAN
rev32 v23.16b, v23.16b
rev32 v24.16b, v24.16b
rev32 v25.16b, v25.16b
rev32 v26.16b, v26.16b
#endif
add v19.4s, v0.4s, v23.4s // k0+w[3:0]
add v20.4s, v0.4s, v24.4s // k0+w[4:7]
add v21.4s, v0.4s, v25.4s // k0+w[11:8]
add v22.4s, v0.4s, v26.4s // k0+w[15:12]
/* [0:16] data compression */
sha1su0 v23.4s, v24.4s, v25.4s // w[16:20]
sha1h s5, s6 // a -> e
sha1c q6, s7, v19.4s // a, b, c, d -> a, b, c, d
sha1su1 v23.4s, v26.4s
sha1su0 v24.4s, v25.4s, v26.4s
sha1h s7, s6
sha1c q6, s5, v20.4s
sha1su1 v24.4s, v23.4s
sha1su0 v25.4s, v26.4s, v23.4s
sha1h s5, s6
sha1c q6, s7, v21.4s
sha1su1 v25.4s, v24.4s
sha1su0 v26.4s, v23.4s, v24.4s
sha1h s7, s6
sha1c q6, s5, v22.4s
sha1su1 v26.4s, v25.4s
add v19.4s, v0.4s, v23.4s // k0+w[19:16]
add v20.4s, v1.4s, v24.4s // k1+w[23:20]
add v21.4s, v1.4s, v25.4s // k1+w[27:24]
add v22.4s, v1.4s, v26.4s // k1+w[31:28]
/* [16:20] data compression */
sha1su0 v23.4s, v24.4s, v25.4s
sha1h s5, s6
sha1c q6, s7, v19.4s
sha1su1 v23.4s, v26.4s
/* [20:40] data compression */
sha1su0 v24.4s, v25.4s, v26.4s
sha1h s7, s6
sha1p q6, s5, v20.4s
sha1su1 v24.4s, v23.4s
sha1su0 v25.4s, v26.4s, v23.4s
sha1h s5, s6
sha1p q6, s7, v21.4s
sha1su1 v25.4s, v24.4s
sha1su0 v26.4s, v23.4s, v24.4s
sha1h s7, s6
sha1p q6, s5, v22.4s
sha1su1 v26.4s, v25.4s
add v19.4s, v1.4s, v23.4s // k1+w[35:32]
add v20.4s, v1.4s, v24.4s // k1+w[39:36]
add v21.4s, v2.4s, v25.4s // k2+w[43:40]
add v22.4s, v2.4s, v26.4s // k2+w[47:44]
sha1su0 v23.4s, v24.4s, v25.4s
sha1h s5, s6
sha1p q6, s7, v19.4s
sha1su1 v23.4s, v26.4s
sha1su0 v24.4s, v25.4s, v26.4s
sha1h s7, s6
sha1p q6, s5, v20.4s
sha1su1 v24.4s, v23.4s
/* [40:60] data compression */
sha1su0 v25.4s, v26.4s, v23.4s
sha1h s5, s6
sha1m q6, s7, v21.4s
sha1su1 v25.4s, v24.4s
sha1su0 v26.4s, v23.4s, v24.4s
sha1h s7, s6
sha1m q6, s5, v22.4s
sha1su1 v26.4s, v25.4s
add v19.4s, v2.4s, v23.4s // k2+w[51:48]
add v20.4s, v2.4s, v24.4s // k2+w[55:52]
add v21.4s, v2.4s, v25.4s // k2+w[59:56]
add v22.4s, v3.4s, v26.4s // k3+w[63:60]
sha1su0 v23.4s, v24.4s, v25.4s
sha1h s5, s6
sha1m q6, s7, v19.4s
sha1su1 v23.4s, v26.4s
sha1su0 v24.4s, v25.4s, v26.4s
sha1h s7, s6
sha1m q6, s5, v20.4s
sha1su1 v24.4s, v23.4s
sha1su0 v25.4s, v26.4s, v23.4s
sha1h s5, s6
sha1m q6, s7, v21.4s
sha1su1 v25.4s, v24.4s
/* [60:80] data compression */
sha1su0 v26.4s, v23.4s, v24.4s
sha1h s7, s6
sha1p q6, s5, v22.4s
sha1su1 v26.4s, v25.4s
add v19.4s, v3.4s, v23.4s // k3+w[67:64]
add v20.4s, v3.4s, v24.4s // k3+w[71:68]
add v21.4s, v3.4s, v25.4s // k3+w[75:72]
add v22.4s, v3.4s, v26.4s // k3+w[79:76]
sha1h s5, s6
sha1p q6, s7, v19.4s
sha1h s7, s6
sha1p q6, s5, v20.4s
sha1h s5, s6
sha1p q6, s7, v21.4s
sha1h s7, s6
sha1p q6, s5, v22.4s
/* calculate H0 H1 H2 H3 H4 */
add v17.4s, v17.4s, v6.4s
add v18.4s, v18.4s, v7.4s
add v6.4s, v17.4s, v16.4s
add v7.4s, v18.4s, v16.4s
cmp x1, #64
b.hs .Lloop_sha1_ext_compress
st1 {v17.4s}, [x2], #16
st1 {v18.s}[0], [x2]
ret
.size SHA1CryptoExt, .-SHA1CryptoExt
#endif
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha1/src/asm/sha1_armv8.S | Motorola 68K Assembly | unknown | 24,861 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SHA1
.file "sha1_x86_64.S"
.text
.set INPUT, %rdi
.set LEN, %rsi
.set HASH, %rdx
.set A, %r8d
.set B, %r9d
.set C, %r10d
.set D, %r11d
.set E, %r12d
.set TEMP, %r13d
.set TEMP1, %r15d
.set TEMP2, %ebx
.set TEMP3, %eax
.set BLK0, %xmm0
.set BLK1, %xmm1
.set BLK2, %xmm2
.set BLK3, %xmm3
.set ZERO, %ymm4
.set EXPAND0, %ymm5
.set EXPAND1, %ymm6
.set EXPAND2, %ymm7
.set EXPAND3, %ymm8
.set TEMP_W0, %ymm9
.set TEMP_W1, %ymm10
.set TEMP_W2, %ymm11
.set KNUM, %ymm12
/* sha1 constant value used */
.section .rodata
.balign 64
.type g_k, %object
g_k:
.long 0x5a827999, 0x5a827999, 0x5a827999, 0x5a827999, 0x5a827999, 0x5a827999, 0x5a827999, 0x5a827999 // K_00_19
.long 0x6ed9eba1, 0x6ed9eba1, 0x6ed9eba1, 0x6ed9eba1, 0x6ed9eba1, 0x6ed9eba1, 0x6ed9eba1, 0x6ed9eba1 // K_20_39
.long 0x8f1bbcdc, 0x8f1bbcdc, 0x8f1bbcdc, 0x8f1bbcdc, 0x8f1bbcdc, 0x8f1bbcdc, 0x8f1bbcdc, 0x8f1bbcdc // K_40_59
.long 0xca62c1d6, 0xca62c1d6, 0xca62c1d6, 0xca62c1d6, 0xca62c1d6, 0xca62c1d6, 0xca62c1d6, 0xca62c1d6 // K_60_79
.size g_k, .-g_k
/* inverted mask */
.balign 64
.type endian_mask, %object
endian_mask:
.long 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f
.long 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f
.size endian_mask, .-endian_mask
/**
* Macro Description: Message compression, 0 to 18 rounds of data compression, pre-computation Next round F0, b
* Input register:
*a - e, temp: Intermediate variable of hash value
* addr: Stack Address, Kt+W
* wkOffset: Kt+W read Offset
* temp1-2: temporary register
* Modify the register: a e temp temp1 temp2
* Output register:
* a: Next round F0
* e: Indicates the value after a cyclic update.
* temp: Next round B
* Macro implementation: F0(b,c,d) = (b AND c) OR ((NOT b) AND d)
* =(((b) & (c)) | ((~(b)) & (d)))
* e = S^5(a) + F0(b,c,d) + e + W(i) + K(i)
* temp = S^30(b)
*/
.macro ROUND00_18 a, temp, b, c, d, e, addr, wkOffset, temp1, temp2
addl \wkOffset(\addr), \e // e = e + W + KT
andn \c, \a, \temp1 // Next (~(b)) & (d)
addl \temp, \e // e = F0(b, c, d) + e + W + KT
rorxl $27, \a, \temp2 // Temp2 = ROTL32(a, 5)
rorxl $2, \a, \temp // Next ROTL32(b, 30)
and \b, \a // Next ((b) & (c))
addl \temp2, \e // e = F0(b, c, d) + e + W + KT + S^5(a)
or \temp1, \a // Next (((b) & (c)) | ((~(b)) & (d)))
.endm
/**
* Macro Description: 0 to 18 rounds of message compression and 16 to 31 message extension,
* pre-calculation Next round F0, b
* Input register:
*a - e, temp: Intermediate variable of hash value
* addr: Stack Address, Kt+W
* wkOffset: Kt+W read offset
* temp1-2: temporary register
* wt_16_13: w(t-16) ~ w(t-13)
* wt_12_9: w(t-12) ~ w(t-9)
* wt_8_5: w(t-8) ~ w(t-5)
* wt_4_1: w(t-4) ~ w(t-1)
* expand0: w(t) ~ w(t+3)
* tempw0-2: temporary register
* zero: register with a value of zero
* knum: k constant value
* Modify the register: a b c d e temp temp1 temp2 expand0 tempw0 tempw1 tempw2
* Output register:
* a: Third round B
* b: Value after four rounds of cyclic update
* c: Next round F0
* d: Next round B
* e: Fourth round B
* temp: next b
* expand0: Value after a round of extension
* Macro implementation: f(b,c,d) = (b AND c) OR ((NOT b) AND d)
* =(((b) & (c)) | ((~(b)) & (d)))
* temp = S^5(a) + f(b,c,d) + e + W(i) + K(i)
* b = S^30(b)
* W(t ) = ROL(W(t-3) ^ W(t-8) ^ W(t-14) ^ W(t-16), 1)
* W(t+1) = ROL(W(t-2) ^ W(t-7) ^ W(t-13) ^ W(t-15), 1)
* W(t+2) = ROL(W(t-1) ^ W(t-6) ^ W(t-12) ^ W(t-14), 1)
* W(t+3) = ROL(0 ^ W(t-5) ^ W(t-11) ^ W(t-13), 1)
* W(t+3) = W(t+3) ^ ROL(W(t), 1)
*/
.macro ROUND00_18_EXPAND a, temp, b, c, d, e, addr, wkOffset, wt_16_13, wt_12_9, wt_8_5, wt_4_1, expand0
vpalignr $8, \wt_16_13, \wt_12_9, TEMP_W1 // Expand w(t-14) w(t-13) w(t-12) w(t-11)
addl \wkOffset(\addr), \e // e = e + W + KT
andn \c, \a, TEMP1 // Next (~(b)) & (d)
addl \temp, \e // e = F0 + e + W + KT
vpalignr $4, \wt_4_1, ZERO, TEMP_W0 // Expand w(t-3) w(t-2) w(t-1) 0
vpxor \wt_8_5, \wt_16_13, \expand0 // Expand w(t-8) ^ w(t-16)
rorxl $27, \a, TEMP2 // Temp2 = ROTL32(a, 5)
rorxl $2, \a, \temp // Next ROTL32(b, 30)
and \b, \a // Next ((b) & (c))
vpxor TEMP_W1, \expand0, \expand0 // Expand w(t-14) ^ w(t-8) ^ w(t-16)
addl TEMP2, \e // e = F0 + e + W + KT + S^5(a)
or TEMP1, \a // Next F0 done
addl \wkOffset + 4(\addr), \d // Next d = d + W + KT
vpxor TEMP_W0, \expand0, TEMP_W0 // Expand tempw0 = w[t:t+4] before rol 1
andn \b, \e, TEMP1 // Next F0
addl \a, \d // d = F0 + d + W + KT
rorxl $27, \e, TEMP2 // Temp2 = ROTL32(E, 5)
rorxl $2, \e, \a // next ROTL32(E, 30)
vpalignr $4, ZERO, TEMP_W0, TEMP_W1 // Expand tempw1 = 0 0 0 w(t)
and \temp, \e // Next F0
addl TEMP2, \d // d = F0 + d + W + KT + S^5(E)
or TEMP1, \e // Next F0 done
vpsrld $31, TEMP_W0, \expand0 // Expand ROL(w(t), w(t+1), w(t+2), w(t+3),1)
addl \wkOffset + 8(\addr), \c // c = c + W + KT
vpaddd TEMP_W0, TEMP_W0, TEMP_W0 // Expand ROL(w(t), w(t+1), w(t+2), w(t+3),1)
andn \temp, \d, TEMP1 // Next F0
addl \e, \c // c = F0 + c + W + KT
rorxl $27, \d, TEMP2 // Temp2 = ROTL32(D, 5)
rorxl $2, \d, \e // Next ROTL32(D, 30)
vpsrld $30, TEMP_W1, TEMP_W2 // Expand ROL(w(t), 2)
and \a, \d // Next F0
addl TEMP2, \c // c = F0 + c + W + KT + S^5(D)
or TEMP1, \d // Next F0 done
vpslld $2, TEMP_W1, TEMP_W1 // Expand ROL(w(t), 2)
vpxor \expand0, TEMP_W0, \expand0 // Expand ROL(w(t), w(t+1), w(t+2), w(t+3),1)
addl \wkOffset + 12(\addr), \b // b = b + W + KT
andn \a, \c, TEMP1 // Next F0
vpxor TEMP_W2, TEMP_W1, TEMP_W0 // Expand ROL(w(t), 2)
addl \d, \b // b = F0 + b + W + KT
rorxl $27, \c, TEMP2 // Temp2 = ROTL32(C, 5)
rorxl $2, \c, \d // Next ROTL32(C, 30)
vpxor \expand0, TEMP_W0, \expand0 // Expand w[t:t+4]
and \e, \c // Next F0
addl TEMP2, \b // b = F0 + b + W + KT + S^5(C)
vpaddd KNUM,\expand0, TEMP_W0 // Expand w + k
or TEMP1, \c // Next F0 done
vmovdqa TEMP_W0, \wkOffset + 128(\addr)
.endm
/**
* Macro Description: Message compression, 20~39, 60~79 round data compression, precomputation Next round F1, b
* Input register:
*a - e, temp: Intermediate variable of hash value
* addr: Stack Address, Kt+W
* wkOffset: Kt+W read offset
* temp1-2: temporary register
* Modify the register: a e temp temp1 temp2
* Output register:
* a: Next round F1
* e: Indicates the value after a cyclic update.
* temp: Next round B
* Macro implementation: F1(b,c,d) = b XOR c XOR d
* =(((b) ^ (c)) ^ (d))
* e = S^5(a) + F1(b,c,d) + e + W(i) + K(i)
* temp = S^30(b)
*/
.macro ROUND20_39 a, temp, b, c, d, e, addr, wkOffset, temp1, temp2
addl \wkOffset(\addr), \e // e = e + W + KT
addl \temp, \e // e = F1(b, c, d) + e + W + KT
rorx $27, \a, TEMP2 // Temp2 = ROTL32(a, 5)
rorx $2, \a, \temp // Next ROTL32(b, 30)
xor \b, \a // Next (b) ^ (c)
addl TEMP2, \e // e = F0(b, c, d) + e + W + KT + S^5(a)
xor \c, \a // Next (b) ^ (c) ^ (d)
.endm
/**
* Macro Description: 20~39, 60~79 round data compression, and 16-31 message extension, precomputation Next round F1, b
* Input register:
*a - e, temp: Intermediate variable of hash value
* addr: Stack Address, Kt+W
* wkOffset: Kt+W read offset
* temp1-2: temporary register
* wt_32_29: w(t-32) ~ w(t-29)
* wt_28_25: w(t-28) ~ w(t-25)
* wt_8_5: w(t-8) ~ w(t-5)
* wt_4_1: w(t-4) ~ w(t-1)
* expand0: w(t) ~ w(t+3)
* zero: register with a value of zero
* knum: k constant value
* Modify the register: a b c d e temp temp1 temp2 wt_32_29 tempw0
* Output register:
* a: Third round B value
* b: Value after four rounds of cyclic update
* c: Next round F1
* d: Next round B
* e: Fourth round B value
* temp: next b
* expand0: Value after a round of extension
* Macro implementation: F1(b,c,d) = b XOR c XOR d
* =(((b) ^ (c)) ^ (d))
* e = S^5(a) + F1(b,c,d) + e + W(i) + K(i)
* temp = S^30(b)
* w(t) = ROL(w(t-3) ^ w(t-8) ^ w(t-14) ^ w(t-16), 1)
* = ROL(w(t-6) ^ w(t-11) ^ w(t-17) ^ w(t-19) ^
* w(t-11) ^ w(t-16) ^ w(t-22) ^ w(t-24) ^
* w(t-17) ^ w(t-22) ^ w(t-28) ^ w(t-30) ^
* w(t-19) ^ w(t-24) ^ w(t-30) ^ w(t-32), 2)
* = ROL(w(t-6) ^ w(t-16) ^ w(t-28) ^ w(t-32), 2)
* w(t+1), w(t+2), w(t+3) in the same way
*/
.macro ROUND20_39_EXPAND a, temp, b, c, d, e, addr, wkOffset, wt_32_29, wt_28_25, wt_16_13, wt_8_5, wt_4_1, wkOffset2
vpalignr $8, \wt_8_5, \wt_4_1, TEMP_W0 // Expand w(t-6), w(t-5), w(t-4), w(t-3)
vpxor \wt_32_29, \wt_16_13, \wt_32_29 // Expand wt_32_29 =w[t-32:t-28] ^ w[t-16:t-12]
addl \wkOffset(\addr), \e // e = e + W + KT
addl \temp, \e // e = F1(b, c, d) + e + W + KT
rorx $27, \a, TEMP2 // temp2 = ROTL32(a, 5)
rorx $2, \a, \temp // Next ROTL32(b, 30)
vpxor \wt_32_29, \wt_28_25, \wt_32_29 // Expand wt_32_29 =w[t-32:t-28] ^ w[t-16:t-12]^ w[t-28:t-24]
xor \b, \a // Next (b) ^ (c)
addl TEMP2, \e // e = F0(b, c, d) + e + W + KT + S^5(a)
xor \c, \a // Next F1 done
addl \wkOffset + 4(\addr), \d // d = d + W + KT
vpxor \wt_32_29, TEMP_W0, \wt_32_29 // Expand wt_32_29 =w[t-32] ^ w[t-16]^ w[t-28]^ w[t-6]
addl \a, \d // d = F1 + d + W + KT
rorx $27, \e, TEMP2 // Temp2 = ROTL32(e, 5)
rorx $2, \e, \a // Next temp = ROTL32(e, 30)
xor \temp, \e // Next F1
addl TEMP2, \d // Expand d = F1 + d + W + KT + S^5(e)
vpsrld $30, \wt_32_29, TEMP_W0 // Expand ROL(wt_32_29,2)
xor \b, \e // Next F1 done
addl \wkOffset + 8(\addr), \c // c = c + W + KT
addl \e, \c // c = F1 + c + W + KT
rorx $27, \d, TEMP2 // Temp2 = ROTL32(e, 5)
rorx $2, \d, \e // Next ROTL32(e, 30)
vpslld $2, \wt_32_29, \wt_32_29
xor \a, \d // Next F1
addl TEMP2, \c // c = F1 + c + W + KT + S^5(e)
xor \temp, \d // Next F1 done
addl \wkOffset + 12(\addr), \b // b = b + W + KT
vpxor \wt_32_29, TEMP_W0, \wt_32_29 // Expand ROL(wt_32_29,2)
rorx $27, \c, TEMP2 // Temp2 = ROTL32(c, 5)
addl \d, \b // b = F1 + b + W + KT
rorx $2, \c, \d // Next ROTL32(c, 30)
vpaddd KNUM, \wt_32_29, TEMP_W0
xor \e, \c // Next F1
addl TEMP2, \b // b = F1 + b + W + KT + S^5(c)
xor \a, \c // Next F1 done
vmovdqa TEMP_W0, \wkOffset2(\addr)
.endm
/**
* Macro Description: Message compression, 40~59 round data compression, pre-computation Next round F2, b
* Input register:
*a - e, temp: Intermediate variable of hash value
* addr: Stack Address, Kt+W
* wkOffset: Kt+W read offset
* temp1-2: temporary register
* Modify the register: a e temp temp1 temp2
* Output register:
* a: Next round F1
* e: Indicates the value after a cyclic update.
* temp: Next round B
* Macro implementation: F1(b,c,d) = (b AND c) OR (b AND d) OR (c AND d)
* =((b^c) & (c^d) ^ c)
* e = S^5(a) + F1(b,c,d) + e + W(i) + K(i)
* temp = S^30(b)
*/
.macro ROUND40_59 a, temp, b, c, d, e, addr, wkOffset, temp1, temp2
addl \wkOffset(\addr), \e // e = e + W + KT
mov \c, \temp1
addl \temp, \e // e = F2(b, c, d) + e + W + KT
xor \b, \temp1 // Next (c^d)
rorx $27, \a, \temp2 // Temp2 = ROTL32(a, 5)
rorx $2, \a, \temp // Next ROTL32(b, 30)
xor \b, \a // Next (b^c)
addl \temp2, \e // e = F0(b, c, d) + e + W + KT + S^5(a)
and \temp1, \a // Next (b^c) & (c^d)
xor \b, \a // Next (((b^c)) & (c^d) ^ c)
.endm
/**
* Macro Description: 40~59 round data compression, and 32 to 79 rounds of message extension,
* precomputation Next round F2, b
* Input register:
*a - e, temp: Intermediate variable of hash value
* addr: Stack Address, Kt+W
* wkOffset: Kt+W read offset
* temp1-2: temporary register
* wt_32_29: w(t-32) ~ w(t-29)
* wt_28_25: w(t-28) ~ w(t-25)
* wt_8_5: w(t-8) ~ w(t-5)
* wt_4_1: w(t-4) ~ w(t-1)
* expand0: w(t) ~ w(t+3)
* zero: register with a value of zero
* knum: k constant value
* Modify the register: a b c d e temp temp1 temp2 wt_32_29 tempw0
* Output register:
* a: Third round B value
* b: Value after four rounds of cyclic update
* c: Next round F1
* d: Next round B
* e: Fourth round B value
* temp: next b
* expand0: Value after a round of extension
* Macro implementation: F1(b,c,d) = (b AND c) OR (b AND d) OR (c AND d)
* =((b^c) & (c^d) ^ c)
* e = S^5(a) + F1(b,c,d) + e + W(i) + K(i)
* w(t) = ROL(w(t-3) ^ w(t-8) ^ w(t-14) ^ w(t-16), 1)
* = ROL(w(t-6) ^ w(t-11) ^ w(t-17) ^ w(t-19) ^
* w(t-11) ^ w(t-16) ^ w(t-22) ^ w(t-24) ^
* w(t-17) ^ w(t-22) ^ w(t-28) ^ w(t-30) ^
* w(t-19) ^ w(t-24) ^ w(t-30) ^ w(t-32), 2)
* = ROL(w(t-6) ^ w(t-16) ^ w(t-28) ^ w(t-32), 2)
* w(t+1), w(t+2), w(t+3) in the same way
*/
.macro ROUND40_59_EXPAND a, temp, b, c, d, e, addr, wkOffset, wt_32_29, wt_28_25, wt_16_13, wt_8_5, wt_4_1, wkOffset2
vpalignr $8, \wt_8_5, \wt_4_1, TEMP_W0 // Expand w(t-6), w(t-5), w(t-4), w(t-3)
vpxor \wt_32_29, \wt_16_13, \wt_32_29 // Expand wt_32_29 =w[t-32:t-28] ^ w[t-16:t-12]
addl \wkOffset(\addr), \e // e = e + W + KT
mov \c, TEMP1
addl \temp, \e // e = F2(b, c, d) + e + W + KT
xor \b, TEMP1 // Next temp1 = (c^d)
rorx $27, \a, TEMP2 // Temp2 = ROTL32(a, 5)
rorx $2, \a, \temp // Next ROTL32(b, 30)
vpxor \wt_32_29, \wt_28_25, \wt_32_29 // Expand wt_32_29 =w[t-32:t-28] ^ w[t-16:t-12]^ w[t-28:t-24]
xor \b, \a // Next (b^c)
addl TEMP2, \e // e = F0(b, c, d) + e + W + KT + S^5(a)
and TEMP1, \a // Next (b^c) & (c^d)
addl \wkOffset + 4(\addr), \d // d = d + W + KT
xor \b, \a // Next (((b^c)) & (c^d) ^ c)
vpxor \wt_32_29, TEMP_W0, \wt_32_29 // Expand wt_32_29 =w[t-32] ^ w[t-16]^ w[t-28]^ w[t-6]
mov \b, TEMP1
addl \a, \d // d = F2 + d + W + KT
xor \temp, TEMP1 // Next F2
rorx $27, \e, TEMP2 // Temp2 = ROTL32(e, 5)
rorx $2, \e, \a // Next ROTL32(e, 30)
addl \wkOffset + 8(\addr), \c // c = c + W + KT
xor \temp, \e // Next F2
vpsrld $30, \wt_32_29, TEMP_W0 // Expand ROL(wt_32_29,2)
and TEMP1, \e // Next F2
addl TEMP2, \d // d = F2 + d + W + KT + S^5(e)
xor \temp, \e // Next F2 done
mov \temp, TEMP1
addl \e, \c // c = F2 + c + W + KT
xor \a, TEMP1 // Next F2
vpslld $2, \wt_32_29, \wt_32_29
rorx $27, \d, TEMP2 // Temp2 = ROTL32(d, 5)
rorx $2, \d, \e // Next ROTL32(d, 30)
xor \a, \d // Next F2
addl TEMP2, \c // c = F2 + c + W + KT + S^5(d)
and TEMP1, \d // Next F2
addl \wkOffset + 12(\addr), \b // b = b + W + KT
vpxor \wt_32_29, TEMP_W0, \wt_32_29 // Expand ROL(wt_32_29,2)
xor \a, \d // Next F2 done
mov \a, TEMP1
addl \d, \b // b = F2 + b + W + KT
xor \e, TEMP1 // Next F2
rorx $27, \c, TEMP2 // Temp2 = ROTL32(c, 5)
rorx $2, \c, \d // Next ROTL32(c, 30)
xor \e, \c // Next F2
vpaddd KNUM, \wt_32_29, TEMP_W0
addl TEMP2, \b // b = F2 + b + W + KT + S^5(c)
and TEMP1, \c // Next F2
xor \e, \c // Next F2 done
vmovdqa TEMP_W0, \wkOffset2(\addr)
.endm
/**
* Function Description: Perform SHA1 compression calculation based on the input message and update the hash value.
* Function prototype: static const uint8_t *SHA1_Step(const uint8_t *input, uint32_t len, uint32_t *h)
* Input register:
* rdi: Pointer to the input data address
* rsi: Message length
* rdx: Storage address of the hash value
* Register usage: r8~r12: A~E, r13: TEMP, r15, ebx, eax: temporary register, ymm0~ymm3: w0~w15 Message block,
* ymm4: 0, ymm5~ymm8: extended message block, ymm9~ymm13: temporary register, ymm13: k+w value
* Output register: rax Returns the address of the message for which SHA1 calculation is not performed.
* Function/Macro Call: ROUND00_18, ROUND00_18_EXPAND, ROUND20_39, ROUND20_39_EXPAND, ROUND40_59, ROUND40_59_EXPAND
*/
.text
.globl SHA1_Step
.type SHA1_Step, @function
SHA1_Step:
.cfi_startproc
cmp $64, LEN
jb .Lend_sha1
push %rbx
push %rbp
push %r12
push %r13
push %r14
push %r15
mov %rsp, %r14
lea -1024(%rsp), %rsp // Apply for 1024-byte stack space.
mov 0(HASH), A // r8~r13: a~e
mov 4(HASH), B
andq $-256, %rsp
mov 8(HASH), C
mov 12(HASH), D
mov 16(HASH), E
.Lloop_sha1_compress:
.align 16
vmovdqu (INPUT), BLK0 // Loads the data of a block to the lower 128 bits
// of the YMM register.
vmovdqu 16(INPUT), BLK1
vmovdqu 32(INPUT), BLK2
sub $64, LEN
vmovdqu 48(INPUT), BLK3
add $64, INPUT
cmp $64, LEN // Check whether the remaining length is greater than 64.
jb .Lsha1_compress
vinserti128 $1, 0(INPUT), %ymm0, %ymm0 // Loads the data of a block to the upper 128 bits
// of the ymm register.
vinserti128 $1, 16(INPUT), %ymm1, %ymm1
vinserti128 $1, 32(INPUT), %ymm2, %ymm2
vinserti128 $1, 48(INPUT), %ymm3, %ymm3
add $64, INPUT
.Lsha1_compress:
vmovdqa endian_mask + 0(%rip), %ymm8 // Endian inversion mask
leaq g_k + 0(%rip), %rbp // Get k
vpshufb %ymm8, %ymm0, %ymm0 // Little endian to big endian
vmovdqa 0(%rbp), KNUM
vpshufb %ymm8, %ymm1, %ymm1
vpaddd KNUM, %ymm0, %ymm13 // w[0:15] + k0
vpshufb %ymm8, %ymm2, %ymm2
vmovdqa %ymm13, 0(%rsp) // wk push stack
vpaddd KNUM, %ymm1, %ymm9
vpshufb %ymm8, %ymm3, %ymm3
vmovdqa %ymm9, 32(%rsp)
vpaddd KNUM, %ymm2, %ymm10
vpxor %ymm4, %ymm4, %ymm4
mov C, TEMP // The first round F0
vmovdqa %ymm10, 64(%rsp)
and B, TEMP // Round0 ((b) & (c))
andn D, B, TEMP2 // Round0 (~(b)) & (d)
vpaddd KNUM, %ymm3, %ymm11
or TEMP2, TEMP // Round0 (((b) & (c)) | ((~(b)) & (d)))
rol $30, B // Round0 B = ROTL32(B, 30)
vmovdqa %ymm11, 96(%rsp)
ROUND00_18_EXPAND A, TEMP, B, C, D, E, %rsp, 0, %ymm0, %ymm1, %ymm2, %ymm3, EXPAND0
vmovdqa 32(%rbp), KNUM
ROUND00_18_EXPAND B, C, D, E, A, TEMP, %rsp, 32, %ymm1, %ymm2, %ymm3, EXPAND0, EXPAND1
ROUND00_18_EXPAND D, E, A, TEMP, B, C, %rsp, 64, %ymm2, %ymm3, EXPAND0, EXPAND1, EXPAND2
ROUND00_18_EXPAND A, TEMP, B, C, D, E, %rsp, 96, %ymm3, EXPAND0, EXPAND1, EXPAND2, EXPAND3
ROUND00_18 B, C, D, E, A, TEMP, %rsp, 128, TEMP1, TEMP2
ROUND00_18 TEMP, B, C, D, E, A, %rsp, 132, TEMP1, TEMP2
ROUND00_18 A, TEMP, B, C, D, E, %rsp, 136, TEMP1, TEMP2 // 18
addl 140( %rsp), D // D = DE + W + KT
rorx $27, E, TEMP2 // TEMP2 = ROTL32(E, 5)
addl A, D // D = F0 + D + W + KT
rorx $2, E, A // Round20 ROTL32(E, 30)
xor TEMP, E // Round20 (TEMP) ^ (E)
addl TEMP2, D // D = F0 + D + W + KT + S^5(E)
xor B, E // Round20 F1
ROUND20_39_EXPAND D, E, A, TEMP, B, C, %rsp, 160, %ymm0, %ymm1, EXPAND0, EXPAND2, EXPAND3, 256
ROUND20_39_EXPAND A, TEMP, B, C, D, E, %rsp, 192, %ymm1, %ymm2, EXPAND1, EXPAND3, %ymm0, 288
vmovdqa 64(%rbp), KNUM
ROUND20_39_EXPAND B, C, D, E, A, TEMP, %rsp, 224, %ymm2, %ymm3, EXPAND2, %ymm0, %ymm1, 320
ROUND20_39_EXPAND D, E, A, TEMP, B, C, %rsp, 256, %ymm3, EXPAND0, EXPAND3, %ymm1, %ymm2, 352
ROUND20_39 A, TEMP, B, C, D, E, %rsp, 288, TEMP1, TEMP2
ROUND20_39 E, A, TEMP, B, C, D, %rsp, 292, TEMP1, TEMP2
ROUND20_39 D, E, A, TEMP, B, C, %rsp, 296, TEMP1, TEMP2 // 38
addl 300(%rsp), B // B = B + W + KT
mov A, TEMP1
addl D, B // B = F1 + B + W + KT
xor E, TEMP1 // Round40 (E^A)
rorx $27, C, TEMP2 // TEMP2 = ROTL32(C, 5)
rorx $2, C, D // Round40 ROTL32(C, 30)
xor E, C // Round40 (E^C)
addl TEMP2, B // B = F1 + B + W + KT + S^5(C)
and TEMP1, C // Round40 (E^A) & (E^C)
xor E, C // Round40 F2
ROUND40_59_EXPAND B, C, D, E, A, TEMP, %rsp, 320, EXPAND0, EXPAND1, %ymm0, %ymm2, %ymm3, 384
ROUND40_59_EXPAND D, E, A, TEMP, B, C, %rsp, 352, EXPAND1, EXPAND2, %ymm1, %ymm3, EXPAND0, 416
ROUND40_59_EXPAND A, TEMP, B, C, D, E, %rsp, 384, EXPAND2, EXPAND3, %ymm2, EXPAND0, EXPAND1, 448
vmovdqa 96(%rbp), KNUM
ROUND40_59_EXPAND B, C, D, E, A, TEMP, %rsp, 416, EXPAND3, %ymm0, %ymm3, EXPAND1, EXPAND2, 480
ROUND40_59 D, E, A, TEMP, B, C, %rsp, 448, TEMP1, TEMP2
ROUND40_59 C, D, E, A, TEMP, B, %rsp, 452, TEMP1, TEMP2
ROUND40_59 B, C, D, E, A, TEMP, %rsp, 456, TEMP1, TEMP2 // 58
addl 460(%rsp), A // A = A + W + KT
rorx $27, TEMP, TEMP2 // TEMP2 = ROTL32(TEMP, 5)
addl B, A // A = F2 + A + W + KT
rorx $2, TEMP, B // Round60 ROTL32(TEMP, 30)
xor C, TEMP // Round60 (C) ^ (TEMP)
addl TEMP2, A // A = F2 + A + W + KT + S^5(TEMP)
xor D, TEMP // Round60 F0
ROUND20_39_EXPAND A, TEMP, B, C, D, E, %rsp, 480, %ymm0, %ymm1, EXPAND0, EXPAND2, EXPAND3, 512
ROUND20_39_EXPAND B, C, D, E, A, TEMP, %rsp, 512, %ymm1, %ymm2, EXPAND1, EXPAND3, %ymm0, 544
ROUND20_39_EXPAND D, E, A, TEMP, B, C, %rsp, 544, %ymm2, %ymm3, EXPAND2, %ymm0, %ymm1, 576
ROUND20_39_EXPAND A, TEMP, B, C, D, E, %rsp, 576, %ymm3, EXPAND0, EXPAND3, %ymm1, %ymm2, 608
ROUND20_39 B, C, D, E, A, TEMP, %rsp, 608, TEMP1, TEMP2
ROUND20_39 TEMP, B, C, D, E, A, %rsp, 612, TEMP1, TEMP2
ROUND20_39 A, TEMP, B, C, D, E, %rsp, 616, TEMP1, TEMP2 // 78
addl 620(%rsp), D // D = D + W + KT
add E, 4(HASH) // Update HASH
lea (A, D), D // D = F1 + D + W + KT
add TEMP, 8(HASH)
rorx $27, E, TEMP2 // TEMP2 = ROTL32(E, 5)
add B, 12(HASH)
addl TEMP2, D // D = F1 + D + W + KT + S^5(E)
add C, 16(HASH)
mov 4(HASH), B
add D, 0(HASH)
mov 8(HASH), C
mov 16(HASH), E
mov 12(HASH), D
mov 0(HASH), A
cmp $64, LEN // Check whether the upper-bit register is calculated.
jb .Lend_sha1_pre
sub $64, LEN
mov C, TEMP
andn D, B, TEMP2 // TEMP2 = (~(b)) & (d)
and B, TEMP // TEMP=((b) & (c))
or TEMP2, TEMP // TEMP = (((b) & (c)) | ((~(b)) & (d)))
rol $30, B // B = ROTL32(B, 30)
ROUND00_18 A, TEMP, B, C, D, E, %rsp, 16, TEMP1, TEMP2
ROUND00_18 E, A, TEMP, B, C, D, %rsp, 20, TEMP1, TEMP2
ROUND00_18 D, E, A, TEMP, B, C, %rsp, 24, TEMP1, TEMP2
ROUND00_18 C, D, E, A, TEMP, B, %rsp, 28, TEMP1, TEMP2 // Round 3
ROUND00_18 B, C, D, E, A, TEMP, %rsp, 48, TEMP1, TEMP2
ROUND00_18 TEMP, B, C, D, E, A, %rsp, 52, TEMP1, TEMP2
ROUND00_18 A, TEMP, B, C, D, E, %rsp, 56, TEMP1, TEMP2
ROUND00_18 E, A, TEMP, B, C, D, %rsp, 60, TEMP1, TEMP2 // Round 7
ROUND00_18 D, E, A, TEMP, B, C, %rsp, 80, TEMP1, TEMP2
ROUND00_18 C, D, E, A, TEMP, B, %rsp, 84, TEMP1, TEMP2
ROUND00_18 B, C, D, E, A, TEMP, %rsp, 88, TEMP1, TEMP2
ROUND00_18 TEMP, B, C, D, E, A, %rsp, 92, TEMP1, TEMP2 // Round 11
ROUND00_18 A, TEMP, B, C, D, E, %rsp, 112, TEMP1, TEMP2
ROUND00_18 E, A, TEMP, B, C, D, %rsp, 116, TEMP1, TEMP2
ROUND00_18 D, E, A, TEMP, B, C, %rsp, 120, TEMP1, TEMP2
ROUND00_18 C, D, E, A, TEMP, B, %rsp, 124, TEMP1, TEMP2 // Round 15
ROUND00_18 B, C, D, E, A, TEMP, %rsp, 144, TEMP1, TEMP2
ROUND00_18 TEMP, B, C, D, E, A, %rsp, 148, TEMP1, TEMP2
ROUND00_18 A, TEMP, B, C, D, E, %rsp, 152, TEMP1, TEMP2 // Round 18
addl 156( %rsp), D // D = D + W + KT
rorx $27, E, TEMP2 // TEMP2 = ROTL32(E, 5)
addl A, D // D = F0 + D + W + KT
rorx $2, E, A // Round20 ROTL32(E, 30)
xor TEMP, E // Round20 (TEMP) ^ (E)
addl TEMP2, D // D = F0 + D + W + KT + S^5(E)
xor B, E // Round20 F1
ROUND20_39 D, E, A, TEMP, B, C, %rsp, 176, TEMP1, TEMP2
ROUND20_39 C, D, E, A, TEMP, B, %rsp, 180, TEMP1, TEMP2
ROUND20_39 B, C, D, E, A, TEMP, %rsp, 184, TEMP1, TEMP2
ROUND20_39 TEMP, B, C, D, E, A, %rsp, 188, TEMP1, TEMP2 // Round 23
ROUND20_39 A, TEMP, B, C, D, E, %rsp, 208, TEMP1, TEMP2
ROUND20_39 E, A, TEMP, B, C, D, %rsp, 212, TEMP1, TEMP2
ROUND20_39 D, E, A, TEMP, B, C, %rsp, 216, TEMP1, TEMP2
ROUND20_39 C, D, E, A, TEMP, B, %rsp, 220, TEMP1, TEMP2 // Round 27
ROUND20_39 B, C, D, E, A, TEMP, %rsp, 240, TEMP1, TEMP2
ROUND20_39 TEMP, B, C, D, E, A, %rsp, 244, TEMP1, TEMP2
ROUND20_39 A, TEMP, B, C, D, E, %rsp, 248, TEMP1, TEMP2
ROUND20_39 E, A, TEMP, B, C, D, %rsp, 252, TEMP1, TEMP2 // Round 31
ROUND20_39 D, E, A, TEMP, B, C, %rsp, 272, TEMP1, TEMP2
ROUND20_39 C, D, E, A, TEMP, B, %rsp, 276, TEMP1, TEMP2
ROUND20_39 B, C, D, E, A, TEMP, %rsp, 280, TEMP1, TEMP2
ROUND20_39 TEMP, B, C, D, E, A, %rsp, 284, TEMP1, TEMP2 // Round 35
ROUND20_39 A, TEMP, B, C, D, E, %rsp, 304, TEMP1, TEMP2
ROUND20_39 E, A, TEMP, B, C, D, %rsp, 308, TEMP1, TEMP2
ROUND20_39 D, E, A, TEMP, B, C, %rsp, 312, TEMP1, TEMP2 // Round 38
addl 316(%rsp), B // B = B + W + KT
mov A, TEMP1
addl D, B // B = F1 + B + W + KT
xor E, TEMP1 // Round40 (A^E)
rorx $2, C, D // Round40 ROTL32(C, 30)
rorx $27, C, TEMP2 // TEMP2 = ROTL32(C, 5)
xor E, C // Round40 (E^C)
addl TEMP2, B // B = F1 + B + W + KT + S^5(C)
and TEMP1, C // Round40 (A^E) & (E^C)
xor E, C // Round40 F2
ROUND40_59 B, C, D, E, A, TEMP, %rsp, 336, TEMP1, TEMP2
ROUND40_59 TEMP, B, C, D, E, A, %rsp, 340, TEMP1, TEMP2
ROUND40_59 A, TEMP, B, C, D, E, %rsp, 344, TEMP1, TEMP2
ROUND40_59 E, A, TEMP, B, C, D, %rsp, 348, TEMP1, TEMP2 // Round 43
ROUND40_59 D, E, A, TEMP, B, C, %rsp, 368, TEMP1, TEMP2
ROUND40_59 C, D, E, A, TEMP, B, %rsp, 372, TEMP1, TEMP2
ROUND40_59 B, C, D, E, A, TEMP, %rsp, 376, TEMP1, TEMP2
ROUND40_59 TEMP, B, C, D, E, A, %rsp, 380, TEMP1, TEMP2 // Round 47
ROUND40_59 A, TEMP, B, C, D, E, %rsp, 400, TEMP1, TEMP2
ROUND40_59 E, A, TEMP, B, C, D, %rsp, 404, TEMP1, TEMP2
ROUND40_59 D, E, A, TEMP, B, C, %rsp, 408, TEMP1, TEMP2
ROUND40_59 C, D, E, A, TEMP, B, %rsp, 412, TEMP1, TEMP2 // Round 51
ROUND40_59 B, C, D, E, A, TEMP, %rsp, 432, TEMP1, TEMP2
ROUND40_59 TEMP, B, C, D, E, A, %rsp, 436, TEMP1, TEMP2
ROUND40_59 A, TEMP, B, C, D, E, %rsp, 440, TEMP1, TEMP2
ROUND40_59 E, A, TEMP, B, C, D, %rsp, 444, TEMP1, TEMP2 // Round 55
ROUND40_59 D, E, A, TEMP, B, C, %rsp, 464, TEMP1, TEMP2
ROUND40_59 C, D, E, A, TEMP, B, %rsp, 468, TEMP1, TEMP2
ROUND40_59 B, C, D, E, A, TEMP, %rsp, 472, TEMP1, TEMP2 // Round 58
addl 476(%rsp), A // A = A + W + KT
rorx $27, TEMP, TEMP2 // TEMP2 = ROTL32(TEMP, 5)
addl B, A // A = F2 + A + W + KT
rorx $2, TEMP, B // Round60 ROTL32(TEMP, 30)
xor C, TEMP // Round60 (TEMP) ^ (c)
addl TEMP2, A // A = F2 + A + W + KT + S^5(TEMP)
xor D, TEMP // Round60 F1
ROUND20_39 A, TEMP, B, C, D, E, %rsp, 496, TEMP1, TEMP2
ROUND20_39 E, A, TEMP, B, C, D, %rsp, 500, TEMP1, TEMP2
ROUND20_39 D, E, A, TEMP, B, C, %rsp, 504, TEMP1, TEMP2
ROUND20_39 C, D, E, A, TEMP, B, %rsp, 508, TEMP1, TEMP2 // Round 63
ROUND20_39 B, C, D, E, A, TEMP, %rsp, 528, TEMP1, TEMP2
ROUND20_39 TEMP, B, C, D, E, A, %rsp, 532, TEMP1, TEMP2
ROUND20_39 A, TEMP, B, C, D, E, %rsp, 536, TEMP1, TEMP2
ROUND20_39 E, A, TEMP, B, C, D, %rsp, 540, TEMP1, TEMP2 // Round 67
ROUND20_39 D, E, A, TEMP, B, C, %rsp, 560, TEMP1, TEMP2
ROUND20_39 C, D, E, A, TEMP, B, %rsp, 564, TEMP1, TEMP2
ROUND20_39 B, C, D, E, A, TEMP, %rsp, 568, TEMP1, TEMP2
ROUND20_39 TEMP, B, C, D, E, A, %rsp, 572, TEMP1, TEMP2 // Round 71
ROUND20_39 A, TEMP, B, C, D, E, %rsp, 592, TEMP1, TEMP2
ROUND20_39 E, A, TEMP, B, C, D, %rsp, 596, TEMP1, TEMP2
ROUND20_39 D, E, A, TEMP, B, C, %rsp, 600, TEMP1, TEMP2
ROUND20_39 C, D, E, A, TEMP, B, %rsp, 604, TEMP1, TEMP2 // Round 75
ROUND20_39 B, C, D, E, A, TEMP, %rsp, 624, TEMP1, TEMP2
ROUND20_39 TEMP, B, C, D, E, A, %rsp, 628, TEMP1, TEMP2
ROUND20_39 A, TEMP, B, C, D, E, %rsp, 632, TEMP1, TEMP2 // Round 78
addl 636(%rsp), D // D = D + W + KT
add E, 4(HASH) // Update HASH
add TEMP, 8(HASH) // Upadate H0~H5
lea (A, D), D // D = F1 + D + W + KT
rorx $27, E, TEMP2 // TEMP2 = ROTL32(E, 5)
add B, 12(HASH)
add C, 16(HASH)
addl TEMP2, D // D = F1 + D + W + KT + S^5(E)
mov 4(HASH), B
mov 8(HASH), C
add D, 0(HASH)
mov 16(HASH), E
mov 12(HASH), D
mov 0(HASH), A
cmp $64, LEN
jae .Lloop_sha1_compress
.Lend_sha1_pre:
mov %r14, %rsp
pop %r15
pop %r14
pop %r13
pop %r12
pop %rbp
pop %rbx
.Lend_sha1:
mov INPUT, %rax
ret
.cfi_endproc
.size SHA1_Step, .-SHA1_Step
#endif
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha1/src/asm/sha1_x86_64.S | Motorola 68K Assembly | unknown | 38,616 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_SHA1) && !defined(HITLS_CRYPTO_SHA1_SMALL_MEM)
#include <stdlib.h>
#include "securec.h"
#include "crypt_errno.h"
#include "crypt_utils.h"
#include "bsl_err_internal.h"
#include "crypt_sha1.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
/* e767 is because H is defined in SHA1 and MD5.
But the both the macros are different. So masked
this error */
#define K0 0x5A827999
#define K1 0x6ED9EBA1
#define K2 0x8F1BBCDC
#define K3 0xCA62C1D6
#define F0(b, c, d) (((b) & (c)) | ((~(b)) & (d)))
#define F1(b, c, d) (((b) ^ (c)) ^ (d))
#define F2(b, c, d) (((b) & (c)) | ((b) & (d)) | ((c) & (d)))
#define F3(b, c, d) (((b) ^ (c)) ^ (d))
#define ROUND00_15(s, a, b, c, d, e, temp, w, Kt) \
do { \
(temp) = ROTL32(a, 5) + F##Kt(b, c, d) + (e) + (w)[s] + K##Kt; \
(b) = ROTL32(b, 30); \
} while (0)
#define ROUND16_79(t, a, b, c, d, e, temp, w, Kt) \
do { \
(w)[(t) & 0xF] = ROTL32( \
(w)[((t) + 13) & 0xF] ^ (w)[((t) + 8) & 0xF] ^ (w)[((t) + 2) & 0xF] ^ (w)[(t) & 0xF], 1); \
ROUND00_15((t) & 0xF, a, b, c, d, e, temp, w, Kt); \
} while (0)
const uint8_t *SHA1_Step(const uint8_t *input, uint32_t len, uint32_t *h)
{
uint32_t temp;
uint32_t w[16];
const uint8_t *data = input;
uint32_t dataLen = len;
while (dataLen >= CRYPT_SHA1_BLOCKSIZE) {
/* Convert data into 32 bits for calculation. */
w[0] = GET_UINT32_BE(data, 0);
w[1] = GET_UINT32_BE(data, 4);
w[2] = GET_UINT32_BE(data, 8);
w[3] = GET_UINT32_BE(data, 12);
w[4] = GET_UINT32_BE(data, 16);
w[5] = GET_UINT32_BE(data, 20);
w[6] = GET_UINT32_BE(data, 24);
w[7] = GET_UINT32_BE(data, 28);
w[8] = GET_UINT32_BE(data, 32);
w[9] = GET_UINT32_BE(data, 36);
w[10] = GET_UINT32_BE(data, 40);
w[11] = GET_UINT32_BE(data, 44);
w[12] = GET_UINT32_BE(data, 48);
w[13] = GET_UINT32_BE(data, 52);
w[14] = GET_UINT32_BE(data, 56);
w[15] = GET_UINT32_BE(data, 60);
uint32_t a = h[0];
uint32_t b = h[1];
uint32_t c = h[2];
uint32_t d = h[3];
uint32_t e = h[4];
// Required by referring to section 6.2 in rfc3174. To ensure performance,
// the variables A\b\c\d\e\TEMP are reused cyclically.
ROUND00_15(0, a, b, c, d, e, temp, w, 0);
ROUND00_15(1, temp, a, b, c, d, e, w, 0);
ROUND00_15(2, e, temp, a, b, c, d, w, 0);
ROUND00_15(3, d, e, temp, a, b, c, w, 0);
ROUND00_15(4, c, d, e, temp, a, b, w, 0);
ROUND00_15(5, b, c, d, e, temp, a, w, 0);
ROUND00_15(6, a, b, c, d, e, temp, w, 0);
ROUND00_15(7, temp, a, b, c, d, e, w, 0);
ROUND00_15(8, e, temp, a, b, c, d, w, 0);
ROUND00_15(9, d, e, temp, a, b, c, w, 0);
ROUND00_15(10, c, d, e, temp, a, b, w, 0);
ROUND00_15(11, b, c, d, e, temp, a, w, 0);
ROUND00_15(12, a, b, c, d, e, temp, w, 0);
ROUND00_15(13, temp, a, b, c, d, e, w, 0);
ROUND00_15(14, e, temp, a, b, c, d, w, 0);
ROUND00_15(15, d, e, temp, a, b, c, w, 0);
ROUND16_79(16, c, d, e, temp, a, b, w, 0);
ROUND16_79(17, b, c, d, e, temp, a, w, 0);
ROUND16_79(18, a, b, c, d, e, temp, w, 0);
ROUND16_79(19, temp, a, b, c, d, e, w, 0);
ROUND16_79(20, e, temp, a, b, c, d, w, 1);
ROUND16_79(21, d, e, temp, a, b, c, w, 1);
ROUND16_79(22, c, d, e, temp, a, b, w, 1);
ROUND16_79(23, b, c, d, e, temp, a, w, 1);
ROUND16_79(24, a, b, c, d, e, temp, w, 1);
ROUND16_79(25, temp, a, b, c, d, e, w, 1);
ROUND16_79(26, e, temp, a, b, c, d, w, 1);
ROUND16_79(27, d, e, temp, a, b, c, w, 1);
ROUND16_79(28, c, d, e, temp, a, b, w, 1);
ROUND16_79(29, b, c, d, e, temp, a, w, 1);
ROUND16_79(30, a, b, c, d, e, temp, w, 1);
ROUND16_79(31, temp, a, b, c, d, e, w, 1);
ROUND16_79(32, e, temp, a, b, c, d, w, 1);
ROUND16_79(33, d, e, temp, a, b, c, w, 1);
ROUND16_79(34, c, d, e, temp, a, b, w, 1);
ROUND16_79(35, b, c, d, e, temp, a, w, 1);
ROUND16_79(36, a, b, c, d, e, temp, w, 1);
ROUND16_79(37, temp, a, b, c, d, e, w, 1);
ROUND16_79(38, e, temp, a, b, c, d, w, 1);
ROUND16_79(39, d, e, temp, a, b, c, w, 1);
ROUND16_79(40, c, d, e, temp, a, b, w, 2);
ROUND16_79(41, b, c, d, e, temp, a, w, 2);
ROUND16_79(42, a, b, c, d, e, temp, w, 2);
ROUND16_79(43, temp, a, b, c, d, e, w, 2);
ROUND16_79(44, e, temp, a, b, c, d, w, 2);
ROUND16_79(45, d, e, temp, a, b, c, w, 2);
ROUND16_79(46, c, d, e, temp, a, b, w, 2);
ROUND16_79(47, b, c, d, e, temp, a, w, 2);
ROUND16_79(48, a, b, c, d, e, temp, w, 2);
ROUND16_79(49, temp, a, b, c, d, e, w, 2);
ROUND16_79(50, e, temp, a, b, c, d, w, 2);
ROUND16_79(51, d, e, temp, a, b, c, w, 2);
ROUND16_79(52, c, d, e, temp, a, b, w, 2);
ROUND16_79(53, b, c, d, e, temp, a, w, 2);
ROUND16_79(54, a, b, c, d, e, temp, w, 2);
ROUND16_79(55, temp, a, b, c, d, e, w, 2);
ROUND16_79(56, e, temp, a, b, c, d, w, 2);
ROUND16_79(57, d, e, temp, a, b, c, w, 2);
ROUND16_79(58, c, d, e, temp, a, b, w, 2);
ROUND16_79(59, b, c, d, e, temp, a, w, 2);
ROUND16_79(60, a, b, c, d, e, temp, w, 3);
ROUND16_79(61, temp, a, b, c, d, e, w, 3);
ROUND16_79(62, e, temp, a, b, c, d, w, 3);
ROUND16_79(63, d, e, temp, a, b, c, w, 3);
ROUND16_79(64, c, d, e, temp, a, b, w, 3);
ROUND16_79(65, b, c, d, e, temp, a, w, 3);
ROUND16_79(66, a, b, c, d, e, temp, w, 3);
ROUND16_79(67, temp, a, b, c, d, e, w, 3);
ROUND16_79(68, e, temp, a, b, c, d, w, 3);
ROUND16_79(69, d, e, temp, a, b, c, w, 3);
ROUND16_79(70, c, d, e, temp, a, b, w, 3);
ROUND16_79(71, b, c, d, e, temp, a, w, 3);
ROUND16_79(72, a, b, c, d, e, temp, w, 3);
ROUND16_79(73, temp, a, b, c, d, e, w, 3);
ROUND16_79(74, e, temp, a, b, c, d, w, 3);
ROUND16_79(75, d, e, temp, a, b, c, w, 3);
ROUND16_79(76, c, d, e, temp, a, b, w, 3);
ROUND16_79(77, b, c, d, e, temp, a, w, 3);
ROUND16_79(78, a, b, c, d, e, temp, w, 3);
ROUND16_79(79, temp, a, b, c, d, e, w, 3);
// Let H0 = H0 + a, H1 = H1 + b, H2 = H2 + c, H3 = H3 + d, H4 = H4 + e.
// Because A, B, C, D and E are reused, after the last round of conversion, A = e, b = temp, c = a, d = b, e = c
h[0] += e; // H[0] += a
h[1] += temp; // H[1] += b
h[2] += a; // H[2] += c
h[3] += b; // H[3] += d
h[4] += c; // H[4] += e
data += CRYPT_SHA1_BLOCKSIZE;
dataLen -= CRYPT_SHA1_BLOCKSIZE;
}
return data;
}
#ifdef __cplusplus
}
#endif
#endif // HITLS_CRYPTO_SHA1 && !HITLS_CRYPTO_SHA1_SMALL_MEM
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha1/src/noasm_sha1.c | C | unknown | 7,553 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
/**
* An implementation of sha1 that has 70% less in rom but lower performance.
*/
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_SHA1) && defined(HITLS_CRYPTO_SHA1_SMALL_MEM)
#include <stdlib.h>
#include "securec.h"
#include "crypt_errno.h"
#include "crypt_utils.h"
#include "bsl_err_internal.h"
#include "crypt_sha1.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
/* e767 is because H is defined in SHA1 and MD5.
But the both the macros are different. So masked
this error */
#define K0 0x5A827999
#define K1 0x6ED9EBA1
#define K2 0x8F1BBCDC
#define K3 0xCA62C1D6
typedef struct {
uint32_t a;
uint32_t b;
uint32_t c;
uint32_t d;
uint32_t e;
uint32_t w[16];
} SHA1_CTX;
#define F0(b, c, d) (((b) & (c)) | ((~(b)) & (d)))
#define F1(b, c, d) (((b) ^ (c)) ^ (d))
#define F2(b, c, d) (((b) & (c)) | ((b) & (d)) | ((c) & (d)))
#define F3(b, c, d) (((b) ^ (c)) ^ (d))
#define ROUND00_15(s, a, b, c, d, e, Kt) \
do { \
temp = ROTL32(a, 5) + F##Kt(b, c, d) + (e) + (ctx.w)[s] + K##Kt; \
e = d; \
d = c; \
c = ROTL32(b, 30); \
b = a; \
a = temp; \
} while (0)
#define ROUND16_79(s, a, b, c, d, e, Kt) \
do { \
(ctx.w)[(s) & 0xF] = ROTL32( \
(ctx.w)[((s) + 13) & 0xF] ^ (ctx.w)[((s) + 8) & 0xF] ^ (ctx.w)[((s) + 2) & 0xF] ^ (ctx.w)[(s) & 0xF], 1); \
ROUND00_15((s) & 0xF, a, b, c, d, e, Kt); \
} while (0)
const uint8_t *SHA1_Step(const uint8_t *input, uint32_t len, uint32_t *h)
{
SHA1_CTX ctx = {0};
uint32_t temp;
const uint8_t *data = input;
uint32_t dataLen = len;
while (dataLen >= CRYPT_SHA1_BLOCKSIZE) {
for (int i = 0; i < 16; ++i) {
ctx.w[i] = GET_UINT32_BE(data, i * 4);
}
ctx.a = h[0];
ctx.b = h[1];
ctx.c = h[2];
ctx.d = h[3];
ctx.e = h[4];
// Round 0-15
for (uint32_t s = 0; s < 16; ++s) {
ROUND00_15(s, ctx.a, ctx.b, ctx.c, ctx.d, ctx.e, 0);
}
// Round 16-79
for (uint32_t s = 16; s < 20; ++s) {
ROUND16_79(s, ctx.a, ctx.b, ctx.c, ctx.d, ctx.e, 0);
}
for (uint32_t s = 20; s < 40; ++s) {
ROUND16_79(s, ctx.a, ctx.b, ctx.c, ctx.d, ctx.e, 1);
}
for (uint32_t s = 40; s < 60; ++s) {
ROUND16_79(s, ctx.a, ctx.b, ctx.c, ctx.d, ctx.e, 2);
}
for (uint32_t s = 60; s < 80; ++s) {
ROUND16_79(s, ctx.a, ctx.b, ctx.c, ctx.d, ctx.e, 3);
}
h[0] += ctx.a;
h[1] += ctx.b;
h[2] += ctx.c;
h[3] += ctx.d;
h[4] += ctx.e;
data += CRYPT_SHA1_BLOCKSIZE;
dataLen -= CRYPT_SHA1_BLOCKSIZE;
}
return data;
}
#ifdef __cplusplus
}
#endif
#endif // HITLS_CRYPTO_SHA1 && HITLS_CRYPTO_SHA1_SMALL_MEM
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha1/src/noasm_sha1_small.c | C | unknown | 3,381 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SHA1
#include <stdlib.h>
#include "securec.h"
#include "crypt_errno.h"
#include "crypt_utils.h"
#include "bsl_err_internal.h"
#include "sha1_core.h"
#include "bsl_sal.h"
#include "crypt_sha1.h"
#include "crypt_types.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
/* SHA-1 context structure */
struct CryptSha1Ctx {
uint8_t m[CRYPT_SHA1_BLOCKSIZE]; /* store the remaining data which less than one block */
uint32_t h[CRYPT_SHA1_DIGESTSIZE / sizeof(uint32_t)]; /* store the intermediate data of the hash value */
uint32_t hNum, lNum; /* input data counter, maximum value 2 ^ 64 bits */
int32_t errorCode; /* Error code */
uint32_t count; /* Number of remaining data bytes less than one block, corresponding to the length of the m */
};
CRYPT_SHA1_Ctx *CRYPT_SHA1_NewCtx(void)
{
return BSL_SAL_Calloc(1, sizeof(CRYPT_SHA1_Ctx));
}
CRYPT_SHA1_Ctx *CRYPT_SHA1_NewCtxEx(void *libCtx, int32_t algId)
{
(void)libCtx;
(void)algId;
return BSL_SAL_Calloc(1, sizeof(CRYPT_SHA1_Ctx));
}
void CRYPT_SHA1_FreeCtx(CRYPT_SHA1_Ctx *ctx)
{
BSL_SAL_ClearFree(ctx, sizeof(CRYPT_SHA1_Ctx));
}
/* e767 is because H is defined in SHA1 and MD5.
But the both the macros are different. So masked
this error */
int32_t CRYPT_SHA1_Init(CRYPT_SHA1_Ctx *ctx, BSL_Param *param)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
(void) param;
(void)memset_s(ctx, sizeof(CRYPT_SHA1_Ctx), 0, sizeof(CRYPT_SHA1_Ctx));
/**
* RFC3174 6.1 Initialize the H constants of the input ctx
* These constants are provided by the standard
*/
ctx->h[0] = 0x67452301;
ctx->h[1] = 0xefcdab89;
ctx->h[2] = 0x98badcfe;
ctx->h[3] = 0x10325476;
ctx->h[4] = 0xc3d2e1f0;
return CRYPT_SUCCESS;
}
int32_t CRYPT_SHA1_Deinit(CRYPT_SHA1_Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
BSL_SAL_CleanseData((void *)(ctx), sizeof(CRYPT_SHA1_Ctx));
return CRYPT_SUCCESS;
}
int32_t CRYPT_SHA1_CopyCtx(CRYPT_SHA1_Ctx *dst, const CRYPT_SHA1_Ctx *src)
{
if (dst == NULL || src == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
(void)memcpy_s(dst, sizeof(CRYPT_SHA1_Ctx), src, sizeof(CRYPT_SHA1_Ctx));
return CRYPT_SUCCESS;
}
CRYPT_SHA1_Ctx *CRYPT_SHA1_DupCtx(const CRYPT_SHA1_Ctx *src)
{
if (src == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return NULL;
}
CRYPT_SHA1_Ctx *newCtx = CRYPT_SHA1_NewCtx();
if (newCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
(void)memcpy_s(newCtx, sizeof(CRYPT_SHA1_Ctx), src, sizeof(CRYPT_SHA1_Ctx));
return newCtx;
}
static int32_t SHA1_CheckIsCorrupted(CRYPT_SHA1_Ctx *ctx, uint32_t textLen)
{
uint32_t low = (ctx->lNum + (textLen << 3)) & 0xffffffffUL;
if (low < ctx->lNum) { /* overflow */
if (++ctx->hNum == 0) {
ctx->errorCode = CRYPT_SHA1_INPUT_OVERFLOW;
BSL_ERR_PUSH_ERROR(CRYPT_SHA1_INPUT_OVERFLOW);
return CRYPT_SHA1_INPUT_OVERFLOW;
}
}
uint32_t high = ctx->hNum + (uint32_t)(textLen >> (32 - 3));
if (high < ctx->hNum) { /* overflow */
ctx->errorCode = CRYPT_SHA1_INPUT_OVERFLOW;
BSL_ERR_PUSH_ERROR(CRYPT_SHA1_INPUT_OVERFLOW);
return CRYPT_SHA1_INPUT_OVERFLOW;
}
ctx->hNum = high;
ctx->lNum = low;
return CRYPT_SUCCESS;
}
static int32_t SHA1_UpdateParamIsValid(CRYPT_SHA1_Ctx *ctx, const uint8_t *data, uint32_t nbytes)
{
if ((ctx == NULL) || (data == NULL && nbytes != 0)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->errorCode != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ctx->errorCode);
return ctx->errorCode;
}
if (SHA1_CheckIsCorrupted(ctx, nbytes) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_SHA1_INPUT_OVERFLOW);
return CRYPT_SHA1_INPUT_OVERFLOW;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_SHA1_Update(CRYPT_SHA1_Ctx *ctx, const uint8_t *in, uint32_t len)
{
int32_t ret = SHA1_UpdateParamIsValid(ctx, in, len);
if (ret != CRYPT_SUCCESS) {
return ret;
}
const uint8_t *data = in;
uint32_t dataLen = len;
uint32_t start = ctx->count;
uint32_t left = CRYPT_SHA1_BLOCKSIZE - start;
/* Check whether the user input data and cached data can form a block. */
if (dataLen < left) {
(void)memcpy_s(&ctx->m[start], left, data, dataLen);
ctx->count += dataLen;
return CRYPT_SUCCESS;
}
/* Preferentially process the buf data and form a block with the user input data. */
if (start != 0) {
(void)memcpy_s(&ctx->m[start], left, data, left);
(void)SHA1_Step(ctx->m, CRYPT_SHA1_BLOCKSIZE, ctx->h);
dataLen -= left;
data += left;
ctx->count = 0;
}
/* Cyclically process the input data */
data = SHA1_Step(data, dataLen, ctx->h);
dataLen = len - (data - in);
/* The remaining data is less than one block and stored in the buf. */
if (dataLen != 0) {
(void)memcpy_s(ctx->m, CRYPT_SHA1_BLOCKSIZE, data, dataLen);
ctx->count = dataLen;
}
return CRYPT_SUCCESS;
}
static int32_t SHA1_FinalParamIsValid(const CRYPT_SHA1_Ctx *ctx, const uint8_t *out, const uint32_t *outLen)
{
if ((ctx == NULL) || (out == NULL) || (outLen == NULL)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (*outLen < CRYPT_SHA1_DIGESTSIZE) {
BSL_ERR_PUSH_ERROR(CRYPT_SHA1_OUT_BUFF_LEN_NOT_ENOUGH);
return CRYPT_SHA1_OUT_BUFF_LEN_NOT_ENOUGH;
}
if (ctx->errorCode != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ctx->errorCode);
return ctx->errorCode;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_SHA1_Final(CRYPT_SHA1_Ctx *ctx, uint8_t *out, uint32_t *len)
{
int32_t ret = SHA1_FinalParamIsValid(ctx, out, len);
if (ret != CRYPT_SUCCESS) {
return ret;
}
uint32_t padLen;
uint32_t padPos;
/* Add "1" to the end of the user data */
ctx->m[ctx->count] = 0x80;
ctx->count++;
/* If here is one complete data block, one complete data block is processed first. */
if (ctx->count == CRYPT_SHA1_BLOCKSIZE) {
(void)SHA1_Step(ctx->m, CRYPT_SHA1_BLOCKSIZE, ctx->h);
ctx->count = 0;
}
/* Calculate the padding position. */
padPos = ctx->count;
padLen = CRYPT_SHA1_BLOCKSIZE - padPos;
if (padLen < 8) { /* 64 bits (8 bytes) of 512 bits are reserved to pad "0" */
(void)memset_s(&ctx->m[padPos], padLen, 0, padLen);
padPos = 0;
padLen = CRYPT_SHA1_BLOCKSIZE;
(void)SHA1_Step(ctx->m, CRYPT_SHA1_BLOCKSIZE, ctx->h);
}
/* offset 8 bytes, reserved for storing the data length */
(void)memset_s(&ctx->m[padPos], (padLen - 8), 0, (padLen - 8));
PUT_UINT32_BE(ctx->hNum, ctx->m, 56); /* The 56th byte starts to store the upper 32-bit data. */
PUT_UINT32_BE(ctx->lNum, ctx->m, 60); /* The 60th byte starts to store the lower 32-bit data. */
(void)SHA1_Step(ctx->m, CRYPT_SHA1_BLOCKSIZE, ctx->h);
PUT_UINT32_BE(ctx->h[0], out, 0);
PUT_UINT32_BE(ctx->h[1], out, 4);
PUT_UINT32_BE(ctx->h[2], out, 8);
PUT_UINT32_BE(ctx->h[3], out, 12);
PUT_UINT32_BE(ctx->h[4], out, 16);
*len = CRYPT_SHA1_DIGESTSIZE;
return CRYPT_SUCCESS;
}
#ifdef HITLS_CRYPTO_PROVIDER
int32_t CRYPT_SHA1_GetParam(CRYPT_SHA1_Ctx *ctx, BSL_Param *param)
{
(void)ctx;
return CRYPT_MdCommonGetParam(CRYPT_SHA1_DIGESTSIZE, CRYPT_SHA1_BLOCKSIZE, param);
}
#endif
#ifdef __cplusplus
}
#endif
#endif // HITLS_CRYPTO_SHA1
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha1/src/sha1.c | C | unknown | 8,448 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef SHA1_CORE_H
#define SHA1_CORE_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SHA1
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
const uint8_t *SHA1_Step(const uint8_t *input, uint32_t len, uint32_t *h);
#ifdef __cplusplus
}
#endif
#endif // HITLS_CRYPTO_SHA1
#endif // SHA1_CORE_H
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha1/src/sha1_core.h | C | unknown | 853 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef CRYPT_SHA2_H
#define CRYPT_SHA2_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SHA2
#include <stdint.h>
#include <stdlib.h>
#include "crypt_types.h"
#include "bsl_params.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
/** @defgroup LLF SHA2 Low level function */
#ifdef HITLS_CRYPTO_SHA224
#define CRYPT_SHA2_224_BLOCKSIZE 64
#define CRYPT_SHA2_224_DIGESTSIZE 28
#endif // HITLS_CRYPTO_SHA224
#ifdef HITLS_CRYPTO_SHA256
#define CRYPT_SHA2_256_BLOCKSIZE 64
#define CRYPT_SHA2_256_DIGESTSIZE 32
#endif // HITLS_CRYPTO_SHA256
#ifdef HITLS_CRYPTO_SHA384
#define CRYPT_SHA2_384_BLOCKSIZE 128
#define CRYPT_SHA2_384_DIGESTSIZE 48
#endif // HITLS_CRYPTO_SHA384
#ifdef HITLS_CRYPTO_SHA512
#define CRYPT_SHA2_512_BLOCKSIZE 128
#define CRYPT_SHA2_512_DIGESTSIZE 64
#endif // HITLS_CRYPTO_SHA512
#define CRYPT_SHA2_224_Squeeze NULL
#define CRYPT_SHA2_256_Squeeze NULL
#define CRYPT_SHA2_384_Squeeze NULL
#define CRYPT_SHA2_512_Squeeze NULL
#ifdef HITLS_CRYPTO_SHA224
typedef struct CryptSha256Ctx CRYPT_SHA2_224_Ctx;
#define CRYPT_SHA2_224_NewCtx CRYPT_SHA2_256_NewCtx
#define CRYPT_SHA2_224_NewCtxEx CRYPT_SHA2_256_NewCtxEx
#define CRYPT_SHA2_224_FreeCtx CRYPT_SHA2_256_FreeCtx
#define CRYPT_SHA2_224_Deinit CRYPT_SHA2_256_Deinit
#define CRYPT_SHA2_224_CopyCtx CRYPT_SHA2_256_CopyCtx
#define CRYPT_SHA2_224_DupCtx CRYPT_SHA2_256_DupCtx
#define CRYPT_SHA2_224_Update CRYPT_SHA2_256_Update
#define CRYPT_SHA2_224_Final CRYPT_SHA2_256_Final
/**
* @defgroup CRYPT_SHA2_224_Init
* @ingroup LLF Low Level Functions
* @par Prototype
* @code
* int32_t CRYPT_SHA2_224_Init(CRYPT_SHA2_224_Ctx *ctx)
* @endcode
*
* @par Purpose
* This is used to initialize the SHA224 ctx for a digest operation.
*
* @par Description
* CRYPT_SHA2_224_Init function initializes the ctx for a digest operation. This function must be called before
* CRYPT_SHA2_224_Update or CRYPT_SHA2_224_Final operations. This function will not allocate memory for any of the
* ctx variables. Instead the caller is expected to pass a ctx pointer pointing to a valid memory location
* (either locally or dynamically allocated).
*
* @param[in] ctx The sha224 ctx
* @param *param [in] Pointer to the parameter.
*
* @retval #CRYPT_SUCCESS ctx is initialized
* @retval #CRYPT_NULL_INPUT ctx is NULL
*/
int32_t CRYPT_SHA2_224_Init(CRYPT_SHA2_224_Ctx *ctx, BSL_Param *param);
#ifdef HITLS_CRYPTO_PROVIDER
/**
* @ingroup SHA224
* @brief SHA224 get param function
* @param ctx [in] Pointer to the SHA224 context.
* @param param [in] Pointer to the parameter.
*
* @retval #CRYPT_SUCCESS Success.
* @retval #CRYPT_NULL_INPUT Pointer param is NULL
* @retval #CRYPT_INVALID_ARG Pointer param is invalid
*/
int32_t CRYPT_SHA2_224_GetParam(CRYPT_SHA2_224_Ctx *ctx, BSL_Param *param);
#else
#define CRYPT_SHA2_224_GetParam NULL
#endif
#endif // HITLS_CRYPTO_SHA224
#ifdef HITLS_CRYPTO_SHA256
typedef struct CryptSha256Ctx CRYPT_SHA2_256_Ctx;
/**
* @ingroup SHA2_256
* @brief Generate md context.
*
* @retval Success: sha256 ctx.
* Fails: NULL.
*/
CRYPT_SHA2_256_Ctx *CRYPT_SHA2_256_NewCtx(void);
/**
* @ingroup SHA2_256
* @brief Generate md context.
*
* @param libCtx [IN] library context
* @param algId [IN] algorithm id
*
* @retval Success: sha256 ctx.
* Fails: NULL.
*/
CRYPT_SHA2_256_Ctx *CRYPT_SHA2_256_NewCtxEx(void *libCtx, int32_t algId);
/**
* @ingroup SHA2_256
* @brief free md context.
*
* @param ctx [IN] md handle
*/
void CRYPT_SHA2_256_FreeCtx(CRYPT_SHA2_256_Ctx *ctx);
/**
* @defgroup CRYPT_SHA2_256_Init
* @ingroup LLF Low Level Functions
* @par Prototype
* @code
* int32_t CRYPT_SHA2_256_Init(CRYPT_SHA2_256_Ctx *ctx)
* @endcode
*
* @par Purpose
* This is used to initialize the SHA256 ctx for a digest operation.
*
* @par Description
* CRYPT_SHA2_256_Init function initializes the ctx for
* a digest operation. This function must be called before
* CRYPT_SHA2_256_Update or CRYPT_SHA2_256_Final operations. This function will not
* allocate memory for any of the ctx variables. Instead the caller is
* expected to pass a ctx pointer pointing to a valid memory location
* (either locally or dynamically allocated).
*
* @param[in] ctx The sha256 ctx
* @param *param [in] Pointer to the parameter.
*
* @retval #CRYPT_SUCCESS ctx is initialized
* @retval #CRYPT_NULL_INPUT ctx is NULL
*/
int32_t CRYPT_SHA2_256_Init(CRYPT_SHA2_256_Ctx *ctx, BSL_Param *param);
/**
* @defgroup CRYPT_SHA2_256_Update
* @ingroup LLF Low Level Functions
* @par Prototype
* @code
* int32_t CRYPT_SHA2_256_Update(CRYPT_SHA2_256_Ctx *ctx, const uint8_t *data, usize_t nbytes)
* @endcode
*
* @par Purpose
* This is used to perform sha256 digest operation on chunks of data.
*
* @par Description
* CRYPT_SHA2_256_Update function performs digest operation on
* chunks of data. This method of digesting is used when data is
* present in multiple buffers or not available all at once.
* CRYPT_SHA2_256_Init must have been called before calling this
* function.
*
* @param[in] ctx The sha256 ctx
* @param[in] data The input data
* @param[in] nbytes The input data length
*
* @retval #CRYPT_SUCCESS If partial digest is calculated
* @retval #CRYPT_NULL_INPUT input arguments is NULL
* @retval #CRYPT_SHA2_ERR_OVERFLOW input message is overflow
*/
int32_t CRYPT_SHA2_256_Update(CRYPT_SHA2_256_Ctx *ctx, const uint8_t *data, uint32_t nbytes);
/**
* @defgroup CRYPT_SHA2_256_Final
* @ingroup LLF Low Level Functions
* @par Prototype
* @code
* int32_t CRYPT_SHA2_256_Final(CRYPT_SHA2_256_Ctx *ctx, uint8_t *digest, uint32_t *len)
* @endcode
*
* @par Purpose
* This is used to complete sha256 digest operation on remaining data, and is
* called at the end of digest operation.
*
* @par Description
* CRYPT_SHA2_256_Final function completes digest operation on remaining data, and
* is called at the end of digest operation.
* CRYPT_SHA2_256_Init must have been called before calling this function. This
* function calculates the digest. The memory for digest must
* already have been allocated.
*
* @param[in] ctx The sha256 ctx
* @param[out] digest The digest
*
* @retval #CRYPT_SUCCESS If partial digest is calculated
* @retval #CRYPT_NULL_INPUT input arguments is NULL
* @retval #CRYPT_SHA2_ERR_OVERFLOW input message is overflow
* @retval #CRYPT_SHA2_OUT_BUFF_LEN_NOT_ENOUGH output buffer is not enough
*/
int32_t CRYPT_SHA2_256_Final(CRYPT_SHA2_256_Ctx *ctx, uint8_t *digest, uint32_t *outlen);
/**
* @ingroup LLF Low Level Functions
*
* @brief SHA256 deinit function
*
* @param[in,out] ctx The SHA256 ctx
*
* @retval #CRYPT_SUCCESS initialization succeeded.
* @retval #CRYPT_NULL_INPUT Pointer ctx is NULL
*/
int32_t CRYPT_SHA2_256_Deinit(CRYPT_SHA2_256_Ctx *ctx);
/**
* @ingroup SHA256
* @brief SHA256 copy CTX function
* @param dst [out] Pointer to the new SHA256 context.
* @param src [in] Pointer to the original SHA256 context.
*/
int32_t CRYPT_SHA2_256_CopyCtx(CRYPT_SHA2_256_Ctx *dst, const CRYPT_SHA2_256_Ctx *src);
/**
* @ingroup SHA256
* @brief SHA256 dup CTX function
* @param src [in] Pointer to the original SHA256 context.
*/
CRYPT_SHA2_256_Ctx *CRYPT_SHA2_256_DupCtx(const CRYPT_SHA2_256_Ctx *src);
#ifdef HITLS_CRYPTO_PROVIDER
/**
* @ingroup SHA256
* @brief SHA256 get param function
* @param ctx [in] Pointer to the SHA256 context.
* @param param [in] Pointer to the parameter.
*
* @retval #CRYPT_SUCCESS Success.
* @retval #CRYPT_NULL_INPUT Pointer param is NULL
* @retval #CRYPT_INVALID_ARG Pointer param is invalid
*/
int32_t CRYPT_SHA2_256_GetParam(CRYPT_SHA2_256_Ctx *ctx, BSL_Param *param);
#else
#define CRYPT_SHA2_256_GetParam NULL
#endif
#endif // HITLS_CRYPTO_SHA256
#ifdef HITLS_CRYPTO_SHA384
typedef struct CryptSha2512Ctx CRYPT_SHA2_384_Ctx;
#define CRYPT_SHA2_384_NewCtx CRYPT_SHA2_512_NewCtx
#define CRYPT_SHA2_384_NewCtxEx CRYPT_SHA2_512_NewCtxEx
#define CRYPT_SHA2_384_FreeCtx CRYPT_SHA2_512_FreeCtx
#define CRYPT_SHA2_384_Deinit CRYPT_SHA2_512_Deinit
#define CRYPT_SHA2_384_CopyCtx CRYPT_SHA2_512_CopyCtx
#define CRYPT_SHA2_384_DupCtx CRYPT_SHA2_512_DupCtx
#define CRYPT_SHA2_384_Update CRYPT_SHA2_512_Update
#define CRYPT_SHA2_384_Final CRYPT_SHA2_512_Final
/**
* @ingroup LLF Low Level Functions
* @par Prototype
* @code
* int32_t CRYPT_SHA2_384_Init(CRYPT_SHA2_384_Ctx *ctx)
* @endcode
*
* @par Purpose
* This is used to initialize the SHA384 ctx for a digest operation.
*
* @par Description
* CRYPT_SHA2_384_Init function initializes the ctx for a digest operation. This function must be called before
* CRYPT_SHA2_384_Update or CRYPT_SHA2_384_Final operations. This function will not allocate memory for any of the
* ctx variables. Instead the caller is expected to pass a ctx pointer pointing to a valid memory location
* (either locally or dynamically allocated).
*
* @param[in,out] ctx The sha384 ctx
* @param *param [in] Pointer to the parameter.
*
* @retval #CRYPT_SUCCESS ctx is initialized
* @retval #CRYPT_NULL_INPUT ctx is NULL
*/
int32_t CRYPT_SHA2_384_Init(CRYPT_SHA2_384_Ctx *ctx, BSL_Param *param);
#ifdef HITLS_CRYPTO_PROVIDER
/**
* @ingroup SHA512
* @brief SHA512 get param function
* @param ctx [in] Pointer to the SHA512 context.
* @param param [in] Pointer to the parameter.
*
* @retval #CRYPT_SUCCESS Success.
* @retval #CRYPT_NULL_INPUT Pointer param is NULL
* @retval #CRYPT_INVALID_ARG Pointer param is invalid
*/
int32_t CRYPT_SHA2_384_GetParam(CRYPT_SHA2_384_Ctx *ctx, BSL_Param *param);
#else
#define CRYPT_SHA2_384_GetParam NULL
#endif
#endif // HITLS_CRYPTO_SHA384
#ifdef HITLS_CRYPTO_SHA512
typedef struct CryptSha2512Ctx CRYPT_SHA2_512_Ctx;
/**
* @ingroup SHA2_512
* @brief Generate md context.
*
* @retval Success: sha512 ctx.
* Fails: NULL.
*/
CRYPT_SHA2_512_Ctx *CRYPT_SHA2_512_NewCtx(void);
/**
* @ingroup SHA2_512
* @brief Generate md context.
*
* @param libCtx [IN] library context
* @param algId [IN] algorithm id
*
* @retval Success: sha512 ctx.
* Fails: NULL.
*/
CRYPT_SHA2_512_Ctx *CRYPT_SHA2_512_NewCtxEx(void *libCtx, int32_t algId);
/**
* @ingroup SHA2_512
* @brief free md context.
*
* @param ctx [IN] md handle
*/
void CRYPT_SHA2_512_FreeCtx(CRYPT_SHA2_512_Ctx *ctx);
/**
* @ingroup LLF Low Level Functions
* @par Prototype
* @code
* int32_t CRYPT_SHA2_512_Init(CRYPT_SHA2_512_Ctx *ctx)
* @endcode
*
* @par Purpose
* This is used to initialize the SHA512 ctx for a digest operation.
*
* @par Description
* CRYPT_SHA2_512_Init function initializes the ctx for a digest operation. This function must be called before
* CRYPT_SHA2_512_Update or CRYPT_SHA2_512_Final operations. This function will not allocate memory for any of the
* ctx variable. Instead the caller is expected to pass a ctx pointer pointing to a valid memory location
* (either locally or dynamically allocated).
*
* @param[in,out] ctx The sha512 ctx
* @param *param [in] Pointer to the parameter.
*
* @retval #CRYPT_SUCCESS ctx is initialized
* @retval #CRYPT_NULL_INPUT ctx is NULL
*/
int32_t CRYPT_SHA2_512_Init(CRYPT_SHA2_512_Ctx *ctx, BSL_Param *param);
/**
* @ingroup LLF Low Level Functions
* @par Prototype
* @code
* int32_t CRYPT_SHA2_512_Update(CRYPT_SHA2_512_Ctx *ctx, const uint8_t *data, usize_t nbytes)
* @endcode
*
* @par Purpose
* This is used to perform sha512 digest operation on chunks of data.
*
* @par Description
* CRYPT_SHA2_512_Update function performs digest operation on chunks of data. This method of digesting is used when
* data is present in multiple buffers or not available all at once. CRYPT_SHA2_512_Init must have been called before
* calling this function.
*
* @param[in,out] ctx The sha512 ctx
* @param[in] data The input data
* @param[in] nbytes The input data length
*
* @retval #CRYPT_SUCCESS If partial digest is calculated
* @retval #CRYPT_NULL_INPUT input arguments is NULL
* @retval #CRYPT_SHA2_INPUT_OVERFLOW input message is overflow
* @retval #CRYPT_SECUREC_FAIL secure c function fail.
*/
int32_t CRYPT_SHA2_512_Update(CRYPT_SHA2_512_Ctx *ctx, const uint8_t *data, uint32_t nbytes);
/**
* @ingroup LLF Low Level Functions
* @par Prototype
* @code
* int32_t CRYPT_SHA2_512_Final(CRYPT_SHA2_512_Ctx *ctx, uint8_t *digest, uint32_t *len)
* @endcode
*
* @par Purpose
* This is used to complete sha512 digest operation on remaining data, and is called at the end of digest operation.
*
* @par Description
* CRYPT_SHA2_512_Final function completes digest operation on remaining data, and is called at the end of digest
* operation. CRYPT_SHA2_512_Init must have been called before calling this function. This function calculates the
* digest. The memory for digest must already have been allocated.
*
* @param[in,out] ctx The sha512 ctx
* @param[out] digest The digest
* @param[in,out] len length of buffer
*
* @retval #CRYPT_SUCCESS If partial digest is calculated
* @retval #CRYPT_NULL_INPUT input arguments is NULL
* @retval #CRYPT_SHA2_INPUT_OVERFLOW input message is overflow
* @retval #CRYPT_SHA2_OUT_BUFF_LEN_NOT_ENOUGH output buffer is not enough
*/
int32_t CRYPT_SHA2_512_Final(CRYPT_SHA2_512_Ctx *ctx, uint8_t *digest, uint32_t *len);
/**
* @ingroup LLF Low Level Functions
*
* @brief SHA512 deinit function
*
* @param[in,out] ctx The SHA512 ctx
*
* @retval #CRYPT_SUCCESS initialization succeeded.
* @retval #CRYPT_NULL_INPUT Pointer ctx is NULL
*/
int32_t CRYPT_SHA2_512_Deinit(CRYPT_SHA2_512_Ctx *ctx);
/**
* @ingroup SHA512
* @brief SHA512 copy CTX function
* @param dst [out] Pointer to the new SHA512 context.
* @param src [in] Pointer to the original SHA512 context.
*/
int32_t CRYPT_SHA2_512_CopyCtx(CRYPT_SHA2_512_Ctx *dst, const CRYPT_SHA2_512_Ctx *src);
/**
* @ingroup SHA512
* @brief SHA512 dup CTX function
* @param src [in] Pointer to the original SHA512 context.
*/
CRYPT_SHA2_512_Ctx *CRYPT_SHA2_512_DupCtx(const CRYPT_SHA2_512_Ctx *src);
#ifdef HITLS_CRYPTO_PROVIDER
/**
* @ingroup SHA512
* @brief SHA512 get param function
* @param ctx [in] Pointer to the SHA512 context.
* @param param [in] Pointer to the parameter.
*
* @retval #CRYPT_SUCCESS Success.
* @retval #CRYPT_NULL_INPUT Pointer param is NULL
* @retval #CRYPT_INVALID_ARG Pointer param is invalid
*/
int32_t CRYPT_SHA2_512_GetParam(CRYPT_SHA2_512_Ctx *ctx, BSL_Param *param);
#else
#define CRYPT_SHA2_512_GetParam NULL
#endif
#endif // HITLS_CRYPTO_SHA512
#ifdef __cplusplus
}
#endif
#endif // HITLS_CRYPTO_SHA2
#endif // CRYPT_SHA2_H
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha2/include/crypt_sha2.h | C | unknown | 15,163 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SHA256
#include "crypt_arm.h"
.arch armv8-a+crypto
/* sha256 used constant value. For the data source, see the RFC4634 document. */
.extern g_cryptArmCpuInfo
.hidden g_cryptArmCpuInfo
.section .rodata
.balign 64
.K256:
.long 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5
.long 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174
.long 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da
.long 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967
.long 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85
.long 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070
.long 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3
.long 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
/*
* Macro description: updates the 32-bit plaintext information. W
* Input register:
* wi_16: W[i-16]
* wi_15: W[i-15]
* wi_7: W[i-7]
* wi_2: W[i-2]
* Modify the register: wi_16 w17 w28
* Output register:
* wi_16: Latest W[i] value, W[i] = sigma1(W[i-2]) + W[i-7] + sigma0(W[i-15]) + W[i-16]
* Function/Macro Call:None
*/
.macro UPDATE_W wi_16, wi_15, wi_7, wi_2
ror w28, \wi_15, #7
ror w17, \wi_2, #17
eor w28, w28, \wi_15, ror#18
eor w17, w17, \wi_2, ror#19
eor w28, w28, \wi_15, lsr#3 // w28 = sigma0(w[i-15])
eor w17, w17, \wi_2, lsr#10 // w17 = sigma1(W[i-2])
add \wi_16, \wi_16, \wi_7 // + W[i-7]
add \wi_16, \wi_16, w28 // + sigma0(w[i-15])
add \wi_16, \wi_16, w17 // + sigma1(W[i-2])
.endm
/*
* Macro description: Processes the update of a round of hash values in 64 rounds of compression.
* Input register:
* x19: Point to the address of the corresponding element in the g_k256 constant
* wi: Plaintext data after processing
* a - h: Intermediate variable of hash value
* Modify the register: h d w16 w17 w28 w29
* Output register:
* h: Indicates the value after a cyclic update.
* d: Indicates the value after a cyclic update.
* Function/Macro Call:None
*/
.macro ONE_ROUND wi, a, b, c, d, e, f, g, h
ldr w16, [x19], #4 // K[i]
and w17, \f, \e // e&f
bic w28, \g, \e // g&(~e)
add \h, \h, w16 // h += K[i]
eor w29, \e, \e, ror#14
ror w16, \e, #6
orr w17, w17, w28 // Ch(e, f, g) = e&f | g&(~e)
add \h, \h, \wi // h += W[i]
eor w29, w16, w29, ror#11 // Sigma1(e) = ROR(e, 6) ^ ROR(e, 11) ^ ROR(e, 25)
eor w28, \a, \c // a^c
eor w16, \a, \b // a^b
add \h, \h, w29 // h += Sigma1(e)
and w28, w28, w16 // (a^b)&(a^c)
eor w29, \a, \a, ror#9
add \h, \h, w17 // h += Ch(e, f, g)
eor w28, w28, \a // Maj(a, b, c) = ((a^b)&(a^c))^a = (a&b)^(b&c)^(a&c)
ror w16, \a, #2
add \d, \d, \h // d += h
add \h, \h, w28 // h += Maj(a, b, c)
eor w29, w16, w29, ror#13 // Sigma0(a) = ROR(a, 2)^ROR(a, 13)^ROR(a, 22)
add \h, \h, w29 // h += Sigma0(a)
.endm
/*
* Function Description:Performs 64 rounds of compression calculation based on the input plaintext data
* and updates the hash value.
* Function prototype:void SHA256CompressMultiBlocks(uint32_t hash[8], const uint8_t *in, uint32_t num);
* Input register:
* x0: Storage address of the hash value
* x1: Pointer to the input data address
* x2: Number of 64 rounds of cycles
* Modify the register: x0-x17
* Output register: None
* Function/Macro Call: None
*
*/
.text
.balign 16
.global SHA256CompressMultiBlocks
.type SHA256CompressMultiBlocks, %function
SHA256CompressMultiBlocks:
cbz x2, .Lend_sha256
/* If the SHA256 cryptography extension instruction is supported, go to. */
adrp x5, g_cryptArmCpuInfo
ldr w6, [x5, #:lo12:g_cryptArmCpuInfo]
tst w6, #CRYPT_ARM_SHA256
bne SHA256CryptoExt
/* Extension instructions are not supported. Base instructions are used. */
stp x29, x30, [sp, #-112]!
add x29, sp, #0
stp x19, x20, [sp, #8*2]
stp x21, x22, [sp, #8*4]
stp x23, x24, [sp, #8*6]
stp x25, x26, [sp, #8*8]
stp x27, x28, [sp, #8*10]
/* load a - h */
ldp w20, w21, [x0]
ldp w22, w23, [x0, #4*2]
ldp w24, w25, [x0, #4*4]
ldp w26, w27, [x0, #4*6]
str x0, [sp, #96]
mov x16, x1 // Enter Value Address
lsl x30, x2, #6 // Number of times to process 2^6 = 64
/* w0-w15 are used to record input values W[i] and temporary registers */
.Lloop_compress_64:
/* Start a 64-round process */
sub x30, x30, #16
adrp x19, .K256
add x19, x19, :lo12:.K256
/* 8 bytes are loaded each time, and then two rounds are processed. */
ldp w0, w1, [x16] // load input value
ldp w2, w3, [x16, #4*2]
ldp w4, w5, [x16, #4*4]
ldp w6, w7, [x16, #4*6]
ldp w8, w9, [x16, #4*8]
ldp w10, w11, [x16, #4*10]
ldp w12, w13, [x16, #4*12]
ldp w14, w15, [x16, #4*14]
add x16, x16, #64
str x16, [sp, #104]
#ifndef HITLS_BIG_ENDIAN
rev w0, w0
rev w1, w1
rev w2, w2
rev w3, w3
rev w4, w4
rev w5, w5
rev w6, w6
rev w7, w7
rev w8, w8
rev w9, w9
rev w10, w10
rev w11, w11
rev w12, w12
rev w13, w13
rev w14, w14
rev w15, w15
#endif
/* w16 w17 w28 w29 used as a temporary register */
ONE_ROUND w0, w20, w21, w22, w23, w24, w25, w26, w27
ONE_ROUND w1, w27, w20, w21, w22, w23, w24, w25, w26
ONE_ROUND w2, w26, w27, w20, w21, w22, w23, w24, w25
ONE_ROUND w3, w25, w26, w27, w20, w21, w22, w23, w24
ONE_ROUND w4, w24, w25, w26, w27, w20, w21, w22, w23
ONE_ROUND w5, w23, w24, w25, w26, w27, w20, w21, w22
ONE_ROUND w6, w22, w23, w24, w25, w26, w27, w20, w21
ONE_ROUND w7, w21, w22, w23, w24, w25, w26, w27, w20
ONE_ROUND w8, w20, w21, w22, w23, w24, w25, w26, w27
ONE_ROUND w9, w27, w20, w21, w22, w23, w24, w25, w26
ONE_ROUND w10, w26, w27, w20, w21, w22, w23, w24, w25
ONE_ROUND w11, w25, w26, w27, w20, w21, w22, w23, w24
ONE_ROUND w12, w24, w25, w26, w27, w20, w21, w22, w23
ONE_ROUND w13, w23, w24, w25, w26, w27, w20, w21, w22
ONE_ROUND w14, w22, w23, w24, w25, w26, w27, w20, w21
ONE_ROUND w15, w21, w22, w23, w24, w25, w26, w27, w20
.Lloop_compress_16_63:
/* Start 16-31, 32-47, 48-63 compression */
sub x30, x30, #16
/* 0 */
UPDATE_W w0, w1, w9, w14
ONE_ROUND w0, w20, w21, w22, w23, w24, w25, w26, w27
/* 1 */
UPDATE_W w1, w2, w10, w15
ONE_ROUND w1, w27, w20, w21, w22, w23, w24, w25, w26
/* 2 */
UPDATE_W w2, w3, w11, w0
ONE_ROUND w2, w26, w27, w20, w21, w22, w23, w24, w25
/* 3 */
UPDATE_W w3, w4, w12, w1
ONE_ROUND w3, w25, w26, w27, w20, w21, w22, w23, w24
/* 4 */
UPDATE_W w4, w5, w13, w2
ONE_ROUND w4, w24, w25, w26, w27, w20, w21, w22, w23
/* 5 */
UPDATE_W w5, w6, w14, w3
ONE_ROUND w5, w23, w24, w25, w26, w27, w20, w21, w22
/* 6 */
UPDATE_W w6, w7, w15, w4
ONE_ROUND w6, w22, w23, w24, w25, w26, w27, w20, w21
/* 7 */
UPDATE_W w7, w8, w0, w5
ONE_ROUND w7, w21, w22, w23, w24, w25, w26, w27, w20
/* 8 */
UPDATE_W w8, w9, w1, w6
ONE_ROUND w8, w20, w21, w22, w23, w24, w25, w26, w27
/* 9 */
UPDATE_W w9, w10, w2, w7
ONE_ROUND w9, w27, w20, w21, w22, w23, w24, w25, w26
/* 10 */
UPDATE_W w10, w11, w3, w8
ONE_ROUND w10, w26, w27, w20, w21, w22, w23, w24, w25
/* 11 */
UPDATE_W w11, w12, w4, w9
ONE_ROUND w11, w25, w26, w27, w20, w21, w22, w23, w24
/* 12 */
UPDATE_W w12, w13, w5, w10
ONE_ROUND w12, w24, w25, w26, w27, w20, w21, w22, w23
/* 13 */
UPDATE_W w13, w14, w6, w11
ONE_ROUND w13, w23, w24, w25, w26, w27, w20, w21, w22
/* 14 */
UPDATE_W w14, w15, w7, w12
ONE_ROUND w14, w22, w23, w24, w25, w26, w27, w20, w21
/* 15 */
UPDATE_W w15, w0, w8, w13
ONE_ROUND w15, w21, w22, w23, w24, w25, w26, w27, w20
/* If the processing length is less than 64 bytes, the loop continues. */
tst x30, #63
bne .Lloop_compress_16_63
/* Stores a - h information. */
ldr x0, [sp, #96]
ldp w10, w11, [x0]
ldp w12, w13, [x0, #4*2]
ldp w14, w15, [x0, #4*4]
ldp w16, w17, [x0, #4*6]
add w20, w20, w10
add w21, w21, w11
add w22, w22, w12
add w23, w23, w13
stp w20, w21, [x0]
add w24, w24, w14
add w25, w25, w15
stp w22, w23, [x0, #4*2]
add w26, w26, w16
add w27, w27, w17
stp w24, w25, [x0, #4*4]
stp w26, w27, [x0, #4*6]
ldr x16, [sp, #104]
/* If the remaining length is not processed, the processing continues for 64 rounds. */
cbnz x30, .Lloop_compress_64
/* The function returns */
ldp x19, x20, [sp, #8*2]
ldp x21, x22, [sp, #8*4]
ldp x23, x24, [sp, #8*6]
ldp x25, x26, [sp, #8*8]
ldp x27, x28, [sp, #8*10]
ldp x29, x30, [sp], #112
.Lend_sha256:
ret
.size SHA256CompressMultiBlocks, .-SHA256CompressMultiBlocks
/*
* Function Description:Performs 64 rounds of compression calculation based on the input plaintext data
* and updates the hash value
* Function prototype:void SHA256CryptoExt(uint32_t hash[8], const uint8_t *in, uint32_t num);
* Input register:
* x0: Storage address of the hash value
* x1: Pointer to the input data address
* x2: Number of 64 rounds of cycles
* Modify the register: x1-x4, v0-v5, v16-v23
* Output register: None
* Function/Macro Call: None
*
*/
.text
.balign 16
.type SHA256CryptoExt, %function
SHA256CryptoExt:
ld1 {v4.4s-v5.4s}, [x0]
.Lloop_compress_64_ext:
adrp x4, .K256
add x4, x4, :lo12:.K256
sub x2, x2, #1
/* 0-15 */
ld1 {v16.16b-v19.16b}, [x1], #64
mov v0.16b, v4.16b
mov v1.16b, v5.16b
rev32 v16.16b, v16.16b
ld1 {v20.4s}, [x4], #16
rev32 v17.16b, v17.16b
ld1 {v21.4s}, [x4], #16
rev32 v18.16b, v18.16b
ld1 {v22.4s}, [x4], #16
add v20.4s, v20.4s, v16.4s
rev32 v19.16b, v19.16b
ld1 {v23.4s}, [x4], #16
sha256su0 v16.4s, v17.4s
mov v2.16b, v0.16b
sha256h q0, q1, v20.4s
sha256h2 q1, q2, v20.4s
add v21.4s, v21.4s, v17.4s
sha256su1 v16.4s, v18.4s, v19.4s
ld1 {v20.4s}, [x4], #16
sha256su0 v17.4s, v18.4s
mov v3.16b, v0.16b
sha256h q0, q1, v21.4s
sha256h2 q1, q3, v21.4s
add v22.4s, v22.4s, v18.4s
sha256su1 v17.4s, v19.4s, v16.4s
ld1 {v21.4s}, [x4], #16
sha256su0 v18.4s, v19.4s
mov v2.16b, v0.16b
sha256h q0, q1, v22.4s
sha256h2 q1, q2, v22.4s
add v23.4s, v23.4s, v19.4s
sha256su1 v18.4s, v16.4s, v17.4s
ld1 {v22.4s}, [x4], #16
sha256su0 v19.4s, v16.4s
mov v3.16b, v0.16b
sha256h q0, q1, v23.4s
sha256h2 q1, q3, v23.4s
add v20.4s, v20.4s, v16.4s
sha256su1 v19.4s, v17.4s, v18.4s
ld1 {v23.4s}, [x4], #16
/* 16-31 */
sha256su0 v16.4s, v17.4s
mov v2.16b, v0.16b
sha256h q0, q1, v20.4s
sha256h2 q1, q2, v20.4s
add v21.4s, v21.4s, v17.4s
sha256su1 v16.4s, v18.4s, v19.4s
ld1 {v20.4s}, [x4], #16
sha256su0 v17.4s, v18.4s
mov v3.16b, v0.16b
sha256h q0, q1, v21.4s
sha256h2 q1, q3, v21.4s
add v22.4s, v22.4s, v18.4s
sha256su1 v17.4s, v19.4s, v16.4s
ld1 {v21.4s}, [x4], #16
mov v2.16b, v0.16b
sha256su0 v18.4s, v19.4s
sha256h q0, q1, v22.4s
sha256h2 q1, q2, v22.4s
add v23.4s, v23.4s, v19.4s
sha256su1 v18.4s, v16.4s, v17.4s
ld1 {v22.4s}, [x4], #16
sha256su0 v19.4s, v16.4s
mov v3.16b, v0.16b
sha256h q0, q1, v23.4s
sha256h2 q1, q3, v23.4s
add v20.4s, v20.4s, v16.4s
sha256su1 v19.4s, v17.4s, v18.4s
ld1 {v23.4s}, [x4], #16
/* 32-47 */
sha256su0 v16.4s, v17.4s
mov v2.16b, v0.16b
sha256h q0, q1, v20.4s
sha256h2 q1, q2, v20.4s
add v21.4s, v21.4s, v17.4s
sha256su1 v16.4s, v18.4s, v19.4s
ld1 {v20.4s}, [x4], #16
sha256su0 v17.4s, v18.4s
mov v3.16b, v0.16b
sha256h q0, q1, v21.4s
sha256h2 q1, q3, v21.4s
add v22.4s, v22.4s, v18.4s
sha256su1 v17.4s, v19.4s, v16.4s
ld1 {v21.4s}, [x4], #16
sha256su0 v18.4s, v19.4s
mov v2.16b, v0.16b
sha256h q0, q1, v22.4s
sha256h2 q1, q2, v22.4s
add v23.4s, v23.4s, v19.4s
sha256su1 v18.4s, v16.4s, v17.4s
ld1 {v22.4s}, [x4], #16
sha256su0 v19.4s, v16.4s
mov v3.16b, v0.16b
sha256h q0, q1, v23.4s
sha256h2 q1, q3, v23.4s
add v20.4s, v20.4s, v16.4s
sha256su1 v19.4s, v17.4s, v18.4s
ld1 {v23.4s}, [x4], #16
/* 48-63 */
mov v2.16b, v0.16b
sha256h q0, q1, v20.4s
add v21.4s, v21.4s, v17.4s
sha256h2 q1, q2, v20.4s
mov v3.16b, v0.16b
sha256h q0, q1, v21.4s
add v22.4s, v22.4s, v18.4s
sha256h2 q1, q3, v21.4s
mov v2.16b, v0.16b
sha256h q0, q1, v22.4s
add v23.4s, v23.4s, v19.4s
sha256h2 q1, q2, v22.4s
mov v3.16b, v0.16b
sha256h q0, q1, v23.4s
sha256h2 q1, q3, v23.4s
/* Add the original hash value */
add v4.4s, v4.4s, v0.4s
add v5.4s, v5.4s, v1.4s
cbnz x2, .Lloop_compress_64_ext
/* Output result */
st1 {v4.4s-v5.4s}, [x0]
ret
.size SHA256CryptoExt, .-SHA256CryptoExt
#endif
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha2/src/asm/sha2_256_armv8.S | Motorola 68K Assembly | unknown | 15,516 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SHA256
.file "sha2_256_x86_64.S"
.set HashAddr, %rdi
.set InAddr, %rsi
.set NUM, %rdx
.set tempFirst, %ebp
.set tempThird, %ebx
.set tempFifth, %edi
.set avx2Temp1, %ymm4
.set avx2Temp2, %ymm5
.set avx2Temp3, %ymm6
.set avx2Temp4, %ymm7
.set avx2Temp5, %ymm10
.set avx2Temp6, %ymm11
.set avx2Temp7, %ymm15
.set BlockFrontMessageW3_0, %xmm0
.set BlockFrontMessageW7_4, %xmm1
.set BlockFrontMessageW11_8, %xmm2
.set BlockFrontMessageW15_12, %xmm3
.set g_maskMerge, %ymm12
.set g_maskShift, %ymm13
.set g_maskTransformEndian, %ymm14
/* Constant value used by sha256. For details about the data source, see the RFC4634 document. */
.section .rodata
.align 64
.type g_K256, %object
g_K256:
.long 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5
.long 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5
.long 0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5
.long 0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5
.long 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3
.long 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3
.long 0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174
.long 0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174
.long 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc
.long 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc
.long 0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da
.long 0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da
.long 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7
.long 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7
.long 0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967
.long 0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967
.long 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13
.long 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13
.long 0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85
.long 0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85
.long 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3
.long 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3
.long 0xd192e819,0xd6990624,0xf40e3585,0x106aa070
.long 0xd192e819,0xd6990624,0xf40e3585,0x106aa070
.long 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5
.long 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5
.long 0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3
.long 0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3
.long 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208
.long 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208
.long 0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2
.long 0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2
.size g_K256, .-g_K256
/* Mask block */
.balign 64
.type g_mask, %object
g_mask:
.long 0x00010203,0x04050607, 0x08090a0b,0x0c0d0e0f
.long 0x00010203,0x04050607, 0x08090a0b,0x0c0d0e0f
.long 0x03020100,0x0b0a0908, 0xffffffff,0xffffffff
.long 0x03020100,0x0b0a0908, 0xffffffff,0xffffffff
.long 0xffffffff,0xffffffff, 0x03020100,0x0b0a0908
.long 0xffffffff,0xffffffff, 0x03020100,0x0b0a0908
.size g_mask, .-g_mask
/*
* Macro description: Processes the fast extension of four messages of two blocks at the same time
* and completes the four-round compression function of the first block.
* Input register:
* WkAddr: Address of the stack space where wi+kt is located.
* a - h: Intermediate variable of hash value
* Modify the register: r8d-r15d, ebp, eax, ebx, ecx, edi, ymm0-ymm10
* Output register:
* a-h: Value after four rounds of cyclic update
* B3_0: Value after data extension
* Naming convention:
* B3_0: w3-w0
* B7_4: w7-w4
* B11_8: w11-w8
* B15_12: w15-w12
* Function/Macro Call:None
* Implementation Description:
* ONE_ROUND algorithm implementation:
* For t = 0 to 63, T1 = h + BSIG1(e) + CH(e,f,g) + Kt + Wt
* T2 = BSIG0(a) + MAJ(a,b,c)
* h = g, g = f, f = e, e = d + T1, d = c, c = b, b = a, a = T1 + T2
* CH( x, y, z) = (x AND y) XOR ( (NOT x) AND z) CH(e,f,g)
* MAJ(a, b, c) = (a AND b) XOR (a AND c) XOR (b AND c)
* = CH(a^b, c, b)
* = ((a XOR b) AND c) XOR ((NOT(a XOR b)) AND b)
* = (b XOR c) AND (a XOR b) XOR b
* BSIG0(x) = ROTR^2(x) XOR ROTR^13(x) XOR ROTR^22(x) BSIG0(a)
* BSIG1(x) = ROTR^6(x) XOR ROTR^11(x) XOR ROTR^25(x) BSIG1(e)
* Optimization idea: b xor c in the next round of MAJ is a xor b in the previous round of MAJ
* to avoid redundant calculation.
*
* UPDATE_4W algorithm implementation:
* For t = 0 to 15 Wt = W0_W15(input w0-w15)
* For t = 16 to 63 Wt = SSIG1(W(t-2)) + W(t-7) + SSIG0(w(t-15)) + W(t-16)
* SSIG0(x) = ROTR^7(x) XOR ROTR^18(x) XOR SHR^3(x)
* SSIG1(x) = ROTR^17(x) XOR ROTR^19(x) XOR SHR^10(x)
* Optimization idea: Optimization point 1: Each WI message block is 32-bit, and the xmm register is
* a 128-bit register. Therefore, the common operation of four WI messages can be
* performed at the same time (SSIG0, W(t-16), W(t-7)).
* Due to the dependency of wi, four wis are calculated each time as the
* optimal solution found so far.
* Optimization point 2: The ymm register is a 256-bit register. Therefore, two rounds
* of 128-bit calculation can be performed at the same time, and two blocks can be used
* for the same calculation.
*/
.macro FOUR_ROUND_UPDATE_4W a, b, c, d, e, f, g, h, tempSwitch2, tempSwitch4, WkAddr, B3_0, B7_4, B11_8, B15_12
vpalignr $4,\B3_0,\B7_4,avx2Temp1 // avx2Temp1->w4_1
add \WkAddr(%rsp),\h // h += Kt + Wt
and \e, tempFifth // e&f
rorx $6, \e, \tempSwitch2 // ROTR^6(e)
add tempFirst, \a // a += BSIG0(a) from last round
rorx $11, \e, tempThird // ROTR^11(e)
andn \g, \e, tempFirst // (~e)&g
xor \tempSwitch2, tempThird // ROTR^6(e) ^ ROTR^11(e)
xor tempFirst, tempFifth // CH(e,f,g)
vpshufd $250, \B15_12, avx2Temp5
rorx $25, \e, \tempSwitch2 // ROTR^25(e)
add tempFifth, \h // h += CH(e,f,g)
xor \tempSwitch2, tempThird // BSIG1(e)
vpalignr $4, \B11_8, \B15_12, avx2Temp2 // avx2Temp2->w12_9
vpslld $14, avx2Temp1, avx2Temp4 // w4_1<<datum line 14
rorx $2, \a, tempFirst // ROTR^2(a)
mov \a, \tempSwitch2 // a
add tempThird, \h // h += BSIG1(e)[h->T1]
vpsrld $3, avx2Temp1, avx2Temp3 // w4_1>>datum line 3
rorx $13, \a, tempFifth // ROTR^13(a)
xor \b, \tempSwitch2 // b^a for next round b^c
add \h, \d // d += T1
vpsrld $10, avx2Temp5, avx2Temp6 // >>10
xor tempFifth, tempFirst // ROTR^2(a) ^ ROTR^13(a)
and \tempSwitch2, \tempSwitch4 // (b^a) & (b^c)
vpsrld $7, avx2Temp1, avx2Temp1 // >>7
vpaddd avx2Temp2, \B3_0, \B3_0
rorx $22, \a, tempThird // ROTR^22(a)
add 4+\WkAddr(%rsp),\g // h += Kt + Wt
xor \b, \tempSwitch4 // Maj(a,b,c)
vpxor avx2Temp3, avx2Temp4, avx2Temp3 // 3 xor 14
mov \e, tempFifth // for next round f
xor tempThird, tempFirst // BSIG0(a)
vpsrlq $17, avx2Temp5, avx2Temp7 // >>17
add \tempSwitch4, \h // h += Maj(a,b,c)
and \d, tempFifth // e&f
rorx $6, \d, \tempSwitch4
add tempFirst, \h // a += BSIG0(a) from last round
vpxor avx2Temp3, avx2Temp1, avx2Temp3 // 7xor14xor3
vpsrlq $19, avx2Temp5, avx2Temp5 // >>19
rorx $11, \d, tempThird
andn \f, \d, tempFirst
xor \tempSwitch4, tempThird
vpsrld $11, avx2Temp1, avx2Temp1 // >>18
xor tempFirst, tempFifth
rorx $25, \d, \tempSwitch4
add tempFifth, \g
xor \tempSwitch4, tempThird
vpslld $11, avx2Temp4, avx2Temp4 // <<25
rorx $2, \h, tempFirst
mov \h, \tempSwitch4
add tempThird, \g
rorx $13, \h,tempFifth
xor \a, \tempSwitch4
vpxor avx2Temp7, avx2Temp6, avx2Temp7 // 17xor10
add \g, \c
xor tempFifth, tempFirst
vpxor avx2Temp3, avx2Temp1, avx2Temp3 // 7xor14xor3xor18
and \tempSwitch4, \tempSwitch2
rorx $22, \h, tempThird
add 8+\WkAddr(%rsp),\f
xor \a, \tempSwitch2
vpxor avx2Temp7, avx2Temp5, avx2Temp7 // 17xor10xor19
mov \d, tempFifth
xor tempThird, tempFirst
add \tempSwitch2, \g
vpshufb g_maskMerge, avx2Temp7, avx2Temp7 // BSIG1 w15_14
vpxor avx2Temp3, avx2Temp4, avx2Temp3 // 7xor14xor3xor18xor25
and \c, tempFifth
rorx $6, \c, \tempSwitch2
add tempFirst, \g
rorx $11, \c, tempThird
vpaddd avx2Temp3, \B3_0, \B3_0 // BSIG0+w(t-16)+w(t-7)
andn \e, \c, tempFirst
xor \tempSwitch2, tempThird
xor tempFirst, tempFifth
rorx $25, \c, \tempSwitch2
add tempFifth, \f
xor \tempSwitch2, tempThird
rorx $2, \g, tempFirst
mov \g, \tempSwitch2
add tempThird, \f
rorx $13, \g, tempFifth
vpaddd \B3_0, avx2Temp7, \B3_0 // w17_16
xor \h, \tempSwitch2
add \f, \b
xor tempFifth, tempFirst
and \tempSwitch2, \tempSwitch4
vpshufd $80, \B3_0, avx2Temp1
rorx $22, \g, tempThird
add 12+\WkAddr(%rsp),\e
xor \h, \tempSwitch4
mov \c, tempFifth
xor tempThird, tempFirst
add \tempSwitch4, \f
vpsrld $10, avx2Temp1, avx2Temp2 // >>10
and \b, tempFifth
rorx $6, \b, \tempSwitch4
vpsrlq $17, avx2Temp1, avx2Temp3 // >>17
add tempFirst, \f
rorx $11, \b, tempThird
andn \d, \b, tempFirst
xor \tempSwitch4, tempThird
vpsrlq $19,avx2Temp1, avx2Temp1 // >>19
xor tempFirst, tempFifth
rorx $25, \b, \tempSwitch4
add tempFifth, \e
xor \tempSwitch4, tempThird
vpxor avx2Temp2, avx2Temp3, avx2Temp3 // 10xor17
rorx $2, \f, tempFirst
mov \f, \tempSwitch4
add tempThird, \e
rorx $13, \f, tempFifth
xor \g, \tempSwitch4
vpxor avx2Temp3, avx2Temp1, avx2Temp3 // 10xor17xor19
add \e, \a
xor tempFifth, tempFirst
and \tempSwitch4, \tempSwitch2
rorx $22, \f, tempThird
vpshufb g_maskShift, avx2Temp3, avx2Temp3 // BSIG1(W17_16)Move to the desired location
xor \g, \tempSwitch2
mov \b, tempFifth
xor tempThird, tempFirst
add \tempSwitch2, \e
vpaddd avx2Temp3, \B3_0, \B3_0 // W19_16
.endm
/*
* Macro description: Processes the update of a round of hash values in 64 rounds of compression.
* Input register:
* wkAddr: wi+kt Stack space address.
* a - h: Intermediate variable of hash value
* Modify the register: r8d-r15d, ebp, eax, ebx, ecx, edi
* Output register:
* a-h: Indicates the value after a cyclic update.
* Function/Macro Call:None
* ONE_ROUND Algorithm Implementation:
* For t = 0 to 63, T1 = h + BSIG1(e) + CH(e,f,g) + Kt + Wt
* T2 = BSIG0(a) + MAJ(a,b,c)
* h = g, g = f, f = e, e = d + T1, d = c, c = b, b = a, a = T1 + T2
* CH( x, y, z) = (x AND y) XOR ( (NOT x) AND z) CH(e,f,g)
* MAJ(a, b, c) = (a AND b) XOR (a AND c) XOR (b AND c)
* = CH(a^b, c, b)
* = ((a XOR b) AND c) XOR ((NOT(a XOR b)) AND b)
* = (b XOR c) AND (a XOR b) XOR b
* BSIG0(x) = ROTR^2(x) XOR ROTR^13(x) XOR ROTR^22(x) BSIG0(a)
* BSIG1(x) = ROTR^6(x) XOR ROTR^11(x) XOR ROTR^25(x) BSIG1(e)
* Optimization idea: b xor c in the next round of MAJ is a xor b in the
* previous round of MAJ to avoid redundant calculation.
* Note: At the end of each round, the tempSwitch2 and tempSwitch4 of the next round need to be exchanged.
*/
.macro ONE_ROUND a, b, c, d, e, f, g, h, tempSwitch2, tempSwitch4, WkAddr
rorx $11, \e, tempThird // ROTR^11(e)
rorx $6, \e, \tempSwitch2 // ROTR^6(e)
add tempFirst, \a // a += BSIG0(a) from last round
and \e, tempFifth // e&f
andn \g, \e, tempFirst // (~e)&g
xor \tempSwitch2, tempThird // ROTR^6(e) ^ ROTR^11(e)
add \WkAddr(%rsp),\h // h += Kt + Wt
xor tempFirst, tempFifth // CH(e,f,g)
rorx $25, \e, \tempSwitch2 // ROTR^25(e)
add tempFifth, \h // h += CH(e,f,g)
xor \tempSwitch2, tempThird // BSIG1(e)
rorx $2, \a, tempFirst // ROTR^2(a)
mov \a, \tempSwitch2 // a
leal (tempThird, \h), \h // h += BSIG1(e)[h->T1]
rorx $13, \a, tempFifth // ROTR^13(a)
xor \b, \tempSwitch2 // b^a for next round b^c
add \h, \d // d += T1
xor tempFifth, tempFirst // ROTR^2(a) ^ ROTR^13(a)
and \tempSwitch2, \tempSwitch4 // (b^a) & (b^c)
rorx $22, \a, tempThird // ROTR^22(a)
xor \b, \tempSwitch4 // Maj(a,b,c)
mov \e, tempFifth // for next round f
xor tempThird, tempFirst // BSIG0(a)
add \tempSwitch4, \h // h += Maj(a,b,c)
.endm
/*
* Function description: Performs 64 rounds of compression calculation based on the input plaintext data and updates the hash value.
* function prototype:void SHA256CompressMultiBlocks(uint32_t hash[8], const uint8_t *in, uint32_t num);
* Input register:
* rdi: Storage address of the hash value
* rsi: Pointer to the input data address (Wi)
* rdx: Number of 64 rounds of cycles. (You need to do several blocks, that is, you need to do several loops.)
* Modify the register: r0-r14
* Output register: None
* Function/Macro Call: None
*/
.text
.globl SHA256CompressMultiBlocks
.type SHA256CompressMultiBlocks,%function
.align 4
SHA256CompressMultiBlocks:
.cfi_startproc
/* Determine whether to end the process directly. */
cmp $0, NUM
je .LEND_SHA256
/* Pop-stack/push stack protection */
pushq %r14
pushq %rbx
pushq %rbp
pushq %r12
pushq %r13
pushq %r15
/* The pre-stored stack space and 32-byte address are aligned.
The original RSP value is added to the stack and the mask is assigned. */
mov %rsp, %r14
mov 0(HashAddr), %r8d
sub $600, %rsp
vmovdqa g_mask + 0(%rip), g_maskTransformEndian
mov 4(HashAddr), %r9d
mov 8(HashAddr), %r10d
and $-256, %rsp
vmovdqa g_mask + 64(%rip), g_maskShift
mov 12(HashAddr), %r11d
mov %r14, 0(%rsp)
/* r8d-r15d: a-h */
mov 16(HashAddr), %r12d
mov 20(HashAddr), %r13d
vmovdqa g_mask + 32(%rip), g_maskMerge
mov 24(HashAddr), %r14d
mov 28(HashAddr), %r15d
.LEND_SHA256_LOOP:
mov InAddr, %rcx
/* Loads the data of a block to the lower 128 bits of the ymm register. */
vmovdqu 0(InAddr), BlockFrontMessageW3_0
vmovdqu 16(InAddr), BlockFrontMessageW7_4
vmovdqu 32(InAddr), BlockFrontMessageW11_8
vmovdqu 48(InAddr), BlockFrontMessageW15_12
/* block Judgment condition processing */
leaq 64(InAddr), InAddr
cmp $1, NUM
cmovne InAddr, %rcx // If num is greater than 1, rcx points to the next block.
/* Load the data of another block to the upper 128 bits of the ymm register. */
vinserti128 $1, 0(%rcx), %ymm0, %ymm0
vinserti128 $1, 16(%rcx), %ymm1, %ymm1
vpshufb g_maskTransformEndian, %ymm0, %ymm0
mov NUM, 16(%rsp)
vinserti128 $1, 32(%rcx), %ymm2, %ymm2
mov HashAddr, 24(%rsp)
vpshufb g_maskTransformEndian, %ymm1, %ymm1
vinserti128 $1, 48(%rcx), %ymm3, %ymm3
vpshufb g_maskTransformEndian, %ymm2, %ymm2
add $64, %rcx
leaq g_K256(%rip), NUM
/* Little-endian order to big-endian order, wi + kt:ymm9-11*/
mov %rcx, 8(%rsp)
leaq 32(%rsp), %rsp
vpaddd 0(NUM), %ymm0, %ymm8
mov %r9d, %ecx
vpaddd 32(NUM), %ymm1, %ymm9
vmovdqa %ymm8, 0(%rsp)
vpshufb g_maskTransformEndian, %ymm3, %ymm3
xor %ebp, %ebp
vpaddd 64(NUM), %ymm2, %ymm10
vmovdqu %ymm9, 32(%rsp)
xor %r10d, %ecx
vpaddd 96(NUM), %ymm3, %ymm11
mov %r13d, %edi
vmovdqa %ymm10, 64(%rsp)
vmovdqu %ymm11, 96(%rsp)
.LEND_SHA256_ROUND_00_47:
/* Next round wi + kt: ymm9-11, 16 rounds of compression + 4 rounds of message block expansion */
/* FOUR_ROUND_UPDATE_4W a, b, c, d, e, f, g, h, tempSwitch2,tempSwitch4, WkAddr,B3_0, B7_4, B11_8, B15_12 */
FOUR_ROUND_UPDATE_4W %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %eax, %ecx, 0, %ymm0, %ymm1, %ymm2, %ymm3
leaq 128(NUM), NUM
FOUR_ROUND_UPDATE_4W %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %eax, %ecx, 32, %ymm1, %ymm2, %ymm3, %ymm0
vpaddd 0(NUM), %ymm0, %ymm8
FOUR_ROUND_UPDATE_4W %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %eax, %ecx, 64, %ymm2, %ymm3, %ymm0, %ymm1
vpaddd 32(NUM), %ymm1, %ymm9
vmovdqa %ymm8, 128(%rsp)
FOUR_ROUND_UPDATE_4W %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %eax, %ecx, 96, %ymm3, %ymm0, %ymm1, %ymm2
vpaddd 64(NUM), %ymm2, %ymm10
vmovdqa %ymm9, 160(%rsp)
vpaddd 96(NUM), %ymm3, %ymm11
vmovdqu %ymm10, 192(%rsp)
vmovdqa %ymm11, 224(%rsp)
/* Next round wi + kt: ymm9-11, 16 rounds of compression + 4 rounds of message block expansion */
/* FOUR_ROUND_UPDATE_4W a, b, c, d, e, f, g, h, tempSwitch2,tempSwitch4, WkAddr,B19_16, B23_20, B27_24, B31_27 */
FOUR_ROUND_UPDATE_4W %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %eax, %ecx, 128, %ymm0, %ymm1, %ymm2, %ymm3
leaq 128(NUM), NUM
FOUR_ROUND_UPDATE_4W %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %eax, %ecx, 160, %ymm1, %ymm2, %ymm3, %ymm0
vpaddd 0(NUM), %ymm0, %ymm8
FOUR_ROUND_UPDATE_4W %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %eax, %ecx, 192, %ymm2, %ymm3, %ymm0, %ymm1
vpaddd 32(NUM), %ymm1, %ymm9
vmovdqa %ymm8, 256(%rsp)
FOUR_ROUND_UPDATE_4W %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %eax, %ecx, 224, %ymm3, %ymm0, %ymm1, %ymm2
vpaddd 64(NUM), %ymm2, %ymm10
vmovdqa %ymm9, 288(%rsp)
vpaddd 96(NUM), %ymm3, %ymm11
vmovdqu %ymm10, 320(%rsp)
vmovdqa %ymm11, 352(%rsp)
/* Next round wi + kt: ymm9-11, 16 rounds of compression + 4 rounds of message block expansion */
/* FOUR_ROUND_UPDATE_4W a, b, c, d, e, f, g, h, tempSwitch2,tempSwitch4, WkAddr,B35_32, B39_36, B43_40, B47_44 */
FOUR_ROUND_UPDATE_4W %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %eax, %ecx, 256, %ymm0, %ymm1, %ymm2, %ymm3
leaq 128(NUM), NUM
FOUR_ROUND_UPDATE_4W %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %eax, %ecx, 288, %ymm1, %ymm2, %ymm3, %ymm0
vpaddd 0(NUM), %ymm0, %ymm8
FOUR_ROUND_UPDATE_4W %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %eax, %ecx, 320, %ymm2, %ymm3, %ymm0, %ymm1
vpaddd 32(NUM), %ymm1, %ymm9
vmovdqa %ymm8, 384(%rsp)
FOUR_ROUND_UPDATE_4W %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %eax, %ecx, 352, %ymm3, %ymm0, %ymm1, %ymm2
vpaddd 64(NUM), %ymm2, %ymm10
vmovdqa %ymm9, 416(%rsp)
vpaddd 96(NUM), %ymm3, %ymm11
vmovdqu %ymm10, 448(%rsp)
vmovdqa %ymm11, 480(%rsp)
.LEND_SHA256_ROUND_48_63:
/* ONE_ROUND a, b, c, d, e, f, g, h, tempSwitch2, Fourth, WkAddr */
ONE_ROUND %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %eax, %ecx, 384
ONE_ROUND %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %ecx, %eax, 388
ONE_ROUND %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %eax, %ecx, 392
ONE_ROUND %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %ecx, %eax, 396
ONE_ROUND %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %eax, %ecx, 416
ONE_ROUND %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %ecx, %eax, 420
ONE_ROUND %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %eax, %ecx, 424
ONE_ROUND %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %ecx, %eax, 428
ONE_ROUND %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %eax, %ecx, 448
ONE_ROUND %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %ecx, %eax, 452
ONE_ROUND %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %eax, %ecx, 456
ONE_ROUND %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %ecx, %eax, 460
ONE_ROUND %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %eax, %ecx, 480
ONE_ROUND %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %ecx, %eax, 484
ONE_ROUND %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %eax, %ecx, 488
ONE_ROUND %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %ecx, %eax, 492
sub $32, %rsp
add %ebp, %r8d // a+=BSIG0
mov 24(%rsp), HashAddr
/* Update the storage hash value. */
add 0(HashAddr), %r8d
add 4(HashAddr), %r9d
mov %r8d, 0(HashAddr)
add 8(HashAddr), %r10d
mov %r9d, 4(HashAddr)
add 12(HashAddr), %r11d
mov %r10d, 8(HashAddr)
add 16(HashAddr), %r12d
mov 16(%rsp), NUM
mov %r11d, 12(HashAddr)
add 20(HashAddr), %r13d
mov %r12d, 16(HashAddr)
add 24(HashAddr), %r14d
mov %r13d, 20(HashAddr)
add 28(HashAddr), %r15d
mov %r14d, 24(HashAddr)
mov %r15d, 28(HashAddr)
cmp $1, NUM
je .LEND_SHA256_FINFISH_INITIAL
/* Data compression of the second block */
xor %ebp, %ebp
mov %r9d, %ecx
xor %r10d, %ecx
mov %r13d, %edi
.LEND_SHA256_NEXT_BLOCK:
/* 0-15 */
/* ONE_ROUND a, b, c, d, e, f, g, h, tempSwitch2,tempSwitch4, WkAddr */
ONE_ROUND %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %eax, %ecx, 16+32
ONE_ROUND %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %ecx, %eax, 20+32
ONE_ROUND %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %eax, %ecx, 24+32
ONE_ROUND %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %ecx, %eax, 28+32
ONE_ROUND %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %eax, %ecx, 48+32
ONE_ROUND %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %ecx, %eax, 52+32
ONE_ROUND %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %eax, %ecx, 56+32
ONE_ROUND %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %ecx, %eax, 60+32
ONE_ROUND %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %eax, %ecx, 80+32
ONE_ROUND %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %ecx, %eax, 84+32
ONE_ROUND %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %eax, %ecx, 88+32
ONE_ROUND %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %ecx, %eax, 92+32
ONE_ROUND %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %eax, %ecx, 112+32
ONE_ROUND %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %ecx, %eax, 116+32
ONE_ROUND %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %eax, %ecx, 120+32
ONE_ROUND %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %ecx, %eax, 124+32
/* 16-31 */
ONE_ROUND %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %eax, %ecx, 16+128+32
ONE_ROUND %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %ecx, %eax, 20+128+32
ONE_ROUND %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %eax, %ecx, 24+128+32
ONE_ROUND %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %ecx, %eax, 28+128+32
ONE_ROUND %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %eax, %ecx, 48+128+32
ONE_ROUND %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %ecx, %eax, 52+128+32
ONE_ROUND %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %eax, %ecx, 56+128+32
ONE_ROUND %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %ecx, %eax, 60+128+32
ONE_ROUND %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %eax, %ecx, 80+128+32
ONE_ROUND %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %ecx, %eax, 84+128+32
ONE_ROUND %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %eax, %ecx, 88+128+32
ONE_ROUND %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %ecx, %eax, 92+128+32
ONE_ROUND %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %eax, %ecx, 112+128+32
ONE_ROUND %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %ecx, %eax, 116+128+32
ONE_ROUND %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %eax, %ecx, 120+128+32
ONE_ROUND %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %ecx, %eax, 124+128+32
/* 32-47 */
ONE_ROUND %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %eax, %ecx, 16+256+32
ONE_ROUND %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %ecx, %eax, 20+256+32
ONE_ROUND %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %eax, %ecx, 24+256+32
ONE_ROUND %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %ecx, %eax, 28+256+32
ONE_ROUND %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %eax, %ecx, 48+256+32
ONE_ROUND %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %ecx, %eax, 52+256+32
ONE_ROUND %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %eax, %ecx, 56+256+32
ONE_ROUND %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %ecx, %eax, 60+256+32
ONE_ROUND %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %eax, %ecx, 80+256+32
ONE_ROUND %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %ecx, %eax, 84+256+32
ONE_ROUND %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %eax, %ecx, 88+256+32
ONE_ROUND %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %ecx, %eax, 92+256+32
ONE_ROUND %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %eax, %ecx, 112+256+32
ONE_ROUND %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %ecx, %eax, 116+256+32
ONE_ROUND %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %eax, %ecx, 120+256+32
ONE_ROUND %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %ecx, %eax, 124+256+32
/* 48-63 */
ONE_ROUND %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %eax, %ecx, 16+384+32
ONE_ROUND %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %ecx, %eax, 20+384+32
ONE_ROUND %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %eax, %ecx, 24+384+32
ONE_ROUND %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %ecx, %eax, 28+384+32
ONE_ROUND %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %eax, %ecx, 48+384+32
ONE_ROUND %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %ecx, %eax, 52+384+32
ONE_ROUND %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %eax, %ecx, 56+384+32
ONE_ROUND %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %ecx, %eax, 60+384+32
ONE_ROUND %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %eax, %ecx, 80+384+32
ONE_ROUND %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %ecx, %eax, 84+384+32
ONE_ROUND %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %r13d, %eax, %ecx, 88+384+32
ONE_ROUND %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %r12d, %ecx, %eax, 92+384+32
ONE_ROUND %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %r11d, %eax, %ecx, 112+384+32
ONE_ROUND %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %r10d, %ecx, %eax, 116+384+32
ONE_ROUND %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %r9d, %eax, %ecx, 120+384+32
ONE_ROUND %r9d, %r10d, %r11d, %r12d, %r13d, %r14d, %r15d, %r8d, %ecx, %eax, 124+384+32
mov 24(%rsp), HashAddr
lea (%ebp, %r8d), %r8d // a+=BSIG0
/* Update the storage hash value. */
add 0(HashAddr), %r8d
add 4(HashAddr), %r9d
mov %r8d, 0(HashAddr)
add 8(HashAddr), %r10d
mov %r9d, 4(HashAddr)
add 12(HashAddr), %r11d
mov %r10d, 8(HashAddr)
add 16(HashAddr), %r12d
mov %r11d, 12(HashAddr)
add 20(HashAddr), %r13d
mov %r12d, 16(HashAddr)
mov 8(%rsp), InAddr
add 24(HashAddr), %r14d
mov %r13d, 20(HashAddr)
mov 16(%rsp), NUM
add 28(HashAddr), %r15d
mov %r14d, 24(HashAddr)
mov %r15d, 28(HashAddr)
sub $2, NUM
ja .LEND_SHA256_LOOP
.LEND_SHA256_FINFISH_INITIAL:
/* Registers and pointers are reset. */
mov 0(%rsp), %rsp
popq %r15
popq %r13
popq %r12
popq %rbp
popq %rbx
popq %r14
.LEND_SHA256:
ret
.cfi_endproc
.size SHA256CompressMultiBlocks, .-SHA256CompressMultiBlocks
#endif
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha2/src/asm/sha2_256_x86_64.S | Unix Assembly | unknown | 30,666 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SHA512
.arch armv8-a+crypto
/* sha512 used constant value. For the data source, see the RFC4634 document. */
.section .rodata
.balign 64
.K512:
.quad 0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc
.quad 0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118
.quad 0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2
.quad 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694
.quad 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65
.quad 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5
.quad 0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4
.quad 0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70
.quad 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df
.quad 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b
.quad 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30
.quad 0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8
.quad 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8
.quad 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3
.quad 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec
.quad 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b
.quad 0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178
.quad 0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b
.quad 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c
.quad 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817
/**
* Macro description: Update the processed 64-bit plaintext information W.
* Input register:
* wi_16: W[i-16]
* wi_15: W[i-15]
* wi_7: W[i-7]
* wi_2: W[i-2]
* Modify the register: wi_16 x17 x28.
* Output register:
* wi_16: latest W[i] value, W[i] = sigma1(W[i-2]) + W[i-7] + sigma0(W[i-15]) + W[i-16]
* Function/Macro Call: None
*/
.macro UPDATE_W wi_16, wi_15, wi_7, wi_2
ror x28, \wi_15, #1
ror x17, \wi_2, #19
eor x28, x28, \wi_15, ror#8
eor x17, x17, \wi_2, ror#61
eor x28, x28, \wi_15, lsr#7
eor x17, x17, \wi_2, lsr#6
add \wi_16, \wi_16, \wi_7
add \wi_16, \wi_16, x28
add \wi_16, \wi_16, x17
.endm
/**
* Macro description: Processes the update of a hash value in 80 rounds of compression.
* Input register:
* x19: indicates the address of the corresponding element in the g_k512 constant.
* wi: plaintext data after processing
* a - h: intermediate variable of the hash value
* Modify the register: h d x16 x17 x28 x29
* Output register:
* h: value after a round of cyclic update
* d: value after a round of cyclic update
* Function/Macro Call: None
*/
.macro ONE_ROUND wi, a, b, c, d, e, f, g, h
ldr x16, [x19], #8 // K[i]
add \h, \h, x16 // h += K[i]
add \h, \h, \wi // h += W[i]
and x17, \f, \e // e&f
bic x28, \g, \e // g&(~e)
orr x17, x17, x28 // Ch(e, f, g) = e&f | g&(~e)
add \h, \h, x17 // h += Ch(e, f, g)
eor x29, \e, \e, ror#23
ror x16, \e, #14
eor x29, x16, x29, ror#18 // Sigma1(e) = ROR(e, 14) ^ ROR(e, 18) ^ ROR(e, 41)
add \h, \h, x29 // h += Sigma1(e)
eor x17, \a, \b // a^b
eor x28, \a, \c // a^c
and x28, x28, x17 // (a^b)&(a^c)
eor x28, x28, \a // Maj(a, b, c) = ((a^b)&(a^c))^a = (a&b)^(b&c)^(a&c)
add \d, \d, \h // d += h
add \h, \h, x28 // h += Maj(a, b, c)
eor x29, \a, \a, ror#5
ror x16, \a, #28
eor x29, x16, x29, ror#34 // Sigma0(a) = ROR(a, 28)^ROR(a, 34)^ROR(a, 39)
add \h, \h, x29 // h += Sigma0(a)
.endm
/**
* Function description: Performs 80 rounds of compression calculation
*based on the input plaintext data and updates the hash value.
* Function prototype: void SHA512CompressMultiBlocks(uint64_t hash[8], const uint8_t *in, uint32_t num);
* Input register:
* x0: indicates the storage address of the hash value.
* x1: pointer to the input data address
* x2: number of 80 rounds of cycles. The value is the input data length divided by 128.
* Change register: x0-x17.
* Output register: None
* Function/Macro Call: None
*
*/
.text
.balign 16
.global SHA512CompressMultiBlocks
.type SHA512CompressMultiBlocks, %function
SHA512CompressMultiBlocks:
cbz x2, .Lend_sha512
stp x29, x30, [sp, #-112]!
add x29, sp, #0
stp x19, x20, [sp, #8*2]
stp x21, x22, [sp, #8*4]
stp x23, x24, [sp, #8*6]
stp x25, x26, [sp, #8*8]
stp x27, x28, [sp, #8*10]
/* load a - h */
ldp x20, x21, [x0]
ldp x22, x23, [x0, #8*2]
ldp x24, x25, [x0, #8*4]
ldp x26, x27, [x0, #8*6]
str x0, [sp, #96]
mov x16, x1 // input Value Address
lsl x30, x2, #2
.Lloop_compress_80:
/* Start 80 rounds of processing */
adrp x19, .K512
add x19, x19, :lo12:.K512
ldp x0, x1, [x16] // Load input values.
ldp x2, x3, [x16, #8*2]
ldp x4, x5, [x16, #8*4]
ldp x6, x7, [x16, #8*6]
ldp x8, x9, [x16, #8*8]
ldp x10, x11, [x16, #8*10]
ldp x12, x13, [x16, #8*12]
ldp x14, x15, [x16, #8*14]
add x16, x16, #8*16
str x16, [sp, #104]
#ifndef HITLS_BIG_ENDIAN
rev x0, x0
rev x1, x1
rev x2, x2
rev x3, x3
rev x4, x4
rev x5, x5
rev x6, x6
rev x7, x7
rev x8, x8
rev x9, x9
rev x10, x10
rev x11, x11
rev x12, x12
rev x13, x13
rev x14, x14
rev x15, x15
#endif
/* x16 x17 x28 x29 used as a temporary register */
ONE_ROUND x0, x20, x21, x22, x23, x24, x25, x26, x27
ONE_ROUND x1, x27, x20, x21, x22, x23, x24, x25, x26
ONE_ROUND x2, x26, x27, x20, x21, x22, x23, x24, x25
ONE_ROUND x3, x25, x26, x27, x20, x21, x22, x23, x24
ONE_ROUND x4, x24, x25, x26, x27, x20, x21, x22, x23
ONE_ROUND x5, x23, x24, x25, x26, x27, x20, x21, x22
ONE_ROUND x6, x22, x23, x24, x25, x26, x27, x20, x21
ONE_ROUND x7, x21, x22, x23, x24, x25, x26, x27, x20
ONE_ROUND x8, x20, x21, x22, x23, x24, x25, x26, x27
ONE_ROUND x9, x27, x20, x21, x22, x23, x24, x25, x26
ONE_ROUND x10, x26, x27, x20, x21, x22, x23, x24, x25
ONE_ROUND x11, x25, x26, x27, x20, x21, x22, x23, x24
ONE_ROUND x12, x24, x25, x26, x27, x20, x21, x22, x23
ONE_ROUND x13, x23, x24, x25, x26, x27, x20, x21, x22
ONE_ROUND x14, x22, x23, x24, x25, x26, x27, x20, x21
ONE_ROUND x15, x21, x22, x23, x24, x25, x26, x27, x20
.Lloop_compress_16_79:
/* Start 16 - 31, 32 - 47, 48 - 63, 64 - 79 compression */
sub x30, x30, #1
/* 0 */
UPDATE_W x0, x1, x9, x14
ONE_ROUND x0, x20, x21, x22, x23, x24, x25, x26, x27
/* 1 */
UPDATE_W x1, x2, x10, x15
ONE_ROUND x1, x27, x20, x21, x22, x23, x24, x25, x26
/* 2 */
UPDATE_W x2, x3, x11, x0
ONE_ROUND x2, x26, x27, x20, x21, x22, x23, x24, x25
/* 3 */
UPDATE_W x3, x4, x12, x1
ONE_ROUND x3, x25, x26, x27, x20, x21, x22, x23, x24
/* 4 */
UPDATE_W x4, x5, x13, x2
ONE_ROUND x4, x24, x25, x26, x27, x20, x21, x22, x23
/* 5 */
UPDATE_W x5, x6, x14, x3
ONE_ROUND x5, x23, x24, x25, x26, x27, x20, x21, x22
/* 6 */
UPDATE_W x6, x7, x15, x4
ONE_ROUND x6, x22, x23, x24, x25, x26, x27, x20, x21
/* 7 */
UPDATE_W x7, x8, x0, x5
ONE_ROUND x7, x21, x22, x23, x24, x25, x26, x27, x20
/* 8 */
UPDATE_W x8, x9, x1, x6
ONE_ROUND x8, x20, x21, x22, x23, x24, x25, x26, x27
/* 9 */
UPDATE_W x9, x10, x2, x7
ONE_ROUND x9, x27, x20, x21, x22, x23, x24, x25, x26
/* 10 */
UPDATE_W x10, x11, x3, x8
ONE_ROUND x10, x26, x27, x20, x21, x22, x23, x24, x25
/* 11 */
UPDATE_W x11, x12, x4, x9
ONE_ROUND x11, x25, x26, x27, x20, x21, x22, x23, x24
/* 12 */
UPDATE_W x12, x13, x5, x10
ONE_ROUND x12, x24, x25, x26, x27, x20, x21, x22, x23
/* 13 */
UPDATE_W x13, x14, x6, x11
ONE_ROUND x13, x23, x24, x25, x26, x27, x20, x21, x22
/* 14 */
UPDATE_W x14, x15, x7, x12
ONE_ROUND x14, x22, x23, x24, x25, x26, x27, x20, x21
/* 15 */
UPDATE_W x15, x0, x8, x13
ONE_ROUND x15, x21, x22, x23, x24, x25, x26, x27, x20
/* If the processing length is not 80, continue the loop. */
tst x30, #3
bne .Lloop_compress_16_79
/* Stores a - h information. */
ldr x0, [sp, #96]
ldp x10, x11, [x0]
ldp x12, x13, [x0, #8*2]
ldp x14, x15, [x0, #8*4]
ldp x16, x17, [x0, #8*6]
add x20, x20, x10
add x21, x21, x11
add x22, x22, x12
add x23, x23, x13
add x24, x24, x14
add x25, x25, x15
add x26, x26, x16
add x27, x27, x17
stp x20, x21, [x0]
stp x22, x23, [x0, #8*2]
stp x24, x25, [x0, #8*4]
stp x26, x27, [x0, #8*6]
ldr x16, [sp, #104]
/* If the remaining length is not processed, continue to process 80 rounds. */
cbnz x30, .Lloop_compress_80
/* The function returns */
ldp x19, x20, [sp, #8*2]
ldp x21, x22, [sp, #8*4]
ldp x23, x24, [sp, #8*6]
ldp x25, x26, [sp, #8*8]
ldp x27, x28, [sp, #8*10]
ldp x29, x30, [sp], #112
.Lend_sha512:
ret
.size SHA512CompressMultiBlocks, .-SHA512CompressMultiBlocks
#endif
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha2/src/asm/sha2_512_armv8.S | Unix Assembly | unknown | 10,889 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SHA512
.file "sha2_512_x86_64.S"
.set TEMP1, %rbp
.set TEMP2, %rax
.set TEMP3, %rbx
.set TEMP4, %rcx
.set TEMP5, %rdi
.set YTEMP1, %ymm8
.set YTEMP2, %ymm9
.set YTEMP3, %ymm10
.set YTEMP4, %ymm11
.set YTEMP5, %ymm12
.set YTEMP6, %ymm13
.set YTEMP7, %ymm14
.equ SHA512_wk, 0
.equ SHA512_in, SHA512_wk + 1280
.equ SHA512_hash, SHA512_in + 8
.equ SHA512_num, SHA512_hash + 8
.equ SHA512_rsp, SHA512_num + 8
.equ SHA512_size, SHA512_rsp + 8
.section .rodata
.balign 64
.type g_k512,%object
g_k512:
.quad 0x428a2f98d728ae22, 0x7137449123ef65cd, 0x428a2f98d728ae22, 0x7137449123ef65cd
.quad 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc
.quad 0x3956c25bf348b538, 0x59f111f1b605d019, 0x3956c25bf348b538, 0x59f111f1b605d019
.quad 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118
.quad 0xd807aa98a3030242, 0x12835b0145706fbe, 0xd807aa98a3030242, 0x12835b0145706fbe
.quad 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2
.quad 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1
.quad 0x9bdc06a725c71235, 0xc19bf174cf692694, 0x9bdc06a725c71235, 0xc19bf174cf692694
.quad 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3
.quad 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65
.quad 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x2de92c6f592b0275, 0x4a7484aa6ea6e483
.quad 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5
.quad 0x983e5152ee66dfab, 0xa831c66d2db43210, 0x983e5152ee66dfab, 0xa831c66d2db43210
.quad 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xb00327c898fb213f, 0xbf597fc7beef0ee4
.quad 0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0xc6e00bf33da88fc2, 0xd5a79147930aa725
.quad 0x06ca6351e003826f, 0x142929670a0e6e70, 0x06ca6351e003826f, 0x142929670a0e6e70
.quad 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x27b70a8546d22ffc, 0x2e1b21385c26c926
.quad 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df
.quad 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x650a73548baf63de, 0x766a0abb3c77b2a8
.quad 0x81c2c92e47edaee6, 0x92722c851482353b, 0x81c2c92e47edaee6, 0x92722c851482353b
.quad 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xa2bfe8a14cf10364, 0xa81a664bbc423001
.quad 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xc24b8b70d0f89791, 0xc76c51a30654be30
.quad 0xd192e819d6ef5218, 0xd69906245565a910, 0xd192e819d6ef5218, 0xd69906245565a910
.quad 0xf40e35855771202a, 0x106aa07032bbd1b8, 0xf40e35855771202a, 0x106aa07032bbd1b8
.quad 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53
.quad 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8
.quad 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb
.quad 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3
.quad 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x748f82ee5defb2fc, 0x78a5636f43172f60
.quad 0x84c87814a1f0ab72, 0x8cc702081a6439ec, 0x84c87814a1f0ab72, 0x8cc702081a6439ec
.quad 0x90befffa23631e28, 0xa4506cebde82bde9, 0x90befffa23631e28, 0xa4506cebde82bde9
.quad 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xbef9a3f7b2c67915, 0xc67178f2e372532b
.quad 0xca273eceea26619c, 0xd186b8c721c0c207, 0xca273eceea26619c, 0xd186b8c721c0c207
.quad 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178
.quad 0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x06f067aa72176fba, 0x0a637dc5a2c898a6
.quad 0x113f9804bef90dae, 0x1b710b35131c471b, 0x113f9804bef90dae, 0x1b710b35131c471b
.quad 0x28db77f523047d84, 0x32caab7b40c72493, 0x28db77f523047d84, 0x32caab7b40c72493
.quad 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c
.quad 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a
.quad 0x5fcb6fab3ad6faec, 0x6c44198c4a475817, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817
.size g_k512, .-g_k512
.balign 64
.type g_endianMask,%object
g_endianMask:
.quad 0x0001020304050607, 0x08090a0b0c0d0e0f
.quad 0x0001020304050607, 0x08090a0b0c0d0e0f
.size g_endianMask, .-g_endianMask
/**
* Macro Description: Processes the update of the hash value in one round of 80 compressions.
* input register:
* addr: Stack space initial address
* wkOffset: wi+k512 Data address offset
* a - h: Intermediate variable of hash value
* Modify the register:temp1, temp2, temp3, temp4, temp5
* Output register:
* h: Indicates the value after a cyclic update.
* d: Indicates the value after a cyclic update.
* temp1: BSIG0(a) from last round
* temp4: b^a for next round b^c
* Function/Macro Call: None
* Implementation Description:
* T1 = h + BSIG1(e) + CH(e,f,g) + Kt + Wt
* T2 = BSIG0(a) + MAJ(a,b,c)
* CH(e, f, g) = (e AND f) XOR ((NOT e) AND g)
* MAJ(a, b, c) = (a AND b) XOR (a AND c) XOR (b AND c)
* = CH(a^b, c, b)
* = ((a XOR b) AND c) XOR ((NOT(a XOR b)) AND b)
* = (b XOR c) AND (a XOR b) XOR b
* BSIG0(x) = ROTR^28(x) XOR ROTR^34(x) XOR ROTR^39(x)
* BSIG1(x) = ROTR^14(x) XOR ROTR^18(x) XOR ROTR^41(x)
* d += T1; h = T1 + T2
* Optimization Principle:asert b^c in temp4, temp1 equal 0, f in temp5 when round begin
* mov b, temp4
* xor temp1, temp1
* xor c, temp4
* mov f, temp5
* swap temp2 temp4 for next round
* add BSIG0(a) back to a when all round finished
*/
.macro ONE_ROUND a, b, c, d, e, f, g, h, temp1, temp2, temp3, temp4, temp5, addr, wkOffset
// asert b^c in temp4, temp1 equal 0, f in temp5 when round begin
addq \wkOffset(\addr), \h // h += Kt + Wt
and \e, \temp5 // e&f
rorx $14, \e, \temp2 // ROTR^14(e)
addq \temp1, \a // a += BSIG0(a) from last round
rorx $18, \e, \temp3 // ROTR^18(e)
andn \g, \e, \temp1 // (~e)&g
xor \temp2, \temp3 // ROTR^14(e) ^ ROTR^18(e)
xor \temp1, \temp5 // CH(e,f,g)
rorx $41, \e, \temp2 // ROTR^41(e)
addq \temp5, \h // h += CH(e,f,g)
xor \temp2, \temp3 // BSIG1(e)
rorx $28, \a, \temp1 // ROTR^28(a)
mov \a, \temp2 // a
addq \temp3, \h // h += BSIG1(e)
rorx $34, \a, \temp5 // ROTR^34(a)
xor \b, \temp2 // b^a for next round b^c
addq \h, \d // d += T1
xor \temp5, \temp1 // ROTR^14(a) ^ ROTR^34(a)
and \temp2, \temp4 // (b^a) & (b^c)
rorx $39, \a, \temp3 // ROTR^39(a)
xor \b, \temp4 // Maj(a,b,c)
mov \e, \temp5 // for next round f
xor \temp3, \temp1 // BSIG0(a)
addq \temp4, \h // h += Maj(a,b,c)
// swap temp2 temp4 for next round
// add BSIG0(a) back to a when all round finished
.endm
/**
* Macro Description: Processes the update of two rounds of hash values in 80 rounds of compression,
* and expands messages.
* Input register:
* addr: Stack space initial address
* wkOffset: wi+k512 Data address offset
* a - h: Intermediate variable of hash value
* wi_17_16: W[i-16-15]
* wi_15_14: W[i-15-14]
* wi_7_6: W[i-7-6]
* wi_9_8: W[i-7-8]
* wi_3_2: W[i-3-2]
* Modify the register:TEMP1, TEMP2, TEMP3, TEMP4, TEMP5, wi_17_16, YTEMP1, YTEMP2, YTEMP3, YTEMP4, YTEMP5, YTEMP6
* Output register:
* h: Value after two rounds of cyclic update
* d: Value after two rounds of cyclic update
* TEMP1: BSIG0(a) from last round
* TEMP4: b^a for next round b^c
* wi_17_16: expanded message
* Function/Macro Call: None
* Implementation Description:
* T1 = h + BSIG1(e) + CH(e,f,g) + Kt + Wt
* T2 = BSIG0(a) + MAJ(a,b,c)
* CH(e, f, g) = (e AND f) XOR ((NOT e) AND g)
* MAJ(a, b, c) = (a AND b) XOR (a AND c) XOR (b AND c)
* = CH(a^b, c, b)
* = ((a XOR b) AND c) XOR ((NOT(a XOR b)) AND b)
* = (b XOR c) AND (a XOR b) XOR b
* BSIG0(x) = ROTR^28(x) XOR ROTR^34(x) XOR ROTR^39(x)
* BSIG1(x) = ROTR^14(x) XOR ROTR^18(x) XOR ROTR^41(x)
* d += T1; h = T1 + T2
*
* wi_16: Latest W[i] value, W[i] = sigma1(W[i-2]) + W[i-7] + sigma0(W[i-15]) + W[i-16]
* SSIG0(x) = ROTR^1(x) XOR ROTR^8(x) XOR SHR^7(x)
* SSIG1(x) = ROTR^19(x) XOR ROTR^61(x) XOR SHR^6(x)
* Optimization Principle:asert b^c in TEMP4, TEMP1 equal 0, f in TEMP5 when round begin
* mov b, TEMP4
* xor TEMP1, TEMP1
* xor c, TEMP4
* mov f, TEMP5
* swap TEMP2 TEMP4 for next round
* add BSIG0(a) back to a when all round finished
*/
.macro TWO_ROUND_UPDATE_2W a, b, c, d, e, f, g, h, wkOffset, wi_17_16, wi_15_14, wi_9_8, wi_7_6, wi_3_2
// 1st round
vpalignr $8, \wi_17_16, \wi_15_14, YTEMP1 // wi_16_15
vpalignr $8, \wi_9_8, \wi_7_6, YTEMP7 // wi_8_7
addq \wkOffset(%rsi), \h // h += Kt + Wt
and \e, TEMP5 // e&f
vpsrlq $1, YTEMP1, YTEMP2
rorx $14, \e, TEMP2 // ROTR^14(e)
addq TEMP1, \a // a += BSIG0(a) from last round
vpsrlq $8, YTEMP1, YTEMP3
rorx $18, \e, TEMP3 // ROTR^18(e)
andn \g, \e, TEMP1 // (~e)&g
vpsrlq $7, YTEMP1, YTEMP4
xor TEMP2, TEMP3 // ROTR^14(e) ^ ROTR^18(e)
xor TEMP1, TEMP5 // CH(e,f,g)
vpsllq $63, YTEMP1, YTEMP5
rorx $41, \e, TEMP2 // ROTR^41(e)
addq TEMP5, \h // h += CH(e,f,g)
vpsllq $56, YTEMP1, YTEMP6
xor TEMP2, TEMP3 // BSIG1(e)
rorx $28, \a, TEMP1 // ROTR^28(a)
vpaddq YTEMP7, \wi_17_16, \wi_17_16 // W[i-17..16] + W[8..7]
mov \a, TEMP2 // a
addq TEMP3, \h // h += BSIG1(e)
vpxor YTEMP5, YTEMP2, YTEMP2 // ROTR^1(wi_16_15)
rorx $34, \a, TEMP5 // ROTR^34(a)
xor \b, TEMP2 // b^a for next round b^c
vpxor YTEMP6, YTEMP3, YTEMP3 // ROTR^8(wi_16_15)
addq \h, \d // d += T1
xor TEMP5, TEMP1 // ROTR^14(a) ^ ROTR^34(a)
vpxor YTEMP4, YTEMP2, YTEMP1
and TEMP2, TEMP4 // (b^a) & (b^c)
rorx $39, \a, TEMP3 // ROTR^39(a)
vpxor YTEMP3, YTEMP1, YTEMP1 // SSIG0(wi_16_15)
xor \b, TEMP4 // Maj(a,b,c)
mov \e, TEMP5 // for next round f
vpaddq YTEMP1, \wi_17_16, \wi_17_16 // SSIG0(wi_16_15) + W[i-17..16] + W[8..7]
xor TEMP3, TEMP1 // BSIG0(a)
addq TEMP4, \h // h += Maj(a,b,c)
// swap TEMP2 TEMP4 for next round
// 2nd round
// ror abcdefgh to habcdefg
vpsrlq $19, \wi_3_2, YTEMP2
addq 8+\wkOffset(%rsi), \g // h += Kt + Wt
and \d, TEMP5 // e&f
vpsrlq $61, \wi_3_2, YTEMP3
rorx $14, \d, TEMP4 // ROTR^14(e)
addq TEMP1, \h // a += BSIG0(a) from last round
vpsrlq $6, \wi_3_2, YTEMP4
rorx $18, \d, TEMP3 // ROTR^18(e)
andn \f, \d, TEMP1 // (~e)&g
vpsllq $45, \wi_3_2, YTEMP5
xor TEMP4, TEMP3 // ROTR^14(e) ^ ROTR^18(e)
xor TEMP1, TEMP5 // CH(e,f,g)
vpsllq $3, \wi_3_2, YTEMP6
rorx $41, \d, TEMP4 // ROTR^41(e)
addq TEMP5, \g // h += CH(e,f,g)
vpxor YTEMP5, YTEMP2, YTEMP2 // ROTR^19(wi_3_2)
xor TEMP4, TEMP3 // BSIG1(e)
rorx $28, \h, TEMP1 // ROTR^28(a)
vpxor YTEMP6, YTEMP3, YTEMP3 // ROTR^61(wi_3_2)
mov \h, TEMP4 // a
addq TEMP3, \g // h += BSIG1(e)
vpxor YTEMP4, YTEMP2, YTEMP1
rorx $34, \h, TEMP5 // ROTR^34(a)
xor \a, TEMP4 // b^a for next round b^c
vpxor YTEMP3, YTEMP1, YTEMP1 // SSIG1(wi_3_2)
addq \g, \c // d += T1
xor TEMP5, TEMP1 // ROTR^14(a) ^ ROTR^34(a)
vpaddq YTEMP1, \wi_17_16, \wi_17_16 // SSIG0(wi_16_15) + W[i-17..16] + W[i-8..7] + SSIG1(wi_3_2)
and TEMP4, TEMP2 // (b^a) & (b^c)
rorx $39, \h, TEMP3 // ROTR^39(a)
vpaddq \wkOffset(%rdx), \wi_17_16, YTEMP1 // wi + k
xor \a, TEMP2 // Maj(a,b,c)
mov \d, TEMP5 // for next round f
vmovdqa YTEMP1, \wkOffset + 256(%rsi)
xor TEMP3, TEMP1 // BSIG0(a)
addq TEMP2, \g // h += Maj(a,b,c)
// swap TEMP2 TEMP4 for next round
// add BSIG0(a) back to a when all round finished
.endm
/**
* Function description: Performs 80 rounds of compression calculation based on the input plaintext data and updates the hash value.
* function prototype:void SHA512CompressMultiBlocks(uint64_t hash[8], const uint8_t *in, uint32_t num);
* input register:
* rdi:function prototype
* rsi:Pointer to the input data address
* rdx:Number of 80 rounds of cycles. The value is the length of the input data divided by 128.
* Register usage:ymm0-ymm7 to participate in the calculation of message blocks (of two data blocks).
* ymm8-ymm14 is temporary wide register
* r8-r15 Storage a-h
* The stack space temporarily stores wi+k512 (1280 bytes) and hash addresses、in、num
* Output register:None
* Function/Macro Call:UPDATE_W、ONE_ROUND
*
*/
.text
.balign 16
.global SHA512CompressMultiBlocks
.type SHA512CompressMultiBlocks, %function
SHA512CompressMultiBlocks:
.cfi_startproc
cmp $0, %rdx
je .Lsha512end
pushq %rbx
pushq %rbp
pushq %r12
pushq %r13
pushq %r14
pushq %r15
mov %rsp, %r14
sub $1320, %rsp
and $-256, %rsp // 32-byte address alignment
mov %r14, SHA512_rsp(%rsp) // rsp The original value is added to the stack.
/* load A-H */
mov 0(%rdi), %r8
mov 8(%rdi), %r9
mov 16(%rdi), %r10
mov 24(%rdi), %r11
mov 32(%rdi), %r12
mov 40(%rdi), %r13
mov 48(%rdi), %r14
mov 56(%rdi), %r15
mov %rdi, SHA512_hash(%rsp)
mov %rsi, SHA512_in(%rsp) // The input data address is stored in the stack.
.Lsha512_loop:
mov SHA512_in(%rsp), %rsi
/* Loads the data of a block to the lower 128 bits of the ymm register. */
vmovdqu 0(%rsi), %xmm0
vmovdqu 16(%rsi), %xmm1
vmovdqu 32(%rsi), %xmm2
vmovdqu 48(%rsi), %xmm3
vmovdqu 64(%rsi), %xmm4
vmovdqu 80(%rsi), %xmm5
vmovdqu 96(%rsi), %xmm6
vmovdqu 112(%rsi), %xmm7
mov %rsi, %rcx
add $128, %rsi
cmp $1, %rdx
cmovne %rsi, %rcx // If num is greater than 1, rcx points to the next block.
mov %rdx, SHA512_num(%rsp) // Remaining nums are added to the stack.
/* Loads the data of a block to the upper 128 bits of the ymm register. */
vinserti128 $1, 0(%rcx), %ymm0, %ymm0
vinserti128 $1, 16(%rcx), %ymm1, %ymm1
vinserti128 $1, 32(%rcx), %ymm2, %ymm2
vinserti128 $1, 48(%rcx), %ymm3, %ymm3
vinserti128 $1, 64(%rcx), %ymm4, %ymm4
vinserti128 $1, 80(%rcx), %ymm5, %ymm5
vinserti128 $1, 96(%rcx), %ymm6, %ymm6
vinserti128 $1, 112(%rcx),%ymm7, %ymm7
add $128, %rcx
mov %rcx, SHA512_in(%rsp) // The input data address is stored in the stack.
vmovdqa g_endianMask + 0(%rip), %ymm8
leaq g_k512 + 0(%rip), %rdx
/* Little-endian order to big-endian order */
vpshufb %ymm8, %ymm0, %ymm0
vpshufb %ymm8, %ymm1, %ymm1
vpshufb %ymm8, %ymm2, %ymm2
vpshufb %ymm8, %ymm3, %ymm3
vpshufb %ymm8, %ymm4, %ymm4
vpshufb %ymm8, %ymm5, %ymm5
vpshufb %ymm8, %ymm6, %ymm6
vpshufb %ymm8, %ymm7, %ymm7
/* w[0..15] + k*/
vpaddq 0(%rdx), %ymm0, %ymm8
vpaddq 32(%rdx), %ymm1, %ymm9
vpaddq 64(%rdx), %ymm2, %ymm10
vpaddq 96(%rdx), %ymm3, %ymm11
vpaddq 128(%rdx), %ymm4, %ymm12
vpaddq 160(%rdx), %ymm5, %ymm13
vpaddq 192(%rdx), %ymm6, %ymm14
vpaddq 224(%rdx), %ymm7, %ymm15
/* wk push stack */
vmovdqa %ymm8, 0(%rsp)
vmovdqa %ymm9, 32(%rsp)
vmovdqa %ymm10, 64(%rsp)
vmovdqa %ymm11, 96(%rsp)
vmovdqa %ymm12, 128(%rsp)
vmovdqa %ymm13, 160(%rsp)
vmovdqa %ymm14, 192(%rsp)
vmovdqa %ymm15, 224(%rsp)
movq $4, 1312(%rsp)
leaq 0(%rsp), %rsi
mov %r9, %rcx // mov b, TEMP4
xor %rbp, %rbp // xor TEMP1, TEMP1
xor %r10, %rcx // xor c, TEMP4
mov %r13, %rdi // mov f, TEMP5
.Lround00_63:
leaq 256(%rdx), %rdx
TWO_ROUND_UPDATE_2W %r8, %r9, %r10, %r11, %r12, %r13, %r14, %r15, 0, %ymm0, %ymm1, %ymm4, %ymm5, %ymm7
TWO_ROUND_UPDATE_2W %r14, %r15, %r8, %r9, %r10, %r11, %r12, %r13, 32, %ymm1, %ymm2, %ymm5, %ymm6, %ymm0
TWO_ROUND_UPDATE_2W %r12, %r13, %r14, %r15, %r8, %r9, %r10, %r11, 64, %ymm2, %ymm3, %ymm6, %ymm7, %ymm1
TWO_ROUND_UPDATE_2W %r10, %r11, %r12, %r13, %r14, %r15, %r8, %r9, 96, %ymm3, %ymm4, %ymm7, %ymm0, %ymm2
TWO_ROUND_UPDATE_2W %r8, %r9, %r10, %r11, %r12, %r13, %r14, %r15, 128, %ymm4, %ymm5, %ymm0, %ymm1, %ymm3
TWO_ROUND_UPDATE_2W %r14, %r15, %r8, %r9, %r10, %r11, %r12, %r13, 160, %ymm5, %ymm6, %ymm1, %ymm2, %ymm4
TWO_ROUND_UPDATE_2W %r12, %r13, %r14, %r15, %r8, %r9, %r10, %r11, 192, %ymm6, %ymm7, %ymm2, %ymm3, %ymm5
TWO_ROUND_UPDATE_2W %r10, %r11, %r12, %r13, %r14, %r15, %r8, %r9, 224, %ymm7, %ymm0, %ymm3, %ymm4, %ymm6
leaq 256(%rsi), %rsi
decq 1312(%rsp)
jne .Lround00_63
/* round 64-79 */
ONE_ROUND %r8, %r9, %r10, %r11, %r12, %r13, %r14, %r15, %rbp, %rax, %rbx, %rcx, %rdi, %rsi, 0
ONE_ROUND %r15, %r8, %r9, %r10, %r11, %r12, %r13, %r14, %rbp, %rcx, %rbx, %rax, %rdi, %rsi, 8
ONE_ROUND %r14, %r15, %r8, %r9, %r10, %r11, %r12, %r13, %rbp, %rax, %rbx, %rcx, %rdi, %rsi, 32
ONE_ROUND %r13, %r14, %r15, %r8, %r9, %r10, %r11, %r12, %rbp, %rcx, %rbx, %rax, %rdi, %rsi, 40
ONE_ROUND %r12, %r13, %r14, %r15, %r8, %r9, %r10, %r11, %rbp, %rax, %rbx, %rcx, %rdi, %rsi, 64
ONE_ROUND %r11, %r12, %r13, %r14, %r15, %r8, %r9, %r10, %rbp, %rcx, %rbx, %rax, %rdi, %rsi, 72
ONE_ROUND %r10, %r11, %r12, %r13, %r14, %r15, %r8, %r9, %rbp, %rax, %rbx, %rcx, %rdi, %rsi, 96
ONE_ROUND %r9, %r10, %r11, %r12, %r13, %r14, %r15, %r8, %rbp, %rcx, %rbx, %rax, %rdi, %rsi, 104
ONE_ROUND %r8, %r9, %r10, %r11, %r12, %r13, %r14, %r15, %rbp, %rax, %rbx, %rcx, %rdi, %rsi, 128
ONE_ROUND %r15, %r8, %r9, %r10, %r11, %r12, %r13, %r14, %rbp, %rcx, %rbx, %rax, %rdi, %rsi, 136
ONE_ROUND %r14, %r15, %r8, %r9, %r10, %r11, %r12, %r13, %rbp, %rax, %rbx, %rcx, %rdi, %rsi, 160
ONE_ROUND %r13, %r14, %r15, %r8, %r9, %r10, %r11, %r12, %rbp, %rcx, %rbx, %rax, %rdi, %rsi, 168
ONE_ROUND %r12, %r13, %r14, %r15, %r8, %r9, %r10, %r11, %rbp, %rax, %rbx, %rcx, %rdi, %rsi, 192
ONE_ROUND %r11, %r12, %r13, %r14, %r15, %r8, %r9, %r10, %rbp, %rcx, %rbx, %rax, %rdi, %rsi, 200
ONE_ROUND %r10, %r11, %r12, %r13, %r14, %r15, %r8, %r9, %rbp, %rax, %rbx, %rcx, %rdi, %rsi, 224
ONE_ROUND %r9, %r10, %r11, %r12, %r13, %r14, %r15, %r8, %rbp, %rcx, %rbx, %rax, %rdi, %rsi, 232
addq %rbp, %r8 // a += BSIG0(a) from last round
leaq -1024(%rsi), %rsi // rsi Point to the original address
/* Update the hash value. */
mov SHA512_hash(%rsp), %rdi
mov SHA512_num(%rsp), %rdx
addq 0(%rdi), %r8
addq 8(%rdi), %r9
addq 16(%rdi), %r10
addq 24(%rdi), %r11
addq 32(%rdi), %r12
addq 40(%rdi), %r13
addq 48(%rdi), %r14
addq 56(%rdi), %r15
mov %r8, 0(%rdi)
mov %r9, 8(%rdi)
mov %r10, 16(%rdi)
mov %r11, 24(%rdi)
mov %r12, 32(%rdi)
mov %r13, 40(%rdi)
mov %r14, 48(%rdi)
mov %r15, 56(%rdi)
cmp $1, %rdx
je .Lsha512_finish
movq $10, 1312(%rsp)
mov %r9, %rcx // mov b, TEMP4
xor %rbp, %rbp // xor TEMP1, TEMP1
xor %r10, %rcx // xor c, TEMP4
mov %r13, %rdi // mov f, TEMP5
.Lnext_block:
ONE_ROUND %r8, %r9, %r10, %r11, %r12, %r13, %r14, %r15, %rbp, %rax, %rbx, %rcx, %rdi, %rsi, 16
ONE_ROUND %r15, %r8, %r9, %r10, %r11, %r12, %r13, %r14, %rbp, %rcx, %rbx, %rax, %rdi, %rsi, 24
ONE_ROUND %r14, %r15, %r8, %r9, %r10, %r11, %r12, %r13, %rbp, %rax, %rbx, %rcx, %rdi, %rsi, 48
ONE_ROUND %r13, %r14, %r15, %r8, %r9, %r10, %r11, %r12, %rbp, %rcx, %rbx, %rax, %rdi, %rsi, 56
ONE_ROUND %r12, %r13, %r14, %r15, %r8, %r9, %r10, %r11, %rbp, %rax, %rbx, %rcx, %rdi, %rsi, 80
ONE_ROUND %r11, %r12, %r13, %r14, %r15, %r8, %r9, %r10, %rbp, %rcx, %rbx, %rax, %rdi, %rsi, 88
ONE_ROUND %r10, %r11, %r12, %r13, %r14, %r15, %r8, %r9, %rbp, %rax, %rbx, %rcx, %rdi, %rsi, 112
ONE_ROUND %r9, %r10, %r11, %r12, %r13, %r14, %r15, %r8, %rbp, %rcx, %rbx, %rax, %rdi, %rsi, 120
leaq 128(%rsi), %rsi
decq 1312(%rsp)
jne .Lnext_block
addq %rbp, %r8 // a += BSIG0(a) from last round
leaq -1280(%rsi), %rsi // rsi Point to the original address
/* Update the hash value. */
mov SHA512_hash(%rsp), %rdi
addq 0(%rdi), %r8
addq 8(%rdi), %r9
addq 16(%rdi), %r10
addq 24(%rdi), %r11
addq 32(%rdi), %r12
addq 40(%rdi), %r13
addq 48(%rdi), %r14
addq 56(%rdi), %r15
mov %r8, 0(%rdi)
mov %r9, 8(%rdi)
mov %r10, 16(%rdi)
mov %r11, 24(%rdi)
mov %r12, 32(%rdi)
mov %r13, 40(%rdi)
mov %r14, 48(%rdi)
mov %r15, 56(%rdi)
sub $2, %rdx
jne .Lsha512_loop
.Lsha512_finish:
mov SHA512_rsp(%rsp), %rsp
popq %r15
popq %r14
popq %r13
popq %r12
popq %rbp
popq %rbx
.Lsha512end:
ret
.cfi_endproc
.size SHA512CompressMultiBlocks, .-SHA512CompressMultiBlocks
#endif
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha2/src/asm/sha2_512_x86_64.S | Unix Assembly | unknown | 23,740 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_SHA256) && !defined(HITLS_CRYPTO_SHA256_SMALL_MEM)
#include "crypt_sha2.h"
#include "crypt_utils.h"
#include "sha2_core.h"
static const uint32_t K256[64] = {
0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL,
0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL,
0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL,
0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL,
0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,
0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL,
0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL,
0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL,
};
#define ROTR32(x, n) (((x) << (32 - (n))) | ((x) >> (n))) // Assumes that x is uint32_t and 0 < n < 32
#define S0(x) (ROTR32((x), 7) ^ ROTR32((x), 18) ^ ((x) >> 3))
#define S1(x) (ROTR32((x), 17) ^ ROTR32((x), 19) ^ ((x) >> 10))
#define R(w, t) \
(S1((w)[(t) - 2]) + (w)[(t) - 7] + \
S0((w)[(t) - 15]) + (w)[(t) - 16])
#define ROUND(a, b, c, d, e, f, g, h, i, k) \
do { \
/* constants: 6, 11, 25 */ \
(h) += (ROTR32((e), 6) ^ ROTR32((e), 11) ^ ROTR32((e), 25)) + \
((g) ^ ((e) & ((f) ^ (g)))) + (k) + (i); \
(d) += (h); \
/* constants: 2, 13, 22 */ \
(h) += (ROTR32((a), 2) ^ ROTR32((a), 13) ^ ROTR32((a), 22)) + \
(((a) & ((b) | (c))) | ((b) & (c))); \
} while (0)
static void CompressBlock(uint32_t state[8], const uint8_t block[CRYPT_SHA2_256_BLOCKSIZE])
{
uint32_t w[64];
// RFC 6.2.1. Prepare the message schedule w:
// For t = 0 to 15
// Wt = M(i)t
for (unsigned i = 0; i < 16; i++) { // 16 rounds to prepare the message schedule
w[i] = GET_UINT32_BE(block, 4 * (i)); /* 4 means bytes of uint32_t */
}
// For t = 16 to 63
// Wt = SSIG1(w(t-2)) + w(t-7) + SSIG0(t-15) + w(t-16)
// @perf: speed up about 18% than expanded in x86_64
// RFC 6.2.2. Initialize the working variables:
// a, b, ..., g, h = H(i-1)[0..7]
uint32_t a = state[0];
uint32_t b = state[1];
uint32_t c = state[2];
uint32_t d = state[3];
uint32_t e = state[4];
uint32_t f = state[5];
uint32_t g = state[6];
uint32_t h = state[7];
// RFC 6.2.3. Perform the main hash computation:
for (unsigned i = 0; i < 16; i += 8) { /* 0 ~ 16 rounds to do hash computation, 8 rounds pre loop */
ROUND(a, b, c, d, e, f, g, h, w[i + 0], K256[i + 0]);
ROUND(h, a, b, c, d, e, f, g, w[i + 1], K256[i + 1]);
ROUND(g, h, a, b, c, d, e, f, w[i + 2], K256[i + 2]);
ROUND(f, g, h, a, b, c, d, e, w[i + 3], K256[i + 3]);
ROUND(e, f, g, h, a, b, c, d, w[i + 4], K256[i + 4]);
ROUND(d, e, f, g, h, a, b, c, w[i + 5], K256[i + 5]);
ROUND(c, d, e, f, g, h, a, b, w[i + 6], K256[i + 6]);
ROUND(b, c, d, e, f, g, h, a, w[i + 7], K256[i + 7]);
}
for (unsigned i = 16; i < 64; i += 8) { /* 16 ~ 64 rounds to do hash computation, 8 rounds pre loop */
w[i + 0] = R(w, i + 0);
ROUND(a, b, c, d, e, f, g, h, w[i + 0], K256[i + 0]);
w[i + 1] = R(w, i + 1);
ROUND(h, a, b, c, d, e, f, g, w[i + 1], K256[i + 1]);
w[i + 2] = R(w, i + 2);
ROUND(g, h, a, b, c, d, e, f, w[i + 2], K256[i + 2]);
w[i + 3] = R(w, i + 3);
ROUND(f, g, h, a, b, c, d, e, w[i + 3], K256[i + 3]);
w[i + 4] = R(w, i + 4);
ROUND(e, f, g, h, a, b, c, d, w[i + 4], K256[i + 4]);
w[i + 5] = R(w, i + 5);
ROUND(d, e, f, g, h, a, b, c, w[i + 5], K256[i + 5]);
w[i + 6] = R(w, i + 6);
ROUND(c, d, e, f, g, h, a, b, w[i + 6], K256[i + 6]);
w[i + 7] = R(w, i + 7);
ROUND(b, c, d, e, f, g, h, a, w[i + 7], K256[i + 7]);
}
// RFC 6.2.4. Compute the intermediate hash value H(i):
// H(i) = [a, b, ..., g, h] + H(i-1)[0..7]
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
state[5] += f;
state[6] += g;
state[7] += h;
}
#undef ROTR32
#undef ROUND
void SHA256CompressMultiBlocks(uint32_t hash[8], const uint8_t *in, uint32_t num)
{
uint32_t n = num;
const uint8_t *p = in;
while (n > 0) {
CompressBlock(hash, p);
p += CRYPT_SHA2_256_BLOCKSIZE;
n--;
}
}
#endif // HITLS_CRYPTO_SHA256 && !HITLS_CRYPTO_SHA256_SMALL_MEM
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha2/src/noasm_sha256.c | C | unknown | 6,003 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
/**
* An implementation of sha1 that has 65% less in rom but lower performance.
*/
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_SHA256) && defined(HITLS_CRYPTO_SHA256_SMALL_MEM)
#include "crypt_sha2.h"
#include "crypt_utils.h"
#include "sha2_core.h"
// Move constants to .rodata section
static const uint32_t K256[64] = {
0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL,
0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL,
0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL,
0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL,
0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,
0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL,
0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL,
0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL,
};
#define ROTR32(x, n) (((x) << (32 - (n))) | ((x) >> (n)))
#define S0(x) (ROTR32((x), 7) ^ ROTR32((x), 18) ^ ((x) >> 3))
#define S1(x) (ROTR32((x), 17) ^ ROTR32((x), 19) ^ ((x) >> 10))
#define R(w, t) (S1((w)[(t) - 2]) + (w)[(t) - 7] + S0((w)[(t) - 15]) + (w)[(t)-16])
#define ROUND(a, b, c, d, e, f, g, h, i, k)
do { \
uint32_t t1 = (h) + (ROTR32((e), 6) ^ ROTR32((e), 11) ^ ROTR32((e), 25)) + \
((g) ^ ((e) & ((f) ^ (g)))) + (k) + (i); \
uint32_t t2 = (ROTR32((a), 2) ^ ROTR32((a), 13) ^ ROTR32((a), 22)) + (((a) & ((b) | (c))) | ((b) & (c))); \
(h) = (g); \
(g) = (f); \
(f) = (e); \
(e) = (d) + t1; \
(d) = (c); \
(c) = (b); \
(b) = (a); \
(a) = t1 + t2; \
} while (0)
static void CompressBlock(uint32_t state[8], const uint8_t block[CRYPT_SHA2_256_BLOCKSIZE])
{
uint32_t w[64];
// RFC 6234 6.2.2 Initialize the working variables
uint32_t a = state[0];
uint32_t b = state[1];
uint32_t c = state[2];
uint32_t d = state[3];
uint32_t e = state[4];
uint32_t f = state[5];
uint32_t g = state[6];
uint32_t h = state[7];
// RFC 6234 6.2.1. Prepare the message schedule w:
for (unsigned i = 0; i < 16; i++) {
w[i] = GET_UINT32_BE(block, 4 * i);
}
// Expand message schedule
for (unsigned i = 16; i < 64; i++) {
w[i] = R(w, i);
}
// RFC 6234 6.2.3 Perform the main hash computation
for (unsigned i = 0; i < 64; i++) {
ROUND(a, b, c, d, e, f, g, h, w[i], K256[i]);
}
// RFC 6234 6.2.4. Compute the intermediate hash value H(i):
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
state[5] += f;
state[6] += g;
state[7] += h;
}
#undef ROTR32
#undef ROUND
void SHA256CompressMultiBlocks(uint32_t hash[8], const uint8_t *in, uint32_t num)
{
uint32_t n = num;
const uint8_t *p = in;
while (n--) {
CompressBlock(hash, p);
p += CRYPT_SHA2_256_BLOCKSIZE;
}
}
#endif // HITLS_CRYPTO_SHA256 && HITLS_CRYPTO_SHA256_SMALL_MEM
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha2/src/noasm_sha256_small.c | C | unknown | 3,916 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_SHA512) && !defined(HITLS_CRYPTO_SHA512_SMALL_MEM)
#include "crypt_sha2.h"
#include "crypt_utils.h"
#include "sha2_core.h"
#ifndef U64
#define U64(v) (uint64_t)(v)
#endif
// define in rfc 4634
static const uint64_t K512[80] = {
U64(0x428a2f98d728ae22), U64(0x7137449123ef65cd), U64(0xb5c0fbcfec4d3b2f), U64(0xe9b5dba58189dbbc),
U64(0x3956c25bf348b538), U64(0x59f111f1b605d019), U64(0x923f82a4af194f9b), U64(0xab1c5ed5da6d8118),
U64(0xd807aa98a3030242), U64(0x12835b0145706fbe), U64(0x243185be4ee4b28c), U64(0x550c7dc3d5ffb4e2),
U64(0x72be5d74f27b896f), U64(0x80deb1fe3b1696b1), U64(0x9bdc06a725c71235), U64(0xc19bf174cf692694),
U64(0xe49b69c19ef14ad2), U64(0xefbe4786384f25e3), U64(0x0fc19dc68b8cd5b5), U64(0x240ca1cc77ac9c65),
U64(0x2de92c6f592b0275), U64(0x4a7484aa6ea6e483), U64(0x5cb0a9dcbd41fbd4), U64(0x76f988da831153b5),
U64(0x983e5152ee66dfab), U64(0xa831c66d2db43210), U64(0xb00327c898fb213f), U64(0xbf597fc7beef0ee4),
U64(0xc6e00bf33da88fc2), U64(0xd5a79147930aa725), U64(0x06ca6351e003826f), U64(0x142929670a0e6e70),
U64(0x27b70a8546d22ffc), U64(0x2e1b21385c26c926), U64(0x4d2c6dfc5ac42aed), U64(0x53380d139d95b3df),
U64(0x650a73548baf63de), U64(0x766a0abb3c77b2a8), U64(0x81c2c92e47edaee6), U64(0x92722c851482353b),
U64(0xa2bfe8a14cf10364), U64(0xa81a664bbc423001), U64(0xc24b8b70d0f89791), U64(0xc76c51a30654be30),
U64(0xd192e819d6ef5218), U64(0xd69906245565a910), U64(0xf40e35855771202a), U64(0x106aa07032bbd1b8),
U64(0x19a4c116b8d2d0c8), U64(0x1e376c085141ab53), U64(0x2748774cdf8eeb99), U64(0x34b0bcb5e19b48a8),
U64(0x391c0cb3c5c95a63), U64(0x4ed8aa4ae3418acb), U64(0x5b9cca4f7763e373), U64(0x682e6ff3d6b2b8a3),
U64(0x748f82ee5defb2fc), U64(0x78a5636f43172f60), U64(0x84c87814a1f0ab72), U64(0x8cc702081a6439ec),
U64(0x90befffa23631e28), U64(0xa4506cebde82bde9), U64(0xbef9a3f7b2c67915), U64(0xc67178f2e372532b),
U64(0xca273eceea26619c), U64(0xd186b8c721c0c207), U64(0xeada7dd6cde0eb1e), U64(0xf57d4f7fee6ed178),
U64(0x06f067aa72176fba), U64(0x0a637dc5a2c898a6), U64(0x113f9804bef90dae), U64(0x1b710b35131c471b),
U64(0x28db77f523047d84), U64(0x32caab7b40c72493), U64(0x3c9ebe0a15c9bebc), U64(0x431d67c49c100d4c),
U64(0x4cc5d4becb3e42b6), U64(0x597f299cfc657e2a), U64(0x5fcb6fab3ad6faec), U64(0x6c44198c4a475817),
};
#undef ROUND00_15
#undef ROUND16_79
#define SHA512_CH(x, y, z) (((x) & (y)) ^ ((~(x)) & (z)))
#define SHA512_MAJ(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
#define SHA512_BSIG0(x) (ROTR64(x, 28) ^ ROTR64(x, 34) ^ ROTR64(x, 39))
#define SHA512_BSIG1(x) (ROTR64(x, 14) ^ ROTR64(x, 18) ^ ROTR64(x, 41))
#define SHA512_SSIG0(x) (ROTR64(x, 1) ^ ROTR64(x, 8) ^ ((x) >> 7))
#define SHA512_SSIG1(x) (ROTR64(x, 19) ^ ROTR64(x, 61) ^ ((x) >> 6))
#define SHA512_ROUND(a, b, c, d, e, f, g, h, t, s, w) \
do { \
(h) += SHA512_BSIG1(e) + SHA512_CH(e, f, g) + K512[t] + (w)[s]; \
(d) += (h); \
(h) += SHA512_BSIG0(a) + SHA512_MAJ(a, b, c); \
} while (0)
#define ROUND00_15(w, a, b, c, d, e, f, g, h, t, M) \
do { \
(w)[t] = Uint64FromBeBytes((M) + (t) * 8); \
SHA512_ROUND(a, b, c, d, e, f, g, h, t, t, w); \
} while (0)
#define ROUND16_79(w, a, b, c, d, e, f, g, h, t, s) \
do { \
(w)[s] += SHA512_SSIG1((w)[((s) + 14) & 0xF]) + (w)[((s) + 9) & 0xF] + SHA512_SSIG0((w)[((s) + 1) & 0xF]); \
SHA512_ROUND(a, b, c, d, e, f, g, h, (t) + (s), s, w); \
} while (0)
void SHA512CompressMultiBlocks(uint64_t hash[8], const uint8_t *bl, uint32_t bcnt)
{
uint32_t t;
uint64_t w[16];
const uint8_t *block = bl;
uint32_t blockn = bcnt;
while (blockn > 0) {
uint64_t a = hash[0];
uint64_t b = hash[1];
uint64_t c = hash[2];
uint64_t d = hash[3];
uint64_t e = hash[4];
uint64_t f = hash[5];
uint64_t g = hash[6];
uint64_t h = hash[7];
ROUND00_15(w, a, b, c, d, e, f, g, h, 0, block);
ROUND00_15(w, h, a, b, c, d, e, f, g, 1, block);
ROUND00_15(w, g, h, a, b, c, d, e, f, 2, block);
ROUND00_15(w, f, g, h, a, b, c, d, e, 3, block);
ROUND00_15(w, e, f, g, h, a, b, c, d, 4, block);
ROUND00_15(w, d, e, f, g, h, a, b, c, 5, block);
ROUND00_15(w, c, d, e, f, g, h, a, b, 6, block);
ROUND00_15(w, b, c, d, e, f, g, h, a, 7, block);
ROUND00_15(w, a, b, c, d, e, f, g, h, 8, block);
ROUND00_15(w, h, a, b, c, d, e, f, g, 9, block);
ROUND00_15(w, g, h, a, b, c, d, e, f, 10, block);
ROUND00_15(w, f, g, h, a, b, c, d, e, 11, block);
ROUND00_15(w, e, f, g, h, a, b, c, d, 12, block);
ROUND00_15(w, d, e, f, g, h, a, b, c, 13, block);
ROUND00_15(w, c, d, e, f, g, h, a, b, 14, block);
ROUND00_15(w, b, c, d, e, f, g, h, a, 15, block);
// 16th - 79th round of operation, corresponding to steps 1 and 3 in rfc6234 6.4
for (t = 16; t < 80; t += 16) {
ROUND16_79(w, a, b, c, d, e, f, g, h, t, 0);
ROUND16_79(w, h, a, b, c, d, e, f, g, t, 1);
ROUND16_79(w, g, h, a, b, c, d, e, f, t, 2);
ROUND16_79(w, f, g, h, a, b, c, d, e, t, 3);
ROUND16_79(w, e, f, g, h, a, b, c, d, t, 4);
ROUND16_79(w, d, e, f, g, h, a, b, c, t, 5);
ROUND16_79(w, c, d, e, f, g, h, a, b, t, 6);
ROUND16_79(w, b, c, d, e, f, g, h, a, t, 7);
ROUND16_79(w, a, b, c, d, e, f, g, h, t, 8);
ROUND16_79(w, h, a, b, c, d, e, f, g, t, 9);
ROUND16_79(w, g, h, a, b, c, d, e, f, t, 10);
ROUND16_79(w, f, g, h, a, b, c, d, e, t, 11);
ROUND16_79(w, e, f, g, h, a, b, c, d, t, 12);
ROUND16_79(w, d, e, f, g, h, a, b, c, t, 13);
ROUND16_79(w, c, d, e, f, g, h, a, b, t, 14);
ROUND16_79(w, b, c, d, e, f, g, h, a, t, 15);
}
// RFC6234 STEP 4: Compute the intermediate hash value H(i)
hash[0] += a;
hash[1] += b;
hash[2] += c;
hash[3] += d;
hash[4] += e;
hash[5] += f;
hash[6] += g;
hash[7] += h;
block += CRYPT_SHA2_512_BLOCKSIZE;
blockn--;
}
}
#endif
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha2/src/noasm_sha512.c | C | unknown | 6,740 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
/**
* An implementation of sha1 that has 70% less in rom but lower performance.
*/
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_SHA512) && defined(HITLS_CRYPTO_SHA512_SMALL_MEM)
#include "crypt_sha2.h"
#include "crypt_utils.h"
#include "sha2_core.h"
#ifndef U64
#define U64(v) (uint64_t)(v)
#endif
// define in rfc 4634
static const uint64_t K512[80] = {
// Round 0-15
U64(0x428a2f98d728ae22), U64(0x7137449123ef65cd), U64(0xb5c0fbcfec4d3b2f), U64(0xe9b5dba58189dbbc),
U64(0x3956c25bf348b538), U64(0x59f111f1b605d019), U64(0x923f82a4af194f9b), U64(0xab1c5ed5da6d8118),
U64(0xd807aa98a3030242), U64(0x12835b0145706fbe), U64(0x243185be4ee4b28c), U64(0x550c7dc3d5ffb4e2),
U64(0x72be5d74f27b896f), U64(0x80deb1fe3b1696b1), U64(0x9bdc06a725c71235), U64(0xc19bf174cf692694),
// Round 16-31
U64(0xe49b69c19ef14ad2), U64(0xefbe4786384f25e3), U64(0x0fc19dc68b8cd5b5), U64(0x240ca1cc77ac9c65),
U64(0x2de92c6f592b0275), U64(0x4a7484aa6ea6e483), U64(0x5cb0a9dcbd41fbd4), U64(0x76f988da831153b5),
U64(0x983e5152ee66dfab), U64(0xa831c66d2db43210), U64(0xb00327c898fb213f), U64(0xbf597fc7beef0ee4),
U64(0xc6e00bf33da88fc2), U64(0xd5a79147930aa725), U64(0x06ca6351e003826f), U64(0x142929670a0e6e70),
// Round 32-47
U64(0x27b70a8546d22ffc), U64(0x2e1b21385c26c926), U64(0x4d2c6dfc5ac42aed), U64(0x53380d139d95b3df),
U64(0x650a73548baf63de), U64(0x766a0abb3c77b2a8), U64(0x81c2c92e47edaee6), U64(0x92722c851482353b),
U64(0xa2bfe8a14cf10364), U64(0xa81a664bbc423001), U64(0xc24b8b70d0f89791), U64(0xc76c51a30654be30),
U64(0xd192e819d6ef5218), U64(0xd69906245565a910), U64(0xf40e35855771202a), U64(0x106aa07032bbd1b8),
// Round 48-63
U64(0x19a4c116b8d2d0c8), U64(0x1e376c085141ab53), U64(0x2748774cdf8eeb99), U64(0x34b0bcb5e19b48a8),
U64(0x391c0cb3c5c95a63), U64(0x4ed8aa4ae3418acb), U64(0x5b9cca4f7763e373), U64(0x682e6ff3d6b2b8a3),
U64(0x748f82ee5defb2fc), U64(0x78a5636f43172f60), U64(0x84c87814a1f0ab72), U64(0x8cc702081a6439ec),
U64(0x90befffa23631e28), U64(0xa4506cebde82bde9), U64(0xbef9a3f7b2c67915), U64(0xc67178f2e372532b),
// Round 64-79
U64(0xca273eceea26619c), U64(0xd186b8c721c0c207), U64(0xeada7dd6cde0eb1e), U64(0xf57d4f7fee6ed178),
U64(0x06f067aa72176fba), U64(0x0a637dc5a2c898a6), U64(0x113f9804bef90dae), U64(0x1b710b35131c471b),
U64(0x28db77f523047d84), U64(0x32caab7b40c72493), U64(0x3c9ebe0a15c9bebc), U64(0x431d67c49c100d4c),
U64(0x4cc5d4becb3e42b6), U64(0x597f299cfc657e2a), U64(0x5fcb6fab3ad6faec), U64(0x6c44198c4a475817)
};
#undef ROUND00_15
#undef ROUND16_79
#define SHA512_CH(x, y, z) (((x) & (y)) ^ ((~(x)) & (z)))
#define SHA512_MAJ(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
#define SHA512_BSIG0(x) (ROTR64(x, 28) ^ ROTR64(x, 34) ^ ROTR64(x, 39))
#define SHA512_BSIG1(x) (ROTR64(x, 14) ^ ROTR64(x, 18) ^ ROTR64(x, 41))
#define SHA512_SSIG0(x) (ROTR64(x, 1) ^ ROTR64(x, 8) ^ ((x) >> 7))
#define SHA512_SSIG1(x) (ROTR64(x, 19) ^ ROTR64(x, 61) ^ ((x) >> 6))
// Prepare the message schedule W
static inline void Sha512ExtendMessage(uint64_t *w, uint32_t t)
{
w[t & 0xF] += SHA512_SSIG1(w[(t - 2) & 0xF]) + w[(t - 7) & 0xF] + SHA512_SSIG0(w[(t - 15) & 0xF]);
}
// Perform the main hash computation
static inline void Sha512Compress(uint64_t *state, uint64_t w, uint64_t k)
{
uint64_t t1 = state[7] + SHA512_BSIG1(state[4]) + SHA512_CH(state[4], state[5], state[6]) + k + w;
uint64_t t2 = SHA512_BSIG0(state[0]) + SHA512_MAJ(state[0], state[1], state[2]);
state[7] = state[6]; // h = g
state[6] = state[5]; // g = f
state[5] = state[4]; // f = e
state[4] = state[3] + t1; // e = d + T1
state[3] = state[2]; // d = c
state[2] = state[1]; // c = b
state[1] = state[0]; // b = a
state[0] = t1 + t2; // a = T1 + T2
}
void SHA512CompressMultiBlocks(uint64_t hash[8], const uint8_t *bl, uint32_t bcnt)
{
uint32_t t;
uint64_t state[8];
uint64_t w[16];
const uint8_t *block = bl;
uint32_t blockn = bcnt;
while (blockn > 0) {
// Initialize the working variables
for (t = 0; t < 8; t++) {
state[t] = hash[t];
}
// Handle the first 16 rounds
for (t = 0; t < 16; t++) {
w[t] = Uint64FromBeBytes(block + t * 8);
Sha512Compress(state, w[t], K512[t]);
}
// 16th - 79th round of operation, corresponding to steps 1 and 3 in rfc6234 6.4
for (t = 16; t < 80; t++) {
Sha512ExtendMessage(w, t);
Sha512Compress(state, w[t & 0xF], K512[t]);
}
// RFC6234 STEP 4: Compute the intermediate hash value H(i)
for (t = 0; t < 8; t++) {
hash[t] += state[t];
}
block += CRYPT_SHA2_512_BLOCKSIZE;
blockn--;
}
}
#endif // HITLS_CRYPTO_SHA512 && HITLS_CRYPTO_SHA512_SMALL_MEM
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha2/src/noasm_sha512_small.c | C | unknown | 5,421 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SHA256
#include "crypt_sha2.h"
#include <stdlib.h>
#include "securec.h"
#include "crypt_errno.h"
#include "crypt_utils.h"
#include "bsl_err_internal.h"
#include "sha2_core.h"
#include "bsl_sal.h"
#include "crypt_types.h"
struct CryptSha256Ctx {
uint32_t h[CRYPT_SHA2_256_DIGESTSIZE / sizeof(uint32_t)]; /* 256 bits for SHA256 state */
uint32_t block[CRYPT_SHA2_256_BLOCKSIZE / sizeof(uint32_t)]; /* 512 bits block cache */
uint32_t lNum, hNum; /* input bits counter, max 2^64 bits */
uint32_t blocklen; /* block length */
uint32_t outlen; /* digest output length */
uint32_t errorCode; /* error Code */
};
CRYPT_SHA2_256_Ctx *CRYPT_SHA2_256_NewCtx(void)
{
return BSL_SAL_Calloc(1, sizeof(CRYPT_SHA2_256_Ctx));
}
CRYPT_SHA2_256_Ctx *CRYPT_SHA2_256_NewCtxEx(void *libCtx, int32_t algId)
{
(void)libCtx;
(void)algId;
return BSL_SAL_Calloc(1, sizeof(CRYPT_SHA2_256_Ctx));
}
void CRYPT_SHA2_256_FreeCtx(CRYPT_SHA2_256_Ctx *ctx)
{
BSL_SAL_ClearFree(ctx, sizeof(CRYPT_SHA2_256_Ctx));
}
int32_t CRYPT_SHA2_256_Init(CRYPT_SHA2_256_Ctx *ctx, BSL_Param *param)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
(void) param;
(void)memset_s(ctx, sizeof(CRYPT_SHA2_256_Ctx), 0, sizeof(CRYPT_SHA2_256_Ctx));
/**
* @RFC 4634 6.1 SHA-224 and SHA-256 Initialization
* SHA-256, the initial hash value, H(0):
* H(0)0 = 6a09e667
* H(0)1 = bb67ae85
* H(0)2 = 3c6ef372
* H(0)3 = a54ff53a
* H(0)4 = 510e527f
* H(0)5 = 9b05688c
* H(0)6 = 1f83d9ab
* H(0)7 = 5be0cd19
*/
ctx->h[0] = 0x6a09e667UL;
ctx->h[1] = 0xbb67ae85UL;
ctx->h[2] = 0x3c6ef372UL;
ctx->h[3] = 0xa54ff53aUL;
ctx->h[4] = 0x510e527fUL;
ctx->h[5] = 0x9b05688cUL;
ctx->h[6] = 0x1f83d9abUL;
ctx->h[7] = 0x5be0cd19UL;
ctx->outlen = CRYPT_SHA2_256_DIGESTSIZE;
return CRYPT_SUCCESS;
}
int32_t CRYPT_SHA2_256_Deinit(CRYPT_SHA2_256_Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
BSL_SAL_CleanseData((void *)(ctx), sizeof(CRYPT_SHA2_256_Ctx));
return CRYPT_SUCCESS;
}
int32_t CRYPT_SHA2_256_CopyCtx(CRYPT_SHA2_256_Ctx *dst, const CRYPT_SHA2_256_Ctx *src)
{
if (dst == NULL || src == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
(void)memcpy_s(dst, sizeof(CRYPT_SHA2_256_Ctx), src, sizeof(CRYPT_SHA2_256_Ctx));
return CRYPT_SUCCESS;
}
CRYPT_SHA2_256_Ctx *CRYPT_SHA2_256_DupCtx(const CRYPT_SHA2_256_Ctx *src)
{
if (src == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return NULL;
}
CRYPT_SHA2_256_Ctx *newCtx = CRYPT_SHA2_256_NewCtx();
if (newCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
(void)memcpy_s(newCtx, sizeof(CRYPT_SHA2_256_Ctx), src, sizeof(CRYPT_SHA2_256_Ctx));
return newCtx;
}
static int32_t CheckIsCorrupted(CRYPT_SHA2_256_Ctx *ctx, uint32_t nbytes);
static int32_t UpdateParamIsValid(CRYPT_SHA2_256_Ctx *ctx, const uint8_t *data, uint32_t nbytes)
{
if ((ctx == NULL) || (data == NULL && nbytes != 0)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->errorCode != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_SHA2_INPUT_OVERFLOW);
return CRYPT_SHA2_INPUT_OVERFLOW;
}
if (CheckIsCorrupted(ctx, nbytes) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_SHA2_INPUT_OVERFLOW);
return CRYPT_SHA2_INPUT_OVERFLOW;
}
return CRYPT_SUCCESS;
}
static int32_t CheckIsCorrupted(CRYPT_SHA2_256_Ctx *ctx, uint32_t nbytes)
{
uint32_t cnt0 = (ctx->lNum + (nbytes << SHIFTS_PER_BYTE)) & 0xffffffffUL;
if (cnt0 < ctx->lNum) { /* overflow */
if (++ctx->hNum == 0) {
ctx->errorCode = CRYPT_SHA2_INPUT_OVERFLOW;
BSL_ERR_PUSH_ERROR(CRYPT_SHA2_INPUT_OVERFLOW);
return CRYPT_SHA2_INPUT_OVERFLOW;
}
}
uint32_t cnt1 = ctx->hNum + (uint32_t)(nbytes >> (BITSIZE(uint32_t) - SHIFTS_PER_BYTE));
if (cnt1 < ctx->hNum) { /* overflow */
ctx->errorCode = CRYPT_SHA2_INPUT_OVERFLOW;
BSL_ERR_PUSH_ERROR(CRYPT_SHA2_INPUT_OVERFLOW);
return CRYPT_SHA2_INPUT_OVERFLOW;
}
ctx->hNum = cnt1;
ctx->lNum = cnt0;
return CRYPT_SUCCESS;
}
int32_t CRYPT_SHA2_256_Update(CRYPT_SHA2_256_Ctx *ctx, const uint8_t *data, uint32_t nbytes)
{
int32_t ret = UpdateParamIsValid(ctx, data, nbytes);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if (nbytes == 0) {
return CRYPT_SUCCESS;
}
const uint8_t *d = data;
uint32_t left = nbytes;
uint32_t n = ctx->blocklen;
uint8_t *p = (uint8_t *)ctx->block;
if (left < CRYPT_SHA2_256_BLOCKSIZE - n) {
if (memcpy_s(p + n, CRYPT_SHA2_256_BLOCKSIZE - n, d, left) != EOK) {
BSL_ERR_PUSH_ERROR(CRYPT_SECUREC_FAIL);
return CRYPT_SECUREC_FAIL;
}
ctx->blocklen += (uint32_t)left;
return CRYPT_SUCCESS;
}
if ((n != 0) && (left >= CRYPT_SHA2_256_BLOCKSIZE - n)) {
if (memcpy_s(p + n, CRYPT_SHA2_256_BLOCKSIZE - n, d, CRYPT_SHA2_256_BLOCKSIZE - n) != EOK) {
BSL_ERR_PUSH_ERROR(CRYPT_SECUREC_FAIL);
return CRYPT_SECUREC_FAIL;
}
SHA256CompressMultiBlocks(ctx->h, p, 1);
n = CRYPT_SHA2_256_BLOCKSIZE - n;
d += n;
left -= n;
ctx->blocklen = 0;
(void)memset_s(p, CRYPT_SHA2_256_BLOCKSIZE, 0, CRYPT_SHA2_256_BLOCKSIZE);
}
n = (uint32_t)(left / CRYPT_SHA2_256_BLOCKSIZE);
if (n > 0) {
SHA256CompressMultiBlocks(ctx->h, d, n);
n *= CRYPT_SHA2_256_BLOCKSIZE;
d += n;
left -= n;
}
if (left != 0) {
ctx->blocklen = (uint32_t)left;
if (memcpy_s((uint8_t *)ctx->block, CRYPT_SHA2_256_BLOCKSIZE, d, left) != EOK) {
BSL_ERR_PUSH_ERROR(CRYPT_SECUREC_FAIL);
return CRYPT_SECUREC_FAIL;
}
}
return CRYPT_SUCCESS;
}
static int32_t FinalParamIsValid(const CRYPT_SHA2_256_Ctx *ctx, const uint8_t *out, const uint32_t *outLen)
{
if ((ctx == NULL) || (out == NULL) || (outLen == NULL)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (*outLen < ctx->outlen) {
BSL_ERR_PUSH_ERROR(CRYPT_SHA2_OUT_BUFF_LEN_NOT_ENOUGH);
return CRYPT_SHA2_OUT_BUFF_LEN_NOT_ENOUGH;
}
if (ctx->errorCode == CRYPT_SHA2_INPUT_OVERFLOW) {
BSL_ERR_PUSH_ERROR(CRYPT_SHA2_INPUT_OVERFLOW);
return CRYPT_SHA2_INPUT_OVERFLOW;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_SHA2_256_Final(CRYPT_SHA2_256_Ctx *ctx, uint8_t *digest, uint32_t *outlen)
{
int32_t ret = FinalParamIsValid(ctx, digest, outlen);
if (ret != CRYPT_SUCCESS) {
return ret;
}
uint8_t *p = (uint8_t *)ctx->block;
uint32_t n = ctx->blocklen;
p[n++] = 0x80;
if (n > (CRYPT_SHA2_256_BLOCKSIZE - 8)) { /* 8 bytes to save bits of input */
(void)memset_s(p + n, CRYPT_SHA2_256_BLOCKSIZE - n, 0, CRYPT_SHA2_256_BLOCKSIZE - n);
n = 0;
SHA256CompressMultiBlocks(ctx->h, p, 1);
}
(void)memset_s(p + n, CRYPT_SHA2_256_BLOCKSIZE - n, 0,
CRYPT_SHA2_256_BLOCKSIZE - 8 - n); /* 8 bytes to save bits of input */
p += CRYPT_SHA2_256_BLOCKSIZE - 8; /* 8 bytes to save bits of input */
PUT_UINT32_BE(ctx->hNum, p, 0);
p += sizeof(uint32_t);
PUT_UINT32_BE(ctx->lNum, p, 0);
p += sizeof(uint32_t);
p -= CRYPT_SHA2_256_BLOCKSIZE;
SHA256CompressMultiBlocks(ctx->h, p, 1);
ctx->blocklen = 0;
(void)memset_s(p, CRYPT_SHA2_256_BLOCKSIZE, 0, CRYPT_SHA2_256_BLOCKSIZE);
n = ctx->outlen / sizeof(uint32_t);
for (uint32_t nn = 0; nn < n; nn++) {
PUT_UINT32_BE(ctx->h[nn], digest, sizeof(uint32_t) * nn);
}
*outlen = ctx->outlen;
return CRYPT_SUCCESS;
}
#ifdef HITLS_CRYPTO_PROVIDER
int32_t CRYPT_SHA2_256_GetParam(CRYPT_SHA2_256_Ctx *ctx, BSL_Param *param)
{
(void)ctx;
return CRYPT_MdCommonGetParam(CRYPT_SHA2_256_DIGESTSIZE, CRYPT_SHA2_256_BLOCKSIZE, param);
}
#endif
#ifdef HITLS_CRYPTO_SHA224
int32_t CRYPT_SHA2_224_Init(CRYPT_SHA2_224_Ctx *ctx, BSL_Param *param)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
(void) param;
(void)memset_s(ctx, sizeof(CRYPT_SHA2_224_Ctx), 0, sizeof(CRYPT_SHA2_224_Ctx));
/**
* @RFC 4634 6.1 SHA-224 and SHA-256 Initialization
* SHA-224, the initial hash value, H(0):
* H(0)0 = c1059ed8
* H(0)1 = 367cd507
* H(0)2 = 3070dd17
* H(0)3 = f70e5939
* H(0)4 = ffc00b31
* H(0)5 = 68581511
* H(0)6 = 64f98fa7
* H(0)7 = befa4fa4
*/
ctx->h[0] = 0xc1059ed8UL;
ctx->h[1] = 0x367cd507UL;
ctx->h[2] = 0x3070dd17UL;
ctx->h[3] = 0xf70e5939UL;
ctx->h[4] = 0xffc00b31UL;
ctx->h[5] = 0x68581511UL;
ctx->h[6] = 0x64f98fa7UL;
ctx->h[7] = 0xbefa4fa4UL;
ctx->outlen = CRYPT_SHA2_224_DIGESTSIZE;
return CRYPT_SUCCESS;
}
#ifdef HITLS_CRYPTO_PROVIDER
int32_t CRYPT_SHA2_224_GetParam(CRYPT_SHA2_224_Ctx *ctx, BSL_Param *param)
{
(void)ctx;
return CRYPT_MdCommonGetParam(CRYPT_SHA2_224_DIGESTSIZE, CRYPT_SHA2_224_BLOCKSIZE, param);
}
#endif
#endif // HITLS_CRYPTO_SHA224
#endif // HITLS_CRYPTO_SHA256
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha2/src/sha2_256.c | C | unknown | 10,121 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SHA512
#include "crypt_sha2.h"
#include <stdlib.h>
#include "securec.h"
#include "crypt_utils.h"
#include "crypt_errno.h"
#include "bsl_err_internal.h"
#include "sha2_core.h"
#include "bsl_sal.h"
#include "crypt_types.h"
#define SHA2_512_PADSIZE 112
// function : num1 += num2(num1 and num2 are 128bit int32_t)
static int32_t Add128Bit(uint64_t *num1h, uint64_t *num1l, uint64_t num2h, uint64_t num2l)
{
uint64_t num1hTemp = *num1h;
uint64_t num1lTemp = *num1l;
uint64_t sumh = num1hTemp;
uint64_t suml = num1lTemp + num2l;
uint64_t carry = 0;
if (suml < num1lTemp) {
carry = 1;
sumh += carry;
}
sumh += num2h;
// num2h + carry >= 1, thus sumh shoud > num1hTemp; otherwise overflow
if ((carry > 0 || num2h > 0) && sumh <= num1hTemp) {
BSL_ERR_PUSH_ERROR(CRYPT_SHA2_INPUT_OVERFLOW);
return CRYPT_SHA2_INPUT_OVERFLOW;
}
*num1h = sumh;
*num1l = suml;
return 0;
}
struct CryptSha2512Ctx {
uint64_t h[CRYPT_SHA2_512_DIGESTSIZE / sizeof(uint64_t)];
uint8_t block[CRYPT_SHA2_512_BLOCKSIZE];
uint64_t lNum, hNum;
uint32_t num, mdlen;
uint32_t errorCode; /* error Code */
};
static int32_t CheckIsCorrupted(CRYPT_SHA2_512_Ctx *ctx, uint32_t nbytes)
{
// bit len of data = len << 3, which may be 2^67, thus need to 2 uint64 to represent
uint64_t bitLenl = (uint64_t)nbytes << 3; // low 64 bit
// high 64 bit, right shift 61 to get higest 3 bit
uint64_t bitLenh = sizeof(nbytes) >= sizeof(uint64_t) ? (uint64_t)nbytes >> 61 : 0;
if (Add128Bit(&ctx->hNum, &ctx->lNum, bitLenh, bitLenl) != 0) {
// overflow, the len of msg over 2 ^ 128;
ctx->errorCode = CRYPT_SHA2_INPUT_OVERFLOW;
BSL_ERR_PUSH_ERROR(CRYPT_SHA2_INPUT_OVERFLOW);
return CRYPT_SHA2_INPUT_OVERFLOW;
}
return CRYPT_SUCCESS;
}
CRYPT_SHA2_512_Ctx *CRYPT_SHA2_512_NewCtx(void)
{
return BSL_SAL_Calloc(1, sizeof(CRYPT_SHA2_512_Ctx));
}
CRYPT_SHA2_512_Ctx *CRYPT_SHA2_512_NewCtxEx(void *libCtx, int32_t algId)
{
(void)libCtx;
(void)algId;
return BSL_SAL_Calloc(1, sizeof(CRYPT_SHA2_512_Ctx));
}
void CRYPT_SHA2_512_FreeCtx(CRYPT_SHA2_512_Ctx *ctx)
{
BSL_SAL_ClearFree(ctx, sizeof(CRYPT_SHA2_512_Ctx));
}
int32_t CRYPT_SHA2_512_Init(CRYPT_SHA2_512_Ctx *ctx, BSL_Param *param)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
(void) param;
(void)memset_s(ctx, sizeof(CRYPT_SHA2_512_Ctx), 0, sizeof(CRYPT_SHA2_512_Ctx));
// see RFC6234 chapter 6.3
ctx->h[0] = U64(0x6a09e667f3bcc908);
ctx->h[1] = U64(0xbb67ae8584caa73b);
ctx->h[2] = U64(0x3c6ef372fe94f82b);
ctx->h[3] = U64(0xa54ff53a5f1d36f1);
ctx->h[4] = U64(0x510e527fade682d1);
ctx->h[5] = U64(0x9b05688c2b3e6c1f);
ctx->h[6] = U64(0x1f83d9abfb41bd6b);
ctx->h[7] = U64(0x5be0cd19137e2179);
ctx->mdlen = CRYPT_SHA2_512_DIGESTSIZE;
return CRYPT_SUCCESS;
}
int32_t CRYPT_SHA2_512_Deinit(CRYPT_SHA2_512_Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
BSL_SAL_CleanseData((void *)(ctx), sizeof(CRYPT_SHA2_512_Ctx));
return CRYPT_SUCCESS;
}
int32_t CRYPT_SHA2_512_CopyCtx(CRYPT_SHA2_512_Ctx *dst, const CRYPT_SHA2_512_Ctx *src)
{
if (dst == NULL || src == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
(void)memcpy_s(dst, sizeof(CRYPT_SHA2_512_Ctx), src, sizeof(CRYPT_SHA2_512_Ctx));
return CRYPT_SUCCESS;
}
CRYPT_SHA2_512_Ctx *CRYPT_SHA2_512_DupCtx(const CRYPT_SHA2_512_Ctx *src)
{
if (src == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return NULL;
}
CRYPT_SHA2_512_Ctx *newCtx = CRYPT_SHA2_512_NewCtx();
if (newCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
(void)memcpy_s(newCtx, sizeof(CRYPT_SHA2_512_Ctx), src, sizeof(CRYPT_SHA2_512_Ctx));
return newCtx;
}
static int32_t UpdateParamIsValid(CRYPT_SHA2_512_Ctx *ctx, const uint8_t *data, uint32_t nbytes)
{
if ((ctx == NULL) || (data == NULL && nbytes != 0)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->errorCode == CRYPT_SHA2_INPUT_OVERFLOW) {
BSL_ERR_PUSH_ERROR(CRYPT_SHA2_INPUT_OVERFLOW);
return CRYPT_SHA2_INPUT_OVERFLOW;
}
return CheckIsCorrupted(ctx, nbytes);
}
int32_t CRYPT_SHA2_512_Update(CRYPT_SHA2_512_Ctx *ctx, const uint8_t *data, uint32_t nbytes)
{
int32_t ret = UpdateParamIsValid(ctx, data, nbytes);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if (nbytes == 0) {
return CRYPT_SUCCESS;
}
const uint32_t n = CRYPT_SHA2_512_BLOCKSIZE - ctx->num;
if (nbytes < n) {
// if the data can't fill block, just copy data to block
(void)memcpy_s(ctx->block + ctx->num, n, data, nbytes);
ctx->num += (uint32_t)nbytes;
return CRYPT_SUCCESS;
}
const uint8_t *d = data;
uint32_t dataLen = nbytes;
if (ctx->num != 0) {
// fill the block first and compute
(void)memcpy_s(ctx->block + ctx->num, n, data, n);
ctx->num = 0;
dataLen -= n;
d += n;
SHA512CompressMultiBlocks(ctx->h, ctx->block, 1);
}
SHA512CompressMultiBlocks(ctx->h, d, dataLen / CRYPT_SHA2_512_BLOCKSIZE);
d += dataLen;
dataLen &= (CRYPT_SHA2_512_BLOCKSIZE - 1);
d -= dataLen;
if (dataLen != 0) {
// copy rest data to blcok
if (memcpy_s(ctx->block, CRYPT_SHA2_512_BLOCKSIZE, d, dataLen) != EOK) {
BSL_ERR_PUSH_ERROR(CRYPT_SECUREC_FAIL);
return CRYPT_SECUREC_FAIL;
}
ctx->num = (uint32_t)dataLen;
}
return CRYPT_SUCCESS;
}
static int32_t FinalParamIsValid(const CRYPT_SHA2_512_Ctx *ctx, const uint8_t *out, const uint32_t *outLen)
{
if ((ctx == NULL) || (out == NULL) || (outLen == NULL)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (*outLen < ctx->mdlen) {
BSL_ERR_PUSH_ERROR(CRYPT_SHA2_OUT_BUFF_LEN_NOT_ENOUGH);
return CRYPT_SHA2_OUT_BUFF_LEN_NOT_ENOUGH;
}
if (ctx->errorCode == CRYPT_SHA2_INPUT_OVERFLOW) {
BSL_ERR_PUSH_ERROR(CRYPT_SHA2_INPUT_OVERFLOW);
return CRYPT_SHA2_INPUT_OVERFLOW;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_SHA2_512_Final(CRYPT_SHA2_512_Ctx *ctx, uint8_t *digest, uint32_t *len)
{
int32_t ret = FinalParamIsValid(ctx, digest, len);
if (ret != CRYPT_SUCCESS) {
return ret;
}
uint32_t pad;
uint32_t n = ctx->num;
uint8_t *block = ctx->block;
block[n++] = 0x80;
if (n > SHA2_512_PADSIZE) {
pad = CRYPT_SHA2_512_BLOCKSIZE - n;
(void)memset_s(block + n, pad, 0, pad);
SHA512CompressMultiBlocks(ctx->h, block, 1);
n = 0;
pad = SHA2_512_PADSIZE;
} else {
pad = SHA2_512_PADSIZE - n;
}
(void)memset_s(block + n, pad, 0, pad);
Uint64ToBeBytes(ctx->hNum, block + SHA2_512_PADSIZE);
Uint64ToBeBytes(ctx->lNum, block + SHA2_512_PADSIZE + sizeof(uint64_t));
SHA512CompressMultiBlocks(ctx->h, block, 1);
uint8_t *out = digest;
uint32_t ncnt = ctx->mdlen >> 3; // MDSize / 8, calculate the number of times that values need to be assigned to out
for (n = 0; n < ncnt; n++) {
Uint64ToBeBytes(ctx->h[n], out);
out += sizeof(uint64_t);
}
*len = ctx->mdlen;
return CRYPT_SUCCESS;
}
#ifdef HITLS_CRYPTO_PROVIDER
int32_t CRYPT_SHA2_512_GetParam(CRYPT_SHA2_512_Ctx *ctx, BSL_Param *param)
{
(void)ctx;
return CRYPT_MdCommonGetParam(CRYPT_SHA2_512_DIGESTSIZE, CRYPT_SHA2_512_BLOCKSIZE, param);
}
#endif
#ifdef HITLS_CRYPTO_SHA384
int32_t CRYPT_SHA2_384_Init(CRYPT_SHA2_384_Ctx *ctx, BSL_Param *param)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
(void) param;
(void)memset_s(ctx, sizeof(CRYPT_SHA2_384_Ctx), 0, sizeof(CRYPT_SHA2_384_Ctx));
ctx->h[0] = U64(0xcbbb9d5dc1059ed8);
ctx->h[1] = U64(0x629a292a367cd507);
ctx->h[2] = U64(0x9159015a3070dd17);
ctx->h[3] = U64(0x152fecd8f70e5939);
ctx->h[4] = U64(0x67332667ffc00b31);
ctx->h[5] = U64(0x8eb44a8768581511);
ctx->h[6] = U64(0xdb0c2e0d64f98fa7);
ctx->h[7] = U64(0x47b5481dbefa4fa4);
ctx->mdlen = CRYPT_SHA2_384_DIGESTSIZE;
return CRYPT_SUCCESS;
}
#ifdef HITLS_CRYPTO_PROVIDER
int32_t CRYPT_SHA2_384_GetParam(CRYPT_SHA2_384_Ctx *ctx, BSL_Param *param)
{
(void)ctx;
return CRYPT_MdCommonGetParam(CRYPT_SHA2_384_DIGESTSIZE, CRYPT_SHA2_384_BLOCKSIZE, param);
}
#endif
#endif // HITLS_CRYPTO_SHA384
#endif // HITLS_CRYPTO_SHA512
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha2/src/sha2_512.c | C | unknown | 9,332 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef SHA2_CORE_H
#define SHA2_CORE_H
#include <stdint.h>
#include "hitls_build.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifndef U64
#define U64(v) (uint64_t)(v)
#endif
#ifdef HITLS_CRYPTO_SHA256
void SHA256CompressMultiBlocks(uint32_t hash[8], const uint8_t *in, uint32_t num);
#endif
#ifdef HITLS_CRYPTO_SHA512
void SHA512CompressMultiBlocks(uint64_t hash[8], const uint8_t *bl, uint32_t bcnt);
#endif
#ifdef __cplusplus
}
#endif
#endif // SHA2_CORE_H
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha2/src/sha2_core.h | C | unknown | 1,007 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef CRYPT_SHA3_H
#define CRYPT_SHA3_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SHA3
#include <stdint.h>
#include <stdlib.h>
#include "crypt_types.h"
#include "bsl_params.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
/** @defgroup LLF SHA3 Low level function */
/* SHA3-224 */
#define CRYPT_SHA3_224_BLOCKSIZE 144 // ((1600 - 224 * 2) / 8)
#define CRYPT_SHA3_224_DIGESTSIZE 28
/* SHA3-256 */
#define CRYPT_SHA3_256_BLOCKSIZE 136 // ((1600 - 256 * 2) / 8)
#define CRYPT_SHA3_256_DIGESTSIZE 32
/* SHA3-384 */
#define CRYPT_SHA3_384_BLOCKSIZE 104 // ((1600 - 384 * 2) / 8)
#define CRYPT_SHA3_384_DIGESTSIZE 48
/* SHA3-512 */
#define CRYPT_SHA3_512_BLOCKSIZE 72 // ((1600 - 512 * 2) / 8)
#define CRYPT_SHA3_512_DIGESTSIZE 64
/* SHAKE128 */
#define CRYPT_SHAKE128_BLOCKSIZE 168 // ((1600 - 128 * 2) / 8)
#define CRYPT_SHAKE128_DIGESTSIZE 0
/* SHAKE256 */
#define CRYPT_SHAKE256_BLOCKSIZE 136 // ((1600 - 256 * 2) / 8)
#define CRYPT_SHAKE256_DIGESTSIZE 0
typedef struct CryptSha3Ctx CRYPT_SHA3_Ctx;
typedef CRYPT_SHA3_Ctx CRYPT_SHA3_224_Ctx;
typedef CRYPT_SHA3_Ctx CRYPT_SHA3_256_Ctx;
typedef CRYPT_SHA3_Ctx CRYPT_SHA3_384_Ctx;
typedef CRYPT_SHA3_Ctx CRYPT_SHA3_512_Ctx;
typedef CRYPT_SHA3_Ctx CRYPT_SHAKE128_Ctx;
typedef CRYPT_SHA3_Ctx CRYPT_SHAKE256_Ctx;
CRYPT_SHA3_Ctx *CRYPT_SHA3_NewCtx(void);
#define CRYPT_SHA3_224_NewCtx CRYPT_SHA3_NewCtx
#define CRYPT_SHA3_256_NewCtx CRYPT_SHA3_NewCtx
#define CRYPT_SHA3_384_NewCtx CRYPT_SHA3_NewCtx
#define CRYPT_SHA3_512_NewCtx CRYPT_SHA3_NewCtx
#define CRYPT_SHAKE128_NewCtx CRYPT_SHA3_NewCtx
#define CRYPT_SHAKE256_NewCtx CRYPT_SHA3_NewCtx
CRYPT_SHA3_Ctx *CRYPT_SHA3_NewCtxEx(void *libCtx, int32_t algId);
#define CRYPT_SHA3_224_NewCtxEx CRYPT_SHA3_NewCtxEx
#define CRYPT_SHA3_256_NewCtxEx CRYPT_SHA3_NewCtxEx
#define CRYPT_SHA3_384_NewCtxEx CRYPT_SHA3_NewCtxEx
#define CRYPT_SHA3_512_NewCtxEx CRYPT_SHA3_NewCtxEx
#define CRYPT_SHAKE128_NewCtxEx CRYPT_SHA3_NewCtxEx
#define CRYPT_SHAKE256_NewCtxEx CRYPT_SHA3_NewCtxEx
void CRYPT_SHA3_FreeCtx(CRYPT_SHA3_Ctx *ctx);
#define CRYPT_SHA3_224_FreeCtx CRYPT_SHA3_FreeCtx
#define CRYPT_SHA3_256_FreeCtx CRYPT_SHA3_FreeCtx
#define CRYPT_SHA3_384_FreeCtx CRYPT_SHA3_FreeCtx
#define CRYPT_SHA3_512_FreeCtx CRYPT_SHA3_FreeCtx
#define CRYPT_SHAKE128_FreeCtx CRYPT_SHA3_FreeCtx
#define CRYPT_SHAKE256_FreeCtx CRYPT_SHA3_FreeCtx
// Initialize the context
int32_t CRYPT_SHA3_224_Init(CRYPT_SHA3_224_Ctx *ctx, BSL_Param *param);
int32_t CRYPT_SHA3_256_Init(CRYPT_SHA3_256_Ctx *ctx, BSL_Param *param);
int32_t CRYPT_SHA3_384_Init(CRYPT_SHA3_384_Ctx *ctx, BSL_Param *param);
int32_t CRYPT_SHA3_512_Init(CRYPT_SHA3_512_Ctx *ctx, BSL_Param *param);
int32_t CRYPT_SHAKE128_Init(CRYPT_SHAKE128_Ctx *ctx, BSL_Param *param);
int32_t CRYPT_SHAKE256_Init(CRYPT_SHAKE256_Ctx *ctx, BSL_Param *param);
// Data update API
int32_t CRYPT_SHA3_Update(CRYPT_SHA3_Ctx *ctx, const uint8_t *in, uint32_t len);
#define CRYPT_SHA3_224_Update CRYPT_SHA3_Update
#define CRYPT_SHA3_256_Update CRYPT_SHA3_Update
#define CRYPT_SHA3_384_Update CRYPT_SHA3_Update
#define CRYPT_SHA3_512_Update CRYPT_SHA3_Update
#define CRYPT_SHAKE128_Update CRYPT_SHA3_Update
#define CRYPT_SHAKE256_Update CRYPT_SHA3_Update
// Padding and output the digest value
int32_t CRYPT_SHA3_Final(CRYPT_SHA3_Ctx *ctx, uint8_t *out, uint32_t *len);
#define CRYPT_SHA3_224_Final CRYPT_SHA3_Final
#define CRYPT_SHA3_256_Final CRYPT_SHA3_Final
#define CRYPT_SHA3_384_Final CRYPT_SHA3_Final
#define CRYPT_SHA3_512_Final CRYPT_SHA3_Final
#define CRYPT_SHAKE128_Final CRYPT_SHA3_Final
#define CRYPT_SHAKE256_Final CRYPT_SHA3_Final
int32_t CRYPT_SHA3_Squeeze(CRYPT_SHA3_Ctx *ctx, uint8_t *out, uint32_t len);
#define CRYPT_SHA3_224_Squeeze NULL
#define CRYPT_SHA3_256_Squeeze NULL
#define CRYPT_SHA3_384_Squeeze NULL
#define CRYPT_SHA3_512_Squeeze NULL
#define CRYPT_SHAKE128_Squeeze CRYPT_SHA3_Squeeze
#define CRYPT_SHAKE256_Squeeze CRYPT_SHA3_Squeeze
// Clear the context
int32_t CRYPT_SHA3_Deinit(CRYPT_SHA3_Ctx *ctx);
#define CRYPT_SHA3_224_Deinit CRYPT_SHA3_Deinit
#define CRYPT_SHA3_256_Deinit CRYPT_SHA3_Deinit
#define CRYPT_SHA3_384_Deinit CRYPT_SHA3_Deinit
#define CRYPT_SHA3_512_Deinit CRYPT_SHA3_Deinit
#define CRYPT_SHAKE128_Deinit CRYPT_SHA3_Deinit
#define CRYPT_SHAKE256_Deinit CRYPT_SHA3_Deinit
// Copy the context
int32_t CRYPT_SHA3_CopyCtx(CRYPT_SHA3_Ctx *dst, const CRYPT_SHA3_Ctx *src);
#define CRYPT_SHA3_224_CopyCtx CRYPT_SHA3_CopyCtx
#define CRYPT_SHA3_256_CopyCtx CRYPT_SHA3_CopyCtx
#define CRYPT_SHA3_384_CopyCtx CRYPT_SHA3_CopyCtx
#define CRYPT_SHA3_512_CopyCtx CRYPT_SHA3_CopyCtx
#define CRYPT_SHAKE128_CopyCtx CRYPT_SHA3_CopyCtx
#define CRYPT_SHAKE256_CopyCtx CRYPT_SHA3_CopyCtx
// Dup the context
CRYPT_SHA3_Ctx *CRYPT_SHA3_DupCtx(const CRYPT_SHA3_Ctx *src);
#define CRYPT_SHA3_224_DupCtx CRYPT_SHA3_DupCtx
#define CRYPT_SHA3_256_DupCtx CRYPT_SHA3_DupCtx
#define CRYPT_SHA3_384_DupCtx CRYPT_SHA3_DupCtx
#define CRYPT_SHA3_512_DupCtx CRYPT_SHA3_DupCtx
#define CRYPT_SHAKE128_DupCtx CRYPT_SHA3_DupCtx
#define CRYPT_SHAKE256_DupCtx CRYPT_SHA3_DupCtx
#ifdef HITLS_CRYPTO_PROVIDER
int32_t CRYPT_SHA3_224_GetParam(CRYPT_SHA3_224_Ctx *ctx, BSL_Param *param);
int32_t CRYPT_SHA3_256_GetParam(CRYPT_SHA3_256_Ctx *ctx, BSL_Param *param);
int32_t CRYPT_SHA3_384_GetParam(CRYPT_SHA3_384_Ctx *ctx, BSL_Param *param);
int32_t CRYPT_SHA3_512_GetParam(CRYPT_SHA3_512_Ctx *ctx, BSL_Param *param);
int32_t CRYPT_SHAKE128_GetParam(CRYPT_SHAKE128_Ctx *ctx, BSL_Param *param);
int32_t CRYPT_SHAKE256_GetParam(CRYPT_SHAKE256_Ctx *ctx, BSL_Param *param);
#else
#define CRYPT_SHA3_224_GetParam NULL
#define CRYPT_SHA3_256_GetParam NULL
#define CRYPT_SHA3_384_GetParam NULL
#define CRYPT_SHA3_512_GetParam NULL
#define CRYPT_SHAKE128_GetParam NULL
#define CRYPT_SHAKE256_GetParam NULL
#endif
#ifdef __cplusplus
}
#endif
#endif // HITLS_CRYPTO_SHA3
#endif // CRYPT_SHA3_H
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha3/include/crypt_sha3.h | C | unknown | 6,405 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SHA3
#include "crypt_arm.h"
.arch armv8-a+crypto
/*
* Status matrix using register aliases
* A00~A04: x0~x4
* A10~A14: x5~x9
* A20~A24: x10~x14
* A30~A34: x15~x19
* A40~A44: x20~x24
* T0~T4: x25~x29 temporary calculation register
*/
A00 .req x0
A01 .req x1
A02 .req x2
A03 .req x3
A04 .req x4
A10 .req x5
A11 .req x6
A12 .req x7
A13 .req x8
A14 .req x9
A20 .req x10
A21 .req x11
A22 .req x12
A23 .req x13
A24 .req x14
A30 .req x15
A31 .req x16
A32 .req x17
A33 .req x18
A34 .req x19
A40 .req x20
A41 .req x21
A42 .req x22
A43 .req x23
A44 .req x24
T0 .req x25
T1 .req x26
T2 .req x27
T3 .req x28
T4 .req x29
/**
* Macro Description: THETA mapping function
* Input register:
* A00~A44: x0~x24 State Matrix
* T0~T4: x25~x29 temporary calculation register
* Modify the register:
* A00~A44: x0~x24 State Matrix
* T0~T4: x25~x29 temporary calculation register
* Output register:
* A00~A44: x0~x24 The latest State Matrix, among them, The values of A10, A20, A30,
* and A40 are temporarily stored by T0, T1, T2, T3.
* T0~T3: x25 to x29 temporarily store the values of A10, A20, A30, and A40.
* Function/Macro Call: None
*/
.macro THETA
// for x in 0…4, C[x] = A[x,0] xor A[x,1] xor A[x,2] xor A[x,3] xor A[x,4]
eor T0, A00, A10
eor T1, A01, A11
eor T2, A02, A12
eor T3, A03, A13
eor T4, A04, A14
stp A00, A10, [sp, #-16]! // Borrow A00 and A10
eor T0, T0, A20
eor T1, T1, A21
eor T2, T2, A22
eor T3, T3, A23
eor T4, T4, A24
eor T0, T0, A30
eor T1, T1, A31
eor T2, T2, A32
eor T3, T3, A33
eor T4, T4, A34
eor T0, T0, A40
eor T1, T1, A41
eor T2, T2, A42
eor T3, T3, A43
eor T4, T4, A44
// D[1] = C[0] xor rol(C[2],1)
eor A00, T0, T2, ror#63 // Borrow A00
// D[2] = C[1] xor rol(C[3],1)
eor A10, T1, T3, ror#63 // Borrow A10
// for y in 0…4, A[y][1] ^= D[1]
eor A01, A01, A00
eor A11, A11, A00
eor A21, A21, A00
eor A31, A31, A00
eor A41, A41, A00
// D[3] = C[2] xor rol(C[4],1)
eor T2, T2, T4, ror#63
// for y in 0…4, A[y][2] ^= D[2]
eor A02, A02, A10
eor A12, A12, A10
eor A22, A22, A10
eor A32, A32, A10
eor A42, A42, A10
// D[4] = C[3] xor rol(C[0],1)
eor T3, T3, T0, ror#63
// for y in 0…4, A[y][3] ^= D[3]
eor A03, A03, T2
eor A13, A13, T2
eor A23, A23, T2
eor A33, A33, T2
eor A43, A43, T2
ldp A00, A10, [sp], #16 // Restore A00 and A10
// D[0] = C[4] xor rol(C[1],1)
eor T4, T4, T1, ror#63
// for y in 0…4, A[y][4] ^= D[4]
eor A04, A04, T3
eor A14, A14, T3
eor A24, A24, T3
eor A34, A34, T3
eor A44, A44, T3
// for y in 0…4, A[y][0] ^= D[0]
eor A00, A00, T4
eor T0, A10, T4 // Store A10, A20, A30, and A40 in the rho phase in advance.
eor T1, A20, T4
eor T2, A30, T4
eor T3, A40, T4
.endm
/**
* Macro Description: RHO mapping function and PI mapping function
* Input register:
* A00~A44: x0~x24 State Matrix among them, The values of A10, A20, A30, and A40 are temporarily stored by T0,
* T1, T2, T3 in the THETA function.
* T0~T3: x25 to x28: temporarily store the values of A10, A20, A30, and A40.
* Modify the register:
* A00~A44: x0~x24 State Matrix
* Output register:
* A00~A44: x0~x24 The latest State Matrix
* Function/Macro Call: None
* Implementation part:
* for x in 0…4: for y in 0…4: A[x, y] = rol(A[y,3x+y], rhotates[y,3x+y])
*/
.macro RHOPi
ror A10, A03, #64-28
ror A20, A01, #64-1
ror A30, A04, #64-27
ror A40, A02, #64-62
ror A01, A11, #64-44
ror A02, A22, #64-43
ror A03, A33, #64-21
ror A04, A44, #64-14
ror A11, A14, #64-20
ror A22, A23, #64-25
ror A33, A32, #64-15
ror A44, A41, #64-2
ror A14, A42, #64-61
ror A23, A34, #64-8
ror A32, A21, #64-10
ror A41, A13, #64-55
ror A42, A24, #64-39
ror A34, A43, #64-56
ror A21, A12, #64-6
ror A13, A31, #64-45
ror A24, T3, #64-18
ror A43, T2, #64-41
ror A12, T1, #64-3
ror A31, T0, #64-36
.endm
/**
* Macro Description: CHI mapping function与IOTA mapping function
* Input register:
* A00~A44: x0~x24 State Matrix
* T0~T3: x25~x28 temporary calculation register
* Modify the register:
* A00~A44: x0~x24 State Matrix
* T0~T3: x25~x28 temporary calculation register
* Output register:
* A00~A44: x0~x24 The latest State Matrix
* Function/Macro Call: None
* Implementation part:
* for x in 0…4: for y in 0…4: A[x, y] ^= not A[x, y+1] and A[x, y+2]
* if x,y = 0,0: A[x, y] = A[x, y] xor iotas[i]
*/
.macro CHIOTA offset
// for y in 0…4: A[0, y] ^= not A[0, y+1] and A[0, y+2]
bic T0, A02, A01
bic T1, A01, A00
bic T2, A00, A04
bic T3, A03, A02
eor A00, A00, T0
eor A01, A01, T3
bic T0, A04, A03
eor A02, A02, T0
eor A03, A03, T2
eor A04, A04, T1
adrp x25, g_roundConstant
add x25, x25, :lo12:g_roundConstant // x25 === T0
ldr T3, [x25, \offset*8]
eor A00, A00, T3 // iota: A[0, 0] = A[0, 0] xor iotas[i]
// for y in 0…4: A[1, y] ^= not A[1, y+1] and A[1, y+2]
bic T0, A12, A11
bic T1, A11, A10
bic T2, A10, A14
bic T3, A13, A12
eor A10, A10, T0
eor A11, A11, T3
bic T0, A14, A13
eor A12, A12, T0
eor A13, A13, T2
eor A14, A14, T1
// for y in 0…4: A[2, y] ^= not A[2, y+1] and A[2, y+2]
bic T0, A22, A21
bic T1, A21, A20
bic T2, A20, A24
bic T3, A23, A22
eor A20, A20, T0
eor A21, A21, T3
bic T0, A24, A23
eor A22, A22, T0
eor A23, A23, T2
eor A24, A24, T1
// for y in 0…4: A[3, y] ^= not A[3, y+1] and A[3, y+2]
bic T0, A32, A31
bic T1, A31, A30
bic T2, A30, A34
bic T3, A33, A32
eor A30, A30, T0
eor A31, A31, T3
bic T0, A34, A33
eor A32, A32, T0
eor A33, A33, T2
eor A34, A34, T1
// for y in 0…4: A[4, y] ^= not A[4, y+1] and A[4, y+2]
bic T0, A42, A41
bic T1, A41, A40
bic T2, A40, A44
bic T3, A43, A42
eor A40, A40, T0
eor A41, A41, T3
bic T0, A44, A43
eor A42, A42, T0
eor A43, A43, T2
eor A44, A44, T1
.endm
/**
* Macro Description: Round of phase mapping
* Input register:
* A00~A44: x0~x24 State Matrix
* T0~T4: x25~x29 temporary calculation register
* Modify the register:
* A00~A44: x0~x24 State Matrix
* T0~T4: x25~x29 temporary calculation register
* Output register:
* A00~A44: The latest State Matrix
* Function/Macro Call: THETA RHOPi CHIOTA
*/
.macro ROUND offset
THETA
RHOPi
CHIOTA \offset
.endm
.macro Keccak
/* The length of the digest after extrusion is greater than r. Then, the digest is mapped and then extruded. */
stp x25, x26, [sp, #-32]!
stp x27, x28, [sp, #8*2]
/* Load states: x0~x24 */
ldp A00, A01, [x25]
ldp A02, A03, [x25, #16]
ldp A04, A10, [x25, #16*2]
ldp A11, A12, [x25, #16*3]
ldp A13, A14, [x25, #16*4]
ldp A20, A21, [x25, #16*5]
ldp A22, A23, [x25, #16*6]
ldp A24, A30, [x25, #16*7]
ldp A31, A32, [x25, #16*8]
ldp A33, A34, [x25, #16*9]
ldp A40, A41, [x25, #16*10]
ldp A42, A43, [x25, #16*11]
ldr A44, [x25, #16*12]
/* Mapping */
ROUND #0
ROUND #1
ROUND #2
ROUND #3
ROUND #4
ROUND #5
ROUND #6
ROUND #7
ROUND #8
ROUND #9
ROUND #10
ROUND #11
ROUND #12
ROUND #13
ROUND #14
ROUND #15
ROUND #16
ROUND #17
ROUND #18
ROUND #19
ROUND #20
ROUND #21
ROUND #22
ROUND #23
ldp x25, x26, [sp], #8*2
ldp x27, x28, [sp], #8*2
/* Store states: x0~x24 */
stp A00, A01, [x25]
stp A02, A03, [x25, #8*2]
stp A04, A10, [x25, #8*4]
stp A11, A12, [x25, #8*6]
stp A13, A14, [x25, #8*8]
stp A20, A21, [x25, #8*10]
stp A22, A23, [x25, #8*12]
stp A24, A30, [x25, #8*14]
stp A31, A32, [x25, #8*16]
stp A33, A34, [x25, #8*18]
stp A40, A41, [x25, #8*20]
stp A42, A43, [x25, #8*22]
str A44, [x25, #8*24]
mov x0, x25
mov x3, x28
.endm
.section .rodata
.balign 64
.type g_roundConstant, %object
g_roundConstant:
.quad 0x0000000000000001
.quad 0x0000000000008082
.quad 0x800000000000808a
.quad 0x8000000080008000
.quad 0x000000000000808b
.quad 0x0000000080000001
.quad 0x8000000080008081
.quad 0x8000000000008009
.quad 0x000000000000008a
.quad 0x0000000000000088
.quad 0x0000000080008009
.quad 0x000000008000000a
.quad 0x000000008000808b
.quad 0x800000000000008b
.quad 0x8000000000008089
.quad 0x8000000000008003
.quad 0x8000000000008002
.quad 0x8000000000000080
.quad 0x000000000000800a
.quad 0x800000008000000a
.quad 0x8000000080008081
.quad 0x8000000000008080
.quad 0x0000000080000001
.quad 0x8000000080008008
.size g_roundConstant, .-g_roundConstant
/**
* Function description: Perform shA3 absorption according to the input message.
* Function prototype: const uint8_t *SHA3_Absorb(uint8_t *state, const uint8_t *in, uinT32_t inLen, uinT32_t r);
* Input register:
* x0: Pointer to the address of the State Matrix
* x1: Pointer to the input data address
* x2: Message length
* x3: Different shA3 algorithms are executed based on the shA3 parameter r.
* Register usage: A00~A44: x0~x24 State Matrix
* T0~T4: x25~x29 temporary calculation register
* Output register: x0 Returns the address of the message for which shA3 calculation is not performed.
* Function/Macro Call: ROUND
*/
.text
.balign 16
.global SHA3_Absorb
.type SHA3_Absorb, %function
SHA3_Absorb:
AARCH64_PACIASP
/* push stack protection */
stp x29, x30, [sp, #-96]!
stp x19, x20, [sp, #8*2]
stp x21, x22, [sp, #8*4]
stp x23, x24, [sp, #8*6]
stp x25, x26, [sp, #8*8]
stp x27, x28, [sp, #8*10]
stp x0, x1, [sp, #-32]!
stp x2, x3, [sp, #8*2]
mov x25, x0
mov x26, x1
mov x27, x2
mov x28, x3
cmp x2, x3
blo .Labsorb_end
/* Load states: x0~x24 */
ldp A00, A01, [x25]
ldp A02, A03, [x25, #16]
ldp A04, A10, [x25, #16*2]
ldp A11, A12, [x25, #16*3]
ldp A13, A14, [x25, #16*4]
ldp A20, A21, [x25, #16*5]
ldp A22, A23, [x25, #16*6]
ldp A24, A30, [x25, #16*7]
ldp A31, A32, [x25, #16*8]
ldp A33, A34, [x25, #16*9]
ldp A40, A41, [x25, #16*10]
ldp A42, A43, [x25, #16*11]
ldr A44, [x25, #16*12]
.Labsorb:
/* Absorb from inputs according to r */
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A00, A00, x25
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A01, A01, x25
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A02, A02, x25
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A03, A03, x25
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A04, A04, x25
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A10, A10, x25
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A11, A11, x25
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A12, A12, x25
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A13, A13, x25
cmp x28, #72 // SHA3_512: 72=8*9: (x0~x8)
beq .Labsorb_mapping
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A14, A14, x25
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A20, A20, x25
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A21, A21, x25
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A22, A22, x25
cmp x28, #104 // SHA3_384: 104=8*13: (x0~x12)
beq .Labsorb_mapping
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A23, A23, x25
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A24, A24, x25
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A30, A30, x25
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A31, A31, x25
cmp x28, #136 // SHA3_256: 136=8*17: (x0~x16)
beq .Labsorb_mapping
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A32, A32, x25
cmp x28, #144 // SHA3_224: 144=8*18: (x0~x17)
beq .Labsorb_mapping
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A33, A33, x25
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A34, A34, x25
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A40, A40, x25
cmp x28, #168 // SHAKE128: 168=8*21: (0~20)
beq .Labsorb_mapping
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A41, A41, x25
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A42, A42, x25
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A43, A43, x25
ldr x25, [x26], #8
#ifdef HITLS_BIG_ENDIAN
rev x25, x25
#endif
eor A44, A44, x25
.Labsorb_mapping:
/* Updating the Input Data Pointer and Length */
sub x27, x27, x28
stp x26, x27, [sp, #8]
/* Mapping */
ROUND #0
ROUND #1
ROUND #2
ROUND #3
ROUND #4
ROUND #5
ROUND #6
ROUND #7
ROUND #8
ROUND #9
ROUND #10
ROUND #11
ROUND #12
ROUND #13
ROUND #14
ROUND #15
ROUND #16
ROUND #17
ROUND #18
ROUND #19
ROUND #20
ROUND #21
ROUND #22
ROUND #23
ldp x26, x27, [sp, #8]
ldr x28, [sp, #24]
cmp x27, x28
bhs .Labsorb
/* Store states: x0~x24 */
ldr x25, [sp]
stp A00, A01, [x25]
stp A02, A03, [x25, #8*2]
stp A04, A10, [x25, #8*4]
stp A11, A12, [x25, #8*6]
stp A13, A14, [x25, #8*8]
stp A20, A21, [x25, #8*10]
stp A22, A23, [x25, #8*12]
stp A24, A30, [x25, #8*14]
stp A31, A32, [x25, #8*16]
stp A33, A34, [x25, #8*18]
stp A40, A41, [x25, #8*20]
stp A42, A43, [x25, #8*22]
str A44, [x25, #8*24]
.Labsorb_end:
/* Return the remaining message address. */
mov x0, x26
/* End popping */
add sp, sp, #32 // skip x0~x3
ldp x29, x30, [sp], #8*2
ldp x19, x20, [sp], #8*2
ldp x21, x22, [sp], #8*2
ldp x23, x24, [sp], #8*2
ldp x25, x26, [sp], #8*2
ldp x27, x28, [sp], #8*2
AARCH64_AUTIASP
ret
.size SHA3_Absorb, .-SHA3_Absorb
.balign 16
/**
* Function description: Perform SHA3 squeezing to obtain the digest message.
* Function prototyp: void SHA3_Squeeze(uint8_t *state, uint8_t *out, uinT32_t outLen, uinT32_t r, bool isNeedKeccak)
* Input register:
* x0: Pointer to the address of the State Matrix
* x1: Pointer to the output summary address
* x2: digist Length
* x3: Different SHA3 algorithms are executed based on the SHA3 parameter r.
* Register usage: A00~A44: x0~x24 State Matrix
* T0~T4: x25~x29 temporary calculation register
* Output register: x1: Pointer to the output summary address
* Function/Macro Call: ROUND
*/
.global SHA3_Squeeze
.type SHA3_Squeeze, %function
SHA3_Squeeze:
AARCH64_PACIASP
/* push stack protection */
stp x29, x30, [sp, #-96]!
stp x19, x20, [sp, #8*2]
stp x21, x22, [sp, #8*4]
stp x23, x24, [sp, #8*6]
stp x25, x26, [sp, #8*8]
stp x27, x28, [sp, #8*10]
mov x25, x0
mov x26, x1
mov x27, x2
mov x28, x3
mov x30, x4
/* Cyclically squeezing message summaries from the State Matrix */
.Loop_squeeze:
ldr x4, [x0], #8
cmp x27, #8
blo .Lsqueeze_tail // If the remaining length is less than 8 bytes, perform single-byte extrusion.
#ifdef HITLS_BIG_ENDIAN
rev x4, x4
#endif
str x4, [x26], #8 // Perform 8-byte squeeze
subs x27, x27, #8
beq .Lsqueeze_done
subs x3, x3, #8
bhi .Loop_squeeze
Keccak
b .Loop_squeeze
/* Single Byte Squeezing */
.Lsqueeze_tail:
strb w4, [x26], #1
lsr x4, x4, #8
subs x27, x27, #1
beq .Lsqueeze_done
strb w4, [x26], #1
lsr x4, x4, #8
subs x27, x27, #1
beq .Lsqueeze_done
strb w4, [x26], #1
lsr x4, x4, #8
subs x27, x27, #1
beq .Lsqueeze_done
strb w4, [x26], #1
lsr x4, x4, #8
subs x27, x27, #1
beq .Lsqueeze_done
strb w4, [x26], #1
lsr x4, x4, #8
subs x27, x27, #1
beq .Lsqueeze_done
strb w4, [x26], #1
lsr x4, x4, #8
subs x27, x27, #1
beq .Lsqueeze_done
strb w4, [x26], #1
.Lsqueeze_done:
/* End popping */
cmp x30, 0
beq .Lsqueeze_end
Keccak
.Lsqueeze_end:
ldp x29, x30, [sp], #8*2
ldp x19, x20, [sp], #8*2
ldp x21, x22, [sp], #8*2
ldp x23, x24, [sp], #8*2
ldp x25, x26, [sp], #8*2
ldp x27, x28, [sp], #8*2
eor x0, x0, x0
AARCH64_AUTIASP
ret
.size SHA3_Squeeze, .-SHA3_Squeeze
#endif
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha3/src/asm/sha3_armv8.S | Unix Assembly | unknown | 18,154 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SHA3
#include <stdlib.h>
#include "securec.h"
#include "crypt_errno.h"
#include "crypt_utils.h"
#include "bsl_err_internal.h"
#include "crypt_sha3.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
static void SHA3_Keccak(uint8_t *state);
static void Round(const uint64_t *a, uint64_t *e, uint32_t i);
#define ROL64(a, offset) ((((uint64_t)(a)) << (offset)) ^ (((uint64_t)(a)) >> (64 - (offset))))
// the rotation offsets, see https://keccak.team/keccak_specs_summary.html
static const uint8_t g_rotationOffset[5][5] = {
{ 0, 1, 62, 28, 27 },
{ 36, 44, 6, 55, 20 },
{ 3, 10, 43, 25, 39 },
{ 41, 45, 15, 21, 8 },
{ 18, 2, 61, 56, 14 }
};
// the round constants, see https://keccak.team/keccak_specs_summary.html
static const uint64_t g_roundConstant[24] = {
(uint64_t)0x0000000000000001, (uint64_t)0x0000000000008082,
(uint64_t)0x800000000000808a, (uint64_t)0x8000000080008000,
(uint64_t)0x000000000000808b, (uint64_t)0x0000000080000001,
(uint64_t)0x8000000080008081, (uint64_t)0x8000000000008009,
(uint64_t)0x000000000000008a, (uint64_t)0x0000000000000088,
(uint64_t)0x0000000080008009, (uint64_t)0x000000008000000a,
(uint64_t)0x000000008000808b, (uint64_t)0x800000000000008b,
(uint64_t)0x8000000000008089, (uint64_t)0x8000000000008003,
(uint64_t)0x8000000000008002, (uint64_t)0x8000000000000080,
(uint64_t)0x000000000000800a, (uint64_t)0x800000008000000a,
(uint64_t)0x8000000080008081, (uint64_t)0x8000000000008080,
(uint64_t)0x0000000080000001, (uint64_t)0x8000000080008008
};
// Absorbing function of the sponge structure
const uint8_t *SHA3_Absorb(uint8_t *state, const uint8_t *in, uint32_t inLen, uint32_t r)
{
const uint8_t *data = (const uint8_t *)in;
uint64_t *pSt = (uint64_t *)state;
uint32_t dataLen = inLen;
// Divide one block data into some uint64_t data (8 bytes) and perform XOR with the status variable.
uint32_t blockInWord = r / 8;
while (dataLen >= r) {
for (uint32_t i = 0; i < blockInWord; i++) {
uint64_t oneLane = GET_UINT64_LE(data, i << 3);
pSt[i] ^= oneLane;
}
// Process one block data.
SHA3_Keccak(state);
dataLen -= r;
data += r;
}
return (const uint8_t *)data;
}
// Squeezing function of the sponge structure
void SHA3_Squeeze(uint8_t *state, uint8_t *out, uint32_t outLen, uint32_t r, bool isNeedKeccak)
{
uint32_t dataLen = outLen;
uint32_t copyLen;
// Divide one block data into some uint64_t data (8 bytes) and perform XOR with the status variable.
uint32_t blockInWord = r / 8;
uint64_t *oneLane = (uint64_t *)state;
uint8_t outTmp[168];
while (dataLen > 0) {
copyLen = (dataLen > r) ? r : dataLen;
for (uint32_t i = 0; i < blockInWord; i++) {
PUT_UINT64_LE(oneLane[i], outTmp, i << 3); // left shift by 3 bits equals i * 8.
}
(void)memcpy_s(out + outLen - dataLen, dataLen, outTmp, copyLen);
dataLen -= copyLen;
if (dataLen > 0 || isNeedKeccak) {
SHA3_Keccak(state);
}
}
}
static void SHA3_Keccak(uint8_t *state)
{
uint8_t stTmp[200] = {0};
// See https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf
// SHA3 depends on keccak-p[1600,24] for 24 rounds of cyclic calculation.
for (uint32_t i = 0; i < 24; i += 2) {
Round((uint64_t *)state, (uint64_t *)stTmp, i);
Round((uint64_t *)stTmp, (uint64_t *)state, i + 1);
}
}
// see section 2.4 Algorithm 1 in https://keccak.team/files/Keccak-implementation-3.2.pdf
static void Round(const uint64_t *a, uint64_t *e, uint32_t i)
{
uint64_t c[5], d[5];
// The corresponding formula for calculating the indexes of array A and array E is (5 * x) + y,
// the value of x is in [0, 4] and the value of y is [0, 4].
// The row coordinates of the array index correspond to y in the algorithm principle,
// and the column coordinates correspond to x in the algorithm principle, for example, A[1, 1] = A[5 * 1 + 1] = A[6]
// THETA operation
c[0] = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20];
c[1] = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21];
c[2] = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22];
c[3] = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23];
c[4] = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24];
d[0] = ROL64(c[1], 1) ^ c[4];
d[1] = ROL64(c[2], 1) ^ c[0];
d[2] = ROL64(c[3], 1) ^ c[1];
d[3] = ROL64(c[4], 1) ^ c[2];
d[4] = ROL64(c[0], 1) ^ c[3];
// THETA RHP Pi operation
c[0] = a[0] ^ d[0];
c[1] = ROL64(a[6] ^ d[1], g_rotationOffset[1][1]);
c[2] = ROL64(a[12] ^ d[2], g_rotationOffset[2][2]);
c[3] = ROL64(a[18] ^ d[3], g_rotationOffset[3][3]);
c[4] = ROL64(a[24] ^ d[4], g_rotationOffset[4][4]);
// CHI IOTA operation,
e[0] = c[0] ^ (~c[1] & c[2]) ^ g_roundConstant[i];
// CHI operation
e[1] = c[1] ^ (~c[2] & c[3]);
e[2] = c[2] ^ (~c[3] & c[4]);
e[3] = c[3] ^ (~c[4] & c[0]);
e[4] = c[4] ^ (~c[0] & c[1]);
// THETA RHP Pi operation
c[0] = ROL64(a[3] ^ d[3], g_rotationOffset[0][3]);
c[1] = ROL64(a[9] ^ d[4], g_rotationOffset[1][4]);
c[2] = ROL64(a[10] ^ d[0], g_rotationOffset[2][0]);
c[3] = ROL64(a[16] ^ d[1], g_rotationOffset[3][1]);
c[4] = ROL64(a[22] ^ d[2], g_rotationOffset[4][2]);
// CHI operation
e[5] = c[0] ^ (~c[1] & c[2]);
e[6] = c[1] ^ (~c[2] & c[3]);
e[7] = c[2] ^ (~c[3] & c[4]);
e[8] = c[3] ^ (~c[4] & c[0]);
e[9] = c[4] ^ (~c[0] & c[1]);
// THETA RHP Pi operation
c[0] = ROL64(a[1] ^ d[1], g_rotationOffset[0][1]);
c[1] = ROL64(a[7] ^ d[2], g_rotationOffset[1][2]);
c[2] = ROL64(a[13] ^ d[3], g_rotationOffset[2][3]);
c[3] = ROL64(a[19] ^ d[4], g_rotationOffset[3][4]);
c[4] = ROL64(a[20] ^ d[0], g_rotationOffset[4][0]);
// CHI operation
e[10] = c[0] ^ (~c[1] & c[2]);
e[11] = c[1] ^ (~c[2] & c[3]);
e[12] = c[2] ^ (~c[3] & c[4]);
e[13] = c[3] ^ (~c[4] & c[0]);
e[14] = c[4] ^ (~c[0] & c[1]);
// THETA RHP Pi operation
c[0] = ROL64(a[4] ^ d[4], g_rotationOffset[0][4]);
c[1] = ROL64(a[5] ^ d[0], g_rotationOffset[1][0]);
c[2] = ROL64(a[11] ^ d[1], g_rotationOffset[2][1]);
c[3] = ROL64(a[17] ^ d[2], g_rotationOffset[3][2]);
c[4] = ROL64(a[23] ^ d[3], g_rotationOffset[4][3]);
// CHI operation
e[15] = c[0] ^ (~c[1] & c[2]);
e[16] = c[1] ^ (~c[2] & c[3]);
e[17] = c[2] ^ (~c[3] & c[4]);
e[18] = c[3] ^ (~c[4] & c[0]);
e[19] = c[4] ^ (~c[0] & c[1]);
// THETA RHP Pi operation
c[0] = ROL64(a[2] ^ d[2], g_rotationOffset[0][2]);
c[1] = ROL64(a[8] ^ d[3], g_rotationOffset[1][3]);
c[2] = ROL64(a[14] ^ d[4], g_rotationOffset[2][4]);
c[3] = ROL64(a[15] ^ d[0], g_rotationOffset[3][0]);
c[4] = ROL64(a[21] ^ d[1], g_rotationOffset[4][1]);
// CHI operation
e[20] = c[0] ^ (~c[1] & c[2]);
e[21] = c[1] ^ (~c[2] & c[3]);
e[22] = c[2] ^ (~c[3] & c[4]);
e[23] = c[3] ^ (~c[4] & c[0]);
e[24] = c[4] ^ (~c[0] & c[1]);
}
#ifdef __cplusplus
}
#endif
#endif // HITLS_CRYPTO_SHA3
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha3/src/noasm_sha3.c | C | unknown | 7,696 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SHA3
#include <stdlib.h>
#include "securec.h"
#include "crypt_errno.h"
#include "crypt_utils.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "sha3_core.h"
#include "crypt_sha3.h"
#include "crypt_types.h"
struct CryptSha3Ctx {
uint8_t state[200]; // State array, 200bytes is 1600bits
uint32_t num; // Data length in the remaining buffer.
uint32_t blockSize; // For example, BlockSize(sha3-224) = ((1600 - 224 * 2) / 8) bytes
uint32_t mdSize; // sha3-224 corresponds to 28 bytes, sha3-256: 32 bytes, sha3-384: 48 bytes, sha3-512: 64 bytes
// Non-integer multiple data cache. 168 = (1600 - 128 * 2) / 8, that is maximum block size used by shake_*
uint8_t buf[168];
uint8_t padChr; // char for padding, sha3_* use 0x06 and shake_* use 0x1f
bool squeeze;
};
CRYPT_SHA3_Ctx *CRYPT_SHA3_NewCtx(void)
{
return BSL_SAL_Calloc(1, sizeof(CRYPT_SHA3_Ctx));
}
CRYPT_SHA3_Ctx *CRYPT_SHA3_NewCtxEx(void *libCtx, int32_t algId)
{
(void)libCtx;
(void)algId;
return BSL_SAL_Calloc(1, sizeof(CRYPT_SHA3_Ctx));
}
void CRYPT_SHA3_FreeCtx(CRYPT_SHA3_Ctx *ctx)
{
BSL_SAL_ClearFree(ctx, sizeof(CRYPT_SHA3_Ctx));
}
static int32_t CRYPT_SHA3_Init(CRYPT_SHA3_Ctx *ctx, uint32_t mdSize, uint32_t blockSize, uint8_t padChr)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
(void)memset_s(ctx, sizeof(CRYPT_SHA3_Ctx), 0, sizeof(CRYPT_SHA3_Ctx));
ctx->mdSize = mdSize;
ctx->padChr = padChr;
ctx->blockSize = blockSize;
return CRYPT_SUCCESS;
}
int32_t CRYPT_SHA3_Update(CRYPT_SHA3_Ctx *ctx, const uint8_t *in, uint32_t len)
{
if (ctx == NULL || (in == NULL && len != 0)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (len == 0) {
return CRYPT_SUCCESS;
}
const uint8_t *data = in;
uint32_t left = ctx->blockSize - ctx->num;
uint32_t dataLen = len;
if (ctx->num != 0) {
if (dataLen < left) {
(void)memcpy_s(ctx->buf + ctx->num, left, data, dataLen);
ctx->num += dataLen;
return CRYPT_SUCCESS;
}
// When the external input data is greater than the remaining space of the block,
// copy the data of the remaining space.
(void)memcpy_s(ctx->buf + ctx->num, left, data, left);
(void)SHA3_Absorb(ctx->state, ctx->buf, ctx->blockSize, ctx->blockSize);
dataLen -= left;
data += left;
ctx->num = 0;
}
data = SHA3_Absorb(ctx->state, data, dataLen, ctx->blockSize);
dataLen = len - (data - in);
if (dataLen != 0) {
// copy the remaining data to the cache array
(void)memcpy_s(ctx->buf, ctx->blockSize, data, dataLen);
ctx->num = dataLen;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_SHA3_Final(CRYPT_SHA3_Ctx *ctx, uint8_t *out, uint32_t *len)
{
if (ctx == NULL || out == NULL || len == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (*len < ctx->mdSize) {
BSL_ERR_PUSH_ERROR(CRYPT_SHA3_OUT_BUFF_LEN_NOT_ENOUGH);
return CRYPT_SHA3_OUT_BUFF_LEN_NOT_ENOUGH;
}
uint32_t left = ctx->blockSize - ctx->num;
uint32_t outLen = (ctx->mdSize == 0) ? *len : ctx->mdSize;
(void)memset_s(ctx->buf + ctx->num, left, 0, left);
ctx->buf[ctx->num] = ctx->padChr;
ctx->buf[ctx->blockSize - 1] |= 0x80; // 0x80 is the last 1 of pad 10*1 mode
(void)SHA3_Absorb(ctx->state, ctx->buf, ctx->blockSize, ctx->blockSize);
SHA3_Squeeze(ctx->state, out, outLen, ctx->blockSize, false);
*len = outLen;
return CRYPT_SUCCESS;
}
int32_t CRYPT_SHA3_Squeeze(CRYPT_SHA3_Ctx *ctx, uint8_t *out, uint32_t len)
{
if (ctx == NULL || out == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (!ctx->squeeze) {
uint32_t left = ctx->blockSize - ctx->num;
(void)memset_s(ctx->buf + ctx->num, left, 0, left);
ctx->buf[ctx->num] = ctx->padChr;
ctx->buf[ctx->blockSize - 1] |= 0x80; // 0x80 is the last 1 of pad 10*1 mode
(void)SHA3_Absorb(ctx->state, ctx->buf, ctx->blockSize, ctx->blockSize);
ctx->num = 0;
ctx->squeeze = true;
}
uint32_t tmpLen = len;
uint8_t *outTmp = out;
if (ctx->num != 0) {
uint32_t outLen = (ctx->num > len) ? len : ctx->num;
(void)memcpy_s(outTmp, outLen, ctx->buf + ctx->blockSize - ctx->num, outLen);
ctx->num -= outLen;
tmpLen -= outLen;
outTmp += outLen;
}
if (tmpLen > ctx->blockSize) {
uint32_t comLen = tmpLen / ctx->blockSize * ctx->blockSize;
SHA3_Squeeze(ctx->state, outTmp, comLen, ctx->blockSize, true);
outTmp += comLen;
tmpLen -= comLen;
}
if (tmpLen != 0) {
SHA3_Squeeze(ctx->state, ctx->buf, ctx->blockSize, ctx->blockSize, true);
(void)memcpy_s(outTmp, tmpLen, ctx->buf, tmpLen);
ctx->num = ctx->blockSize - tmpLen;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_SHA3_Deinit(CRYPT_SHA3_Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
BSL_SAL_CleanseData(ctx, sizeof(CRYPT_SHA3_Ctx));
return CRYPT_SUCCESS;
}
int32_t CRYPT_SHA3_CopyCtx(CRYPT_SHA3_Ctx *dst, const CRYPT_SHA3_Ctx *src)
{
if (dst == NULL || src == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
(void)memcpy_s(dst, sizeof(CRYPT_SHA3_Ctx), src, sizeof(CRYPT_SHA3_Ctx));
return CRYPT_SUCCESS;
}
CRYPT_SHA3_Ctx *CRYPT_SHA3_DupCtx(const CRYPT_SHA3_Ctx *src)
{
if (src == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return NULL;
}
CRYPT_SHA3_Ctx *newCtx = CRYPT_SHA3_NewCtx();
if (newCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
(void)memcpy_s(newCtx, sizeof(CRYPT_SHA3_Ctx), src, sizeof(CRYPT_SHA3_Ctx));
return newCtx;
}
int32_t CRYPT_SHA3_224_Init(CRYPT_SHA3_224_Ctx *ctx, BSL_Param *param)
{
(void) param;
// 0x06 is SHA3 padding character, see https://keccak.team/keccak_specs_summary.html
return CRYPT_SHA3_Init(ctx, CRYPT_SHA3_224_DIGESTSIZE, CRYPT_SHA3_224_BLOCKSIZE, 0x06);
}
int32_t CRYPT_SHA3_256_Init(CRYPT_SHA3_256_Ctx *ctx, BSL_Param *param)
{
(void) param;
// 0x06 is SHA3 padding character, see https://keccak.team/keccak_specs_summary.html
return CRYPT_SHA3_Init(ctx, CRYPT_SHA3_256_DIGESTSIZE, CRYPT_SHA3_256_BLOCKSIZE, 0x06);
}
int32_t CRYPT_SHA3_384_Init(CRYPT_SHA3_384_Ctx *ctx, BSL_Param *param)
{
(void) param;
// 0x06 is SHA3 padding character, see https://keccak.team/keccak_specs_summary.html
return CRYPT_SHA3_Init(ctx, CRYPT_SHA3_384_DIGESTSIZE, CRYPT_SHA3_384_BLOCKSIZE, 0x06);
}
int32_t CRYPT_SHA3_512_Init(CRYPT_SHA3_512_Ctx *ctx, BSL_Param *param)
{
(void) param;
// 0x06 is SHA3 padding character, see https://keccak.team/keccak_specs_summary.html
return CRYPT_SHA3_Init(ctx, CRYPT_SHA3_512_DIGESTSIZE, CRYPT_SHA3_512_BLOCKSIZE, 0x06);
}
int32_t CRYPT_SHAKE128_Init(CRYPT_SHAKE128_Ctx *ctx, BSL_Param *param)
{
(void) param;
// 0x1f is SHA3 padding character, see https://keccak.team/keccak_specs_summary.html
return CRYPT_SHA3_Init(ctx, 0, CRYPT_SHAKE128_BLOCKSIZE, 0x1F);
}
int32_t CRYPT_SHAKE256_Init(CRYPT_SHAKE256_Ctx *ctx, BSL_Param *param)
{
(void) param;
// 0x1f is SHA3 padding character, see https://keccak.team/keccak_specs_summary.html
return CRYPT_SHA3_Init(ctx, 0, CRYPT_SHAKE256_BLOCKSIZE, 0x1F);
}
#ifdef HITLS_CRYPTO_PROVIDER
int32_t CRYPT_SHA3_224_GetParam(CRYPT_SHA3_224_Ctx *ctx, BSL_Param *param)
{
(void)ctx;
return CRYPT_MdCommonGetParam(CRYPT_SHA3_224_DIGESTSIZE, CRYPT_SHA3_224_BLOCKSIZE, param);
}
int32_t CRYPT_SHA3_256_GetParam(CRYPT_SHA3_256_Ctx *ctx, BSL_Param *param)
{
(void)ctx;
return CRYPT_MdCommonGetParam(CRYPT_SHA3_256_DIGESTSIZE, CRYPT_SHA3_256_BLOCKSIZE, param);
}
int32_t CRYPT_SHA3_384_GetParam(CRYPT_SHA3_384_Ctx *ctx, BSL_Param *param)
{
(void)ctx;
return CRYPT_MdCommonGetParam(CRYPT_SHA3_384_DIGESTSIZE, CRYPT_SHA3_384_BLOCKSIZE, param);
}
int32_t CRYPT_SHA3_512_GetParam(CRYPT_SHA3_512_Ctx *ctx, BSL_Param *param)
{
(void)ctx;
return CRYPT_MdCommonGetParam(CRYPT_SHA3_512_DIGESTSIZE, CRYPT_SHA3_512_BLOCKSIZE, param);
}
int32_t CRYPT_SHAKE128_GetParam(CRYPT_SHAKE128_Ctx *ctx, BSL_Param *param)
{
(void)ctx;
return CRYPT_MdCommonGetParam(CRYPT_SHAKE128_DIGESTSIZE, CRYPT_SHAKE128_BLOCKSIZE, param);
}
int32_t CRYPT_SHAKE256_GetParam(CRYPT_SHAKE256_Ctx *ctx, BSL_Param *param)
{
(void)ctx;
return CRYPT_MdCommonGetParam(CRYPT_SHAKE128_DIGESTSIZE, CRYPT_SHAKE256_BLOCKSIZE, param);
}
#endif // HITLS_CRYPTO_PROVIDER
#endif // HITLS_CRYPTO_SHA3
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha3/src/sha3.c | C | unknown | 9,465 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef SHA3_CORE_H
#define SHA3_CORE_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SHA3
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
const uint8_t *SHA3_Absorb(uint8_t *state, const uint8_t *in, uint32_t inLen, uint32_t r);
void SHA3_Squeeze(uint8_t *state, uint8_t *out, uint32_t outLen, uint32_t r, bool isNeedKeccak);
#ifdef __cplusplus
}
#endif
#endif // HITLS_CRYPTO_SHA3
#endif // SHA3_CORE_H
| 2302_82127028/openHiTLS-examples_1508 | crypto/sha3/src/sha3_core.h | C | unknown | 966 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef CRYPT_SIPHASH_H
#define CRYPT_SIPHASH_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SIPHASH
#include <stdint.h>
#include <stdlib.h>
#include "crypt_local_types.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
#define SIPHASH_KEY_SIZE 16 // 128 bit
#define SIPHASH_WORD_SIZE 8 // 64 bit
#define DEFAULT_COMPRESSION_ROUND 2
#define DEFAULT_FINALIZATION_ROUND 4
// The siphash has only two output lengths: 8-byte and 16-byte.
#define SIPHASH_MIN_DIGEST_SIZE 8
#define SIPHASH_MAX_DIGEST_SIZE 16
typedef struct SIPHASH_Ctx CRYPT_SIPHASH_Ctx;
#define CRYPT_SIPHASH_SetParam NULL
/**
* @brief Create a new siphash context.
* @param id [IN] MAC algorithm id
* @retval Pointer to the created siphash context.
*/
CRYPT_SIPHASH_Ctx *CRYPT_SIPHASH_NewCtx(CRYPT_MAC_AlgId id);
/**
* @brief Create a new siphash context with external library context.
* @param libCtx [in] External library context
* @param id [in] siphash algorithm ID
* @return Pointer to the siphash context
*/
CRYPT_SIPHASH_Ctx *CRYPT_SIPHASH_NewCtxEx(void *libCtx, CRYPT_MAC_AlgId id);
/**
* @brief Initialize the siphash context by using the key passed by the user.
* @param ctx [IN] siphash context
* @param key [IN] MAC symmetric key
* @param len [IN] Key length. The length of the siphash key is fixed to 128 bits.
* @param param [IN] param, reserved.
* @retval #CRYPT_SUCCESS Succeeded.
* @retval #CRYPT_NULL_INPUT The input parameter is NULL.
* #CRYPT_INVALID_ARG invalid input parameter. For example, the input key length is not 128 bits.
*/
int32_t CRYPT_SIPHASH_Init(CRYPT_SIPHASH_Ctx *ctx, const uint8_t *key, uint32_t keyLen, void *param);
/**
* @brief siphash update, supporting streaming update
* @param ctx [IN] siphash context
* @param in [IN] Point to the data buffer for MAC calculation.
* @param inlen [IN] Length of the data to be calculated
* @retval #CRYPT_SUCCESS Succeeded.
* @retval #CRYPT_NULL_INPUT The input parameter is NULL.
*/
int32_t CRYPT_SIPHASH_Update(CRYPT_SIPHASH_Ctx *ctx, const uint8_t *in, uint32_t inlen);
/**
* @brief siphash closeout calculation
* @param ctx [IN] siphash context
* @param out [OUT] Output data. Sufficient memory must be allocated to store CMAC results and cannot be null.
* @param outlen [IN/OUT] Output data length
* @retval #CRYPT_SUCCESS Succeeded.
* @retval #CRYPT_NULL_INPUT The input parameter is NULL.
* @retval #CRYPT_SIPHASH_OUT_BUFF_LEN_NOT_ENOUGH The output buffer is insufficient.
*/
int32_t CRYPT_SIPHASH_Final(CRYPT_SIPHASH_Ctx *ctx, uint8_t *out, uint32_t *outlen);
/**
* @brief Re-initialize the siphash context
* @param ctx [IN] siphash context
* @retval #CRYPT_SUCCESS Succeeded.
* @retval #CRYPT_NULL_INPUT The input parameter is NULL.
*/
int32_t CRYPT_SIPHASH_Reinit(CRYPT_SIPHASH_Ctx *ctx);
/**
* @brief siphash de-initialization
* @param ctx [IN] siphash context
* @retval #CRYPT_SUCCESS Succeeded.
* @retval #CRYPT_NULL_INPUT The input parameter is NULL.
*/
int32_t CRYPT_SIPHASH_Deinit(CRYPT_SIPHASH_Ctx *ctx);
/**
* @brief siphash control
* @param ctx [IN] siphash context
* @param opt [IN] control option
* @param val [IN]/[OUT] Control value
* @param len [IN] control value length
* @retval #CRYPT_SUCCESS Succeeded.
* @retval #CRYPT_NULL_INPUT The input parameter is NULL.
* For other error codes, see crypt_errno.h.
*/
int32_t CRYPT_SIPHASH_Ctrl(CRYPT_SIPHASH_Ctx *ctx, uint32_t opt, void *val, uint32_t len);
/**
* @brief siphash free context
* @param ctx [IN] siphash context
*/
void CRYPT_SIPHASH_FreeCtx(CRYPT_SIPHASH_Ctx *ctx);
#ifdef __cplusplus
}
#endif
#endif /* HITLS_CRYPTO_SIPHASH */
#endif
| 2302_82127028/openHiTLS-examples_1508 | crypto/siphash/include/crypt_siphash.h | C | unknown | 4,397 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SIPHASH
#include <stdlib.h>
#include <stdio.h>
#include "securec.h"
#include "crypt_errno.h"
#include "crypt_utils.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "crypt_siphash.h"
#include "eal_mac_local.h"
#define SIPHASH_HALF_KEY_SIZE 8
#define BYTE_TO_BITS_RATIO 8
#define LROT_UINT64(num, bits) (uint64_t)(((num) << (bits)) | ((num) >> (64 - (bits))))
#define SIPHASH_SIX_OCTET_TO_BITS ((BYTE_TO_BITS_RATIO) * 6)
#define SIPHASH_FIVE_OCTET_TO_BITS ((BYTE_TO_BITS_RATIO) * 5)
#define SIPHASH_FOUR_OCTET_TO_BITS ((BYTE_TO_BITS_RATIO) * 4)
#define SIPHASH_THREE_OCTET_TO_BITS ((BYTE_TO_BITS_RATIO) * 3)
#define SIPHASH_TWO_OCTET_TO_BITS ((BYTE_TO_BITS_RATIO) * 2)
#define SIPHASH_ONE_OCTET_TO_BITS ((BYTE_TO_BITS_RATIO) * 1)
struct SIPHASH_Ctx {
uint64_t state0;
uint64_t state1;
uint64_t state2;
uint64_t state3;
uint16_t compressionRounds;
uint16_t finalizationRounds;
uint32_t hashSize;
uint32_t accInLen;
uint32_t offset;
uint8_t remainder[SIPHASH_WORD_SIZE];
};
static inline uint64_t BytesToUint64LittleEndian(const uint8_t key[SIPHASH_WORD_SIZE])
{
uint64_t ret = 0ULL;
for (uint32_t i = 0; i < SIPHASH_WORD_SIZE; i++) {
ret = ret | (((uint64_t)key[i]) << (i * BYTE_TO_BITS_RATIO));
}
return ret;
}
static void Uint64ToBytesLittleEndian(uint64_t src, uint8_t out[SIPHASH_WORD_SIZE])
{
for (uint32_t i = 0; i < SIPHASH_WORD_SIZE; i++) {
out[i] = (uint8_t)(src >> (i * BYTE_TO_BITS_RATIO));
}
}
static uint64_t DealLastWord(uint64_t lastWord, const uint8_t *bytes, size_t bytesLen)
{
uint64_t tmpLastWord = lastWord;
switch (bytesLen) {
case 7:
// Do not need to run break from the case, fall through the switch-case.
// The remaining 7 bytes are to be processed and shift to left by 6 bytes.
tmpLastWord |= ((uint64_t)bytes[6]) << SIPHASH_SIX_OCTET_TO_BITS;
/* fall-through */
case 6:
tmpLastWord |= ((uint64_t)bytes[5]) << SIPHASH_FIVE_OCTET_TO_BITS;
/* fall-through */
case 5:
tmpLastWord |= ((uint64_t)bytes[4]) << SIPHASH_FOUR_OCTET_TO_BITS;
/* fall-through */
case 4:
tmpLastWord |= ((uint64_t)bytes[3]) << SIPHASH_THREE_OCTET_TO_BITS;
/* fall-through */
case 3:
tmpLastWord |= ((uint64_t)bytes[2]) << SIPHASH_TWO_OCTET_TO_BITS;
/* fall-through */
case 2:
tmpLastWord |= ((uint64_t)bytes[1]) << SIPHASH_ONE_OCTET_TO_BITS;
/* fall-through */
case 1:
tmpLastWord |= ((uint64_t)bytes[0]);
/* fall-through */
default: // case 0
break;
}
return tmpLastWord;
}
static void SiproundOperation(uint64_t *state0, uint64_t *state1, uint64_t *state2, uint64_t *state3)
{
(*state0) += (*state1);
(*state1) = LROT_UINT64(*state1, 13);
(*state1) ^= (*state0);
(*state0) = LROT_UINT64(*state0, 32);
(*state2) += (*state3);
(*state3) = LROT_UINT64(*state3, 16);
(*state3) ^= (*state2);
(*state0) += (*state3);
(*state3) = LROT_UINT64(*state3, 21);
(*state3) ^= (*state0);
(*state2) += (*state1);
(*state1) = LROT_UINT64(*state1, 17);
(*state1) ^= (*state2);
(*state2) = LROT_UINT64(*state2, 32);
}
static void UpdateInternalState(uint64_t curWord, CRYPT_SIPHASH_Ctx *ctx, uint16_t rounds)
{
(ctx->state3) ^= curWord;
for (uint16_t j = 0; j < rounds; j++) {
SiproundOperation(&(ctx->state0), &(ctx->state1), &(ctx->state2), &(ctx->state3));
}
(ctx->state0) ^= curWord;
}
static int32_t CRYPT_SIPHASH_GetMacLen(const CRYPT_SIPHASH_Ctx *ctx, void *val, uint32_t len)
{
if (val == NULL || len != sizeof(uint32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
*(uint32_t *)val = ctx->hashSize;
return CRYPT_SUCCESS;
}
CRYPT_SIPHASH_Ctx *CRYPT_SIPHASH_NewCtx(CRYPT_MAC_AlgId id)
{
EAL_MacDepMethod macMethod = {0};
int32_t ret = EAL_MacFindDepMethod(id, NULL, NULL, &macMethod, NULL, false);
if (ret != CRYPT_SUCCESS) {
return NULL;
}
CRYPT_SIPHASH_Ctx *ctx = BSL_SAL_Calloc(1, sizeof(CRYPT_SIPHASH_Ctx));
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
const EAL_SiphashMethod *method = macMethod.method.sip;
uint16_t cRounds = method->compressionRounds;
uint16_t dRounds = method->finalizationRounds;
// fill compressionRounds and finalizationRounds
ctx->compressionRounds = ((cRounds == 0) ? DEFAULT_COMPRESSION_ROUND : cRounds);
ctx->finalizationRounds = ((dRounds == 0) ? DEFAULT_FINALIZATION_ROUND : dRounds);
ctx->hashSize = method->hashSize;
ctx->accInLen = 0;
ctx->offset = 0;
return ctx;
}
CRYPT_SIPHASH_Ctx *CRYPT_SIPHASH_NewCtxEx(void *libCtx, CRYPT_MAC_AlgId id)
{
(void)libCtx;
return CRYPT_SIPHASH_NewCtx(id);
}
int32_t CRYPT_SIPHASH_Init(CRYPT_SIPHASH_Ctx *ctx, const uint8_t *key, uint32_t keyLen, void *param)
{
(void)param;
if (ctx == NULL || key == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
// invalid key size
size_t hashSize = ctx->hashSize;
if (keyLen != SIPHASH_KEY_SIZE) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
// invalid digest size
if (!((hashSize == SIPHASH_MIN_DIGEST_SIZE) || (hashSize == SIPHASH_MAX_DIGEST_SIZE))) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
// split key byte array to two parts: k0, k1
uint64_t numKey0 = BytesToUint64LittleEndian(key);
uint64_t numKey1 = BytesToUint64LittleEndian(key + SIPHASH_HALF_KEY_SIZE);
// fill internal state
ctx->state0 = numKey0 ^ 0x736f6d6570736575ULL;
ctx->state1 = numKey1 ^ 0x646f72616e646f6dULL;
ctx->state2 = numKey0 ^ 0x6c7967656e657261ULL;
ctx->state3 = numKey1 ^ 0x7465646279746573ULL;
if (hashSize == SIPHASH_MAX_DIGEST_SIZE) {
ctx->state1 ^= 0xee;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_SIPHASH_Update(CRYPT_SIPHASH_Ctx *ctx, const uint8_t *in, uint32_t inlen)
{
if (ctx == NULL || (in == NULL && inlen != 0)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (inlen > UINT32_MAX - ctx->accInLen) {
BSL_ERR_PUSH_ERROR(CRYPT_SIPHASH_INPUT_OVERFLOW);
return CRYPT_SIPHASH_INPUT_OVERFLOW;
}
const uint8_t *tmpIn = in;
uint32_t tmpInlen = inlen;
ctx->accInLen += tmpInlen;
uint64_t curWord = 0;
if (ctx->offset != 0) {
size_t emptySpaceLen = SIPHASH_WORD_SIZE - ctx->offset;
if (tmpInlen < emptySpaceLen) {
(void)memcpy_s(ctx->remainder + (ctx->offset), tmpInlen, tmpIn, tmpInlen);
// update offset, emptySpaceLen shrinks
ctx->offset += tmpInlen;
return CRYPT_SUCCESS;
}
// fill ctx->remainder[SIPHASH_WORD_SIZE - ctx->offset] to ctx->remainder[SIPHASH_WORD_SIZE - 1] using in
(void)memcpy_s(ctx->remainder + (ctx->offset), emptySpaceLen, tmpIn, emptySpaceLen);
// update inlen
tmpInlen -= (uint32_t)emptySpaceLen;
// consume emptySpaceLen data of in
tmpIn += emptySpaceLen;
curWord = BytesToUint64LittleEndian(ctx->remainder);
(void)UpdateInternalState(curWord, ctx, ctx->compressionRounds);
}
size_t remainLen = tmpInlen & (SIPHASH_WORD_SIZE - 1); // inlen mod 8
const uint8_t *lastWordPos = tmpIn + tmpInlen - remainLen;
while (tmpIn != lastWordPos) {
curWord = BytesToUint64LittleEndian(tmpIn);
(void)UpdateInternalState(curWord, ctx, ctx->compressionRounds);
tmpIn += SIPHASH_WORD_SIZE;
}
if (remainLen > 0) {
(void)memcpy_s(ctx->remainder, remainLen, lastWordPos, remainLen);
}
ctx->offset = (uint32_t)remainLen;
return CRYPT_SUCCESS;
}
int32_t CRYPT_SIPHASH_Final(CRYPT_SIPHASH_Ctx *ctx, uint8_t *out, uint32_t *outlen)
{
if (ctx == NULL || out == NULL || outlen == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (*outlen < ctx->hashSize) {
BSL_ERR_PUSH_ERROR(CRYPT_SIPHASH_OUT_BUFF_LEN_NOT_ENOUGH);
return CRYPT_SIPHASH_OUT_BUFF_LEN_NOT_ENOUGH;
}
*outlen = ctx->hashSize;
uint64_t mLen = ctx->accInLen; // message length
uint64_t tmpLastWord = mLen << 56; // put (mLen mod 256) at high address
size_t remainLen = ctx->offset;
uint64_t curWord = DealLastWord(tmpLastWord, ctx->remainder, remainLen);
(void)UpdateInternalState(curWord, ctx, ctx->compressionRounds);
if (*outlen == SIPHASH_MIN_DIGEST_SIZE) {
(ctx->state2) ^= 0xff;
} else {
(ctx->state2) ^= 0xee;
}
for (uint16_t j = 0; j < ctx->finalizationRounds; j++) {
(void)SiproundOperation(&(ctx->state0), &(ctx->state1), &(ctx->state2), &(ctx->state3));
}
uint64_t state = (ctx->state0) ^ (ctx->state1) ^ (ctx->state2) ^ (ctx->state3);
(void)Uint64ToBytesLittleEndian(state, out);
if (*outlen == SIPHASH_MIN_DIGEST_SIZE) {
return CRYPT_SUCCESS;
}
(ctx->state1) ^= 0xdd;
for (uint16_t j = 0; j < ctx->finalizationRounds; j++) {
(void)SiproundOperation(&(ctx->state0), &(ctx->state1), &(ctx->state2), &(ctx->state3));
}
state = (ctx->state0) ^ (ctx->state1) ^ (ctx->state2) ^ (ctx->state3);
(void)Uint64ToBytesLittleEndian(state, out + SIPHASH_WORD_SIZE);
return CRYPT_SUCCESS;
}
int32_t CRYPT_SIPHASH_Reinit(CRYPT_SIPHASH_Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
ctx->state0 = 0;
ctx->state1 = 0;
ctx->state2 = 0;
ctx->state3 = 0;
ctx->accInLen = 0;
ctx->offset = 0;
(void)memset_s(ctx->remainder, SIPHASH_WORD_SIZE, 0, SIPHASH_WORD_SIZE);
return CRYPT_SUCCESS;
}
int32_t CRYPT_SIPHASH_Deinit(CRYPT_SIPHASH_Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_SIPHASH_Ctrl(CRYPT_SIPHASH_Ctx *ctx, uint32_t opt, void *val, uint32_t len)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
switch (opt) {
case CRYPT_CTRL_GET_MACLEN:
return CRYPT_SIPHASH_GetMacLen(ctx, val, len);
default:
break;
}
BSL_ERR_PUSH_ERROR(CRYPT_SIPHASH_ERR_UNSUPPORTED_CTRL_OPTION);
return CRYPT_SIPHASH_ERR_UNSUPPORTED_CTRL_OPTION;
}
void CRYPT_SIPHASH_FreeCtx(CRYPT_SIPHASH_Ctx *ctx)
{
if (ctx != NULL) {
BSL_SAL_Free(ctx);
}
}
#endif /* HITLS_CRYPTO_SIPHASH */
| 2302_82127028/openHiTLS-examples_1508 | crypto/siphash/src/siphash.c | C | unknown | 11,401 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef CRYPT_SLH_DSA_H
#define CRYPT_SLH_DSA_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SLH_DSA
#include <stdint.h>
#include "bsl_params.h"
typedef struct SlhDsaCtx CryptSlhDsaCtx;
typedef struct HashFuncs SlhDsaHashFuncs;
typedef union Adrs SlhDsaAdrs;
/**
* @brief Create a new SLH-DSA context
*
* @return CryptSlhDsaCtx* Pointer to the new SLH-DSA context
*/
CryptSlhDsaCtx *CRYPT_SLH_DSA_NewCtx(void);
/**
* @brief Create a new SLH-DSA context
*
* @param libCtx Pointer to the library context
*
* @return CryptSlhDsaCtx* Pointer to the new SLH-DSA context
*/
CryptSlhDsaCtx *CRYPT_SLH_DSA_NewCtxEx(void *libCtx);
/**
* @brief Free a SLH-DSA context
*
* @param ctx Pointer to the SLH-DSA context
*/
void CRYPT_SLH_DSA_FreeCtx(CryptSlhDsaCtx *ctx);
/**
* @brief Generate a SLH-DSA key pair
*
* @param ctx Pointer to the SLH-DSA context
*/
int32_t CRYPT_SLH_DSA_Gen(CryptSlhDsaCtx *ctx);
/**
* @brief Sign data using SLH-DSA
*
* @param ctx Pointer to the SLH-DSA context
* @param algId Algorithm ID
* @param data Pointer to the data to sign
* @param dataLen Length of the data
* @param sign Pointer to the signature
* @param signLen Length of the signature
*/
int32_t CRYPT_SLH_DSA_Sign(CryptSlhDsaCtx *ctx, int32_t algId, const uint8_t *data, uint32_t dataLen, uint8_t *sign,
uint32_t *signLen);
/**
* @brief Verify data using SLH-DSA
*
* @param ctx Pointer to the SLH-DSA context
* @param algId Algorithm ID
* @param data Pointer to the data to verify
* @param dataLen Length of the data
* @param sign Pointer to the signature
* @param signLen Length of the signature
*/
int32_t CRYPT_SLH_DSA_Verify(const CryptSlhDsaCtx *ctx, int32_t algId, const uint8_t *data, uint32_t dataLen,
const uint8_t *sign, uint32_t signLen);
/**
* @brief Control function for SLH-DSA
*
* @param ctx Pointer to the SLH-DSA context
* @param opt Option
* @param val Value
* @param len Length of the value
*/
int32_t CRYPT_SLH_DSA_Ctrl(CryptSlhDsaCtx *ctx, int32_t opt, void *val, uint32_t len);
/**
* @brief Get the public key of SLH-DSA
*
* @param ctx Pointer to the SLH-DSA context
* @param pub Pointer to the public key
*/
int32_t CRYPT_SLH_DSA_GetPubKey(const CryptSlhDsaCtx *ctx, CRYPT_SlhDsaPub *pub);
/**
* @brief Get the private key of SLH-DSA
*
* @param ctx Pointer to the SLH-DSA context
* @param prv Pointer to the private key
*/
int32_t CRYPT_SLH_DSA_GetPrvKey(const CryptSlhDsaCtx *ctx, CRYPT_SlhDsaPrv *prv);
/**
* @brief Set the public key of SLH-DSA
*
* @param ctx Pointer to the SLH-DSA context
* @param pub Pointer to the public key
*/
int32_t CRYPT_SLH_DSA_SetPubKey(CryptSlhDsaCtx *ctx, const CRYPT_SlhDsaPub *pub);
/**
* @brief Set the private key of SLH-DSA
*
* @param ctx Pointer to the SLH-DSA context
* @param prv Pointer to the private key
*/
int32_t CRYPT_SLH_DSA_SetPrvKey(CryptSlhDsaCtx *ctx, const CRYPT_SlhDsaPrv *prv);
#ifdef HITLS_BSL_PARAMS
/**
* @brief Get the public key of SLH-DSA
*
* @param ctx Pointer to the SLH-DSA context
* @param para Pointer to the public key
*/
int32_t CRYPT_SLH_DSA_GetPubKeyEx(const CryptSlhDsaCtx *ctx, BSL_Param *para);
/**
* @brief Get the private key of SLH-DSA
*
* @param ctx Pointer to the SLH-DSA context
* @param para Pointer to the private key
*/
int32_t CRYPT_SLH_DSA_GetPrvKeyEx(const CryptSlhDsaCtx *ctx, BSL_Param *para);
/**
* @brief Set the public key of SLH-DSA
*
* @param ctx Pointer to the SLH-DSA context
* @param para Pointer to the public key
*/
int32_t CRYPT_SLH_DSA_SetPubKeyEx(CryptSlhDsaCtx *ctx, const BSL_Param *para);
/**
* @brief Set the private key of SLH-DSA
*
* @param ctx Pointer to the SLH-DSA context
* @param para Pointer to the private key
*/
int32_t CRYPT_SLH_DSA_SetPrvKeyEx(CryptSlhDsaCtx *ctx, const BSL_Param *para);
#endif
#ifdef HITLS_CRYPTO_SLH_DSA_CHECK
/**
* @brief Check the key pair of SLH-DSA
*
* @param checkType Check type
* @param pkey1 Pointer to the first SLH-DSA context
* @param pkey2 Pointer to the second SLH-DSA context
*
* @retval CRYPT_SUCCESS check success.
* Others. For details, see error code in errno.
*/
int32_t CRYPT_SLH_DSA_Check(uint32_t checkType, const CryptSlhDsaCtx *pkey1, const CryptSlhDsaCtx *pkey2);
#endif // HITLS_CRYPTO_SLH_DSA_CHECK
#endif // HITLS_CRYPTO_SLH_DSA
#endif // CRYPT_SLH_DSA_H | 2302_82127028/openHiTLS-examples_1508 | crypto/slh_dsa/include/crypt_slh_dsa.h | C | unknown | 4,946 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SLH_DSA
#include <stddef.h>
#include "securec.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "bsl_obj_internal.h"
#include "bsl_asn1_internal.h"
#include "crypt_errno.h"
#include "crypt_algid.h"
#include "crypt_util_rand.h"
#include "eal_md_local.h"
#include "crypt_slh_dsa.h"
#include "slh_dsa_local.h"
#include "slh_dsa_hash.h"
#include "slh_dsa_fors.h"
#include "slh_dsa_xmss.h"
#include "slh_dsa_hypertree.h"
#define MAX_DIGEST_SIZE 64
#define BYTE_BITS 8
#define SLH_DSA_PREFIX_LEN 2
#define ASN1_HEADER_LEN 2
#define SPLIT_CEIL(a, b) (((a) + (b) - 1) / (b))
#define SPLIT_BYTES(a) SPLIT_CEIL(a, BYTE_BITS)
#define NUM_OF_CRYPT_SLH_DSA_ALGID 12
typedef struct {
BSL_Param *pubSeed;
BSL_Param *pubRoot;
} SlhDsaPubKeyParam;
typedef struct {
BSL_Param *prvSeed;
BSL_Param *prvPrf;
BSL_Param *pubSeed;
BSL_Param *pubRoot;
} SlhDsaPrvKeyParam;
// reference to FIPS-205, table 2
static uint32_t g_slhDsaN[NUM_OF_CRYPT_SLH_DSA_ALGID] = {16, 16, 16, 16, 24, 24, 24, 24, 32, 32, 32, 32};
static uint32_t g_slhDsaH[NUM_OF_CRYPT_SLH_DSA_ALGID] = {63, 63, 66, 66, 63, 63, 66, 66, 64, 64, 68, 68};
static uint32_t g_slhDsaD[NUM_OF_CRYPT_SLH_DSA_ALGID] = {7, 7, 22, 22, 7, 7, 22, 22, 8, 8, 17, 17};
static uint32_t g_slhDsaHp[NUM_OF_CRYPT_SLH_DSA_ALGID] = {9, 9, 3, 3, 9, 9, 3, 3, 8, 8, 4, 4}; // xmss height
static uint32_t g_slhDsaA[NUM_OF_CRYPT_SLH_DSA_ALGID] = {12, 12, 6, 6, 14, 14, 8, 8, 14, 14, 9, 9};
static uint32_t g_slhDsaK[NUM_OF_CRYPT_SLH_DSA_ALGID] = {14, 14, 33, 33, 17, 17, 33, 33, 22, 22, 35, 35};
static uint32_t g_slhDsaM[NUM_OF_CRYPT_SLH_DSA_ALGID] = {30, 30, 34, 34, 39, 39, 42, 42, 47, 47, 49, 49};
static uint32_t g_slhDsaPkBytes[NUM_OF_CRYPT_SLH_DSA_ALGID] = {32, 32, 32, 32, 48, 48, 48, 48, 64, 64, 64, 64};
static uint32_t g_slhDsaSigBytes[NUM_OF_CRYPT_SLH_DSA_ALGID] = {7856, 7856, 17088, 17088, 16224, 16224,
35664, 35664, 29792, 29792, 49856, 49856};
static uint8_t g_secCategory[] = {1, 1, 1, 1, 3, 3, 3, 3, 5, 5, 5, 5};
// "UC" means uncompressed
static void UCAdrsSetLayerAddr(SlhDsaAdrs *adrs, uint32_t layer)
{
PUT_UINT32_BE(layer, adrs->uc.layerAddr, 0);
}
static void UCAdrsSetTreeAddr(SlhDsaAdrs *adrs, uint64_t tree)
{
// Write 8-byte tree address starting from offset 4 in 12-byte treeAddr field
PUT_UINT64_BE(tree, adrs->uc.treeAddr, 4);
}
static void UCAdrsSetType(SlhDsaAdrs *adrs, AdrsType type)
{
PUT_UINT32_BE(type, adrs->uc.type, 0);
(void)memset_s(adrs->uc.padding, sizeof(adrs->uc.padding), 0, sizeof(adrs->uc.padding));
}
static void UCAdrsSetKeyPairAddr(SlhDsaAdrs *adrs, uint32_t keyPair)
{
PUT_UINT32_BE(keyPair, adrs->uc.padding, 0);
}
static void UCAdrsSetChainAddr(SlhDsaAdrs *adrs, uint32_t chain)
{
PUT_UINT32_BE(chain, adrs->uc.padding, 4); // chain address is 4 bytes, start from 4-th byte
}
static void UCAdrsSetTreeHeight(SlhDsaAdrs *adrs, uint32_t height)
{
PUT_UINT32_BE(height, adrs->uc.padding, 4); // tree height is 4 bytes, start from 4-th byte
}
static void UCAdrsSetHashAddr(SlhDsaAdrs *adrs, uint32_t hash)
{
PUT_UINT32_BE(hash, adrs->uc.padding, 8); // hash address is 4 bytes, start from 8-th byte
}
static void UCAdrsSetTreeIndex(SlhDsaAdrs *adrs, uint32_t index)
{
PUT_UINT32_BE(index, adrs->uc.padding, 8); // tree index is 4 bytes, start from 8-th byte
}
static uint32_t UCAdrsGetTreeHeight(const SlhDsaAdrs *adrs)
{
return GET_UINT32_BE(adrs->uc.padding, 0);
}
static uint32_t UCAdrsGetTreeIndex(const SlhDsaAdrs *adrs)
{
return GET_UINT32_BE(adrs->uc.padding, 8); // tree index is 4 bytes, start from 8-th byte
}
static void UCAdrsCopyKeyPairAddr(SlhDsaAdrs *adrs, const SlhDsaAdrs *adrs2)
{
(void)memcpy_s(adrs->uc.padding, sizeof(adrs->uc.padding), adrs2->uc.padding,
4); // key pair address is 4 bytes, start from 4-th byte
}
static uint32_t UCAdrsGetAdrsLen(void)
{
return SLH_DSA_ADRS_LEN;
}
// "C" means compressed
static void CAdrsSetLayerAddr(SlhDsaAdrs *adrs, uint32_t layer)
{
adrs->c.layerAddr = (uint8_t)layer;
}
static void CAdrsSetTreeAddr(SlhDsaAdrs *adrs, uint64_t tree)
{
// Write 8-byte tree address starting from offset 0 in 8-byte treeAddr field
PUT_UINT64_BE(tree, adrs->c.treeAddr, 0);
}
static void CAdrsSetType(SlhDsaAdrs *adrs, AdrsType type)
{
adrs->c.type = type;
(void)memset_s(adrs->c.padding, sizeof(adrs->c.padding), 0, sizeof(adrs->c.padding));
}
static void CAdrsSetKeyPairAddr(SlhDsaAdrs *adrs, uint32_t keyPair)
{
PUT_UINT32_BE(keyPair, adrs->c.padding, 0);
}
static void CAdrsSetChainAddr(SlhDsaAdrs *adrs, uint32_t chain)
{
PUT_UINT32_BE(chain, adrs->c.padding, 4); // chain address is 4 bytes, start from 4-th byte
}
static void CAdrsSetTreeHeight(SlhDsaAdrs *adrs, uint32_t height)
{
PUT_UINT32_BE(height, adrs->c.padding, 4); // tree height is 4 bytes, start from 4-th byte
}
static void CAdrsSetHashAddr(SlhDsaAdrs *adrs, uint32_t hash)
{
PUT_UINT32_BE(hash, adrs->c.padding, 8); // hash address is 4 bytes, start from 8-th byte
}
static void CAdrsSetTreeIndex(SlhDsaAdrs *adrs, uint32_t index)
{
PUT_UINT32_BE(index, adrs->c.padding, 8); // tree index is 4 bytes, start from 8-th byte
}
static uint32_t CAdrsGetTreeHeight(const SlhDsaAdrs *adrs)
{
return GET_UINT32_BE(adrs->c.padding, 0); // tree height is 4 bytes, start from 0-th byte
}
static uint32_t CAdrsGetTreeIndex(const SlhDsaAdrs *adrs)
{
return GET_UINT32_BE(adrs->c.padding, 8); // tree index is 4 bytes, start from 8-th byte
}
static void CAdrsCopyKeyPairAddr(SlhDsaAdrs *adrs, const SlhDsaAdrs *adrs2)
{
(void)memcpy_s(adrs->c.padding, sizeof(adrs->c.padding), adrs2->c.padding,
4); // key pair address is 4 bytes, start from 4-th byte
}
static uint32_t CAdrsGetAdrsLen(void)
{
return SLH_DSA_ADRS_COMPRESSED_LEN;
}
static AdrsOps g_adrsOps[2] = {{
.setLayerAddr = UCAdrsSetLayerAddr,
.setTreeAddr = UCAdrsSetTreeAddr,
.setType = UCAdrsSetType,
.setKeyPairAddr = UCAdrsSetKeyPairAddr,
.setChainAddr = UCAdrsSetChainAddr,
.setTreeHeight = UCAdrsSetTreeHeight,
.setHashAddr = UCAdrsSetHashAddr,
.setTreeIndex = UCAdrsSetTreeIndex,
.getTreeHeight = UCAdrsGetTreeHeight,
.getTreeIndex = UCAdrsGetTreeIndex,
.copyKeyPairAddr = UCAdrsCopyKeyPairAddr,
.getAdrsLen = UCAdrsGetAdrsLen,
},
{
.setLayerAddr = CAdrsSetLayerAddr,
.setTreeAddr = CAdrsSetTreeAddr,
.setType = CAdrsSetType,
.setKeyPairAddr = CAdrsSetKeyPairAddr,
.setChainAddr = CAdrsSetChainAddr,
.setTreeHeight = CAdrsSetTreeHeight,
.setHashAddr = CAdrsSetHashAddr,
.setTreeIndex = CAdrsSetTreeIndex,
.getTreeHeight = CAdrsGetTreeHeight,
.getTreeIndex = CAdrsGetTreeIndex,
.copyKeyPairAddr = CAdrsCopyKeyPairAddr,
.getAdrsLen = CAdrsGetAdrsLen,
}};
void BaseB(const uint8_t *x, uint32_t xLen, uint32_t b, uint32_t *out, uint32_t outLen)
{
uint32_t bit = 0;
uint32_t o = 0;
uint32_t xi = 0;
for (uint32_t i = 0; i < outLen; i++) {
while (bit < b && xi < xLen) {
o = (o << BYTE_BITS) + x[xi];
bit += 8;
xi++;
}
bit -= b;
out[i] = o >> bit;
// keep the remaining bits
o &= (1 << bit) - 1;
}
}
// ToInt(b[0:l]) mod 2^m
static uint64_t ToIntMod(const uint8_t *b, uint32_t l, uint32_t m)
{
uint64_t ret = 0;
for (uint32_t i = 0; i < l; i++) {
ret = (ret << BYTE_BITS) + b[i];
}
return ret & (~(uint64_t)0 >> (64 - m)); // mod 2^m is same to ~(uint64_t)0 >> (64 - m)
}
CryptSlhDsaCtx *CRYPT_SLH_DSA_NewCtx(void)
{
CryptSlhDsaCtx *ctx = (CryptSlhDsaCtx *)BSL_SAL_Calloc(sizeof(CryptSlhDsaCtx), 1);
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
ctx->para.algId = 0;
ctx->isPrehash = false;
ctx->isDeterministic = false;
return ctx;
}
CryptSlhDsaCtx *CRYPT_SLH_DSA_NewCtxEx(void *libCtx)
{
CryptSlhDsaCtx *ctx = CRYPT_SLH_DSA_NewCtx();
if (ctx == NULL) {
return NULL;
}
ctx->libCtx = libCtx;
return ctx;
}
void CRYPT_SLH_DSA_FreeCtx(CryptSlhDsaCtx *ctx)
{
if (ctx == NULL) {
return;
}
BSL_SAL_Free(ctx->context);
BSL_SAL_ClearFree(ctx->addrand, ctx->addrandLen);
BSL_SAL_CleanseData(ctx->prvKey.seed, sizeof(ctx->prvKey.seed));
BSL_SAL_CleanseData(ctx->prvKey.prf, sizeof(ctx->prvKey.prf));
BSL_SAL_Free(ctx);
}
static bool CheckNotSlhDsaAlgId(int32_t algId)
{
if (algId > CRYPT_SLH_DSA_SHAKE_256F || algId < CRYPT_SLH_DSA_SHA2_128S) {
return true;
}
return false;
}
int32_t CRYPT_SLH_DSA_Gen(CryptSlhDsaCtx *ctx)
{
int32_t ret;
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (CheckNotSlhDsaAlgId(ctx->para.algId)) {
BSL_ERR_PUSH_ERROR(CRYPT_SLHDSA_ERR_INVALID_ALGID);
return CRYPT_SLHDSA_ERR_INVALID_ALGID;
}
uint32_t n = ctx->para.n;
uint32_t d = ctx->para.d;
uint32_t hp = ctx->para.hp;
ret = CRYPT_RandEx(ctx->libCtx, ctx->prvKey.seed, n);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = CRYPT_RandEx(ctx->libCtx, ctx->prvKey.prf, n);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = CRYPT_RandEx(ctx->libCtx, ctx->prvKey.pub.seed, n);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
SlhDsaAdrs adrs = {0};
ctx->adrsOps.setLayerAddr(&adrs, d - 1);
uint8_t node[SLH_DSA_MAX_N] = {0};
ret = XmssNode(node, 0, hp, &adrs, ctx, NULL, 0);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
(void)memcpy_s(ctx->prvKey.pub.root, n, node, n);
ctx->keyType = SLH_DSA_PRVKEY | SLH_DSA_PUBKEY;
return CRYPT_SUCCESS;
}
static int32_t GetAddRand(CryptSlhDsaCtx *ctx)
{
if (ctx->addrand != NULL) {
// the additional rand is set.
return CRYPT_SUCCESS;
}
if (!ctx->isDeterministic) {
ctx->addrand = (uint8_t *)BSL_SAL_Malloc(ctx->para.n);
if (ctx->addrand == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
int32_t ret = CRYPT_RandEx(ctx->libCtx, ctx->addrand, ctx->para.n);
if (ret != CRYPT_SUCCESS) {
return ret;
}
} else {
// FIPS-204, Algorithm 19, line 2.
// if is deterministic, use the public key seed as the random number.
uint8_t *rand = (uint8_t *)BSL_SAL_Malloc(ctx->para.n);
if (rand == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
(void)memcpy_s(rand, ctx->para.n, ctx->prvKey.pub.seed, ctx->para.n);
ctx->addrand = rand;
}
ctx->addrandLen = ctx->para.n;
return CRYPT_SUCCESS;
}
static void GetTreeAndLeafIdx(const uint8_t *digest, const CryptSlhDsaCtx *ctx, uint64_t *treeIdx, uint32_t *leafIdx)
{
uint32_t a = ctx->para.a;
uint32_t k = ctx->para.k;
uint32_t h = ctx->para.h;
uint32_t d = ctx->para.d;
uint32_t mdIdx = SPLIT_BYTES(k * a);
uint32_t treeIdxLen = SPLIT_BYTES(h - h / d);
uint32_t leafIdxLen = SPLIT_BYTES(h / d);
*treeIdx = ToIntMod(digest + mdIdx, treeIdxLen, h - h / d);
*leafIdx = (uint32_t)ToIntMod(digest + mdIdx + treeIdxLen, leafIdxLen, h / d);
}
static int32_t CRYPT_SLH_DSA_SignInternal(CryptSlhDsaCtx *ctx, const uint8_t *msg, uint32_t msgLen, uint8_t *sig,
uint32_t *sigLen)
{
int32_t ret;
uint32_t n = ctx->para.n;
uint32_t a = ctx->para.a;
uint32_t k = ctx->para.k;
uint32_t sigBytes = ctx->para.sigBytes;
uint32_t mdIdx = SPLIT_BYTES(k * a);
uint64_t treeIdx;
uint32_t leafIdx;
if (*sigLen < sigBytes) {
BSL_ERR_PUSH_ERROR(CRYPT_SLHDSA_ERR_INVALID_SIG_LEN);
return CRYPT_SLHDSA_ERR_INVALID_SIG_LEN;
}
SlhDsaAdrs adrs = {0};
uint32_t offset = 0;
uint32_t left = *sigLen;
ret = GetAddRand(ctx);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = ctx->hashFuncs.prfmsg(ctx, ctx->addrand, msg, msgLen, sig);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
offset += n;
uint8_t digest[SLH_DSA_MAX_M] = {0};
ret = ctx->hashFuncs.hmsg(ctx, sig, msg, msgLen, NULL, digest);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
GetTreeAndLeafIdx(digest, ctx, &treeIdx, &leafIdx);
ctx->adrsOps.setTreeAddr(&adrs, treeIdx);
ctx->adrsOps.setType(&adrs, FORS_TREE);
ctx->adrsOps.setKeyPairAddr(&adrs, leafIdx);
ret = ForsSign(digest, mdIdx, &adrs, ctx, sig + offset, &left);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
uint8_t pk[SLH_DSA_MAX_N] = {0};
ret = ForsPkFromSig(sig + n, left, digest, mdIdx, &adrs, ctx, pk);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
offset += left;
left = *sigLen - offset;
ret = HypertreeSign(pk, n, treeIdx, leafIdx, ctx, sig + offset, &left);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
*sigLen = offset + left;
return CRYPT_SUCCESS;
}
static int32_t CRYPT_SLH_DSA_VerifyInternal(const CryptSlhDsaCtx *ctx, const uint8_t *msg, uint32_t msgLen,
const uint8_t *sig, uint32_t sigLen)
{
int32_t ret;
uint32_t n = ctx->para.n;
uint32_t a = ctx->para.a;
uint32_t k = ctx->para.k;
uint32_t sigBytes = ctx->para.sigBytes;
uint32_t mdIdx = SPLIT_BYTES(k * a);
uint64_t treeIdx;
uint32_t leafIdx;
if (sigLen != sigBytes) {
BSL_ERR_PUSH_ERROR(CRYPT_SLHDSA_ERR_INVALID_SIG_LEN);
return CRYPT_SLHDSA_ERR_INVALID_SIG_LEN;
}
SlhDsaAdrs adrs = {0};
uint32_t offset = 0;
uint8_t digest[SLH_DSA_MAX_M] = {0};
ret = ctx->hashFuncs.hmsg(ctx, sig, msg, msgLen, NULL, digest);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
offset += n;
GetTreeAndLeafIdx(digest, ctx, &treeIdx, &leafIdx);
ctx->adrsOps.setTreeAddr(&adrs, treeIdx);
ctx->adrsOps.setType(&adrs, FORS_TREE);
ctx->adrsOps.setKeyPairAddr(&adrs, leafIdx);
uint8_t pk[SLH_DSA_MAX_N] = {0};
ret = ForsPkFromSig(sig + offset, (1 + a) * k * n, digest, mdIdx, &adrs, ctx, pk);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
offset += (1 + a) * k * n;
ret = HypertreeVerify(pk, n, sig + offset, sigLen - offset, treeIdx, leafIdx, ctx);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
return CRYPT_SUCCESS;
}
static uint32_t GetMdSize(const EAL_MdMethod *hashMethod, int32_t hashId)
{
if (hashId == CRYPT_MD_SHAKE128) {
return 32; // To use SHAKE128, generate a 32-byte digest.
} else if (hashId == CRYPT_MD_SHAKE256) {
return 64; // To use SHAKE256, generate a 64-byte digest.
}
return hashMethod->mdSize;
}
static int32_t MsgEncode(const CryptSlhDsaCtx *ctx, int32_t algId, const uint8_t *data, uint32_t dataLen,
uint8_t **mpOut, uint32_t *mpLenOut)
{
int32_t ret;
BslOidString *oid = NULL;
uint32_t offset = 0;
uint8_t prehash[MAX_DIGEST_SIZE] = {0};
uint32_t prehashLen = sizeof(prehash);
uint32_t mpLen = SLH_DSA_PREFIX_LEN + ctx->contextLen;
if (ctx->isPrehash) {
oid = BSL_OBJ_GetOID((BslCid)algId);
if (oid == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_SLHDSA_ERR_PREHASH_ID_NOT_SUPPORTED);
return CRYPT_SLHDSA_ERR_PREHASH_ID_NOT_SUPPORTED;
}
mpLen += 2 + oid->octetLen; // asn1 header length is 2
prehashLen = GetMdSize(EAL_MdFindDefaultMethod(algId), algId);
const CRYPT_ConstData constData = {data, dataLen};
ret = CRYPT_CalcHash(NULL, EAL_MdFindDefaultMethod(algId), &constData, 1, prehash, &prehashLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
mpLen += prehashLen;
} else {
mpLen += dataLen;
}
uint8_t *mp = (uint8_t *)BSL_SAL_Malloc(mpLen);
if (mp == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
mp[0] = ctx->isPrehash ? 1 : 0;
mp[1] = (uint8_t)ctx->contextLen;
(void)memcpy_s(mp + SLH_DSA_PREFIX_LEN, mpLen - SLH_DSA_PREFIX_LEN, ctx->context, ctx->contextLen);
offset += SLH_DSA_PREFIX_LEN + ctx->contextLen;
if (ctx->isPrehash) {
// asn1 encoding of hash oid
(mp + offset)[0] = BSL_ASN1_TAG_OBJECT_ID;
(mp + offset)[1] = (uint8_t)oid->octetLen;
offset += 2; // asn1 header length is 2
(void)memcpy_s(mp + offset, mpLen - offset, oid->octs, oid->octetLen);
offset += oid->octetLen;
(void)memcpy_s(mp + offset, mpLen - offset, prehash, prehashLen);
} else {
(void)memcpy_s(mp + offset, mpLen - offset, data, dataLen);
}
*mpOut = mp;
*mpLenOut = mpLen;
return CRYPT_SUCCESS;
}
int32_t CRYPT_SLH_DSA_Sign(CryptSlhDsaCtx *ctx, int32_t algId, const uint8_t *data, uint32_t dataLen, uint8_t *sign,
uint32_t *signLen)
{
int32_t ret;
uint8_t *mp = NULL;
uint32_t mpLen = 0;
if (ctx == NULL || data == NULL || dataLen == 0 || sign == NULL || signLen == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
ret = MsgEncode(ctx, algId, data, dataLen, &mp, &mpLen);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = CRYPT_SLH_DSA_SignInternal(ctx, mp, mpLen, sign, signLen);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_Free(mp);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BSL_SAL_Free(mp);
return CRYPT_SUCCESS;
}
int32_t CRYPT_SLH_DSA_Verify(const CryptSlhDsaCtx *ctx, int32_t algId, const uint8_t *data, uint32_t dataLen,
const uint8_t *sign, uint32_t signLen)
{
(void)algId;
int32_t ret;
uint8_t *mp = NULL;
uint32_t mpLen = 0;
if (ctx == NULL || data == NULL || dataLen == 0 || sign == NULL || signLen == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
ret = MsgEncode(ctx, algId, data, dataLen, &mp, &mpLen);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = CRYPT_SLH_DSA_VerifyInternal(ctx, mp, mpLen, sign, signLen);
BSL_SAL_Free(mp);
return ret;
}
static int32_t SlhDsaSetAlgId(CryptSlhDsaCtx *ctx, void *val, uint32_t len)
{
if (val == NULL || len != sizeof(int32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
CRYPT_PKEY_ParaId algId = *(CRYPT_PKEY_ParaId *)val;
if (CheckNotSlhDsaAlgId(algId)) {
BSL_ERR_PUSH_ERROR(CRYPT_SLHDSA_ERR_INVALID_ALGID);
return CRYPT_SLHDSA_ERR_INVALID_ALGID;
}
ctx->para.algId = algId;
int32_t index = algId - CRYPT_SLH_DSA_SHA2_128S;
ctx->para.n = g_slhDsaN[index];
ctx->para.h = g_slhDsaH[index];
ctx->para.d = g_slhDsaD[index];
ctx->para.hp = g_slhDsaHp[index];
ctx->para.a = g_slhDsaA[index];
ctx->para.k = g_slhDsaK[index];
ctx->para.m = g_slhDsaM[index];
ctx->para.pkBytes = g_slhDsaPkBytes[index];
ctx->para.sigBytes = g_slhDsaSigBytes[index];
ctx->para.secCategory = g_secCategory[index];
SlhDsaInitHashFuncs(ctx);
if (ctx->para.isCompressed) {
ctx->adrsOps = g_adrsOps[1];
} else {
ctx->adrsOps = g_adrsOps[0];
}
return CRYPT_SUCCESS;
}
static int32_t SetContextInfo(CryptSlhDsaCtx *ctx, void *val, uint32_t len)
{
if (val == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
if (len > 255) {
BSL_ERR_PUSH_ERROR(CRYPT_SLHDSA_ERR_CONTEXT_LEN_OVERFLOW);
return CRYPT_SLHDSA_ERR_CONTEXT_LEN_OVERFLOW;
}
ctx->contextLen = len;
BSL_SAL_Free(ctx->context);
ctx->context = (uint8_t *)BSL_SAL_Malloc(len);
if (ctx->context == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
(void)memcpy_s(ctx->context, len, val, len);
return CRYPT_SUCCESS;
}
static int32_t SetAddrand(CryptSlhDsaCtx *ctx, void *val, uint32_t len)
{
if (val == NULL || len != ctx->para.n) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
BSL_SAL_FREE(ctx->addrand);
uint8_t *rand = (uint8_t *)BSL_SAL_Malloc(len);
if (rand == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
(void)memcpy_s(rand, len, val, len);
ctx->addrand = rand;
ctx->addrandLen = len;
return CRYPT_SUCCESS;
}
int32_t CRYPT_SLH_DSA_Ctrl(CryptSlhDsaCtx *ctx, int32_t opt, void *val, uint32_t len)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
switch (opt) {
case CRYPT_CTRL_SET_PARA_BY_ID:
return SlhDsaSetAlgId(ctx, val, len);
case CRYPT_CTRL_SET_PREHASH_FLAG:
if (val == NULL || len != sizeof(int32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
ctx->isPrehash = (*(int32_t *)val != 0);
return CRYPT_SUCCESS;
case CRYPT_CTRL_SET_CTX_INFO:
return SetContextInfo(ctx, val, len);
case CRYPT_CTRL_GET_SLH_DSA_KEY_LEN:
if (val == NULL || len != sizeof(uint32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
*(uint32_t *)val = ctx->para.n;
return CRYPT_SUCCESS;
case CRYPT_CTRL_SET_DETERMINISTIC_FLAG:
if (val == NULL || len != sizeof(int32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
ctx->isDeterministic = (*(int32_t *)val != 0);
return CRYPT_SUCCESS;
case CRYPT_CTRL_SET_SLH_DSA_ADDRAND:
return SetAddrand(ctx, val, len);
case CRYPT_CTRL_CLEAN_PUB_KEY:
BSL_SAL_CleanseData(ctx->prvKey.pub.seed, sizeof(ctx->prvKey.pub.seed));
BSL_SAL_CleanseData(ctx->prvKey.pub.root, sizeof(ctx->prvKey.pub.root));
return CRYPT_SUCCESS;
default:
BSL_ERR_PUSH_ERROR(CRYPT_NOT_SUPPORT);
return CRYPT_NOT_SUPPORT;
}
}
static int32_t PubKeyCheck(const CryptSlhDsaCtx *ctx, const CRYPT_SlhDsaPub *pub)
{
if (ctx == NULL || pub == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (pub->seed == NULL || pub->root == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (pub->len != ctx->para.n) {
BSL_ERR_PUSH_ERROR(CRYPT_SLHDSA_ERR_INVALID_KEYLEN);
return CRYPT_SLHDSA_ERR_INVALID_KEYLEN;
}
return CRYPT_SUCCESS;
}
static int32_t PrvKeyCheck(const CryptSlhDsaCtx *ctx, const CRYPT_SlhDsaPrv *prv)
{
if (ctx == NULL || prv == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (prv->prf == NULL || prv->seed == NULL || prv->pub.root == NULL || prv->pub.seed == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (prv->pub.len != ctx->para.n) {
BSL_ERR_PUSH_ERROR(CRYPT_SLHDSA_ERR_INVALID_KEYLEN);
return CRYPT_SLHDSA_ERR_INVALID_KEYLEN;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_SLH_DSA_GetPubKey(const CryptSlhDsaCtx *ctx, CRYPT_SlhDsaPub *pub)
{
int32_t ret = PubKeyCheck(ctx, pub);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
pub->len = ctx->para.n;
(void)memcpy_s(pub->seed, pub->len, ctx->prvKey.pub.seed, ctx->para.n);
(void)memcpy_s(pub->root, pub->len, ctx->prvKey.pub.root, ctx->para.n);
return CRYPT_SUCCESS;
}
int32_t CRYPT_SLH_DSA_GetPrvKey(const CryptSlhDsaCtx *ctx, CRYPT_SlhDsaPrv *prv)
{
int32_t ret = PrvKeyCheck(ctx, prv);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
prv->pub.len = ctx->para.n;
(void)memcpy_s(prv->seed, prv->pub.len, ctx->prvKey.seed, ctx->para.n);
(void)memcpy_s(prv->prf, prv->pub.len, ctx->prvKey.prf, ctx->para.n);
(void)memcpy_s(prv->pub.seed, prv->pub.len, ctx->prvKey.pub.seed, ctx->para.n);
(void)memcpy_s(prv->pub.root, prv->pub.len, ctx->prvKey.pub.root, ctx->para.n);
return CRYPT_SUCCESS;
}
int32_t CRYPT_SLH_DSA_SetPubKey(CryptSlhDsaCtx *ctx, const CRYPT_SlhDsaPub *pub)
{
int32_t ret = PubKeyCheck(ctx, pub);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
(void)memcpy_s(ctx->prvKey.pub.seed, ctx->para.n, pub->seed, ctx->para.n);
(void)memcpy_s(ctx->prvKey.pub.root, ctx->para.n, pub->root, ctx->para.n);
return CRYPT_SUCCESS;
}
int32_t CRYPT_SLH_DSA_SetPrvKey(CryptSlhDsaCtx *ctx, const CRYPT_SlhDsaPrv *prv)
{
int32_t ret = PrvKeyCheck(ctx, prv);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
(void)memcpy_s(ctx->prvKey.seed, sizeof(ctx->prvKey.seed), prv->seed, ctx->para.n);
(void)memcpy_s(ctx->prvKey.prf, sizeof(ctx->prvKey.prf), prv->prf, ctx->para.n);
(void)memcpy_s(ctx->prvKey.pub.seed, sizeof(ctx->prvKey.pub.seed), prv->pub.seed, ctx->para.n);
(void)memcpy_s(ctx->prvKey.pub.root, sizeof(ctx->prvKey.pub.root), prv->pub.root, ctx->para.n);
return CRYPT_SUCCESS;
}
#ifdef HITLS_BSL_PARAMS
static int32_t PubKeyParamCheck(const CryptSlhDsaCtx *ctx, BSL_Param *para, SlhDsaPubKeyParam *pub)
{
if (ctx == NULL || para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
pub->pubSeed = BSL_PARAM_FindParam(para, CRYPT_PARAM_SLH_DSA_PUB_SEED);
pub->pubRoot = BSL_PARAM_FindParam(para, CRYPT_PARAM_SLH_DSA_PUB_ROOT);
if (pub->pubSeed == NULL || pub->pubSeed->value == NULL || pub->pubRoot == NULL || pub->pubRoot->value == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (pub->pubSeed->valueLen != ctx->para.n || pub->pubRoot->valueLen != ctx->para.n) {
BSL_ERR_PUSH_ERROR(CRYPT_SLHDSA_ERR_INVALID_KEYLEN);
return CRYPT_SLHDSA_ERR_INVALID_KEYLEN;
}
return CRYPT_SUCCESS;
}
static int32_t PrvKeyParamCheck(const CryptSlhDsaCtx *ctx, BSL_Param *para, SlhDsaPrvKeyParam *prv)
{
if (ctx == NULL || para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
prv->prvSeed = BSL_PARAM_FindParam(para, CRYPT_PARAM_SLH_DSA_PRV_SEED);
prv->prvPrf = BSL_PARAM_FindParam(para, CRYPT_PARAM_SLH_DSA_PRV_PRF);
prv->pubSeed = BSL_PARAM_FindParam(para, CRYPT_PARAM_SLH_DSA_PUB_SEED);
prv->pubRoot = BSL_PARAM_FindParam(para, CRYPT_PARAM_SLH_DSA_PUB_ROOT);
if (prv->prvSeed == NULL || prv->prvSeed->value == NULL || prv->prvPrf == NULL || prv->prvPrf->value == NULL ||
prv->pubSeed == NULL || prv->pubSeed->value == NULL || prv->pubRoot == NULL || prv->pubRoot->value == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (prv->prvSeed->valueLen != ctx->para.n || prv->prvPrf->valueLen != ctx->para.n ||
prv->pubSeed->valueLen != ctx->para.n || prv->pubRoot->valueLen != ctx->para.n) {
BSL_ERR_PUSH_ERROR(CRYPT_SLHDSA_ERR_INVALID_KEYLEN);
return CRYPT_SLHDSA_ERR_INVALID_KEYLEN;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_SLH_DSA_GetPubKeyEx(const CryptSlhDsaCtx *ctx, BSL_Param *para)
{
SlhDsaPubKeyParam pub;
int32_t ret = PubKeyParamCheck(ctx, para, &pub);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if ((ctx->keyType & SLH_DSA_PUBKEY) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_SLHDSA_ERR_NO_PUBKEY);
return CRYPT_SLHDSA_ERR_NO_PUBKEY;
}
pub.pubSeed->useLen = pub.pubRoot->useLen = ctx->para.n;
(void)memcpy_s(pub.pubSeed->value, pub.pubSeed->valueLen, ctx->prvKey.pub.seed, ctx->para.n);
(void)memcpy_s(pub.pubRoot->value, pub.pubRoot->valueLen, ctx->prvKey.pub.root, ctx->para.n);
return CRYPT_SUCCESS;
}
int32_t CRYPT_SLH_DSA_GetPrvKeyEx(const CryptSlhDsaCtx *ctx, BSL_Param *para)
{
SlhDsaPrvKeyParam prv;
int32_t ret = PrvKeyParamCheck(ctx, para, &prv);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if ((ctx->keyType & SLH_DSA_PRVKEY) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_SLHDSA_ERR_NO_PRVKEY);
return CRYPT_SLHDSA_ERR_NO_PRVKEY;
}
prv.prvSeed->useLen = ctx->para.n;
prv.prvPrf->useLen = ctx->para.n;
prv.pubSeed->useLen = ctx->para.n;
prv.pubRoot->useLen = ctx->para.n;
(void)memcpy_s(prv.prvSeed->value, prv.prvSeed->valueLen, ctx->prvKey.seed, ctx->para.n);
(void)memcpy_s(prv.prvPrf->value, prv.prvPrf->valueLen, ctx->prvKey.prf, ctx->para.n);
(void)memcpy_s(prv.pubSeed->value, prv.pubSeed->valueLen, ctx->prvKey.pub.seed, ctx->para.n);
(void)memcpy_s(prv.pubRoot->value, prv.pubRoot->valueLen, ctx->prvKey.pub.root, ctx->para.n);
return CRYPT_SUCCESS;
}
int32_t CRYPT_SLH_DSA_SetPubKeyEx(CryptSlhDsaCtx *ctx, const BSL_Param *para)
{
SlhDsaPubKeyParam pub;
int32_t ret = PubKeyParamCheck(ctx, (BSL_Param *)(uintptr_t)para, &pub);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
(void)memcpy_s(ctx->prvKey.pub.seed, ctx->para.n, pub.pubSeed->value, ctx->para.n);
(void)memcpy_s(ctx->prvKey.pub.root, ctx->para.n, pub.pubRoot->value, ctx->para.n);
ctx->keyType |= SLH_DSA_PUBKEY;
return CRYPT_SUCCESS;
}
int32_t CRYPT_SLH_DSA_SetPrvKeyEx(CryptSlhDsaCtx *ctx, const BSL_Param *para)
{
SlhDsaPrvKeyParam prv;
int32_t ret = PrvKeyParamCheck(ctx, (BSL_Param *)(uintptr_t)para, &prv);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
(void)memcpy_s(ctx->prvKey.seed, sizeof(ctx->prvKey.seed), prv.prvSeed->value, ctx->para.n);
(void)memcpy_s(ctx->prvKey.prf, sizeof(ctx->prvKey.prf), prv.prvPrf->value, ctx->para.n);
(void)memcpy_s(ctx->prvKey.pub.seed, sizeof(ctx->prvKey.pub.seed), prv.pubSeed->value, ctx->para.n);
(void)memcpy_s(ctx->prvKey.pub.root, sizeof(ctx->prvKey.pub.root), prv.pubRoot->value, ctx->para.n);
ctx->keyType |= SLH_DSA_PRVKEY;
return CRYPT_SUCCESS;
}
#endif
#ifdef HITLS_CRYPTO_SLH_DSA_CHECK
static int32_t SlhDsaKeyPairCheck(const CryptSlhDsaCtx *pubKey, const CryptSlhDsaCtx *prvKey)
{
if (pubKey == NULL || prvKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (CheckNotSlhDsaAlgId(pubKey->para.algId) || CheckNotSlhDsaAlgId(prvKey->para.algId)) {
BSL_ERR_PUSH_ERROR(CRYPT_SLHDSA_ERR_INVALID_ALGID);
return CRYPT_SLHDSA_ERR_INVALID_ALGID;
}
if (pubKey->para.algId != prvKey->para.algId) {
BSL_ERR_PUSH_ERROR(CRYPT_SLHDSA_PAIRWISE_CHECK_FAIL);
return CRYPT_SLHDSA_PAIRWISE_CHECK_FAIL;
}
if ((pubKey->keyType & SLH_DSA_PUBKEY) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_SLHDSA_ERR_NO_PUBKEY);
return CRYPT_SLHDSA_ERR_NO_PUBKEY;
}
if ((prvKey->keyType & SLH_DSA_PRVKEY) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_SLHDSA_ERR_NO_PRVKEY);
return CRYPT_SLHDSA_ERR_NO_PRVKEY;
}
SlhDsaAdrs adrs = {0};
prvKey->adrsOps.setLayerAddr(&adrs, prvKey->para.d - 1);
uint8_t node[SLH_DSA_MAX_N] = {0};
int32_t ret = XmssNode(node, 0, prvKey->para.hp, &adrs, prvKey, NULL, 0);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (memcmp(node, pubKey->prvKey.pub.root, SLH_DSA_MAX_N) != 0) {
ret = CRYPT_SLHDSA_PAIRWISE_CHECK_FAIL;
BSL_ERR_PUSH_ERROR(CRYPT_SLHDSA_PAIRWISE_CHECK_FAIL);
}
return ret;
}
static int32_t SlhDsaPrvKeyCheck(const CryptSlhDsaCtx *prvKey)
{
if (prvKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (CheckNotSlhDsaAlgId(prvKey->para.algId)) {
BSL_ERR_PUSH_ERROR(CRYPT_SLHDSA_ERR_INVALID_ALGID);
return CRYPT_SLHDSA_ERR_INVALID_ALGID;
}
if ((prvKey->keyType & SLH_DSA_PRVKEY) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_SLHDSA_ERR_NO_PRVKEY);
return CRYPT_SLHDSA_ERR_NO_PRVKEY;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_SLH_DSA_Check(uint32_t checkType, const CryptSlhDsaCtx *pkey1, const CryptSlhDsaCtx *pkey2)
{
switch (checkType) {
case CRYPT_PKEY_CHECK_KEYPAIR:
return SlhDsaKeyPairCheck(pkey1, pkey2);
case CRYPT_PKEY_CHECK_PRVKEY:
return SlhDsaPrvKeyCheck(pkey1);
default:
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
}
#endif // HITLS_CRYPTO_SLH_DSA_CHECK
#endif // HITLS_CRYPTO_SLH_DSA
| 2302_82127028/openHiTLS-examples_1508 | crypto/slh_dsa/src/slh_dsa.c | C | unknown | 33,906 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SLH_DSA
#include <stdint.h>
#include <stddef.h>
#include "securec.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "slh_dsa_local.h"
#include "slh_dsa_fors.h"
int32_t ForsSign(const uint8_t *md, uint32_t mdLen, SlhDsaAdrs *adrs, const CryptSlhDsaCtx *ctx, uint8_t *sig,
uint32_t *sigLen)
{
int32_t ret = CRYPT_SLHDSA_ERR_INVALID_SIG_LEN;
uint32_t n = ctx->para.n;
uint32_t a = ctx->para.a;
uint32_t k = ctx->para.k;
if (*sigLen < (a + 1) * n * k) {
return CRYPT_SLHDSA_ERR_SIG_LEN_NOT_ENOUGH;
}
uint32_t *indices = (uint32_t *)BSL_SAL_Malloc(k * sizeof(uint32_t));
if (indices == NULL) {
return BSL_MALLOC_FAIL;
}
BaseB(md, mdLen, a, indices, k);
uint32_t offset = 0;
for (uint32_t i = 0; i < k; i++) {
ret = ForsGenPrvKey(adrs, indices[i] + (i << a), ctx, sig + offset);
if (ret != 0) {
goto ERR;
}
offset += n;
for (uint32_t j = 0; j < a; j++) {
uint32_t s = (indices[i] >> j) ^ 1;
ret = ForsNode((i << (a - j)) + s, j, adrs, ctx, sig + offset);
if (ret != 0) {
goto ERR;
}
offset += n;
}
}
*sigLen = offset;
ERR:
BSL_SAL_Free(indices);
return ret;
}
int32_t ForsPkFromSig(const uint8_t *sig, uint32_t sigLen, const uint8_t *md, uint32_t mdLen, SlhDsaAdrs *adrs,
const CryptSlhDsaCtx *ctx, uint8_t *pk)
{
int32_t ret;
uint32_t *indices = NULL;
uint8_t *root = NULL;
uint32_t n = ctx->para.n;
uint32_t a = ctx->para.a;
uint32_t k = ctx->para.k;
if (sigLen < (a + 1) * n * k) {
return CRYPT_SLHDSA_ERR_SIG_LEN_NOT_ENOUGH;
}
indices = (uint32_t *)BSL_SAL_Malloc(k * sizeof(uint32_t));
if (indices == NULL) {
ret = BSL_MALLOC_FAIL;
goto ERR;
}
root = (uint8_t *)BSL_SAL_Malloc(n * k);
if (root == NULL) {
ret = BSL_MALLOC_FAIL;
goto ERR;
}
BaseB(md, mdLen, a, indices, k);
uint8_t node0[SLH_DSA_MAX_N] = {0};
uint8_t node1[SLH_DSA_MAX_N] = {0};
for (uint32_t i = 0; i < k; i++) {
ctx->adrsOps.setTreeHeight(adrs, 0);
ctx->adrsOps.setTreeIndex(adrs, (i << a) + indices[i]);
ret = ctx->hashFuncs.f(ctx, adrs, sig + (a + 1) * n * i, n, node0);
if (ret != 0) {
goto ERR;
}
const uint8_t *auth = sig + (a + 1) * n * i + n;
for (uint32_t j = 0; j < a; j++) {
uint8_t tmp[SLH_DSA_MAX_N * 2];
ctx->adrsOps.setTreeHeight(adrs, j + 1);
if (((indices[i] >> j) & 1) == 1) {
ctx->adrsOps.setTreeIndex(adrs, (ctx->adrsOps.getTreeIndex(adrs) - 1) >> 1);
(void)memcpy_s(tmp, sizeof(tmp), auth + j * n, n);
(void)memcpy_s(tmp + n, sizeof(tmp) - n, node0, n);
} else {
ctx->adrsOps.setTreeIndex(adrs, ctx->adrsOps.getTreeIndex(adrs) >> 1);
(void)memcpy_s(tmp, sizeof(tmp), node0, n);
(void)memcpy_s(tmp + n, sizeof(tmp) - n, auth + j * n, n);
}
ret = ctx->hashFuncs.h(ctx, adrs, tmp, 2 * n, node1);
if (ret != 0) {
goto ERR;
}
(void)memcpy_s(node0, sizeof(node0), node1, sizeof(node1));
}
(void)memcpy_s(root + i * n, (k - i) * n, node0, n);
}
SlhDsaAdrs forspkAdrs = *adrs;
ctx->adrsOps.setType(&forspkAdrs, FORS_ROOTS);
ctx->adrsOps.copyKeyPairAddr(&forspkAdrs, adrs);
ret = ctx->hashFuncs.tl(ctx, &forspkAdrs, root, n * k, pk);
if (ret != 0) {
goto ERR;
}
ERR:
BSL_SAL_Free(indices);
BSL_SAL_Free(root);
return ret;
}
int32_t ForsGenPrvKey(const SlhDsaAdrs *adrs, uint32_t idx, const CryptSlhDsaCtx *ctx, uint8_t *sk)
{
SlhDsaAdrs skadrs = *adrs;
ctx->adrsOps.setType(&skadrs, FORS_PRF);
ctx->adrsOps.copyKeyPairAddr(&skadrs, adrs);
ctx->adrsOps.setTreeIndex(&skadrs, idx);
return ctx->hashFuncs.prf(ctx, &skadrs, sk);
}
int32_t ForsNode(uint32_t idx, uint32_t height, SlhDsaAdrs *adrs, const CryptSlhDsaCtx *ctx, uint8_t *node)
{
int32_t ret;
uint32_t n = ctx->para.n;
if (height == 0) {
uint8_t sk[SLH_DSA_MAX_N] = {0};
ret = ForsGenPrvKey(adrs, idx, ctx, sk);
if (ret != 0) {
return ret;
}
ctx->adrsOps.setTreeHeight(adrs, height);
ctx->adrsOps.setTreeIndex(adrs, idx);
return ctx->hashFuncs.f(ctx, adrs, sk, n, node);
}
uint8_t dnode[SLH_DSA_MAX_N * 2];
ret = ForsNode(idx * 2, height - 1, adrs, ctx, dnode);
if (ret != 0) {
return ret;
}
ret = ForsNode(idx * 2 + 1, height - 1, adrs, ctx, dnode + n);
if (ret != 0) {
return ret;
}
ctx->adrsOps.setTreeHeight(adrs, height);
ctx->adrsOps.setTreeIndex(adrs, idx);
return ctx->hashFuncs.h(ctx, adrs, dnode, 2 * n, node);
}
#endif // HITLS_CRYPTO_SLH_DSA
| 2302_82127028/openHiTLS-examples_1508 | crypto/slh_dsa/src/slh_dsa_fors.c | C | unknown | 5,616 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef CRYPT_SLH_DSA_FORS_H
#define CRYPT_SLH_DSA_FORS_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SLH_DSA
#include <stdint.h>
#include "crypt_slh_dsa.h"
#include "slh_dsa_local.h"
/**
* @brief Sign a message using FORS
*
* @param md Input message to sign (already hashed to appropriate length)
* @param mdLen Length of the message
* @param adrs Address structure for domain separation
* @param ctx Context
* @param sig Output signature
* @param sigLen Length of the signature
* @return int 0 on success, error code otherwise
*/
int32_t ForsSign(const uint8_t *md, uint32_t mdLen, SlhDsaAdrs *adrs, const CryptSlhDsaCtx *ctx, uint8_t *sig,
uint32_t *sigLen);
/**
* @brief Verify a FORS signature
*
* @param sig Input signature
* @param sigLen Length of the signature
* @param md Input message that was signed
* @param mdLen Length of the message
* @param adrs Address structure for domain separation
* @param ctx Context
* @param pk Output public key
* @return int 0 if signature is valid, error code otherwise
*/
int32_t ForsPkFromSig(const uint8_t *sig, uint32_t sigLen, const uint8_t *md, uint32_t mdLen, SlhDsaAdrs *adrs,
const CryptSlhDsaCtx *ctx, uint8_t *pk);
/**
* @brief Generate a FORS private value
*
* @param adrs Address structure for domain separation
* @param idx Tree index
* @param ctx Context
* @param sk Output private value, the length is n
* @return int 0 on success, error code otherwise
*/
int32_t ForsGenPrvKey(const SlhDsaAdrs *adrs, uint32_t idx, const CryptSlhDsaCtx *ctx, uint8_t *sk);
/**
* @brief Generate a FORS node
*
* @param idx Tree index
* @param height Height of the tree
* @param adrs Address structure for domain separation
* @param ctx Context
* @param node Output node, the length is n
* @return int 0 on success, error code otherwise
*/
int32_t ForsNode(uint32_t idx, uint32_t height, SlhDsaAdrs *adrs, const CryptSlhDsaCtx *ctx, uint8_t *node);
#endif // HITLS_CRYPTO_SLH_DSA
#endif // CRYPT_SLH_DSA_FORS_H | 2302_82127028/openHiTLS-examples_1508 | crypto/slh_dsa/src/slh_dsa_fors.h | C | unknown | 2,585 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SLH_DSA
#include "securec.h"
#include "bsl_err_internal.h"
#include "crypt_errno.h"
#include "crypt_algid.h"
#include "crypt_types.h"
#include "crypt_eal_md.h"
#include "crypt_eal_mac.h"
#include "eal_md_local.h"
#include "slh_dsa_local.h"
#include "slh_dsa_hash.h"
#define SHA256_PADDING_LEN 64
#define SHA512_PADDING_LEN 128
static int32_t CalcMultiMsgHash(CRYPT_MD_AlgId mdId, const CRYPT_ConstData *hashData, uint32_t hashDataLen,
uint8_t *out, uint32_t outLen)
{
uint8_t tmp[MAX_MDSIZE] = {0};
uint32_t tmpLen = sizeof(tmp);
int32_t ret = CRYPT_CalcHash(NULL, EAL_MdFindDefaultMethod(mdId), hashData, hashDataLen, tmp, &tmpLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
(void)memcpy_s(out, outLen, tmp, outLen);
return CRYPT_SUCCESS;
}
static int32_t PrfmsgShake256(const CryptSlhDsaCtx *ctx, const uint8_t *rand, const uint8_t *msg, uint32_t msgLen,
uint8_t *out)
{
uint32_t n = ctx->para.n;
const CRYPT_ConstData hashData[] = {{ctx->prvKey.prf, n}, {rand, n}, {msg, msgLen}};
return CalcMultiMsgHash(CRYPT_MD_SHAKE256, hashData, sizeof(hashData) / sizeof(hashData[0]), out, n);
}
static int32_t HmsgShake256(const CryptSlhDsaCtx *ctx, const uint8_t *r, const uint8_t *msg, uint32_t msgLen,
const uint8_t *idx, uint8_t *out)
{
(void)idx;
uint32_t n = ctx->para.n;
uint32_t m = ctx->para.m;
const CRYPT_ConstData hashData[] = {{r, n}, {ctx->prvKey.pub.seed, n}, {ctx->prvKey.pub.root, n}, {msg, msgLen}};
return CalcMultiMsgHash(CRYPT_MD_SHAKE256, hashData, sizeof(hashData) / sizeof(hashData[0]), out, m);
}
static int32_t PrfShake256(const CryptSlhDsaCtx *ctx, const SlhDsaAdrs *adrs, uint8_t *out)
{
uint32_t n = ctx->para.n;
const CRYPT_ConstData hashData[] = {
{ctx->prvKey.pub.seed, n}, {adrs->bytes, ctx->adrsOps.getAdrsLen()}, {ctx->prvKey.seed, n}};
return CalcMultiMsgHash(CRYPT_MD_SHAKE256, hashData, sizeof(hashData) / sizeof(hashData[0]), out, n);
}
static int32_t HShake256(const CryptSlhDsaCtx *ctx, const SlhDsaAdrs *adrs, const uint8_t *msg, uint32_t msgLen,
uint8_t *out)
{
uint32_t n = ctx->para.n;
const CRYPT_ConstData hashData[] = {
{ctx->prvKey.pub.seed, n}, {adrs->bytes, ctx->adrsOps.getAdrsLen()}, {msg, msgLen}};
return CalcMultiMsgHash(CRYPT_MD_SHAKE256, hashData, sizeof(hashData) / sizeof(hashData[0]), out, n);
}
static int32_t TlShake256(const CryptSlhDsaCtx *ctx, const SlhDsaAdrs *adrs, const uint8_t *msg, uint32_t msgLen,
uint8_t *out)
{
return HShake256(ctx, adrs, msg, msgLen, out);
}
static int32_t FShake256(const CryptSlhDsaCtx *ctx, const SlhDsaAdrs *adrs, const uint8_t *msg, uint32_t msgLen,
uint8_t *out)
{
return HShake256(ctx, adrs, msg, msgLen, out);
}
static int32_t Prfmsg(const CryptSlhDsaCtx *ctx, const uint8_t *rand, const uint8_t *msg, uint32_t msgLen, uint8_t *out,
CRYPT_MAC_AlgId macId)
{
int32_t ret;
uint32_t n = ctx->para.n;
uint8_t tmp[MAX_MDSIZE] = {0};
uint32_t tmpLen = sizeof(tmp);
CRYPT_EAL_MacCtx *mdCtx = CRYPT_EAL_ProviderMacNewCtx(ctx->libCtx, macId, NULL);
if (mdCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
GOTO_ERR_IF_EX(CRYPT_EAL_MacInit(mdCtx, ctx->prvKey.prf, n), ret);
GOTO_ERR_IF_EX(CRYPT_EAL_MacUpdate(mdCtx, rand, n), ret);
GOTO_ERR_IF_EX(CRYPT_EAL_MacUpdate(mdCtx, msg, msgLen), ret);
GOTO_ERR_IF_EX(CRYPT_EAL_MacFinal(mdCtx, tmp, &tmpLen), ret);
(void)memcpy_s(out, n, tmp, n);
ERR:
CRYPT_EAL_MacFreeCtx(mdCtx);
return ret;
}
static int32_t PrfmsgSha256(const CryptSlhDsaCtx *ctx, const uint8_t *rand, const uint8_t *msg, uint32_t msgLen,
uint8_t *out)
{
return Prfmsg(ctx, rand, msg, msgLen, out, CRYPT_MAC_HMAC_SHA256);
}
static int32_t PrfmsgSha512(const CryptSlhDsaCtx *ctx, const uint8_t *rand, const uint8_t *msg, uint32_t msgLen,
uint8_t *out)
{
return Prfmsg(ctx, rand, msg, msgLen, out, CRYPT_MAC_HMAC_SHA512);
}
static int32_t HmsgSha(const CryptSlhDsaCtx *ctx, const uint8_t *r, const uint8_t *seed, const uint8_t *root,
const uint8_t *msg, uint32_t msgLen, uint8_t *out, CRYPT_MD_AlgId mdId)
{
int32_t ret;
uint32_t m = ctx->para.m;
uint32_t n = ctx->para.n;
uint32_t tmpLen;
uint8_t tmpSeed[2 * SLH_DSA_MAX_N + MAX_MDSIZE] = {0}; // 2 is for double
uint32_t tmpSeedLen = 0;
(void)memcpy_s(tmpSeed, sizeof(tmpSeed), r, n);
(void)memcpy_s(tmpSeed + n, sizeof(tmpSeed) - n, seed, n);
tmpSeedLen = n + n;
tmpLen = CRYPT_EAL_MdGetDigestSize(mdId);
const CRYPT_ConstData hashData[] = {{tmpSeed, tmpSeedLen}, {root, n}, {msg, msgLen}};
ret = CalcMultiMsgHash(mdId, hashData, sizeof(hashData) / sizeof(hashData[0]), tmpSeed + tmpSeedLen, tmpLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
tmpSeedLen += tmpLen;
return CRYPT_Mgf1(NULL, EAL_MdFindDefaultMethod(mdId), tmpSeed, tmpSeedLen, out, m);
}
static int32_t HmsgSha256(const CryptSlhDsaCtx *ctx, const uint8_t *r, const uint8_t *msg, uint32_t msgLen,
const uint8_t *idx, uint8_t *out)
{
(void)idx;
return HmsgSha(ctx, r, ctx->prvKey.pub.seed, ctx->prvKey.pub.root, msg, msgLen, out, CRYPT_MD_SHA256);
}
static int32_t HmsgSha512(const CryptSlhDsaCtx *ctx, const uint8_t *r, const uint8_t *msg, uint32_t msgLen,
const uint8_t *idx, uint8_t *out)
{
(void)idx;
return HmsgSha(ctx, r, ctx->prvKey.pub.seed, ctx->prvKey.pub.root, msg, msgLen, out, CRYPT_MD_SHA512);
}
static int32_t PrfSha256(const CryptSlhDsaCtx *ctx, const SlhDsaAdrs *adrs, uint8_t *out)
{
uint32_t n = ctx->para.n;
uint8_t padding[SHA256_PADDING_LEN] = {0};
const CRYPT_ConstData hashData[] = {{ctx->prvKey.pub.seed, n},
{padding, sizeof(padding) - n},
{adrs->bytes, ctx->adrsOps.getAdrsLen()},
{ctx->prvKey.seed, n}};
return CalcMultiMsgHash(CRYPT_MD_SHA256, hashData, sizeof(hashData) / sizeof(hashData[0]), out, n);
}
static int32_t HSha256(const CryptSlhDsaCtx *ctx, const SlhDsaAdrs *adrs, const uint8_t *msg, uint32_t msgLen,
uint8_t *out)
{
uint32_t n = ctx->para.n;
uint8_t padding[SHA256_PADDING_LEN] = {0};
const CRYPT_ConstData hashData[] = {{ctx->prvKey.pub.seed, n},
{padding, sizeof(padding) - n},
{adrs->bytes, ctx->adrsOps.getAdrsLen()},
{msg, msgLen}};
return CalcMultiMsgHash(CRYPT_MD_SHA256, hashData, sizeof(hashData) / sizeof(hashData[0]), out, n);
}
static int32_t FSha256(const CryptSlhDsaCtx *ctx, const SlhDsaAdrs *adrs, const uint8_t *msg, uint32_t msgLen,
uint8_t *out)
{
return HSha256(ctx, adrs, msg, msgLen, out);
}
static int32_t TlSha256(const CryptSlhDsaCtx *ctx, const SlhDsaAdrs *adrs, const uint8_t *msg, uint32_t msgLen,
uint8_t *out)
{
return HSha256(ctx, adrs, msg, msgLen, out);
}
static int32_t HSha512(const CryptSlhDsaCtx *ctx, const SlhDsaAdrs *adrs, const uint8_t *msg, uint32_t msgLen,
uint8_t *out)
{
uint32_t n = ctx->para.n;
uint8_t padding[SHA512_PADDING_LEN] = {0};
const CRYPT_ConstData hashData[] = {{ctx->prvKey.pub.seed, n},
{padding, sizeof(padding) - n},
{adrs->bytes, ctx->adrsOps.getAdrsLen()},
{msg, msgLen}};
return CalcMultiMsgHash(CRYPT_MD_SHA512, hashData, sizeof(hashData) / sizeof(hashData[0]), out, n);
}
static int32_t TlSha512(const CryptSlhDsaCtx *ctx, const SlhDsaAdrs *adrs, const uint8_t *msg, uint32_t msgLen,
uint8_t *out)
{
return HSha512(ctx, adrs, msg, msgLen, out);
}
void SlhDsaInitHashFuncs(CryptSlhDsaCtx *ctx)
{
CRYPT_PKEY_ParaId algId = ctx->para.algId;
SlhDsaHashFuncs *hashFuncs = &ctx->hashFuncs;
if (algId == CRYPT_SLH_DSA_SHA2_128S || algId == CRYPT_SLH_DSA_SHA2_128F || algId == CRYPT_SLH_DSA_SHA2_192S ||
algId == CRYPT_SLH_DSA_SHA2_192F || algId == CRYPT_SLH_DSA_SHA2_256S || algId == CRYPT_SLH_DSA_SHA2_256F) {
ctx->para.isCompressed = true;
hashFuncs->prf = PrfSha256;
hashFuncs->f = FSha256;
if (ctx->para.secCategory == 1) {
hashFuncs->prfmsg = PrfmsgSha256;
hashFuncs->hmsg = HmsgSha256;
hashFuncs->tl = TlSha256;
hashFuncs->h = HSha256;
} else {
hashFuncs->prfmsg = PrfmsgSha512;
hashFuncs->hmsg = HmsgSha512;
hashFuncs->tl = TlSha512;
hashFuncs->h = HSha512;
}
} else {
ctx->para.isCompressed = false;
hashFuncs->prfmsg = PrfmsgShake256;
hashFuncs->hmsg = HmsgShake256;
hashFuncs->prf = PrfShake256;
hashFuncs->tl = TlShake256;
hashFuncs->f = FShake256;
hashFuncs->h = HShake256;
}
}
#endif // HITLS_CRYPTO_SLH_DSA
| 2302_82127028/openHiTLS-examples_1508 | crypto/slh_dsa/src/slh_dsa_hash.c | C | unknown | 10,019 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef SLH_DSA_HASH_H
#define SLH_DSA_HASH_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SLH_DSA
#include <stdint.h>
#include "bsl_params.h"
#include "crypt_slh_dsa.h"
#define MAX_MDSIZE 64
// The length "out" is n, the max length is SLH_DSA_MAX_N
typedef int32_t (*SlhDsaPrf)(const CryptSlhDsaCtx *ctx, const SlhDsaAdrs *adrs, uint8_t *out);
typedef int32_t (*SlhDsaTl)(const CryptSlhDsaCtx *ctx, const SlhDsaAdrs *adrs, const uint8_t *msg, uint32_t msgLen,
uint8_t *out);
typedef int32_t (*SlhDsaH)(const CryptSlhDsaCtx *ctx, const SlhDsaAdrs *adrs, const uint8_t *msg, uint32_t msgLen,
uint8_t *out);
typedef int32_t (*SlhDsaF)(const CryptSlhDsaCtx *ctx, const SlhDsaAdrs *adrs, const uint8_t *msg, uint32_t msgLen,
uint8_t *out);
// The length of "prf", "rand" and "out" is n, the max length is SLH_DSA_MAX_N
typedef int32_t (*SlhDsaPrfMsg)(const CryptSlhDsaCtx *ctx, const uint8_t *rand, const uint8_t *msg, uint32_t msgLen,
uint8_t *out);
// The length of "r", "seed" and "root" is n, the max length is SLH_DSA_MAX_N
// the max length of "out" is SLH_DSA_MAX_M
typedef int32_t (*SlhDsaHmsg)(const CryptSlhDsaCtx *ctx, const uint8_t *r, const uint8_t *msg, uint32_t msgLen,
const uint8_t *idx, uint8_t *out);
struct HashFuncs {
SlhDsaPrf prf;
SlhDsaTl tl;
SlhDsaH h;
SlhDsaF f;
SlhDsaPrfMsg prfmsg;
SlhDsaHmsg hmsg;
};
void SlhDsaInitHashFuncs(CryptSlhDsaCtx *ctx);
#endif // HITLS_CRYPTO_SLH_DSA
#endif // SLH_DSA_HASH_H
| 2302_82127028/openHiTLS-examples_1508 | crypto/slh_dsa/src/slh_dsa_hash.h | C | unknown | 2,152 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SLH_DSA
#include <stdint.h>
#include "securec.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "slh_dsa_local.h"
#include "slh_dsa_xmss.h"
#include "slh_dsa_hypertree.h"
int32_t HypertreeSign(const uint8_t *msg, uint32_t msgLen, uint64_t treeIdx, uint32_t leafIdx,
const CryptSlhDsaCtx *ctx, uint8_t *sig, uint32_t *sigLen)
{
int32_t ret;
uint32_t n = ctx->para.n;
uint32_t hp = ctx->para.hp;
uint32_t d = ctx->para.d;
uint32_t len = 2 * n + 3;
uint32_t retLen = (len + hp) * n * d;
uint32_t leafIdxTmp = leafIdx;
uint64_t treeIdxTmp = treeIdx;
if (*sigLen < retLen) {
return CRYPT_SLHDSA_ERR_SIG_LEN_NOT_ENOUGH;
}
SlhDsaAdrs adrs = {0};
uint32_t offset = 0;
uint32_t tmpLen = *sigLen;
uint8_t root[MAX_MDSIZE] = {0};
// the msgLen is actually n.
(void)memcpy_s(root, sizeof(root), msg, msgLen);
for (uint32_t j = 0; j < d; j++) {
if (j != 0) {
leafIdxTmp = (uint32_t)(treeIdxTmp & ((1UL << hp) - 1));
treeIdxTmp = treeIdxTmp >> hp;
ctx->adrsOps.setLayerAddr(&adrs, j);
}
ctx->adrsOps.setTreeAddr(&adrs, treeIdxTmp);
tmpLen = retLen - offset;
ret = XmssSign(root, n, leafIdxTmp, &adrs, ctx, sig + offset, &tmpLen, root);
if (ret != CRYPT_SUCCESS) {
return ret;
}
offset += tmpLen;
}
*sigLen = retLen;
return CRYPT_SUCCESS;
}
int32_t HypertreeVerify(const uint8_t *msg, uint32_t msgLen, const uint8_t *sig, uint32_t sigLen, uint64_t treeIdx,
uint32_t leafIdx, const CryptSlhDsaCtx *ctx)
{
int32_t ret;
uint32_t n = ctx->para.n;
uint32_t hp = ctx->para.hp;
uint32_t d = ctx->para.d;
uint32_t len = 2 * n + 3;
uint32_t retLen = (len + hp) * n * d;
uint32_t leafIdxTmp = leafIdx;
uint64_t treeIdxTmp = treeIdx;
if (sigLen < retLen) {
return CRYPT_SLHDSA_ERR_SIG_LEN_NOT_ENOUGH;
}
SlhDsaAdrs adrs = {0};
uint32_t offset = 0;
uint8_t node[MAX_MDSIZE] = {0};
// the msgLen is actually n.
(void)memcpy_s(node, sizeof(node), msg, msgLen);
for (uint32_t j = 0; j < d; j++) {
if (j != 0) {
leafIdxTmp = (uint32_t)(treeIdxTmp & ((1UL << hp) - 1));
treeIdxTmp = treeIdxTmp >> hp;
ctx->adrsOps.setLayerAddr(&adrs, j);
}
ctx->adrsOps.setTreeAddr(&adrs, treeIdxTmp);
ret = XmssPkFromSig(leafIdxTmp, sig + offset, sigLen - offset, node, n, &adrs, ctx, node);
if (ret != CRYPT_SUCCESS) {
return ret;
}
offset += (len + hp) * n;
}
if (memcmp(node, ctx->prvKey.pub.root, n) != 0) {
return CRYPT_SLHDSA_ERR_HYPERTREE_VERIFY_FAIL;
}
return CRYPT_SUCCESS;
}
#endif // HITLS_CRYPTO_SLH_DSA
| 2302_82127028/openHiTLS-examples_1508 | crypto/slh_dsa/src/slh_dsa_hypertree.c | C | unknown | 3,451 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef CRYPT_SLH_DSA_HYPERTREE_H
#define CRYPT_SLH_DSA_HYPERTREE_H
#include <stdint.h>
#include "slh_dsa_local.h"
#ifdef HITLS_CRYPTO_SLH_DSA
/**
* @brief Sign a message using Hypertree
*
* @param msg Input message to sign
* @param msgLen Length of the message
* @param treeIdx Index of the tree to use
* @param leafIdx Index of the leaf to use
* @param ctx Context of SLH-DSA
* @param sig Output signature
* @param sigLen Length of the signature
* @return int 0 on success, error code otherwise
*/
int32_t HypertreeSign(const uint8_t *msg, uint32_t msgLen, uint64_t treeIdx, uint32_t leafIdx,
const CryptSlhDsaCtx *ctx, uint8_t *sig, uint32_t *sigLen);
/**
* @brief Verify a Hypertree signature
*
* @param msg Input message that was signed
* @param msgLen Length of the message
* @param sig Hypertree signature to verify
* @param sigLen Length of the signature
* @param treeIdx Index of the tree to use
* @param leafIdx Index of the leaf to use
* @param ctx Context of SLH-DSA
* @return int 0 if signature is valid, error code otherwise
*/
int32_t HypertreeVerify(const uint8_t *msg, uint32_t msgLen, const uint8_t *sig, uint32_t sigLen, uint64_t treeIdx,
uint32_t leafIdx, const CryptSlhDsaCtx *ctx);
#endif // HITLS_CRYPTO_SLH_DSA
#endif // CRYPT_SLH_DSA_HYPERTREE_H | 2302_82127028/openHiTLS-examples_1508 | crypto/slh_dsa/src/slh_dsa_hypertree.h | C | unknown | 1,889 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef SLH_DSA_LOCAL_H
#define SLH_DSA_LOCAL_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SLH_DSA
#include <stdint.h>
#include "bsl_params.h"
#include "crypt_algid.h"
#include "crypt_types.h"
#include "crypt_utils.h"
#include "slh_dsa_hash.h"
#include "crypt_types.h"
#define SLH_DSA_ADRS_LEN 32
#define SLH_DSA_ADRS_COMPRESSED_LEN 22
#define SLH_DSA_MAX_N 32 // Security parameter (hash output length)
#define SLH_DSA_MAX_M 49
#define SLH_DSA_LGW 4
#define SLH_DSA_W 16 // 2^SLH_DSA_LGW
#define SLH_DSA_PRVKEY 0x1
#define SLH_DSA_PUBKEY 0x10
typedef enum {
WOTS_HASH,
WOTS_PK,
TREE,
FORS_TREE,
FORS_ROOTS,
WOTS_PRF,
FORS_PRF,
} AdrsType;
/**
* @brief Address structure definition
*
* all the address is big-endian
* it can be a address or a compressed address
* Address:
* | layer address | 4 bytes
* | tree address | 12 bytes
* | type | 4 bytes
* | padding | 12 bytes
*
* Compressed Address:
* | layer address | 1 bytes
* | tree address | 8 bytes
* | type | 1 bytes
* | padding | 12 bytes
* | hole | 10 bytes
*/
union Adrs {
struct {
uint8_t layerAddr[4];
uint8_t treeAddr[12];
uint8_t type[4];
uint8_t padding[12];
} uc;
struct {
uint8_t layerAddr;
uint8_t treeAddr[8];
uint8_t type;
uint8_t padding[12];
} c;
struct {
uint8_t layerAddr[4];
uint8_t treeAddr[8];
uint8_t type[4];
uint8_t padding[16];
} x;
uint8_t bytes[SLH_DSA_ADRS_LEN];
};
// adrs operations functions
typedef void (*AdrsSetLayerAddr)(SlhDsaAdrs *adrs, uint32_t layer);
typedef void (*AdrsSetTreeAddr)(SlhDsaAdrs *adrs, uint64_t tree);
typedef void (*AdrsSetType)(SlhDsaAdrs *adrs, AdrsType type);
typedef void (*AdrsSetKeyPairAddr)(SlhDsaAdrs *adrs, uint32_t keyPair);
typedef void (*AdrsSetChainAddr)(SlhDsaAdrs *adrs, uint32_t chain);
typedef void (*AdrsSetTreeHeight)(SlhDsaAdrs *adrs, uint32_t height);
typedef void (*AdrsSetHashAddr)(SlhDsaAdrs *adrs, uint32_t hash);
typedef void (*AdrsSetTreeIndex)(SlhDsaAdrs *adrs, uint32_t index);
typedef void (*AdrsSetKeyAndMask)(SlhDsaAdrs *adrs, uint32_t index); // for XMSS only
typedef uint32_t (*AdrsGetTreeHeight)(const SlhDsaAdrs *adrs);
typedef uint32_t (*AdrsGetTreeIndex)(const SlhDsaAdrs *adrs);
typedef void (*AdrsCopyKeyPairAddr)(SlhDsaAdrs *adrs, const SlhDsaAdrs *adrs2);
typedef uint32_t (*AdrsGetAdrsLen)(void);
typedef struct {
AdrsSetLayerAddr setLayerAddr;
AdrsSetTreeAddr setTreeAddr;
AdrsSetType setType;
AdrsSetKeyPairAddr setKeyPairAddr;
AdrsSetChainAddr setChainAddr;
AdrsSetTreeHeight setTreeHeight;
AdrsSetHashAddr setHashAddr;
AdrsSetTreeIndex setTreeIndex;
AdrsSetKeyAndMask setKeyAndMask; // for XMSS only
AdrsGetTreeHeight getTreeHeight;
AdrsGetTreeIndex getTreeIndex;
AdrsCopyKeyPairAddr copyKeyPairAddr;
AdrsGetAdrsLen getAdrsLen;
} AdrsOps;
// b can be 4, 6, 8, 9, 12, 14
// so use uint32_t to receive the BaseB value
void BaseB(const uint8_t *x, uint32_t xLen, uint32_t b, uint32_t *out, uint32_t outLen);
typedef struct {
int algId; // CRYPT_PKEY_ParaId (SLH_DSA_AlgId or XMSS_AlgId)
bool isCompressed;
uint32_t n;
uint32_t h;
uint32_t d;
uint32_t hp;
uint32_t a;
uint32_t k;
uint32_t m;
uint32_t secCategory;
uint32_t pkBytes;
uint32_t sigBytes;
} SlhDsaPara;
typedef struct {
uint8_t seed[MAX_MDSIZE]; // pubkey seed for generating keys
uint8_t root[MAX_MDSIZE]; // pubkey root for generating keys
} SlhDsaPubKey;
/**
* @brief SLH-DSA private key structure
*/
typedef struct {
uint8_t seed[MAX_MDSIZE]; // prvkey seed for generating keys
uint8_t prf[MAX_MDSIZE]; // prvkey prf for generating keys
uint64_t index; // the next unused WOTS+ key index, for XMSS only
SlhDsaPubKey pub;
} SlhDsaPrvKey;
struct SlhDsaCtx {
SlhDsaPara para;
uint8_t *context; // user specific context
uint32_t contextLen; // length of the user specific context
bool isDeterministic;
uint8_t *addrand; // optional random bytes, can be set through CTRL interface, or comes from RNG
uint32_t addrandLen; // length of the optional random bytes
bool isPrehash;
bool isXmss; /* XMSS and SLH-DSA share common structure,
* true : XMSS, false : SLH-DSA */
SlhDsaPrvKey prvKey;
SlhDsaHashFuncs hashFuncs;
AdrsOps adrsOps;
uint8_t keyType; /* specify the key type */
void *libCtx;
};
#endif // HITLS_CRYPTO_SLH_DSA
#endif // SLH_DSA_LOCAL_H
| 2302_82127028/openHiTLS-examples_1508 | crypto/slh_dsa/src/slh_dsa_local.h | C | unknown | 5,215 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SLH_DSA
#include <stdint.h>
#include <string.h>
#include "securec.h"
#include "bsl_errno.h"
#include "crypt_errno.h"
#include "bsl_sal.h"
#include "slh_dsa_local.h"
#include "slh_dsa_wots.h"
static int32_t MsgToBaseW(const CryptSlhDsaCtx *ctx, const uint8_t *msg, uint32_t msgLen, uint32_t *out)
{
uint32_t n = ctx->para.n;
uint32_t len1 = 2 * n;
uint32_t len2 = 3;
BaseB(msg, msgLen, SLH_DSA_LGW, out, len1);
// todo: check if csum overflow
uint64_t csum = 0;
for (uint32_t i = 0; i < len1; i++) {
csum += SLH_DSA_W - 1 - out[i];
}
csum <<= SLH_DSA_LGW;
uint8_t csumBytes[2];
csumBytes[0] = (uint8_t)(csum >> 8);
csumBytes[1] = (uint8_t)csum;
BaseB(csumBytes, 2, SLH_DSA_LGW, out + len1, len2);
return 0;
}
int32_t WotsChain(const uint8_t *x, uint32_t xLen, uint32_t start, uint32_t end, const uint8_t *seed, SlhDsaAdrs *adrs,
const CryptSlhDsaCtx *ctx, uint8_t *output)
{
(void)seed;
int32_t ret;
uint8_t tmp[MAX_MDSIZE];
(void)memcpy_s(tmp, sizeof(tmp), x, xLen);
uint32_t tmpLen = xLen;
for (uint32_t i = start; i < start + end; i++) {
ctx->adrsOps.setHashAddr(adrs, i);
ret = ctx->hashFuncs.f(ctx, adrs, tmp, tmpLen, tmp);
if (ret != 0) {
return ret;
}
}
(void)memcpy_s(output, tmpLen, tmp, tmpLen);
return 0;
}
int WotsGeneratePublicKey(uint8_t *pub, SlhDsaAdrs *adrs, const CryptSlhDsaCtx *ctx)
{
int32_t ret;
uint32_t n = ctx->para.n;
uint32_t len = 2 * n + 3;
SlhDsaAdrs skAdrs = *adrs;
if (!ctx->isXmss) {
ctx->adrsOps.setType(&skAdrs, WOTS_PRF);
ctx->adrsOps.copyKeyPairAddr(&skAdrs, adrs);
}
uint8_t *tmp = (uint8_t *)BSL_SAL_Malloc(len * n);
if (tmp == NULL) {
return BSL_MALLOC_FAIL;
}
for (uint32_t i = 0; i < len; i++) {
ctx->adrsOps.setChainAddr(&skAdrs, i);
uint8_t sk[MAX_MDSIZE] = {0};
ret = ctx->hashFuncs.prf(ctx, &skAdrs, sk);
if (ret != 0) {
goto ERR;
}
ctx->adrsOps.setChainAddr(adrs, i);
ret = WotsChain(sk, n, 0, SLH_DSA_W - 1, ctx->prvKey.pub.seed, adrs, ctx, (tmp + i * n));
if (ret != 0) {
goto ERR;
}
}
// compress public key
SlhDsaAdrs wotspk = *adrs;
ctx->adrsOps.setType(&wotspk, WOTS_PK);
ctx->adrsOps.copyKeyPairAddr(&wotspk, adrs);
ret = ctx->hashFuncs.tl(ctx, &wotspk, tmp, len * n, pub);
ERR:
BSL_SAL_Free(tmp);
return ret;
}
int32_t WotsSign(uint8_t *sig, uint32_t *sigLen, const uint8_t *msg, uint32_t msgLen, SlhDsaAdrs *adrs,
const CryptSlhDsaCtx *ctx)
{
int32_t ret;
uint32_t n = ctx->para.n;
uint32_t len = 2 * n + 3;
if (*sigLen < len * n) {
return CRYPT_BN_BUFF_LEN_NOT_ENOUGH;
}
uint32_t *msgw = (uint32_t *)BSL_SAL_Malloc(len * sizeof(uint32_t));
if (msgw == NULL) {
return BSL_MALLOC_FAIL;
}
ret = MsgToBaseW(ctx, msg, msgLen, msgw);
if (ret != 0) {
goto ERR;
}
SlhDsaAdrs skAdrs = *adrs;
if (!ctx->isXmss) {
ctx->adrsOps.setType(&skAdrs, WOTS_PRF);
ctx->adrsOps.copyKeyPairAddr(&skAdrs, adrs);
}
for (uint32_t i = 0; i < len; i++) {
ctx->adrsOps.setChainAddr(&skAdrs, i);
uint8_t sk[MAX_MDSIZE] = {0};
ret = ctx->hashFuncs.prf(ctx, &skAdrs, sk);
if (ret != 0) {
goto ERR;
}
ctx->adrsOps.setChainAddr(adrs, i);
ret = WotsChain(sk, n, 0, msgw[i], ctx->prvKey.pub.seed, adrs, ctx, sig + i * n);
if (ret != 0) {
goto ERR;
}
}
ERR:
BSL_SAL_Free(msgw);
*sigLen = len * n;
return ret;
}
int32_t WotsPubKeyFromSig(const uint8_t *msg, uint32_t msgLen, const uint8_t *sig, uint32_t sigLen, SlhDsaAdrs *adrs,
const CryptSlhDsaCtx *ctx, uint8_t *pub)
{
int32_t ret;
uint32_t n = ctx->para.n;
uint32_t len = 2 * n + 3;
uint32_t *msgw = NULL;
uint8_t *tmp = NULL;
if (sigLen < len * n) {
return CRYPT_SLHDSA_ERR_SIG_LEN_NOT_ENOUGH;
}
msgw = (uint32_t *)BSL_SAL_Malloc(len * sizeof(uint32_t));
if (msgw == NULL) {
return BSL_MALLOC_FAIL;
}
ret = MsgToBaseW(ctx, msg, msgLen, msgw);
if (ret != 0) {
goto ERR;
}
tmp = (uint8_t *)BSL_SAL_Malloc(len * n);
if (tmp == NULL) {
ret = BSL_MALLOC_FAIL;
goto ERR;
}
for (uint32_t i = 0; i < len; i++) {
ctx->adrsOps.setChainAddr(adrs, i);
ret = WotsChain(sig + i * n, n, msgw[i], SLH_DSA_W - 1 - msgw[i], ctx->prvKey.pub.seed, adrs, ctx, tmp + i * n);
if (ret != 0) {
goto ERR;
}
}
SlhDsaAdrs wotspk = *adrs;
ctx->adrsOps.setType(&wotspk, WOTS_PK);
ctx->adrsOps.copyKeyPairAddr(&wotspk, adrs);
ret = ctx->hashFuncs.tl(ctx, &wotspk, tmp, len * n, pub);
ERR:
BSL_SAL_Free(msgw);
if (tmp != NULL) {
BSL_SAL_Free(tmp);
}
return ret;
}
#endif // HITLS_CRYPTO_SLH_DSA
| 2302_82127028/openHiTLS-examples_1508 | crypto/slh_dsa/src/slh_dsa_wots.c | C | unknown | 5,653 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef CRYPT_SLH_DSA_WOTS_H
#define CRYPT_SLH_DSA_WOTS_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SLH_DSA
#include <stdint.h>
#include "crypt_slh_dsa.h"
/**
* @brief Compute a WOTS+ public key from a private key
*
* @param pub Output WOTS+ public key
* @param seed Public seed for chain computation
* @param adrs Address structure for domain separation
* @return int 0 on success, error code otherwise
*/
int WotsGeneratePublicKey(uint8_t *pub, SlhDsaAdrs *adrs, const CryptSlhDsaCtx *ctx);
/**
* @brief Sign a message using WOTS+
*
* @param sig Output WOTS+ signature
* @param sigLen Length of the signature
* @param msg Input message to sign
* @param msgLen Length of the message
* @param adrs Address structure for domain separation
* @param ctx SLH-DSA context
* @return int 0 on success, error code otherwise
*/
int32_t WotsSign(uint8_t *sig, uint32_t *sigLen, const uint8_t *msg, uint32_t msgLen, SlhDsaAdrs *adrs,
const CryptSlhDsaCtx *ctx);
/**
* @brief Compute a WOTS+ public key from a signature and message
*
* @param msg Input message that was signed
* @param msgLen Length of the message
* @param sig WOTS+ signature
* @param sigLen Length of the signature
* @param adrs Address structure for domain separation
* @param ctx SLH-DSA context
* @param pub Output reconstructed WOTS+ public key, the length is n
* @return int 0 on success, error code otherwise
*/
int32_t WotsPubKeyFromSig(const uint8_t *msg, uint32_t msgLen, const uint8_t *sig, uint32_t sigLen, SlhDsaAdrs *adrs,
const CryptSlhDsaCtx *ctx, uint8_t *pub);
/**
* @brief Compute a WOTS+ chain
*
* @param x Input private key value to chain
* @param xLen Length of the input private key value
* @param start Starting position in the chain
* @param end Ending position in the chain
* @param seed Public seed for chain computation
* @param adrs Address structure for domain separation
* @param ctx SLH-DSA context
* @param output Output chain result, the length is n
* @return int 0 on success, error code otherwise
*/
int32_t WotsChain(const uint8_t *x, uint32_t xLen, uint32_t start, uint32_t end, const uint8_t *seed, SlhDsaAdrs *adrs,
const CryptSlhDsaCtx *ctx, uint8_t *output);
#endif // HITLS_CRYPTO_SLH_DSA
#endif // CRYPT_SLH_DSA_WOTS_H | 2302_82127028/openHiTLS-examples_1508 | crypto/slh_dsa/src/slh_dsa_wots.h | C | unknown | 2,873 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SLH_DSA
#include <stdint.h>
#include <stddef.h>
#include "securec.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "slh_dsa_local.h"
#include "slh_dsa_xmss.h"
#include "slh_dsa_wots.h"
int32_t XmssNode(uint8_t *node, uint32_t idx, uint32_t height, SlhDsaAdrs *adrs, const CryptSlhDsaCtx *ctx,
uint8_t *AuthPath, uint32_t LeafIdx)
{
int32_t ret;
if (node == NULL || adrs == NULL || ctx == NULL) {
return CRYPT_NULL_INPUT;
}
uint32_t n = ctx->para.n;
// If height is 0, compute WOTS+ public key
if (height == 0) {
ctx->adrsOps.setType(adrs, WOTS_HASH);
ctx->adrsOps.setKeyPairAddr(adrs, idx);
ret = WotsGeneratePublicKey(node, adrs, ctx);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if (AuthPath && (idx == ((LeafIdx >> height) ^ 0x01))) {
(void)memcpy_s(AuthPath + (height * n), n, node, n);
}
return CRYPT_SUCCESS;
}
// Compute internal node
uint8_t leftNode[MAX_MDSIZE] = {0};
uint8_t rightNode[MAX_MDSIZE] = {0};
// Compute left child
ret = XmssNode(leftNode, 2 * idx, height - 1, adrs, ctx, AuthPath, LeafIdx);
if (ret != CRYPT_SUCCESS) {
return ret;
}
// Compute right child
ret = XmssNode(rightNode, 2 * idx + 1, height - 1, adrs, ctx, AuthPath, LeafIdx);
if (ret != CRYPT_SUCCESS) {
return ret;
}
// Hash children to get parent node
ctx->adrsOps.setType(adrs, TREE);
if (ctx->isXmss) {
/* tree height is the 'lower' layer for xmss */
ctx->adrsOps.setTreeHeight(adrs, height - 1);
} else {
ctx->adrsOps.setTreeHeight(adrs, height);
}
ctx->adrsOps.setTreeIndex(adrs, idx);
uint8_t tmp[MAX_MDSIZE * 2];
(void)memcpy_s(tmp, MAX_MDSIZE * 2, leftNode, n);
(void)memcpy_s(tmp + n, MAX_MDSIZE * 2 - n, rightNode, n);
ret = ctx->hashFuncs.h(ctx, adrs, tmp, 2 * n, node);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if ((height != ctx->para.hp) &&
AuthPath && (idx == ((LeafIdx >> height) ^ 0x01))) {
(void)memcpy_s(AuthPath + (height * n), n, node, n);
}
return CRYPT_SUCCESS;
}
int32_t XmssSign(const uint8_t *msg, size_t msgLen, uint32_t idx, SlhDsaAdrs *adrs, const CryptSlhDsaCtx *ctx,
uint8_t *sig, uint32_t *sigLen, uint8_t *root)
{
int32_t ret;
uint32_t n = ctx->para.n;
uint32_t hp = ctx->para.hp;
uint32_t len = 2 * n + 3;
if (*sigLen < (len + hp) * n) {
return CRYPT_SLHDSA_ERR_SIG_LEN_NOT_ENOUGH;
}
ctx->adrsOps.setType(adrs, WOTS_HASH);
ctx->adrsOps.setKeyPairAddr(adrs, idx);
uint32_t tmpLen = len * n;
ret = WotsSign(sig, &tmpLen, msg, (uint32_t)msgLen, adrs, ctx);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = XmssNode(root, 0, hp, adrs, ctx, sig + (len * n), idx);
if (ret != CRYPT_SUCCESS) {
return ret;
}
*sigLen = (len + hp) * n;
return CRYPT_SUCCESS;
}
int32_t XmssPkFromSig(uint32_t idx, const uint8_t *sig, uint32_t sigLen, const uint8_t *msg, uint32_t msgLen,
SlhDsaAdrs *adrs, const CryptSlhDsaCtx *ctx, uint8_t *pk)
{
int32_t ret;
uint32_t n = ctx->para.n;
uint32_t hp = ctx->para.hp;
uint32_t len = 2 * n + 3;
if (sigLen < (len + hp) * n) {
return CRYPT_SLHDSA_ERR_SIG_LEN_NOT_ENOUGH;
}
ctx->adrsOps.setType(adrs, WOTS_HASH);
ctx->adrsOps.setKeyPairAddr(adrs, idx);
uint8_t node0[MAX_MDSIZE] = {0};
uint8_t node1[MAX_MDSIZE] = {0};
ret = WotsPubKeyFromSig(msg, msgLen, sig, sigLen, adrs, ctx, node0);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ctx->adrsOps.setType(adrs, TREE);
ctx->adrsOps.setTreeIndex(adrs, idx);
for (uint32_t k = 0; k < hp; k++) {
if (ctx->isXmss) {
/* tree height is the 'lower' layer for xmss */
ctx->adrsOps.setTreeHeight(adrs, k);
} else {
ctx->adrsOps.setTreeHeight(adrs, k + 1);
}
uint8_t tmp[MAX_MDSIZE * 2];
if (((idx >> k) & 1) != 0) {
(void)memcpy_s(tmp, sizeof(tmp), sig + (len + k) * n, n);
(void)memcpy_s(tmp + n, sizeof(tmp) - n, node0, n);
ctx->adrsOps.setTreeIndex(adrs, (ctx->adrsOps.getTreeIndex(adrs) - 1) >> 1);
} else {
(void)memcpy_s(tmp, sizeof(tmp), node0, n);
(void)memcpy_s(tmp + n, sizeof(tmp) - n, sig + (len + k) * n, n);
ctx->adrsOps.setTreeIndex(adrs, ctx->adrsOps.getTreeIndex(adrs) >> 1);
}
ret = ctx->hashFuncs.h(ctx, adrs, tmp, 2 * n, node1);
if (ret != CRYPT_SUCCESS) {
return ret;
}
(void)memcpy_s(node0, sizeof(node0), node1, sizeof(node1));
}
(void)memcpy_s(pk, n, node0, n);
return CRYPT_SUCCESS;
}
#endif // HITLS_CRYPTO_SLH_DSA
| 2302_82127028/openHiTLS-examples_1508 | crypto/slh_dsa/src/slh_dsa_xmss.c | C | unknown | 5,503 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef CRYPT_SLH_DSA_XMSS_H
#define CRYPT_SLH_DSA_XMSS_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SLH_DSA
#include <stdint.h>
#include "crypt_slh_dsa.h"
/**
* @brief Sign a message using XMSS
*
* @param sig Output XMSS signature
* @param sigLen Length of the signature
* @param msg Input message to sign
* @param msgLen Length of the message
* @param idx Index of the used WOTS+ key pair
* @param adrs Address structure for domain separation
* @param ctx SLH-DSA context
* @param root root node of XMSS tree
* @return int 0 on success, error code otherwise
*/
int32_t XmssSign(const uint8_t *msg, size_t msgLen, uint32_t idx, SlhDsaAdrs *adrs, const CryptSlhDsaCtx *ctx,
uint8_t *sig, uint32_t *sigLen, uint8_t *root);
/**
* @brief Compute an internal node of the XMSS tree
*
* @param node Output internal node
* @param idx Node index at the given height
* @param height Node height in the tree
* @param adrs Address structure for domain separation
* @param ctx SLH-DSA context
* @param AuthPath authentication path for the LeafIdx
* @param LeafIdx WOTS+ key pair index
* @return int 0 on success, error code otherwise
*/
int32_t XmssNode(uint8_t *node, uint32_t idx, uint32_t height, SlhDsaAdrs *adrs, const CryptSlhDsaCtx *ctx,
uint8_t *AuthPath, uint32_t LeafIdx);
/**
* @brief Compute a public key from a signature and message
*
* @param idx Index of the used WOTS+ key pair
* @param sig Signature
* @param sigLen Length of the signature
* @param msg Message
* @param msgLen Length of the message
* @param adrs Address structure for domain separation
* @param ctx SLH-DSA context
* @param pk Output public key, the length is n
* @return int 0 on success, error code otherwise
*/
int32_t XmssPkFromSig(uint32_t idx, const uint8_t *sig, uint32_t sigLen, const uint8_t *msg, uint32_t msgLen,
SlhDsaAdrs *adrs, const CryptSlhDsaCtx *ctx, uint8_t *pk);
#endif // HITLS_CRYPTO_SLH_DSA
#endif // CRYPT_SLH_DSA_XMSS_H
| 2302_82127028/openHiTLS-examples_1508 | crypto/slh_dsa/src/slh_dsa_xmss.h | C | unknown | 2,563 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef CRYPT_SM2_H
#define CRYPT_SM2_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SM2
#include <stdint.h>
#include "crypt_types.h"
#include "crypt_ecc.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
typedef struct SM2_Ctx CRYPT_SM2_Ctx;
/* SM2 parameter structure */
typedef struct EccPara CRYPT_Sm2Para;
/**
* @ingroup sm2
* @brief sm2 Allocate the context memory space.
*
* @retval (CRYPT_SM2_Ctx *) Pointer to the memory space of the allocated context
* @retval NULL Invalid null pointer.
*/
CRYPT_SM2_Ctx *CRYPT_SM2_NewCtx(void);
/**
* @ingroup sm2
* @brief sm2 Allocate the context memory space.
*
* @param libCtx [IN] Library context
*
* @retval (CRYPT_SM2_Ctx *) Pointer to the memory space of the allocated context
* @retval NULL Invalid null pointer.
*/
CRYPT_SM2_Ctx *CRYPT_SM2_NewCtxEx(void *libCtx);
/**
* @ingroup sm2
* @brief Copy the sm2 context. After the duplication is complete, invoke the CRYPT_SM2_FreeCtx to release the memory.
*
* @param ctx [IN] Source SM2 context
*
* @return CRYPT_SM2_Ctx SM2 context pointer=
*/
CRYPT_SM2_Ctx *CRYPT_SM2_DupCtx(CRYPT_SM2_Ctx *ctx);
/**
* @ingroup sm2
* @brief release sm2 key context structure
*
* @param ctx [IN] Context structure to be released.
*/
void CRYPT_SM2_FreeCtx(CRYPT_SM2_Ctx *ctx);
/**
* @ingroup sm2
* @brief sm2 Obtain the key length.
*
* @param ctx [IN] sm2 context structure
*
* @retval 0 The input is incorrect or the corresponding key structure does not contain valid key length.
* @retval uint32_t Valid key length
*/
uint32_t CRYPT_SM2_GetBits(const CRYPT_SM2_Ctx *ctx);
/**
* @ingroup sm2
* @brief Generate the SM2 key pair.
*
* @param ctx [IN/OUT] sm2 context structure
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval ECC error code. An error occurred in the internal ECC calculation.
* @retval CRYPT_SUCCESS The key pair is successfully generated.
*/
int32_t CRYPT_SM2_Gen(CRYPT_SM2_Ctx *ctx);
#ifdef HITLS_CRYPTO_SM2_SIGN
/**
* @ingroup sm2
* @brief sm2 obtain the length of the signature data, in bytes.
*
* @param ctx [IN] sm2 context structure
*
* @retval 0 The input is incorrect or the corresponding key structure does not contain valid parameter data.
* @retval uint32_t Length required for valid signature data
*/
uint32_t CRYPT_SM2_GetSignLen(const CRYPT_SM2_Ctx *ctx);
/**
* @ingroup sm2
* @brief SM2 Signature
*
* @param ctx [IN] sm2 context structure
* @param algId [IN] md algId
* @param data [IN] Data to be signed
* @param dataLen [IN] Length of the data to be signed
* @param sign [OUT] Signature data
* @param signLen [IN/OUT] The input parameter is the space length of the sign,
* and the output parameter is the valid length of the sign.
* The required space can be obtained by calling CRYPT_SM2_GetSignLen.
*
* @retval CRYPT_NULL_INPUT Error null pointer input
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_SM2_ERR_EMPTY_KEY The key cannot be empty.
* @retval CRYPT_SM2_BUFF_LEN_NOT_ENOUGH The buffer length is insufficient.
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval ECC error. An error occurred in the internal ECC calculation.
* @retval CRYPT_SUCCESS Signed successfully.
*/
int32_t CRYPT_SM2_Sign(const CRYPT_SM2_Ctx *ctx, int32_t algId, const uint8_t *data, uint32_t dataLen,
uint8_t *sign, uint32_t *signLen);
/**
* @ingroup sm2
* @brief SM2 Verify the signature.
*
* @param ctx [IN] sm2 context structure
* @param algId [IN] md algId
* @param data [IN] Data to be signed
* @param dataLen [IN] Length of the data to be signed
* @param sign [IN] Signature data
* @param signLen [IN] Valid length of the sign
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_SM2_VERIFY_FAIL Failed to verify the signature.
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval ECC error. An error occurred in the internal ECC calculation.
* @retval DSA error. An error occurs in the DSA encoding and decoding part.
* @retval CRYPT_SUCCESS The signature verification is successful.
*/
int32_t CRYPT_SM2_Verify(const CRYPT_SM2_Ctx *ctx, int32_t algId, const uint8_t *data, uint32_t dataLen,
const uint8_t *sign, uint32_t signLen);
#endif
/**
* @ingroup sm2
* @brief SM2 Set the private key data.
*
* @param ctx [OUT] sm2 context structure
* @param prv [IN] External private key data
*
* @retval CRYPT_NULL_INPUT Error null pointer input
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval ECC error. An error occurred in the internal ECC calculation.
* @retval CRYPT_SUCCESS set successfully.
*/
int32_t CRYPT_SM2_SetPrvKey(CRYPT_SM2_Ctx *ctx, const CRYPT_Sm2Prv *prv);
/**
* @ingroup sm2
* @brief SM2 Set the public key data.
*
* @param ctx [OUT] sm2 context structure
* @param pub [IN] External public key data
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval ECC error. An error occurred in the internal ECC calculation.
* @retval CRYPT_SUCCESS set successfully.
*/
int32_t CRYPT_SM2_SetPubKey(CRYPT_SM2_Ctx *ctx, const CRYPT_DsaPub *pub);
/**
* @ingroup sm2
* @brief SM2 Obtain the private key data.
*
* @param ctx [IN] sm2 context structure
* @param prv [OUT] External private key data
*
* @retval CRYPT_NULL_INPUT Error null pointer input
* @retval CRYPT_ECC_PKEY_ERR_EMPTY_KEY The key is empty.
* @retval ECC error. An error occurred in the internal ECC calculation.
* @retval CRYPT_SUCCESS obtained successfully.
*/
int32_t CRYPT_SM2_GetPrvKey(const CRYPT_SM2_Ctx *ctx, CRYPT_DsaPrv *prv);
/**
* @ingroup sm2
* @brief SM2 Obtain the public key data.
*
* @param ctx [IN] sm2 context structure
* @param pub [OUT] External public key data
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_ECC_PKEY_ERR_EMPTY_KEY The key is empty.
* @retval ECC error. An error occurred in the internal ECC calculation.
* @retval CRYPT_SUCCESS Obtained successfully.
*/
int32_t CRYPT_SM2_GetPubKey(const CRYPT_SM2_Ctx *ctx, CRYPT_DsaPub *pub);
#ifdef HITLS_BSL_PARAMS
/**
* @ingroup sm2
* @brief SM2 Set the private key data.
*
* @param ctx [OUT] sm2 context structure
* @param para [IN] External private key data
*
* @retval CRYPT_NULL_INPUT Error null pointer input
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval ECC error. An error occurred in the internal ECC calculation.
* @retval CRYPT_SUCCESS set successfully.
*/
int32_t CRYPT_SM2_SetPrvKeyEx(CRYPT_SM2_Ctx *ctx, const BSL_Param *para);
/**
* @ingroup sm2
* @brief SM2 Set the public key data.
*
* @param ctx [OUT] sm2 context structure
* @param para [IN] External public key data
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval ECC error. An error occurred in the internal ECC calculation.
* @retval CRYPT_SUCCESS set successfully.
*/
int32_t CRYPT_SM2_SetPubKeyEx(CRYPT_SM2_Ctx *ctx, const BSL_Param *para);
/**
* @ingroup sm2
* @brief SM2 Obtain the private key data.
*
* @param ctx [IN] sm2 context structure
* @param para [OUT] External private key data
*
* @retval CRYPT_NULL_INPUT Error null pointer input
* @retval CRYPT_ECC_PKEY_ERR_EMPTY_KEY The key is empty.
* @retval ECC error. An error occurred in the internal ECC calculation.
* @retval CRYPT_SUCCESS obtained successfully.
*/
int32_t CRYPT_SM2_GetPrvKeyEx(const CRYPT_SM2_Ctx *ctx, BSL_Param *para);
/**
* @ingroup sm2
* @brief SM2 Obtain the public key data.
*
* @param ctx [IN] sm2 context structure
* @param para [OUT] External public key data
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_ECC_PKEY_ERR_EMPTY_KEY The key is empty.
* @retval ECC error. An error occurred in the internal ECC calculation.
* @retval CRYPT_SUCCESS Obtained successfully.
*/
int32_t CRYPT_SM2_GetPubKeyEx(const CRYPT_SM2_Ctx *ctx, BSL_Param *para);
#endif
/**
* @ingroup sm2
* @brief sm2 control interface
*
* @param ctx [IN/OUT] sm2 context structure
* @param opt [IN] Operation mode. For details, see ECC_CtrlType.
* @param val [IN] Input parameter
* @param len [IN] val Length
*
* @retval CRYPT_SUCCESS set successfully.
* @retval CRYPT_NULL_INPUT If any input parameter is empty
* @retval For other error codes, see crypt_errno.h.
*/
int32_t CRYPT_SM2_Ctrl(CRYPT_SM2_Ctx *ctx, int32_t opt, void *val, uint32_t len);
#ifdef HITLS_CRYPTO_SM2_EXCH
/**
* @ingroup sm2
* @brief sm2 Generate the shared key.
*
* @param selfCtx [IN] Local context structure
* @param peerCtx [IN] Peer context structure
* @param out [OUT] Generated shared key
* @param outlen [IN/OUT] Length of the generated shared key
*
* @retval CRYPT_SUCCESS secceeded.
* @retval CRYPT_NULL_INPUT If any input parameter is empty
* @retval For other error codes, see crypt_errno.h.
*/
int32_t CRYPT_SM2_KapComputeKey(const CRYPT_SM2_Ctx *selfCtx, const CRYPT_SM2_Ctx *peerCtx, uint8_t *out,
uint32_t *outlen);
#endif
#ifdef HITLS_CRYPTO_SM2_CRYPT
/**
* @ingroup sm2
* @brief sm2 Encryption
* @param ctx [IN] Context structure
* @param data [IN] Plaintext
* @param datalen [IN] Plaintext length
* @param out [OUT] Output ciphertext
* @param outlen [OUT] Ciphertext length
*
* @retval CRYPT_SUCCESS secceeded.
* @retval CRYPT_NULL_INPUT If any input parameter is empty
* @retval For other error codes, see crypt_errno.h.
*/
int32_t CRYPT_SM2_Encrypt(CRYPT_SM2_Ctx *ctx, const uint8_t *data, uint32_t datalen, uint8_t *out, uint32_t *outlen);
/**
* @ingroup sm2
* @brief sm2 Decryption
* @param ctx [IN] Context structure
* @param data [IN] Received ciphertext
* @param datalen [IN] Ciphertext length
* @param out [OUT] Output plaintext after decryption
* @param outlen [OUT] Length of the decrypted plaintext
*
* @retval CRYPT_SUCCESS secceeded.
* @retval CRYPT_NULL_INPUT If any input parameter is empty
* @retval For other error codes, see crypt_errno.h.
*/
int32_t CRYPT_SM2_Decrypt(CRYPT_SM2_Ctx *ctx, const uint8_t *data, uint32_t datalen, uint8_t *out, uint32_t *outlen);
#endif
/**
* @ingroup sm2
* @brief sm2 Compare the public key and parameters.
*
* @param a [IN] sm2 context structure
* @param b [IN] sm2 context structure
*
* @retval CRYPT_SUCCESS is the same
* For other error codes, see crypt_errno.h.
*/
int32_t CRYPT_SM2_Cmp(const CRYPT_SM2_Ctx *a, const CRYPT_SM2_Ctx *b);
/**
* @ingroup sm2
* @brief sm2 get security bits
*
* @param ctx [IN] sm2 Context structure
*
* @retval security bits
*/
int32_t CRYPT_SM2_GetSecBits(const CRYPT_SM2_Ctx *ctx);
/**
* @ingroup sm2
* @brief sm2 import key
*
* @param ctx [IN/OUT] sm2 context structure
* @param params [IN] key parameters
*/
int32_t CRYPT_SM2_Import(CRYPT_SM2_Ctx *ctx, const BSL_Param *params);
/**
* @ingroup sm2
* @brief sm2 export key
*
* @param ctx [IN] sm2 context structure
* @param params [IN/OUT] key parameters
*/
int32_t CRYPT_SM2_Export(const CRYPT_SM2_Ctx *ctx, BSL_Param *params);
#ifdef HITLS_CRYPTO_SM2_CHECK
/**
* @ingroup sm2
* @brief sm2 check public key
*
* @param checkType [IN] check type
* @param pkey1 [IN] sm2 context structure
* @param pkey2 [IN] sm2 context structure
*
* @retval CRYPT_SUCCESS is the same
* Others. For details, see error code in errno.
*/
int32_t CRYPT_SM2_Check(uint32_t checkType, const CRYPT_SM2_Ctx *pkey1, const CRYPT_SM2_Ctx *pkey2);
#endif // HITLS_CRYPTO_SM2_CHECK
#ifdef __cplusplus
}
#endif
#endif // HITLS_CRYPTO_SM2
#endif // CRYPT_SM2_H
| 2302_82127028/openHiTLS-examples_1508 | crypto/sm2/include/crypt_sm2.h | C | unknown | 12,846 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SM2_CRYPT
#include <limits.h>
#include "securec.h"
#include "crypt_errno.h"
#include "crypt_types.h"
#include "crypt_utils.h"
#include "bsl_sal.h"
#include "bsl_err_internal.h"
#include "crypt_bn.h"
#include "crypt_ecc.h"
#include "crypt_ecc_pkey.h"
#include "crypt_local_types.h"
#include "sm2_local.h"
#include "crypt_sm2.h"
#include "crypt_encode_internal.h"
#define SM2_POINT_SINGLE_COORDINATE_LEN 32
#define SM2_POINT_COORDINATE_LEN 65
static void EncryptMemFree(ECC_Point *c1, ECC_Point *tmp, BN_BigNum *k, bool isInternal,
BN_BigNum *order, uint8_t *c2)
{
ECC_FreePoint(c1);
ECC_FreePoint(tmp);
if (isInternal) {
BN_Destroy(k);
}
BN_Destroy(order);
BSL_SAL_FREE(c2);
}
static int32_t ParaCheckAndCalculate(CRYPT_SM2_Ctx *ctx, ECC_Point *tmp, BN_BigNum *k)
{
int32_t ret;
// Check whether [h]PB is equal to infinity point.
GOTO_ERR_IF(ECC_PointCheck(ctx->pkey->pubkey), ret);
// Calculate [k] * PB
GOTO_ERR_IF(ECC_PointMul(ctx->pkey->para, tmp, k, ctx->pkey->pubkey), ret);
ERR:
return ret;
}
static int32_t Sm3Hash(const EAL_MdMethod *hashMethod, const uint8_t *pbBuf, const uint8_t *data, uint32_t datalen,
uint8_t *c3Buf, uint32_t *c3BufLen)
{
int32_t ret;
void *mdCtx = hashMethod->newCtx(NULL, hashMethod->id);
if (mdCtx == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
GOTO_ERR_IF(hashMethod->init(mdCtx, NULL), ret);
GOTO_ERR_IF(hashMethod->update(mdCtx, pbBuf + 1,
SM2_POINT_SINGLE_COORDINATE_LEN), ret); // Horizontal coordinate x2 of PB
GOTO_ERR_IF(hashMethod->update(mdCtx, data, datalen), ret); // M
GOTO_ERR_IF(hashMethod->update(mdCtx, pbBuf + SM2_POINT_SINGLE_COORDINATE_LEN + 1,
SM2_POINT_SINGLE_COORDINATE_LEN), ret); // Vertical coordinate y2 of PB
// Calculated c3, in c3Buf
GOTO_ERR_IF(hashMethod->final(mdCtx, c3Buf, c3BufLen), ret);
ERR:
hashMethod->freeCtx(mdCtx);
return ret;
}
static int32_t IsDataZero(const uint8_t *data, uint32_t datalen)
{
uint8_t check = 0;
for (uint32_t i = 0; i < datalen; i++) {
check |= data[i];
}
if (check == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_DECRYPT_FAIL);
return CRYPT_SM2_DECRYPT_FAIL;
}
return CRYPT_SUCCESS;
}
static int32_t MemAllocCheck(const BN_BigNum *k, const BN_BigNum *order,
const ECC_Point *c1, const ECC_Point *tmp, const uint8_t *c2)
{
if (k == NULL || order == NULL || c1 == NULL || tmp == NULL || c2 == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
return CRYPT_SUCCESS;
}
static void XorCalculate(uint8_t *c2, const uint8_t *data, uint32_t datalen)
{
uint32_t i;
for (i = 0; i < datalen; ++i) {
c2[i] ^= data[i];
}
return;
}
#ifdef HITLS_CRYPTO_ACVP_TESTS
int32_t CRYPT_SM2_SetK(CRYPT_SM2_Ctx *ctx, uint8_t *val, uint32_t len)
{
if (ctx == NULL || val == NULL || len <= 0) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->paraEx.k != NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_K_REPEAT_SET_ERROR);
return CRYPT_SM2_K_REPEAT_SET_ERROR;
}
BN_BigNum *k = BN_Create(CRYPT_SM2_GetBits(ctx));
if (k == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
int32_t ret = BN_Bin2Bn(k, val, len);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
if (BN_IsZero(k)) {
BSL_ERR_PUSH_ERROR(BSL_INVALID_ARG);
ret = BSL_INVALID_ARG;
goto EXIT;
}
ctx->paraEx.k = k;
return CRYPT_SUCCESS;
EXIT:
BN_Destroy(k);
return ret;
}
#endif
static int32_t EncryptInputCheck(const CRYPT_SM2_Ctx *ctx, const uint8_t *data, uint32_t datalen,
const uint8_t *out, const uint32_t *outlen)
{
// 0-length plaintext encryption is not supported.
if (ctx == NULL || data == NULL || datalen == 0 || out == NULL || outlen == NULL || *outlen == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
uint32_t encodeLen = 0;
int32_t ret = CRYPT_EAL_GetSm2EncryptDataEncodeLen(SM2_POINT_SINGLE_COORDINATE_LEN, SM2_POINT_SINGLE_COORDINATE_LEN,
SM3_MD_SIZE, datalen, &encodeLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (*outlen < encodeLen) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_BUFF_LEN_NOT_ENOUGH);
return CRYPT_SM2_BUFF_LEN_NOT_ENOUGH;
}
if (ctx->pkey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_ERR_EMPTY_KEY);
return CRYPT_SM2_ERR_EMPTY_KEY;
}
if (ctx->pkey->pubkey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_NO_PUBKEY);
return CRYPT_SM2_NO_PUBKEY;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_SM2_Encrypt(CRYPT_SM2_Ctx *ctx, const uint8_t *data, uint32_t datalen, uint8_t *out, uint32_t *outlen)
{
int32_t ret = EncryptInputCheck(ctx, data, datalen, out, outlen);
if (ret != CRYPT_SUCCESS) {
return ret;
}
uint32_t i;
BN_BigNum *k = NULL;
bool isInternal = false;
#ifdef HITLS_CRYPTO_ACVP_TESTS
k = ctx->paraEx.k;
#endif
if (k == NULL) {
k = BN_Create(CRYPT_SM2_GetBits(ctx));
isInternal = true;
}
BN_BigNum *order = ECC_GetParaN(ctx->pkey->para);
ECC_Point *c1 = ECC_NewPoint(ctx->pkey->para);
ECC_Point *tmp = ECC_NewPoint(ctx->pkey->para);
uint32_t buflen = SM2_POINT_COORDINATE_LEN;
uint8_t c1Buf[SM2_POINT_COORDINATE_LEN];
uint8_t tmpBuf[SM2_POINT_COORDINATE_LEN];
uint8_t *c2 = BSL_SAL_Malloc(datalen);
uint8_t c3Buf[SM3_MD_SIZE];
uint32_t c3BufLen = SM3_MD_SIZE;
CRYPT_SM2_EncryptData encData = {
// +1: Skip one byte for '04'
.x = c1Buf + 1, .xLen = SM2_POINT_SINGLE_COORDINATE_LEN,
.y = c1Buf + SM2_POINT_SINGLE_COORDINATE_LEN + 1, .yLen = SM2_POINT_SINGLE_COORDINATE_LEN,
.hash = c3Buf, .hashLen = c3BufLen,
.cipher = c2, .cipherLen = datalen,
};
GOTO_ERR_IF(MemAllocCheck(k, order, c1, tmp, c2), ret);
for (i = 0; i < CRYPT_ECC_TRY_MAX_CNT; i++) {
#ifdef HITLS_CRYPTO_ACVP_TESTS
if (isInternal) {
#endif
GOTO_ERR_IF(BN_RandRangeEx(ctx->pkey->libCtx, k, order), ret);
if (BN_IsZero(k)) {
continue;
}
#ifdef HITLS_CRYPTO_ACVP_TESTS
}
#endif
// c1 = k * G
GOTO_ERR_IF(ECC_PointMul(ctx->pkey->para, c1, k, NULL), ret);
// Convert the point format into binary data stream and save the data stream in tmpbuf.
GOTO_ERR_IF(ECC_EncodePoint(ctx->pkey->para, c1, c1Buf, &buflen, CRYPT_POINT_UNCOMPRESSED), ret);
GOTO_ERR_IF(ParaCheckAndCalculate(ctx, tmp, k), ret);
GOTO_ERR_IF(ECC_EncodePoint(ctx->pkey->para, tmp, tmpBuf, &buflen, CRYPT_POINT_UNCOMPRESSED), ret);
// Calculate the kdf.
GOTO_ERR_IF(KdfGmt0032012(c2, &datalen, tmpBuf + 1, buflen - 1, ctx->hashMethod), ret);
if (IsDataZero(c2, datalen) == CRYPT_SUCCESS) {
break;
}
}
if (i == CRYPT_ECC_TRY_MAX_CNT) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_ERR_TRY_CNT);
ret = CRYPT_SM2_ERR_TRY_CNT;
goto ERR;
}
// Bitwise XOR
XorCalculate(c2, data, datalen);
// x2 || M || y2, calculate the hash value
GOTO_ERR_IF(Sm3Hash(ctx->hashMethod, tmpBuf, data, datalen, c3Buf, &c3BufLen), ret);
GOTO_ERR_IF(CRYPT_EAL_EncodeSm2EncryptData(&encData, out, outlen), ret);
ERR:
EncryptMemFree(c1, tmp, k, isInternal, order, c2);
return ret;
}
static int32_t IsUEqualToC3(const uint8_t *data, const uint8_t *sm3Buf, uint32_t sm3BufLen)
{
uint8_t check = 0;
for (uint32_t i = 0; i < sm3BufLen; i++) {
check |= sm3Buf[i] ^ data[i + SM2_POINT_COORDINATE_LEN];
}
if (check != 0) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_DECRYPT_FAIL);
return CRYPT_SM2_DECRYPT_FAIL;
}
return CRYPT_SUCCESS;
}
static int32_t DecryptInputCheck(const CRYPT_SM2_Ctx *ctx, const uint8_t *data, uint32_t datalen,
const uint8_t *out, const uint32_t *outlen)
{
// 0-length plaintext decryption is not supported.
if (ctx == NULL || data == NULL || datalen == 0 || out == NULL || outlen == NULL || *outlen == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->pkey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_ERR_EMPTY_KEY);
return CRYPT_SM2_ERR_EMPTY_KEY;
}
if (ctx->pkey->prvkey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_NO_PRVKEY);
return CRYPT_SM2_NO_PRVKEY;
}
return CRYPT_SUCCESS;
}
static int32_t DecodeEncryptData(const uint8_t *data, uint32_t datalen, uint8_t **decode,
const uint8_t **cipher, uint32_t *cipherLen)
{
*decode = BSL_SAL_Calloc(1u, datalen);
if (*decode == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
// Add uncompressed point identifier
(*decode)[0] = 0x04;
CRYPT_SM2_EncryptData encData = {
.x = *decode + 1, // Reserve one byte for '04'
.xLen = SM2_POINT_SINGLE_COORDINATE_LEN,
.y = *decode + SM2_POINT_SINGLE_COORDINATE_LEN + 1,
.yLen = SM2_POINT_SINGLE_COORDINATE_LEN,
.hash = *decode + SM2_POINT_COORDINATE_LEN,
.hashLen = SM3_MD_SIZE,
.cipher = *decode + SM2_POINT_COORDINATE_LEN + SM3_MD_SIZE,
.cipherLen = datalen - SM2_POINT_COORDINATE_LEN - SM3_MD_SIZE
};
int32_t ret = CRYPT_EAL_DecodeSm2EncryptData(data, datalen, &encData);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_Free(*decode);
*decode = NULL;
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// Return cipher related information
*cipher = encData.cipher;
*cipherLen = encData.cipherLen;
return CRYPT_SUCCESS;
}
int32_t CRYPT_SM2_Decrypt(CRYPT_SM2_Ctx *ctx, const uint8_t *data, uint32_t datalen, uint8_t *out, uint32_t *outlen)
{
// take out the c1
int32_t ret = DecryptInputCheck(ctx, data, datalen, out, outlen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
uint8_t *decode = NULL;
const uint8_t *cipher = NULL;
uint32_t cipherLen = 0;
ret = DecodeEncryptData(data, datalen, &decode, &cipher, &cipherLen);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if (*outlen < cipherLen) {
BSL_SAL_Free(decode);
BSL_ERR_PUSH_ERROR(CRYPT_SM2_BUFF_LEN_NOT_ENOUGH);
return CRYPT_SM2_BUFF_LEN_NOT_ENOUGH;
}
uint8_t sm3Buf[SM3_MD_SIZE];
uint32_t sm3BufLen = SM3_MD_SIZE;
uint32_t tmplen = SM2_POINT_COORDINATE_LEN;
uint8_t tmpBuf[SM2_POINT_COORDINATE_LEN];
ECC_Point *c1 = ECC_NewPoint(ctx->pkey->para);
ECC_Point *tmp = ECC_NewPoint(ctx->pkey->para);
uint8_t *t = BSL_SAL_Malloc(cipherLen);
if (c1 == NULL || tmp == NULL || t == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
GOTO_ERR_IF(ECC_DecodePoint(ctx->pkey->para, c1, decode, SM2_POINT_COORDINATE_LEN), ret);
// Calculate [dB]C1 = (x2, y2) and save it to the point tmp.
GOTO_ERR_IF(ECC_PointMul(ctx->pkey->para, tmp, ctx->pkey->prvkey, c1), ret);
// Extract x and y of the point tmp and save them to tmpbuf.
GOTO_ERR_IF(ECC_EncodePoint(ctx->pkey->para, tmp, tmpBuf, &tmplen, CRYPT_POINT_UNCOMPRESSED), ret);
// Calculate the kdf(x2 || y2, cipherLen).
GOTO_ERR_IF(KdfGmt0032012(t, &cipherLen, tmpBuf + 1, tmplen - 1, ctx->hashMethod), ret);
// Check whether t is all 0s. If yes, report an error and exit.
GOTO_ERR_IF(IsDataZero(t, cipherLen), ret);
// Calculate M' = C2 ^ t
// Bitwise XOR, and the result is still stored in t.
for (uint32_t i = 0; i < cipherLen; ++i) {
t[i] ^= cipher[i];
}
// Calculate hash(x2 || t || y2)
GOTO_ERR_IF(Sm3Hash(ctx->hashMethod, tmpBuf, t, cipherLen, sm3Buf, &sm3BufLen), ret);
// Check whether u is equal to c3.
GOTO_ERR_IF(IsUEqualToC3(decode, sm3Buf, sm3BufLen), ret);
// The verification is successful. M' is the last plaintext.
(void)memcpy_s(out, *outlen, t, cipherLen);
*outlen = cipherLen;
ERR:
BSL_SAL_FREE(decode);
ECC_FreePoint(c1);
ECC_FreePoint(tmp);
BSL_SAL_CleanseData((void*)t, cipherLen);
BSL_SAL_FREE(t);
return ret;
}
#endif // HITLS_CRYPTO_SM2_CRYPT
| 2302_82127028/openHiTLS-examples_1508 | crypto/sm2/src/sm2_crypt.c | C | unknown | 13,150 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_SM2_EXCH) || defined(HITLS_CRYPTO_SM2_CRYPT)
#include <stdbool.h>
#include "crypt_errno.h"
#include "crypt_types.h"
#include "crypt_utils.h"
#include "securec.h"
#include "bsl_sal.h"
#include "bsl_err_internal.h"
#include "crypt_bn.h"
#include "crypt_ecc.h"
#include "crypt_ecc_pkey.h"
#include "crypt_local_types.h"
#include "crypt_sm2.h"
#include "sm2_local.h"
/* GM/T003_2012 Defined Key Derive Function */
int32_t KdfGmt0032012(uint8_t *out, const uint32_t *outlen, const uint8_t *z, uint32_t zlen,
const EAL_MdMethod *hashMethod)
{
if (out == NULL || outlen == NULL || *outlen == 0 || (z == NULL && zlen != 0) || hashMethod == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
uint32_t counter;
uint8_t ctr[4];
uint32_t mdlen;
int32_t ret;
uint32_t len = MAX_MD_SIZE;
void *mdCtx = hashMethod->newCtx(NULL, hashMethod->id);
uint8_t dgst[MAX_MD_SIZE];
uint8_t *tmp = out;
uint32_t tmplen = *outlen;
if (mdCtx == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
goto ERR;
}
mdlen = (uint32_t)hashMethod->mdSize;
for (counter = 1;; counter++) {
GOTO_ERR_IF(hashMethod->init(mdCtx, NULL), ret);
PUT_UINT32_BE(counter, ctr, 0);
GOTO_ERR_IF(hashMethod->update(mdCtx, z, zlen), ret);
GOTO_ERR_IF(hashMethod->update(mdCtx, ctr, sizeof(ctr)), ret);
GOTO_ERR_IF(hashMethod->final(mdCtx, dgst, &len), ret);
if (tmplen > mdlen) {
(void)memcpy_s(tmp, tmplen, dgst, mdlen);
tmp += mdlen;
tmplen -= mdlen;
} else {
(void)memcpy_s(tmp, tmplen, dgst, tmplen);
(void)memset_s(dgst, mdlen, 0, mdlen);
break;
}
}
ERR:
hashMethod->freeCtx(mdCtx);
return ret;
}
void Sm2CleanR(CRYPT_SM2_Ctx *ctx)
{
BN_Destroy(ctx->r);
ctx->r = NULL;
ECC_FreePoint(ctx->pointR);
ctx->pointR = NULL;
return;
}
static int32_t Sm2CalculateKey(const CRYPT_SM2_Ctx *selfCtx, const CRYPT_SM2_Ctx *peerCtx, ECC_Point *uorv,
uint8_t *out, uint32_t *outlen)
{
uint32_t keyBits = CRYPT_SM2_GetBits(selfCtx);
uint32_t elementLen = (keyBits + 7) / 8; // Multiply keyBits by 8. Add 7 to round up the result.
int32_t ret;
uint32_t bufLen = elementLen * 2 + SM3_MD_SIZE * 2 + 1; /* add 1 byte tag; 2: 2 coordinates x and y, 2 z values */
uint32_t dataLen = 0; // length of actual data;
uint32_t curLen = 0; // length of buffer reserved for the current operation.
uint8_t *buf = (uint8_t *)BSL_SAL_Calloc(bufLen, sizeof(uint8_t));
if (buf == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
goto ERR;
}
/* 1 : Get public key for uorv, Notice: the first byte is a tag, not a valid char */
curLen = elementLen * 2 + 1; // add 1 byte tag; 2: 2 coordinates x and y
GOTO_ERR_IF(ECC_EncodePoint(selfCtx->pkey->para, uorv, buf, &curLen, CRYPT_POINT_UNCOMPRESSED), ret);
dataLen += curLen;
if (selfCtx->server == 1) {
/* SIDE A, Z_A || Z_B, server is initiator(Z_A), client is responder(Z_B) */
curLen = SM3_MD_SIZE;
GOTO_ERR_IF_EX(Sm2ComputeZDigest(selfCtx, buf + dataLen, &curLen), ret);
dataLen += curLen;
}
/* Caculate Peer z */
curLen = SM3_MD_SIZE;
GOTO_ERR_IF_EX(Sm2ComputeZDigest(peerCtx, buf + dataLen, &curLen), ret);
dataLen += curLen;
if (selfCtx->server == 0) {
/* SIDE B */
curLen = SM3_MD_SIZE;
GOTO_ERR_IF_EX(Sm2ComputeZDigest(selfCtx, buf + dataLen, &curLen), ret);
dataLen += curLen;
}
GOTO_ERR_IF(KdfGmt0032012(out, outlen, (const uint8_t *)(buf + 1), dataLen - 1, selfCtx->hashMethod), ret);
ERR:
BSL_SAL_FREE(buf);
return ret;
}
static int32_t IsParamValid(const CRYPT_SM2_Ctx *selfCtx, const CRYPT_SM2_Ctx *peerCtx)
{
if (selfCtx->pkey->prvkey == NULL || peerCtx->pkey->pubkey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_ERR_EMPTY_KEY);
return CRYPT_SM2_ERR_EMPTY_KEY;
}
if (selfCtx->hashMethod == NULL || peerCtx->hashMethod == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_ERR_NO_HASH_METHOD);
return CRYPT_SM2_ERR_NO_HASH_METHOD;
}
if (peerCtx->pointR == NULL || selfCtx->r == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_R_NOT_SET);
return CRYPT_SM2_R_NOT_SET;
}
if (selfCtx->pkey->pubkey == NULL) {
int32_t ret = ECC_GenPublicKey(selfCtx->pkey);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
return CRYPT_SUCCESS;
}
void BnMemDestroy(BN_BigNum *xs, BN_BigNum *xp, BN_BigNum *t,
BN_BigNum *twoPowerW, BN_BigNum *order)
{
BN_Destroy(xs);
BN_Destroy(xp);
BN_Destroy(t);
BN_Destroy(twoPowerW);
BN_Destroy(order);
}
static int32_t Sm3MsgHash(const EAL_MdMethod *hashMethod, const uint8_t *yBuf, const uint8_t *hashBuf,
uint8_t *out, uint32_t *outlen, uint8_t tag)
{
int32_t ret;
void *mdCtx = hashMethod->newCtx(NULL, hashMethod->id);
if (mdCtx == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
GOTO_ERR_IF(hashMethod->init(mdCtx, NULL), ret);
GOTO_ERR_IF(hashMethod->update(mdCtx, &tag, 1), ret);
GOTO_ERR_IF(hashMethod->update(mdCtx, yBuf, SM3_MD_SIZE), ret);
GOTO_ERR_IF(hashMethod->update(mdCtx, hashBuf, SM3_MD_SIZE), ret);
GOTO_ERR_IF(hashMethod->final(mdCtx, out, outlen), ret);
ERR:
hashMethod->freeCtx(mdCtx);
return ret;
}
static int32_t Sm3InnerHash(const EAL_MdMethod *hashMethod, const uint8_t *coordinate, const uint8_t *zBuf,
uint32_t zlen, const uint8_t *rBuf, uint8_t *out, uint32_t *outlen)
{
int32_t ret;
void *mdCtx = hashMethod->newCtx(NULL, hashMethod->id);
if (mdCtx == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
GOTO_ERR_IF(hashMethod->init(mdCtx, NULL), ret);
GOTO_ERR_IF(hashMethod->update(mdCtx, coordinate, SM2_X_LEN), ret);
GOTO_ERR_IF(hashMethod->update(mdCtx, zBuf, zlen), ret);
GOTO_ERR_IF(hashMethod->update(mdCtx, rBuf, SM2_TWO_POINT_COORDINATE_LEN), ret);
GOTO_ERR_IF(hashMethod->final(mdCtx, out, outlen), ret);
ERR:
hashMethod->freeCtx(mdCtx);
return ret;
}
int32_t Sm2KapFinalCheck(CRYPT_SM2_Ctx *sCtx, CRYPT_SM2_Ctx *pCtx, ECC_Point *uorv)
{
int32_t ret;
uint32_t len = SM3_MD_SIZE;
uint8_t r1Buf[SM2_POINT_COORDINATE_LEN];
uint8_t r2Buf[SM2_POINT_COORDINATE_LEN];
uint8_t rBuf[SM2_TWO_POINT_COORDINATE_LEN];
uint8_t xBuf[SM2_X_LEN];
uint8_t yBuf[SM2_X_LEN];
uint8_t zBuf[SM2_POINT_COORDINATE_LEN - 1];
uint8_t stmpBuf[SM3_MD_SIZE];
uint32_t buflen = SM2_POINT_COORDINATE_LEN;
uint32_t zlen = 0;
uint8_t tag1 = 0x03;
uint8_t tag2 = 0x02;
// Xv
GOTO_ERR_IF(ECC_EncodePoint(sCtx->pkey->para, uorv, r1Buf, &buflen, CRYPT_POINT_UNCOMPRESSED), ret);
(void)memcpy_s(xBuf, SM2_X_LEN, r1Buf + 1, SM2_X_LEN);
(void)memcpy_s(yBuf, SM2_X_LEN, r1Buf + 1 + SM2_X_LEN, SM2_X_LEN);
// Calculate ZA || ZB
if (sCtx->server == 1) {
/* SIDE A, Z_A || Z_B, server is initiator(Z_A), client is responder(Z_B) */
GOTO_ERR_IF_EX(Sm2ComputeZDigest(sCtx, zBuf, &len), ret);
zlen += len;
GOTO_ERR_IF(ECC_EncodePoint(sCtx->pkey->para, sCtx->pointR, r1Buf, &buflen, CRYPT_POINT_UNCOMPRESSED), ret);
GOTO_ERR_IF(ECC_EncodePoint(sCtx->pkey->para, pCtx->pointR, r2Buf, &buflen, CRYPT_POINT_UNCOMPRESSED), ret);
}
/* Calculate Peer z */
GOTO_ERR_IF_EX(Sm2ComputeZDigest(pCtx, zBuf + zlen, &len), ret);
zlen += len;
if (sCtx->server == 0) {
/* SIDE B */
GOTO_ERR_IF_EX(Sm2ComputeZDigest(sCtx, zBuf + zlen, &len), ret);
zlen += len;
GOTO_ERR_IF(ECC_EncodePoint(sCtx->pkey->para, pCtx->pointR, r1Buf, &buflen, CRYPT_POINT_UNCOMPRESSED), ret);
GOTO_ERR_IF(ECC_EncodePoint(sCtx->pkey->para, sCtx->pointR, r2Buf, &buflen, CRYPT_POINT_UNCOMPRESSED), ret);
tag1 = 0x02;
tag2 = 0x03;
}
(void)memcpy_s(rBuf, SM2_TWO_POINT_COORDINATE_LEN, r1Buf + 1, SM2_POINT_COORDINATE_LEN - 1);
(void)memcpy_s(rBuf + SM2_POINT_COORDINATE_LEN - 1, SM2_TWO_POINT_COORDINATE_LEN - SM2_POINT_COORDINATE_LEN + 1,
r2Buf + 1, SM2_POINT_COORDINATE_LEN - 1);
// Calculate the hash value.
GOTO_ERR_IF_EX(Sm3InnerHash(sCtx->hashMethod, xBuf, zBuf, zlen, rBuf, stmpBuf, &len), ret);
// Calculate the hash value sent to the peer end.
GOTO_ERR_IF_EX(Sm3MsgHash(sCtx->hashMethod, yBuf, stmpBuf, sCtx->sumSend, &len, tag1), ret);
// Computes the hash value for validation
GOTO_ERR_IF_EX(Sm3MsgHash(sCtx->hashMethod, yBuf, stmpBuf, sCtx->sumCheck, &len, tag2), ret);
sCtx->isSumValid = 1;
return ret;
ERR:
sCtx->isSumValid = 0; // Reset checksum validity flag
return ret;
}
static int SM2_PKG_Kdf(const CRYPT_SM2_Ctx *ctx, uint8_t *in, const uint32_t inLen, uint8_t *out, uint32_t *outLen)
{
int32_t ret;
const uint32_t shareKeyLen = 16;
const EAL_MdMethod *hashMethod = ctx->hashMethod;
uint8_t *tmp = BSL_SAL_Malloc(hashMethod->mdSize);
uint32_t tmpLen = hashMethod->mdSize;
void *mdCtx = hashMethod->newCtx(NULL, hashMethod->id);
if (mdCtx == NULL || tmp == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
GOTO_ERR_IF(hashMethod->init(mdCtx, NULL), ret);
GOTO_ERR_IF(hashMethod->update(mdCtx, in, inLen), ret);
GOTO_ERR_IF(hashMethod->final(mdCtx, tmp, &tmpLen), ret);
if (memcpy_s(out, *outLen, tmp, shareKeyLen) != EOK) {
ret = CRYPT_SECUREC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
*outLen = shareKeyLen;
ERR:
hashMethod->freeCtx(mdCtx);
BSL_SAL_ClearFree(tmp, hashMethod->mdSize);
return ret;
}
static int32_t SM2_PKGComputeKey(const CRYPT_SM2_Ctx *selfCtx, const CRYPT_SM2_Ctx *peerCtx,
uint8_t *out, uint32_t *outlen)
{
if (selfCtx->pkey == NULL || peerCtx->pkey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (selfCtx->hashMethod == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_ERR_NO_HASH_METHOD);
return CRYPT_SM2_ERR_NO_HASH_METHOD;
}
int32_t ret;
uint8_t sharePointCode[65] = {0};
uint32_t codeLen = sizeof(sharePointCode);
const ECC_Pkey *eccPkey = selfCtx->pkey;
BN_BigNum *tmpPrvkey = BN_Dup(eccPkey->prvkey);
ECC_Point *sharePoint = ECC_NewPoint(eccPkey->para);
if ((tmpPrvkey == NULL) || (sharePoint == NULL)) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
GOTO_ERR_IF(ECC_PointMul(eccPkey->para, sharePoint, eccPkey->prvkey, peerCtx->pkey->pubkey), ret);
GOTO_ERR_IF(ECC_PointCheck(sharePoint), ret);
GOTO_ERR_IF_EX(ECC_EncodePoint(eccPkey->para, sharePoint, sharePointCode, &codeLen, CRYPT_POINT_UNCOMPRESSED), ret);
GOTO_ERR_IF_EX(SM2_PKG_Kdf(selfCtx, sharePointCode + 1, codeLen - 1, out, outlen), ret);
ERR:
BN_Destroy(tmpPrvkey);
ECC_FreePoint(sharePoint);
return ret;
}
int32_t CRYPT_SM2_KapComputeKey(const CRYPT_SM2_Ctx *selfCtx, const CRYPT_SM2_Ctx *peerCtx,
uint8_t *out, uint32_t *outlen)
{
if (selfCtx == NULL || peerCtx == NULL || out == NULL || outlen == NULL || *outlen == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (selfCtx->pkgImpl != 0) {
return SM2_PKGComputeKey(selfCtx, peerCtx, out, outlen);
}
ECC_Point *uorv = ECC_NewPoint(selfCtx->pkey->para);
uint32_t keyBits = CRYPT_SM2_GetBits(selfCtx);
BN_BigNum *xs = BN_Create(keyBits);
BN_BigNum *xp = BN_Create(keyBits);
BN_BigNum *t = BN_Create(keyBits);
BN_BigNum *twoPowerW = BN_Create(keyBits);
BN_BigNum *order = ECC_GetParaN(selfCtx->pkey->para);
uint32_t w;
int32_t ret;
BN_Optimizer *opt = BN_OptimizerCreate();
if (uorv == NULL || xs == NULL || xp == NULL || t == NULL || twoPowerW == NULL ||
order == NULL || opt == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
GOTO_ERR_IF(IsParamValid(selfCtx, peerCtx), ret);
/* Second: Caculate -- w */
// w is equal to the number of digits of n rounded up, divided by 2, and then subtracted by 1.
w = (BN_Bits(order) + 1) / 2 - 1;
GOTO_ERR_IF(BN_Zeroize(twoPowerW), ret);
GOTO_ERR_IF(BN_SetBit(twoPowerW, w), ret);
/* Third: Caculate -- X = 2 ^ w + (x & (2 ^ w - 1)) = 2 ^ w + (x mod 2 ^ w) */
/* Get x */
GOTO_ERR_IF(ECC_GetPointDataX(selfCtx->pkey->para, selfCtx->pointR, xs), ret);
GOTO_ERR_IF(ECC_GetPointDataX(peerCtx->pkey->para, peerCtx->pointR, xp), ret);
/* x mod 2 ^ w */
/* Caculate Self x */
GOTO_ERR_IF(BN_Mod(xs, xs, twoPowerW, opt), ret);
GOTO_ERR_IF(BN_Add(xs, xs, twoPowerW), ret);
/* Caculate Peer x */
GOTO_ERR_IF(BN_Mod(xp, xp, twoPowerW, opt), ret);
GOTO_ERR_IF(BN_Add(xp, xp, twoPowerW), ret);
/* Forth: Caculate t */
GOTO_ERR_IF(BN_ModMul(t, xs, selfCtx->r, order, opt), ret);
GOTO_ERR_IF(BN_ModAddQuick(t, t, selfCtx->pkey->prvkey, order, opt), ret);
/* Fifth: Caculate V or U */
GOTO_ERR_IF(ECC_PointMul(peerCtx->pkey->para, uorv, xp, peerCtx->pointR), ret);
/* P + [x]R */
GOTO_ERR_IF(ECC_PointAddAffine(selfCtx->pkey->para, uorv, uorv, peerCtx->pkey->pubkey), ret);
GOTO_ERR_IF(ECC_PointMul(selfCtx->pkey->para, uorv, t, uorv), ret);
/* Detect uorv is in */
GOTO_ERR_IF(ECC_PointCheck(uorv), ret);
/* Sixth: Caculate Key -- Need Xuorv, Yuorv, Zc, Zs, klen */
GOTO_ERR_IF_EX(Sm2CalculateKey(selfCtx, peerCtx, uorv, out, outlen), ret);
GOTO_ERR_IF_EX(Sm2KapFinalCheck((CRYPT_SM2_Ctx *)(uintptr_t)selfCtx, (CRYPT_SM2_Ctx *)(uintptr_t)peerCtx, uorv),
ret);
ERR:
BnMemDestroy(xs, xp, t, twoPowerW, order);
ECC_FreePoint(uorv);
Sm2CleanR((CRYPT_SM2_Ctx *)(uintptr_t)selfCtx);
BN_OptimizerDestroy(opt);
return ret;
}
#endif
| 2302_82127028/openHiTLS-examples_1508 | crypto/sm2/src/sm2_exch.c | C | unknown | 14,731 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef SM2_LOCAL_H
#define SM2_LOCAL_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SM2
#include <stdint.h>
#include "crypt_sm2.h"
#include "crypt_local_types.h"
#include "crypt_ecc_pkey.h"
#include "sal_atomic.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
#define SM2_MAX_ID_BITS 65535
#define SM2_MAX_ID_LENGTH (SM2_MAX_ID_BITS / 8)
#define SM2_MAX_PUBKEY_DATA_LENGTH 256
#define MAX_MD_SIZE 64
#define SM3_MD_SIZE 32
#define SM2_POINT_SINGLE_COORDINATE_LEN 32
#define SM2_POINT_COORDINATE_LEN 65
#define SM2_TWO_POINT_COORDINATE_LEN 128
#define SM2_X_LEN 32
#ifdef HITLS_CRYPTO_ACVP_TESTS
typedef struct {
BN_BigNum *k; // random k
} SM2_ParaEx;
#endif
/* SM2 key context */
struct SM2_Ctx {
ECC_Pkey *pkey;
uint32_t pkgImpl;
ECC_Point *pointR; // Local R
const EAL_MdMethod *hashMethod;
BN_BigNum *r; // Local r
uint8_t *userId; // User ID
uint32_t userIdLen; // the length of User ID
int32_t server; // 1: the initiator, 0: the receiver, and the default value is 1.
uint8_t sumCheck[SM3_MD_SIZE]; // Hash value used as a check
uint8_t sumSend[SM3_MD_SIZE]; // Hash value sent to the peer end
uint8_t isSumValid; // Indicates whether the checksum is valid. 1: valid; 0: invalid.
BSL_SAL_RefCount references;
#ifdef HITLS_CRYPTO_ACVP_TESTS
SM2_ParaEx paraEx;
#endif
};
/**
* @ingroup sm2
* @brief The sm2 invokes the SM3 to calculate the hash value.
*
* @param ctx [IN] sm2 context structure
* @param out [IN/OUT] Hash value
* @param outLen [IN/OUT] Length of the hash value
*
* @retval CRYPT_SUCCESS calculated successfully.
* @retval Other: The calculation fails. For details about the return value type, see crypt_errno.h.
*/
int32_t Sm2ComputeZDigest(const CRYPT_SM2_Ctx *ctx, uint8_t *out, uint32_t *outLen);
#if defined(HITLS_CRYPTO_SM2_EXCH) || defined(HITLS_CRYPTO_SM2_CRYPT)
/**
* @ingroup sm2
* @brief sm2 kdf function
*
* @param out [IN/OUT] Calculation result
* @param outlen [IN/OUT] Output data length
* @param z [IN] Input data
* @param zlen [IN] Length of the input data
* @param hashMethod [IN] hash method
*
* @retval CRYPT_SUCCESS calculated successfully.
* @retval Other: The calculation fails. For details about the return value type, see crypt_errno.h.
*/
int32_t KdfGmt0032012(uint8_t *out, const uint32_t *outlen, const uint8_t *z, uint32_t zlen,
const EAL_MdMethod *hashMethod);
#ifdef HITLS_CRYPTO_ACVP_TESTS
/**
* @ingroup sm2
* @brief set random k for the sm2 context
*
* @param ctx [IN] Source SM2 context
* @param para [IN] random k
*/
int32_t CRYPT_SM2_SetK(CRYPT_SM2_Ctx *ctx, uint8_t *val, uint32_t len);
#endif
#endif
#ifdef __cplusplus
}
#endif
#endif // HITLS_CRYPTO_SM2
#endif // SM2_LOCAL_H
| 2302_82127028/openHiTLS-examples_1508 | crypto/sm2/src/sm2_local.h | C | unknown | 3,307 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SM2
#include <stdbool.h>
#include "crypt_errno.h"
#include "crypt_types.h"
#include "crypt_utils.h"
#include "securec.h"
#include "bsl_sal.h"
#include "bsl_err_internal.h"
#include "crypt_bn.h"
#include "crypt_encode_internal.h"
#include "crypt_ecc.h"
#include "crypt_ecc_pkey.h"
#include "crypt_local_types.h"
#include "crypt_sm2.h"
#include "sm2_local.h"
#include "eal_md_local.h"
#include "crypt_params_key.h"
static int32_t Sm2SetUserId(CRYPT_SM2_Ctx *ctx, const uint8_t *val, uint32_t len)
{
ctx->userId = BSL_SAL_Calloc(len, 1u);
if (ctx->userId == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
(void) memcpy_s(ctx->userId, len, val, len);
ctx->userIdLen = len;
return CRYPT_SUCCESS;
}
CRYPT_SM2_Ctx *CRYPT_SM2_NewCtx(void)
{
CRYPT_SM2_Ctx *ctx = BSL_SAL_Calloc(1u, sizeof(CRYPT_SM2_Ctx));
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return NULL;
}
ctx->pkey = ECC_PkeyNewCtx(CRYPT_ECC_SM2);
if (ctx->pkey == NULL) {
CRYPT_SM2_FreeCtx(ctx);
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
const EAL_MdMethod *mdMethod = EAL_MdFindDefaultMethod(CRYPT_MD_SM3);
if (mdMethod == NULL) {
CRYPT_SM2_FreeCtx(ctx);
BSL_ERR_PUSH_ERROR(CRYPT_EVENT_ERR);
return NULL;
}
ctx->hashMethod = (const EAL_MdMethod *)mdMethod;
ctx->server = 1; // Indicates the initiator by default.
ctx->isSumValid = 0; // checksum is invalid by default.
BSL_SAL_ReferencesInit(&(ctx->references));
return ctx;
}
CRYPT_SM2_Ctx *CRYPT_SM2_NewCtxEx(void *libCtx)
{
CRYPT_SM2_Ctx *ctx = CRYPT_SM2_NewCtx();
if (ctx == NULL) {
return NULL;
}
ctx->pkey->libCtx = libCtx;
ECC_SetLibCtx(ctx->pkey->libCtx, ctx->pkey->para);
return ctx;
}
CRYPT_SM2_Ctx *CRYPT_SM2_DupCtx(CRYPT_SM2_Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return NULL;
}
CRYPT_SM2_Ctx *newCtx = BSL_SAL_Calloc(1u, sizeof(CRYPT_SM2_Ctx));
if (newCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
GOTO_ERR_IF_SRC_NOT_NULL(newCtx->pkey, ctx->pkey, ECC_DupCtx(ctx->pkey), CRYPT_MEM_ALLOC_FAIL);
GOTO_ERR_IF_SRC_NOT_NULL(newCtx->pointR, ctx->pointR, ECC_DupPoint(ctx->pointR), CRYPT_MEM_ALLOC_FAIL);
GOTO_ERR_IF_SRC_NOT_NULL(newCtx->r, ctx->r, BN_Dup(ctx->r), CRYPT_MEM_ALLOC_FAIL);
GOTO_ERR_IF_SRC_NOT_NULL(newCtx->userId, ctx->userId, BSL_SAL_Dump(ctx->userId, ctx->userIdLen),
CRYPT_MEM_ALLOC_FAIL);
newCtx->userIdLen = ctx->userIdLen;
newCtx->pkgImpl = ctx->pkgImpl;
newCtx->hashMethod = ctx->hashMethod;
newCtx->server = ctx->server;
newCtx->isSumValid = ctx->isSumValid;
BSL_SAL_ReferencesInit(&(newCtx->references));
(void)memcpy_s(newCtx->sumCheck, SM3_MD_SIZE, ctx->sumCheck, SM3_MD_SIZE);
(void)memcpy_s(newCtx->sumSend, SM3_MD_SIZE, ctx->sumSend, SM3_MD_SIZE);
return newCtx;
ERR:
CRYPT_SM2_FreeCtx(newCtx);
return NULL;
}
void CRYPT_SM2_FreeCtx(CRYPT_SM2_Ctx *ctx)
{
int val = 0;
if (ctx == NULL) {
return;
}
BSL_SAL_AtomicDownReferences(&(ctx->references), &val);
if (val > 0) {
return;
}
BSL_SAL_ReferencesFree(&(ctx->references));
ECC_FreeCtx(ctx->pkey);
BSL_SAL_FREE(ctx->userId);
BN_Destroy(ctx->r);
ECC_FreePoint(ctx->pointR);
#ifdef HITLS_CRYPTO_ACVP_TESTS
BN_Destroy(ctx->paraEx.k);
#endif
BSL_SAL_FREE(ctx);
return;
}
int32_t Sm2ComputeZDigest(const CRYPT_SM2_Ctx *ctx, uint8_t *out, uint32_t *outLen)
{
int32_t ret;
if (ctx->userIdLen >= (UINT16_MAX / 8)) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_ID_TOO_LARGE);
return CRYPT_SM2_ID_TOO_LARGE;
}
/* 2-byte id length in bits */
uint16_t entl = (uint16_t)(8 * ctx->userIdLen);
uint8_t eByte = (uint8_t)(entl >> 8);
uint8_t maxPubData[SM2_MAX_PUBKEY_DATA_LENGTH] = {0};
CRYPT_Sm2Pub pub = {maxPubData, SM2_MAX_PUBKEY_DATA_LENGTH};
uint32_t keyBits = CRYPT_SM2_GetBits(ctx);
BN_BigNum *a = ECC_GetParaA(ctx->pkey->para);
BN_BigNum *b = ECC_GetParaB(ctx->pkey->para);
BN_BigNum *xG = ECC_GetParaX(ctx->pkey->para);
BN_BigNum *yG = ECC_GetParaY(ctx->pkey->para);
void *mdCtx = ctx->hashMethod->newCtx(NULL, ctx->hashMethod->id);
uint8_t *buf = BSL_SAL_Calloc(1u, keyBits);
if (a == NULL || b == NULL || xG == NULL || yG == NULL || buf == NULL || mdCtx == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
BSL_Param tmpPara[2] = {{CRYPT_PARAM_EC_PUBKEY, BSL_PARAM_TYPE_OCTETS, maxPubData,
SM2_MAX_PUBKEY_DATA_LENGTH, 0}, BSL_PARAM_END};
GOTO_ERR_IF(CRYPT_SM2_GetPubKeyEx(ctx, tmpPara), ret);
pub.len = tmpPara[0].useLen;
GOTO_ERR_IF(ctx->hashMethod->init(mdCtx, NULL), ret);
// User A has a distinguishable identifier IDA with a length of entlenA bits,
// and ENTLA is two bytes converted from an integer entlenA
// H256(ENTLA || IDA || a || b || xG || yG || xA || yA)
GOTO_ERR_IF(ctx->hashMethod->update(mdCtx, &eByte, 1), ret); // ENTLA
eByte = entl & 0xFF;
GOTO_ERR_IF(ctx->hashMethod->update(mdCtx, &eByte, 1), ret); // ENTLA
if (ctx->userIdLen > 0) {
GOTO_ERR_IF(ctx->hashMethod->update(mdCtx, ctx->userId, ctx->userIdLen), ret); // IDA
}
GOTO_ERR_IF_EX(BN_Bn2Bin(a, buf, &keyBits), ret);
GOTO_ERR_IF(ctx->hashMethod->update(mdCtx, buf, keyBits), ret); // a
GOTO_ERR_IF_EX(BN_Bn2Bin(b, buf, &keyBits), ret);
GOTO_ERR_IF(ctx->hashMethod->update(mdCtx, buf, keyBits), ret); // b
GOTO_ERR_IF_EX(BN_Bn2Bin(xG, buf, &keyBits), ret);
GOTO_ERR_IF(ctx->hashMethod->update(mdCtx, buf, keyBits), ret); // xG
keyBits = CRYPT_SM2_GetBits(ctx);
GOTO_ERR_IF_EX(BN_Bn2Bin(yG, buf, &keyBits), ret);
GOTO_ERR_IF(ctx->hashMethod->update(mdCtx, buf, keyBits), ret); // yG
GOTO_ERR_IF(ctx->hashMethod->update(mdCtx, pub.data + 1, pub.len - 1), ret); // xA and yA
GOTO_ERR_IF(ctx->hashMethod->final(mdCtx, out, outLen), ret);
ERR:
ctx->hashMethod->freeCtx(mdCtx);
BN_Destroy(a);
BN_Destroy(b);
BN_Destroy(xG);
BN_Destroy(yG);
BSL_SAL_FREE(buf);
return ret;
}
#ifdef HITLS_CRYPTO_SM2_SIGN
static int32_t Sm2ComputeMsgHash(const CRYPT_SM2_Ctx *ctx, const uint8_t *msg, uint32_t msgLen, BN_BigNum *e)
{
int ret;
uint8_t out[SM3_MD_SIZE];
uint32_t outLen = sizeof(out);
void *mdCtx = ctx->hashMethod->newCtx(NULL, ctx->hashMethod->id);
if (mdCtx == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
GOTO_ERR_IF_EX(Sm2ComputeZDigest(ctx, out, &outLen), ret);
GOTO_ERR_IF(ctx->hashMethod->init(mdCtx, NULL), ret);
GOTO_ERR_IF(ctx->hashMethod->update(mdCtx, out, outLen), ret);
GOTO_ERR_IF(ctx->hashMethod->update(mdCtx, msg, msgLen), ret);
GOTO_ERR_IF(ctx->hashMethod->final(mdCtx, out, &outLen), ret);
GOTO_ERR_IF_EX(BN_Bin2Bn(e, out, outLen), ret);
ERR:
ctx->hashMethod->freeCtx(mdCtx);
return ret;
}
#endif
uint32_t CRYPT_SM2_GetBits(const CRYPT_SM2_Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return 0;
}
return ECC_PkeyGetBits(ctx->pkey);
}
int32_t CRYPT_SM2_SetPrvKey(CRYPT_SM2_Ctx *ctx, const CRYPT_Sm2Prv *prv)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
return ECC_PkeySetPrvKey(ctx->pkey, prv);
}
int32_t CRYPT_SM2_SetPubKey(CRYPT_SM2_Ctx *ctx, const CRYPT_Sm2Pub *pub)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
return ECC_PkeySetPubKey(ctx->pkey, pub);
}
int32_t CRYPT_SM2_GetPrvKey(const CRYPT_SM2_Ctx *ctx, CRYPT_Sm2Prv *prv)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
return ECC_PkeyGetPrvKey(ctx->pkey, prv);
}
int32_t CRYPT_SM2_GetPubKey(const CRYPT_SM2_Ctx *ctx, CRYPT_Sm2Pub *pub)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
return ECC_PkeyGetPubKey(ctx->pkey, pub);
}
#ifdef HITLS_BSL_PARAMS
int32_t CRYPT_SM2_SetPrvKeyEx(CRYPT_SM2_Ctx *ctx, const BSL_Param *para)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
return ECC_PkeySetPrvKeyEx(ctx->pkey, para);
}
int32_t CRYPT_SM2_SetPubKeyEx(CRYPT_SM2_Ctx *ctx, const BSL_Param *para)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
return ECC_PkeySetPubKeyEx(ctx->pkey, para);
}
int32_t CRYPT_SM2_GetPrvKeyEx(const CRYPT_SM2_Ctx *ctx, BSL_Param *para)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
return ECC_PkeyGetPrvKeyEx(ctx->pkey, para);
}
int32_t CRYPT_SM2_GetPubKeyEx(const CRYPT_SM2_Ctx *ctx, BSL_Param *para)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
return ECC_PkeyGetPubKeyEx(ctx->pkey, para);
}
#endif
int32_t CRYPT_SM2_Gen(CRYPT_SM2_Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
return ECC_PkeyGen(ctx->pkey);
}
#ifdef HITLS_CRYPTO_PROVIDER
int32_t CRYPT_SM2_Import(CRYPT_SM2_Ctx *ctx, const BSL_Param *params)
{
if (ctx == NULL || params == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret;
const BSL_Param *prv = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_EC_PRVKEY);
const BSL_Param *pub = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_EC_PUBKEY);
if (prv != NULL) {
ret = CRYPT_SM2_SetPrvKeyEx(ctx, prv);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
if (pub != NULL) {
ret = CRYPT_SM2_SetPubKeyEx(ctx, pub);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_SM2_Export(const CRYPT_SM2_Ctx *ctx, BSL_Param *params)
{
if (ctx == NULL || params == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
uint32_t index = 0;
uint32_t keyBytes = (CRYPT_SM2_GetBits(ctx) + 7) / 8;
CRYPT_EAL_ProcessFuncCb processCb = NULL;
void *args = NULL;
BSL_Param sm2Params[3] = {0};
int32_t ret = CRYPT_GetPkeyProcessParams(params, &processCb, &args);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
uint8_t *buffer = BSL_SAL_Calloc(1, keyBytes * 2);
if (buffer == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
if (ctx->pkey->prvkey != NULL) {
(void)BSL_PARAM_InitValue(&sm2Params[index], CRYPT_PARAM_EC_PRVKEY, BSL_PARAM_TYPE_OCTETS, buffer, keyBytes);
ret = CRYPT_SM2_GetPrvKeyEx(ctx, sm2Params);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_Free(buffer);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
sm2Params[index].valueLen = sm2Params[index].useLen;
index++;
}
if (ctx->pkey->pubkey != NULL) {
(void)BSL_PARAM_InitValue(&sm2Params[index], CRYPT_PARAM_EC_PUBKEY, BSL_PARAM_TYPE_OCTETS,
buffer, keyBytes);
ret = CRYPT_SM2_GetPubKeyEx(ctx, sm2Params);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_Free(buffer);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
sm2Params[index].valueLen = sm2Params[index].useLen;
index++;
}
ret = processCb(sm2Params, args);
BSL_SAL_Free(buffer);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
#endif
#ifdef HITLS_CRYPTO_SM2_SIGN
uint32_t CRYPT_SM2_GetSignLen(const CRYPT_SM2_Ctx *ctx)
{
if (ctx == NULL || ctx->pkey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return 0;
}
uint32_t qLen = (ECC_ParaBits(ctx->pkey->para) / 8) + 1;
uint32_t maxSignLen = 0;
int32_t ret = CRYPT_EAL_GetSignEncodeLen(qLen, qLen, &maxSignLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return 0;
}
return maxSignLen;
}
static int32_t Sm2SignCore(const CRYPT_SM2_Ctx *ctx, BN_BigNum *e, BN_BigNum *r, BN_BigNum *s)
{
uint32_t keyBits = CRYPT_SM2_GetBits(ctx);
BN_BigNum *k = BN_Create(keyBits);
BN_BigNum *tmp = BN_Create(keyBits);
// An extra bit is allocated to prevent the number of bits in the result of adding BNs from exceeding the keybits.
BN_BigNum *t = BN_Create(keyBits + 1);
BN_BigNum *paraN = ECC_GetParaN(ctx->pkey->para);
ECC_Point *pt = ECC_NewPoint(ctx->pkey->para);
BN_Optimizer *opt = BN_OptimizerCreate();
int32_t ret, i;
if ((k == NULL) || (tmp == NULL) || (t == NULL) || (pt == NULL) || (paraN == NULL) || (opt == NULL)) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
ret = CRYPT_MEM_ALLOC_FAIL;
goto ERR;
}
for (i = 0; i < CRYPT_ECC_TRY_MAX_CNT; i++) {
GOTO_ERR_IF(BN_RandRangeEx(ctx->pkey->libCtx, k, paraN), ret);
if (BN_IsZero(k)) {
continue;
}
// pt = k * G
GOTO_ERR_IF(ECC_PointMul(ctx->pkey->para, pt, k, NULL), ret);
// r = (e + pt->x) mod n
GOTO_ERR_IF(ECC_GetPointDataX(ctx->pkey->para, pt, tmp), ret);
GOTO_ERR_IF(BN_ModAdd(r, e, tmp, paraN, opt), ret);
// if r == 0 || r + k == n, then restart
GOTO_ERR_IF(BN_Add(t, r, k), ret);
if (BN_IsZero(r) || BN_Cmp(t, paraN) == 0) {
continue;
}
// prvkey * r mod n == (r * dA) mod n
GOTO_ERR_IF(BN_ModMul(s, ctx->pkey->prvkey, r, paraN, opt), ret);
// k - prvkey * r mod n
GOTO_ERR_IF(BN_ModSub(s, k, s, paraN, opt), ret);
// 1/(1 + d) mod n, tmp stores 1/(1 + d)
GOTO_ERR_IF(BN_AddLimb(t, ctx->pkey->prvkey, 1), ret);
GOTO_ERR_IF(ECC_ModOrderInv(ctx->pkey->para, tmp, t), ret);
// s = (1/(1+d)) * (k - prvkey * r) mod n
GOTO_ERR_IF(BN_ModMul(s, tmp, s, paraN, opt), ret);
// if s == 0, then restart
if (BN_IsZero(s) != true) {
break;
}
}
if (i >= CRYPT_ECC_TRY_MAX_CNT) {
ret = CRYPT_SM2_ERR_TRY_CNT;
BSL_ERR_PUSH_ERROR(ret);
}
ERR:
BN_Destroy(k);
BN_Destroy(tmp);
BN_Destroy(t);
BN_Destroy(paraN);
ECC_FreePoint(pt);
BN_OptimizerDestroy(opt);
return ret;
}
int32_t KeyCheckAndPubGen(const CRYPT_SM2_Ctx *ctx)
{
int32_t ret;
if (ctx->pkey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_ERR_EMPTY_KEY);
return CRYPT_SM2_ERR_EMPTY_KEY;
}
if (ctx->pkey->prvkey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_NO_PRVKEY);
return CRYPT_SM2_NO_PRVKEY;
}
if (ctx->pkey->pubkey != NULL) {
return CRYPT_SUCCESS;
}
ret = ECC_GenPublicKey(ctx->pkey);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
int32_t CRYPT_SM2_Sign(const CRYPT_SM2_Ctx *ctx, int32_t algId, const uint8_t *data, uint32_t dataLen,
uint8_t *sign, uint32_t *signLen)
{
int32_t ret;
if (algId != CRYPT_MD_SM3) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_ALGID);
return CRYPT_EAL_ERR_ALGID;
}
if ((ctx == NULL) || (sign == NULL) || (signLen == NULL) || ((data == NULL) && (dataLen != 0))) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
ret = KeyCheckAndPubGen(ctx);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if (ctx->hashMethod == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_ERR_NO_HASH_METHOD);
return CRYPT_SM2_ERR_NO_HASH_METHOD;
}
if (*signLen < CRYPT_SM2_GetSignLen(ctx)) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_BUFF_LEN_NOT_ENOUGH);
return CRYPT_SM2_BUFF_LEN_NOT_ENOUGH;
}
uint32_t keyBits = CRYPT_SM2_GetBits(ctx);
BN_BigNum *r = BN_Create(keyBits);
BN_BigNum *s = BN_Create(keyBits);
BN_BigNum *d = BN_Create(keyBits);
if (r == NULL || s == NULL || d == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
GOTO_ERR_IF_EX(Sm2ComputeMsgHash(ctx, data, dataLen, d), ret);
GOTO_ERR_IF_EX(Sm2SignCore(ctx, d, r, s), ret);
ret = CRYPT_EAL_EncodeSign(r, s, sign, signLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
ERR:
BN_Destroy(r);
BN_Destroy(s);
BN_Destroy(d);
return ret;
}
static int32_t VerifyCheckSign(const CRYPT_SM2_Ctx *ctx, BN_BigNum *r, BN_BigNum *s)
{
if (ctx->pkey->para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
BN_BigNum *paraN = ECC_GetParaN(ctx->pkey->para);
if (paraN == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
if ((BN_Cmp(r, paraN) >= 0) || (BN_Cmp(s, paraN) >= 0)) {
BN_Destroy(paraN);
BSL_ERR_PUSH_ERROR(CRYPT_SM2_VERIFY_FAIL);
return CRYPT_SM2_VERIFY_FAIL;
}
BN_Destroy(paraN);
if (BN_IsZero(r) || BN_IsZero(s)) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_VERIFY_FAIL);
return CRYPT_SM2_VERIFY_FAIL;
}
return CRYPT_SUCCESS;
}
static int32_t Sm2VerifyCore(const CRYPT_SM2_Ctx *ctx, BN_BigNum *e, const BN_BigNum *r, const BN_BigNum *s)
{
uint32_t keyBits = CRYPT_SM2_GetBits(ctx);
BN_BigNum *t = BN_Create(keyBits);
ECC_Point *tpt = ECC_NewPoint(ctx->pkey->para);
BN_BigNum *tptX = BN_Create(keyBits);
BN_Optimizer *opt = BN_OptimizerCreate();
BN_BigNum *paraN = ECC_GetParaN(ctx->pkey->para);
int32_t ret;
if ((t == NULL) || (tpt == NULL) || (tptX == NULL) || (paraN == NULL) || (opt == NULL)) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
ret = CRYPT_MEM_ALLOC_FAIL;
goto ERR;
}
// B5: calculate t = (r' + s') modn, verification failed if t=0
GOTO_ERR_IF_EX(BN_ModAddQuick(t, r, s, paraN, opt), ret);
if (BN_IsZero(t)) {
ret = CRYPT_SM2_VERIFY_FAIL;
BSL_ERR_PUSH_ERROR(ret);
}
// calculate the point (x1', y1')=[s']G + [t]PA
GOTO_ERR_IF(ECC_PointMulAdd(ctx->pkey->para, tpt, s, t, ctx->pkey->pubkey), ret);
GOTO_ERR_IF_EX(ECC_GetPointDataX(ctx->pkey->para, tpt, tptX), ret);
// calculate R=(e'+x1') modn, verification pass if yes, otherwise failed
GOTO_ERR_IF_EX(BN_ModAdd(t, e, tptX, paraN, opt), ret);
if (BN_Cmp(r, t) != 0) {
ret = CRYPT_SM2_VERIFY_FAIL;
BSL_ERR_PUSH_ERROR(ret);
}
ERR:
BN_Destroy(t);
BN_Destroy(paraN);
ECC_FreePoint(tpt);
BN_Destroy(tptX);
BN_OptimizerDestroy(opt);
return ret;
}
static int32_t IsParaVaild(const CRYPT_SM2_Ctx *ctx)
{
if (ctx->pkey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_ERR_EMPTY_KEY);
return CRYPT_SM2_ERR_EMPTY_KEY;
}
if (ctx->pkey->pubkey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_NO_PUBKEY);
return CRYPT_SM2_NO_PUBKEY;
}
if (ctx->hashMethod == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_ERR_NO_HASH_METHOD);
return CRYPT_SM2_ERR_NO_HASH_METHOD;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_SM2_Verify(const CRYPT_SM2_Ctx *ctx, int32_t algId, const uint8_t *data, uint32_t dataLen,
const uint8_t *sign, uint32_t signLen)
{
if (algId != CRYPT_MD_SM3) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_ALGID);
return CRYPT_EAL_ERR_ALGID;
}
if ((ctx == NULL) || ((data == NULL) && (dataLen != 0)) || (sign == NULL) || (signLen == 0)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
uint32_t keyBits = CRYPT_SM2_GetBits(ctx);
int32_t ret = IsParaVaild(ctx);
if (ret != CRYPT_SUCCESS) {
return ret;
}
BN_BigNum *r = BN_Create(keyBits);
BN_BigNum *s = BN_Create(keyBits);
BN_BigNum *e = BN_Create(keyBits);
if (r == NULL || s == NULL || e == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
GOTO_ERR_IF_EX(Sm2ComputeMsgHash(ctx, data, dataLen, e), ret);
GOTO_ERR_IF(CRYPT_EAL_DecodeSign(sign, signLen, r, s), ret);
// Verify that r->s and s->s are within the range of 1~n-1.
GOTO_ERR_IF_EX(VerifyCheckSign(ctx, r, s), ret);
GOTO_ERR_IF_EX(Sm2VerifyCore(ctx, e, r, s), ret);
ERR:
BN_Destroy(r);
BN_Destroy(s);
BN_Destroy(e);
return ret;
}
#endif
static void Sm2Clean(CRYPT_SM2_Ctx *ctx)
{
BN_Destroy(ctx->r);
ctx->r = NULL;
ECC_FreePoint(ctx->pointR);
ctx->pointR = NULL;
ctx->isSumValid = 0;
return;
}
static int32_t Sm2GenerateR(CRYPT_SM2_Ctx *ctx, void *val, uint32_t len)
{
if (val == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret;
Sm2Clean(ctx);
uint32_t keyBits = CRYPT_SM2_GetBits(ctx);
int32_t tryNum = 0;
BN_BigNum *order = ECC_GetParaN(ctx->pkey->para);
ctx->r = BN_Create(keyBits);
ctx->pointR = ECC_NewPoint(ctx->pkey->para);
BN_BigNum *tmp = BN_Create(keyBits);
if (order == NULL || ctx->r == NULL || ctx->pointR == NULL || tmp == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
for (; tryNum < CRYPT_ECC_TRY_MAX_CNT; tryNum++) {
GOTO_ERR_IF_EX(BN_RandRangeEx(ctx->pkey->libCtx, ctx->r, order), ret);
if (!BN_IsZero(ctx->r)) {
break;
}
}
if (tryNum >= CRYPT_ECC_TRY_MAX_CNT) {
ret = CRYPT_SM2_ERR_TRY_CNT;
BSL_ERR_PUSH_ERROR(CRYPT_SM2_ERR_TRY_CNT);
goto ERR;
}
GOTO_ERR_IF(ECC_PointMul(ctx->pkey->para, ctx->pointR, ctx->r, NULL), ret);
GOTO_ERR_IF(ECC_GetPointDataX(ctx->pkey->para, ctx->pointR, tmp), ret);
GOTO_ERR_IF(ECC_EncodePoint(ctx->pkey->para, ctx->pointR, (uint8_t *)val, &len, CRYPT_POINT_UNCOMPRESSED), ret);
BN_Destroy(tmp);
BN_Destroy(order);
return ret;
ERR:
BN_Destroy(tmp);
BN_Destroy(order);
Sm2Clean(ctx);
return ret;
}
static int32_t Sm2SetR(CRYPT_SM2_Ctx *ctx, const void *val, uint32_t len)
{
if (val == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret;
Sm2Clean(ctx);
ECC_Point *rs = ECC_NewPoint(ctx->pkey->para);
if (rs == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
ret = ECC_DecodePoint(ctx->pkey->para, rs, (const uint8_t *)val, len);
if (ret != CRYPT_SUCCESS) {
ECC_FreePoint(rs);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ctx->pointR = rs;
return ret;
}
static int32_t Sm2SetRandom(CRYPT_SM2_Ctx *ctx, const void *val, uint32_t len)
{
int32_t ret;
uint32_t keyBits = CRYPT_SM2_GetBits(ctx);
BN_BigNum *order = ECC_GetParaN(ctx->pkey->para);
ctx->r = BN_Create(keyBits);
ctx->pointR = ECC_NewPoint(ctx->pkey->para);
BN_BigNum *tmp = BN_Create(keyBits);
if (order == NULL || ctx->r == NULL || ctx->pointR == NULL || tmp == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
ret = BN_Bin2Bn(ctx->r, (const uint8_t *)val, len);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
GOTO_ERR_IF(ECC_PointMul(ctx->pkey->para, ctx->pointR, ctx->r, NULL), ret);
GOTO_ERR_IF(ECC_GetPointDataX(ctx->pkey->para, ctx->pointR, tmp), ret);
BN_Destroy(order);
BN_Destroy(tmp);
return ret;
ERR:
BN_Destroy(order);
BN_Destroy(tmp);
Sm2Clean(ctx);
return ret;
}
static int32_t Sm2GetSumSend(CRYPT_SM2_Ctx *ctx, void *val, uint32_t len)
{
if (val == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret;
if (ctx->isSumValid != 1) {
ret = CRYPT_SM2_ERR_S_NOT_SET;
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (len != SM3_MD_SIZE) {
ret = CRYPT_SM2_BUFF_LEN_NOT_ENOUGH;
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = memcpy_s((uint8_t *)val, len, ctx->sumSend, SM3_MD_SIZE);
if (ret != EOK) {
ret = CRYPT_SM2_ERR_GET_S;
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
return CRYPT_SUCCESS;
}
/* consttime memcmp function */
static int32_t IsDataEqual(const uint8_t *data1, const uint8_t *data2, uint32_t len)
{
uint8_t check = 0;
for (uint32_t i = 0; i < len; i++) {
check |= data1[i] ^ data2[i];
}
if (check != 0) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_EXCH_VERIFY_FAIL);
return CRYPT_SM2_EXCH_VERIFY_FAIL;
}
return CRYPT_SUCCESS;
}
static int32_t Sm2DoCheck(CRYPT_SM2_Ctx *ctx, const void *val, uint32_t len)
{
if (val == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret;
if (ctx->isSumValid != 1) {
ret = CRYPT_SM2_ERR_S_NOT_SET;
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (len != SM3_MD_SIZE) {
ret = CRYPT_SM2_ERR_DATA_LEN;
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = IsDataEqual(ctx->sumCheck, val, len);
if (ret != CRYPT_SUCCESS) {
ctx->isSumValid = 0;
}
return ret;
}
static int32_t CtrlServerSet(CRYPT_SM2_Ctx *ctx, const void *val, uint32_t len)
{
if (val == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (len != sizeof(uint32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_ERR_CTRL_LEN);
return CRYPT_SM2_ERR_CTRL_LEN;
}
const int32_t t = *(const int32_t *)val;
if (t != 0 && t != 1) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_INVALID_SERVER_TYPE);
return CRYPT_SM2_INVALID_SERVER_TYPE;
}
ctx->server = t;
return CRYPT_SUCCESS;
}
static int32_t CtrlUserId(CRYPT_SM2_Ctx *ctx, const void *val, uint32_t len)
{
if (val == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (len == 0 || len > SM2_MAX_ID_LENGTH) {
BSL_ERR_PUSH_ERROR(CRYPT_ECC_PKEY_ERR_CTRL_LEN);
return CRYPT_ECC_PKEY_ERR_CTRL_LEN;
}
BSL_SAL_FREE(ctx->userId);
return Sm2SetUserId(ctx, val, len);
}
static int32_t Sm2SetPKG(CRYPT_SM2_Ctx *ctx, const void *val, uint32_t len)
{
if (val == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (len != sizeof(uint32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_ERR_CTRL_LEN);
return CRYPT_SM2_ERR_CTRL_LEN;
}
if (*(const uint32_t *)val != 0 && *(const uint32_t *)val != 1) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
ctx->pkgImpl = *(const uint32_t *)val;
return CRYPT_SUCCESS;
}
static int32_t SM2UpReferences(CRYPT_SM2_Ctx *ctx, void *val, uint32_t len)
{
if (val == NULL || len != (uint32_t)sizeof(int)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
return BSL_SAL_AtomicUpReferences(&(ctx->references), (int *)val);
}
static int32_t CRYPT_SM2_GetLen(const CRYPT_SM2_Ctx *ctx, GetLenFunc func, void *val, uint32_t len)
{
if (val == NULL || len != sizeof(int32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
*(int32_t *)val = func(ctx);
return CRYPT_SUCCESS;
}
int32_t CRYPT_SM2_Ctrl(CRYPT_SM2_Ctx *ctx, int32_t opt, void *val, uint32_t len)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret = CRYPT_SM2_ERR_UNSUPPORTED_CTRL_OPTION;
switch (opt) {
case CRYPT_CTRL_GET_BITS:
return CRYPT_SM2_GetLen(ctx, (GetLenFunc)CRYPT_SM2_GetBits, val, len);
#ifdef HITLS_CRYPTO_SM2_SIGN
case CRYPT_CTRL_GET_SIGNLEN:
return CRYPT_SM2_GetLen(ctx, (GetLenFunc)CRYPT_SM2_GetSignLen, val, len);
#endif
case CRYPT_CTRL_GET_SECBITS:
return CRYPT_SM2_GetLen(ctx, (GetLenFunc)CRYPT_SM2_GetSecBits, val, len);
case CRYPT_CTRL_SET_SM2_SERVER:
ret = CtrlServerSet(ctx, val, len);
break;
case CRYPT_CTRL_SET_SM2_USER_ID:
ret = CtrlUserId(ctx, val, len);
break;
case CRYPT_CTRL_GENE_SM2_R:
ret = Sm2GenerateR(ctx, val, len);
break;
case CRYPT_CTRL_SET_SM2_R:
ret = Sm2SetR(ctx, val, len);
break;
#ifdef HITLS_CRYPTO_ACVP_TESTS
case CRYPT_CTRL_SET_SM2_K:
ret = CRYPT_SM2_SetK(ctx, val, len);
break;
#endif
case CRYPT_CTRL_SET_SM2_RANDOM:
ret = Sm2SetRandom(ctx, val, len);
break;
case CRYPT_CTRL_GET_SM2_SEND_CHECK:
ret = Sm2GetSumSend(ctx, val, len);
break;
case CRYPT_CTRL_SM2_DO_CHECK:
ret = Sm2DoCheck(ctx, val, len);
break;
case CRYPT_CTRL_SET_SM2_PKG:
ret = Sm2SetPKG(ctx, val, len);
break;
case CRYPT_CTRL_UP_REFERENCES:
ret = SM2UpReferences(ctx, val, len);
break;
default:
ret = ECC_PkeyCtrl(ctx->pkey, opt, val, len);
break;
}
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
int32_t CRYPT_SM2_Cmp(const CRYPT_SM2_Ctx *a, const CRYPT_SM2_Ctx *b)
{
if (a == NULL || b == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
return ECC_PkeyCmp(a->pkey, b->pkey);
}
int32_t CRYPT_SM2_GetSecBits(const CRYPT_SM2_Ctx *ctx)
{
if (ctx == NULL || ctx->pkey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return 0;
}
return ECC_GetSecBits(ctx->pkey->para);
}
#ifdef HITLS_CRYPTO_SM2_CHECK
int32_t CRYPT_SM2_Check(uint32_t checkType, const CRYPT_SM2_Ctx *pkey1, const CRYPT_SM2_Ctx *pkey2)
{
int32_t ret;
switch (checkType) {
case CRYPT_PKEY_CHECK_KEYPAIR:
if (pkey1 == NULL || pkey2 == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
ret = ECC_PkeyCheck(pkey1->pkey, pkey2->pkey, checkType);
break;
case CRYPT_PKEY_CHECK_PRVKEY:
if (pkey1 == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
ret = ECC_PkeyCheck(pkey1->pkey, NULL, checkType);
break;
default:
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
if (ret == CRYPT_ECC_PAIRWISE_CHECK_FAIL) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_PAIRWISE_CHECK_FAIL);
return CRYPT_SM2_PAIRWISE_CHECK_FAIL;
}
if (ret == CRYPT_ECC_INVALID_PRVKEY) {
BSL_ERR_PUSH_ERROR(CRYPT_SM2_INVALID_PRVKEY);
return CRYPT_SM2_INVALID_PRVKEY;
}
return ret; // may be other error occurred.
}
#endif // HITLS_CRYPTO_SM2_CHECK
#endif
| 2302_82127028/openHiTLS-examples_1508 | crypto/sm2/src/sm2_sign.c | C | unknown | 31,840 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef CRYPT_SM3_H
#define CRYPT_SM3_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SM3
#include <stdint.h>
#include <stdlib.h>
#include "crypt_types.h"
#include "bsl_params.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
#define CRYPT_SM3_BLOCKSIZE 64
#define CRYPT_SM3_DIGESTSIZE 32
typedef struct CryptSm3Ctx CRYPT_SM3_Ctx;
#define CRYPT_SM3_Squeeze NULL
/**
* @ingroup SM3
* @brief Generate md context.
*
* @retval Success: sm3 ctx.
* Fails: NULL.
*/
CRYPT_SM3_Ctx *CRYPT_SM3_NewCtx(void);
/**
* @ingroup SM3
* @brief Generate md context.
*
* @param libCtx [IN] library context
* @param algId [IN] algorithm id
*
* @retval Success: sm3 ctx.
* Fails: NULL.
*/
CRYPT_SM3_Ctx *CRYPT_SM3_NewCtxEx(void *libCtx, int32_t algId);
/**
* @ingroup SM3
* @brief free md context.
*
* @param ctx [IN] md handle
*/
void CRYPT_SM3_FreeCtx(CRYPT_SM3_Ctx *ctx);
/**
* @ingroup SM3
* @brief This API is used to initialize the SM3 context.
*
* @param ctx [in,out] SM3 context pointer.
* @param *param [in] Pointer to the parameter.
*
* @retval #CRYPT_SUCCESS initialization succeeded.
* @retval #CRYPT_NULL_INPUT Pointer ctx is NULL
*/
int32_t CRYPT_SM3_Init(CRYPT_SM3_Ctx *ctx, BSL_Param *param);
/**
* @ingroup SM3
* @brief Encode the text and update the message digest.
*
* @param ctx [in,out] SM3 context pointer.
* @param in [in] Pointer to the data to be calculated
* @param len [in] Length of the data to be calculated
*
* @retval #CRYPT_SUCCESS succeeded in updating the internal status of the digest.
* @retval #CRYPT_NULL_INPUT The input parameter is NULL.
* @retval #CRYPT_SM3_INPUT_OVERFLOW Accumulated input data length exceeds the maximum (2^64 bits).
*/
int32_t CRYPT_SM3_Update(CRYPT_SM3_Ctx *ctx, const uint8_t *in, uint32_t len);
/**
* @ingroup SM3
* @brief Obtain the message digest based on the passed SM3 text.
*
* @param ctx [in,out] SM3 context pointer.
* @param out [in] digest buffer
* @param outLen [in,out] digest buffer size
*
* @retval #CRYPT_SUCCESS succeeded in updating the internal status of the digest.
* @retval #CRYPT_NULL_INPUT The input parameter is NULL.
* @retval #CRYPT_SM3_OUT_BUFF_LEN_NOT_ENOUGH The output buffer is insufficient.
*/
int32_t CRYPT_SM3_Final(CRYPT_SM3_Ctx *ctx, uint8_t *out, uint32_t *outLen);
/**
* @ingroup SM3
* @brief SM3 Deinitialization API
* @param ctx [in,out] SM3 context pointer.
*
* @retval #CRYPT_SUCCESS Deinitialization succeeded.
* @retval #CRYPT_NULL_INPUT Pointer ctx is NULL
*/
int32_t CRYPT_SM3_Deinit(CRYPT_SM3_Ctx *ctx);
/**
* @ingroup SM3
* @brief Copy SM3 CTX function
* @param dst [out] SM3 context pointer.
* @param src [in] Pointer to the original SM3 context.
*
* @retval #CRYPT_SUCCESS Copy succeeded.
* @retval #CRYPT_NULL_INPUT Pointer src is NULL
*/
int32_t CRYPT_SM3_CopyCtx(CRYPT_SM3_Ctx *dst, const CRYPT_SM3_Ctx *src);
/**
* @ingroup SM3
* @brief Dup SM3 CTX function
* @param src [in] Pointer to the original SM3 context.
*
* @retval Success: sm3 ctx.
* Fails: NULL.
*/
CRYPT_SM3_Ctx *CRYPT_SM3_DupCtx(const CRYPT_SM3_Ctx *src);
#ifdef HITLS_CRYPTO_PROVIDER
/**
* @ingroup SM3
* @brief SM3 get param function
* @param ctx [in] Pointer to the SM3 context.
* @param param [in] Pointer to the parameter.
*
* @retval #CRYPT_SUCCESS initialization succeeded.
* @retval #CRYPT_NULL_INPUT Pointer ctx is NULL
* @retval #CRYPT_INVALID_ARG Pointer param is invalid
*/
int32_t CRYPT_SM3_GetParam(CRYPT_SM3_Ctx *ctx, BSL_Param *param);
#else
#define CRYPT_SM3_GetParam NULL
#endif // HITLS_CRYPTO_PROVIDER
#ifdef __cplusplus
}
#endif /* __cpluscplus */
#endif // HITLS_CRYPTO_SM3
#endif // CRYPT_SM3_H
| 2302_82127028/openHiTLS-examples_1508 | crypto/sm3/include/crypt_sm3.h | C | unknown | 4,358 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*
* -----------------------------------------------------------------------------
*
* ARMv7 assembly optimization for SM3:
* Contributors: Zhao Runchen, Li Xukai, Wang Weijia
* Affiliation: Shandong University and Quan Cheng Laboratory
* Date: 2025.7.10
*
* -----------------------------------------------------------------------------
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SM3
.syntax unified
.arch armv7
.thumb
// State update function for 0~15 rounds, sp register points to the message w[i], r0 is the constant 0x79cc4519
.macro RF0 a b c d e f g h i
LDR r1, [sp], #0x04 // r1 = w[i]
LDR r2, [sp, #0x0C] // r2 = w[i+4]
EOR r2, r1 // r2 = w[i] ^ w[i+4]
ADD \h, r1 // h += w[i] (r1 is free now)
ADD \d, r2 // d += w[i] ^ w[i + 4] (r2 is free now)
ADD r1, \e, r0, ROR #(32-\i%32)%32 // r1 = ss1 = ((a <<< 12) + e + T[i]) <<< 7
ADD r1, r1, \a, ROR #20
ROR r1, #25
EOR r3, \e, \f // h += (e ^ f ^ g) + ss1
EOR r3, \g
ADD \h, r3
ADD \h, r1
EOR r3, \h, \h, ROR #23 // h = h ^ (h <<< 9) ^ (h <<< 17)
EOR \h, r3, \h, ROR #15
EOR r2, r1, \a, ROR #20 // r2 = ss2 = (a <<< 12) ^ ss1
EOR r3, \a, \b // d += (a ^ b ^ c)+ ss2
EOR r3, \c
ADD \d, r3
ADD \d, r2
ROR \b, #23 // b = b <<< 9, f = f <<< 19
ROR \f, #13
.endm
// State update function for rounds 16~63, sp register points to the message w[i], r0 is the constant 0x7a879d8a
.macro RF1 a b c d e f g h i
LDR r1, [sp], #0x04 // r1 = w[i]
LDR r2, [sp, #0x0C] // r2 = w[i+4]
EOR r2, r1 // r2 = w[i] ^ w[i+4]
ADD \h, r1 // h += w[i] (r1 is free now)
ADD \d, r2 // d += w[i] ^ w[i + 4] (r2 is free now)
ADD r1, \e, r0, ROR #(32-\i%32)%32 // r1 = ss1 = ((a <<< 12) + e + T[i]) <<< 7
ADD r1, r1, \a, ROR #20
ROR r1, #25
EOR r3, \f, \g // h += (e & f) | (~e & g) + ss1 = ((f ^ g) & e) ^ g + ss1
AND r3, \e
EOR r3, \g
ADD \h, r3
ADD \h, r1
EOR r3, \h, \h, ROR #23 // h = P0(h) = h ^ (h <<< 9) ^ (h <<< 17)
EOR \h, r3, \h, ROR #15
EOR r2, r1, \a, ROR #20 // ss2 = (a <<< 12) ^ ss1 (r1 is free now)
EOR r3, \b, \c // d += ((a & b) | (a & c) | (b & c)) + ss2 = (a & (b | c)) | ((b & c)) + ss2
AND r3, \a
AND r1, \b, \c
EOR r3, r1
ADD \d, r3
ADD \d, r2
ROR \b, #23 // b = b <<< 9, f = f <<< 19
ROR \f, #13
.endm
// Message expansion: w[i+16] = P1(w[i] ^ w[i+7] ^ (w[i+13] <<< 15)) ^ (w[i+3] <<< 7) ^ w[i+10]
// P1(x) = x ^ x <<< 15 ^ x <<< 23 = x ^ x >>> 17 ^ x >>> 9
// Since the width of the sliding registers (w0-w13) is 14, there are no additional registers available for calculating P1(x).
// Therefore, w7 will be used as a temporary register here and restored from memory later.
// We hope you can have a better way to avoid reading the memory one more time.
.macro MSGEXP w0 w3 w7 w10 w13 i
LDR \w13, [sp, #((13 + \i) << 2)]
EOR \w0, \w0, \w7
EOR \w0, \w0, \w13, ROR #17
EOR \w7, \w0, \w0, ROR #17
EOR \w0, \w7, \w0, ROR #9
EOR \w0, \w0, \w3, ROR #25
EOR \w0, \w10
LDR \w7, [sp, #((7 + \i) << 2)]
STR \w0, [sp, #((16 + \i) << 2)]
.endm
// void SM3_CompressAsm(uint32_t state[8], const uint8_t *data, uint32_t blockCnt);
.globl SM3_CompressAsm
.type SM3_CompressAsm, %function
.align 4
SM3_CompressAsm:
PUSH {v1-ip, lr}
.Lloop_start:
SUBS r2, r2, 1
BCC .Lloop_end
PUSH {r0-r2}
SUB sp, sp, #(52<<2)
ADD r1, #0x40
LDR v3, [r1, #-4]!
LDR v2, [r1, #-4]!
LDR v1, [r1, #-4]!
REV v1, v1
REV v2, v2
REV v3, v3
PUSH {v1-v3}
LDR r12, [r1, #-4]!
LDR r11, [r1, #-4]!
LDR r10, [r1, #-4]!
LDR r9, [r1, #-4]!
LDR r8, [r1, #-4]!
LDR r7, [r1, #-4]!
LDR r6, [r1, #-4]!
LDR r5, [r1, #-4]!
LDR r4, [r1, #-4]!
LDR r3, [r1, #-4]!
LDR r2, [r1, #-4]!
LDR r0, [r1, #-8]!
LDR r1, [r1, #4]
REV r0, r0
REV r1, r1
REV r2, r2
REV r3, r3
REV r4, r4
REV r5, r5
REV r6, r6
REV r7, r7
REV r8, r8
REV r9, r9
REV r10, r10
REV r11, r11
REV r12, r12
PUSH {r0-r12}
MSGEXP r0 r3 r7 r10 r14 0
MSGEXP r1 r4 r8 r11 r0 1
MSGEXP r2 r5 r9 r12 r1 2
MSGEXP r3 r6 r10 r14 r2 3
MSGEXP r4 r7 r11 r0 r3 4
MSGEXP r5 r8 r12 r1 r4 5
MSGEXP r6 r9 r14 r2 r5 6
MSGEXP r7 r10 r0 r3 r6 7
MSGEXP r8 r11 r1 r4 r7 8
MSGEXP r9 r12 r2 r5 r8 9
MSGEXP r10 r14 r3 r6 r9 10
MSGEXP r11 r0 r4 r7 r10 11
MSGEXP r12 r1 r5 r8 r11 12
MSGEXP r14 r2 r6 r9 r12 13
MSGEXP r0 r3 r7 r10 r14 14
MSGEXP r1 r4 r8 r11 r0 15
MSGEXP r2 r5 r9 r12 r1 16
MSGEXP r3 r6 r10 r14 r2 17
MSGEXP r4 r7 r11 r0 r3 18
MSGEXP r5 r8 r12 r1 r4 19
MSGEXP r6 r9 r14 r2 r5 20
MSGEXP r7 r10 r0 r3 r6 21
MSGEXP r8 r11 r1 r4 r7 22
MSGEXP r9 r12 r2 r5 r8 23
MSGEXP r10 r14 r3 r6 r9 24
MSGEXP r11 r0 r4 r7 r10 25
MSGEXP r12 r1 r5 r8 r11 26
MSGEXP r14 r2 r6 r9 r12 27
MSGEXP r0 r3 r7 r10 r14 28
MSGEXP r1 r4 r8 r11 r0 29
MSGEXP r2 r5 r9 r12 r1 30
MSGEXP r3 r6 r10 r14 r2 31
MSGEXP r4 r7 r11 r0 r3 32
MSGEXP r5 r8 r12 r1 r4 33
MSGEXP r6 r9 r14 r2 r5 34
MSGEXP r7 r10 r0 r3 r6 35
MSGEXP r8 r11 r1 r4 r7 36
MSGEXP r9 r12 r2 r5 r8 37
MSGEXP r10 r14 r3 r6 r9 38
MSGEXP r11 r0 r4 r7 r10 39
MSGEXP r12 r1 r5 r8 r11 40
MSGEXP r14 r2 r6 r9 r12 41
MSGEXP r0 r3 r7 r10 r14 42
MSGEXP r1 r4 r8 r11 r0 43
MSGEXP r2 r5 r9 r12 r1 44
MSGEXP r3 r6 r10 r14 r2 45
MSGEXP r4 r7 r11 r0 r3 46
MSGEXP r5 r8 r12 r1 r4 47
MSGEXP r6 r9 r14 r2 r5 48
MSGEXP r7 r10 r0 r3 r6 49
MSGEXP r8 r11 r1 r4 r7 50
MSGEXP r9 r12 r2 r5 r8 51
// Load the state.
LDR r0, =0x79cc4519
LDR r1, [sp, #(68 << 2)]
LDM r1, {v1-v8}
// Note: Since the LDR offset relative to the current PC value cannot exceed 4KB in ARMV7,
// and there are approximately 2000 lines of instructions inside this function that are out of the offset range,
// we declare the literal pool here and skip it.
B 1f
.ltorg
1: // 0-15
RF0 v1 v2 v3 v4 v5 v6 v7 v8 0
RF0 v4 v1 v2 v3 v8 v5 v6 v7 1
RF0 v3 v4 v1 v2 v7 v8 v5 v6 2
RF0 v2 v3 v4 v1 v6 v7 v8 v5 3
RF0 v1 v2 v3 v4 v5 v6 v7 v8 4
RF0 v4 v1 v2 v3 v8 v5 v6 v7 5
RF0 v3 v4 v1 v2 v7 v8 v5 v6 6
RF0 v2 v3 v4 v1 v6 v7 v8 v5 7
RF0 v1 v2 v3 v4 v5 v6 v7 v8 8
RF0 v4 v1 v2 v3 v8 v5 v6 v7 9
RF0 v3 v4 v1 v2 v7 v8 v5 v6 10
RF0 v2 v3 v4 v1 v6 v7 v8 v5 11
RF0 v1 v2 v3 v4 v5 v6 v7 v8 12
RF0 v4 v1 v2 v3 v8 v5 v6 v7 13
RF0 v3 v4 v1 v2 v7 v8 v5 v6 14
RF0 v2 v3 v4 v1 v6 v7 v8 v5 15
// 16-31
LDR r0 , =0x7a879d8a
RF1 v1 v2 v3 v4 v5 v6 v7 v8 16
RF1 v4 v1 v2 v3 v8 v5 v6 v7 17
RF1 v3 v4 v1 v2 v7 v8 v5 v6 18
RF1 v2 v3 v4 v1 v6 v7 v8 v5 19
RF1 v1 v2 v3 v4 v5 v6 v7 v8 20
RF1 v4 v1 v2 v3 v8 v5 v6 v7 21
RF1 v3 v4 v1 v2 v7 v8 v5 v6 22
RF1 v2 v3 v4 v1 v6 v7 v8 v5 23
RF1 v1 v2 v3 v4 v5 v6 v7 v8 24
RF1 v4 v1 v2 v3 v8 v5 v6 v7 25
RF1 v3 v4 v1 v2 v7 v8 v5 v6 26
RF1 v2 v3 v4 v1 v6 v7 v8 v5 27
RF1 v1 v2 v3 v4 v5 v6 v7 v8 28
RF1 v4 v1 v2 v3 v8 v5 v6 v7 29
RF1 v3 v4 v1 v2 v7 v8 v5 v6 30
RF1 v2 v3 v4 v1 v6 v7 v8 v5 31
// 32-47
RF1 v1 v2 v3 v4 v5 v6 v7 v8 32
RF1 v4 v1 v2 v3 v8 v5 v6 v7 33
RF1 v3 v4 v1 v2 v7 v8 v5 v6 34
RF1 v2 v3 v4 v1 v6 v7 v8 v5 35
RF1 v1 v2 v3 v4 v5 v6 v7 v8 36
RF1 v4 v1 v2 v3 v8 v5 v6 v7 37
RF1 v3 v4 v1 v2 v7 v8 v5 v6 38
RF1 v2 v3 v4 v1 v6 v7 v8 v5 39
RF1 v1 v2 v3 v4 v5 v6 v7 v8 40
RF1 v4 v1 v2 v3 v8 v5 v6 v7 41
RF1 v3 v4 v1 v2 v7 v8 v5 v6 42
RF1 v2 v3 v4 v1 v6 v7 v8 v5 43
RF1 v1 v2 v3 v4 v5 v6 v7 v8 44
RF1 v4 v1 v2 v3 v8 v5 v6 v7 45
RF1 v3 v4 v1 v2 v7 v8 v5 v6 46
RF1 v2 v3 v4 v1 v6 v7 v8 v5 47
// 48-63
RF1 v1 v2 v3 v4 v5 v6 v7 v8 48
RF1 v4 v1 v2 v3 v8 v5 v6 v7 49
RF1 v3 v4 v1 v2 v7 v8 v5 v6 50
RF1 v2 v3 v4 v1 v6 v7 v8 v5 51
RF1 v1 v2 v3 v4 v5 v6 v7 v8 52
RF1 v4 v1 v2 v3 v8 v5 v6 v7 53
RF1 v3 v4 v1 v2 v7 v8 v5 v6 54
RF1 v2 v3 v4 v1 v6 v7 v8 v5 55
RF1 v1 v2 v3 v4 v5 v6 v7 v8 56
RF1 v4 v1 v2 v3 v8 v5 v6 v7 57
RF1 v3 v4 v1 v2 v7 v8 v5 v6 58
RF1 v2 v3 v4 v1 v6 v7 v8 v5 59
RF1 v1 v2 v3 v4 v5 v6 v7 v8 60
RF1 v4 v1 v2 v3 v8 v5 v6 v7 61
RF1 v3 v4 v1 v2 v7 v8 v5 v6 62
RF1 v2 v3 v4 v1 v6 v7 v8 v5 63
// Load the state back and update it.
ADD sp, sp, #16
LDR ip, [sp]
LDM ip!, {r0-r3}
EOR v1, r0
EOR v2, r1
EOR v3, r2
EOR v4, r3
LDM ip!, {r0-r3}
EOR v5, r0
EOR v6, r1
EOR v7, r2
EOR v8, r3
STMDB ip, {v1-v8}
POP {r0-r2}
ADD r1, r1, #0x40
B .Lloop_start
.Lloop_end:
POP {v1-ip, lr}
MOV pc, lr
.end
#endif | 2302_82127028/openHiTLS-examples_1508 | crypto/sm3/src/asm/sm3_armv7.S | Unix Assembly | unknown | 10,036 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SM3
#include "crypt_arm.h"
.arch armv8-a+crypto
// The first 16 of the compression function, w13 is Tj.
.macro first16 A B C D E F G H W1 W2
ror w13, w13, #31
ror w10, \A, #20
add w9, \E, w10
eor w12, \E, \F
ror \F, \F, #13
eor w12, w12, \G
add w12, w12, \H
add w9, w9, w13
ror w9, w9, #25
add w12, w12, w9
eor w10, w10, w9
add w12, w12, \W1
eor \H, w12, w12, ror #23
ror w9, w12, #15
eor \H, \H, w9
eor w11, \A, \B
ror \B, \B, #23
eor w11, w11, \C
add w11, w11, \D
add w11, w11, w10
eor w9, \W1, \W2
add \D, w11, w9
.endm
// Compress the last 48 of the function, w13 is Tj
.macro second48 A B C D E F G H W1 W2
ror w13, w13, #31
orr w11, \B, \C
eor w12, \F, \G
ror \F, \F, #13
ror w10, \A, #20
add w9, w10, \E
and w14, \A, w11
and w12, w12, \E
eor w12, w12, \G
add w12, w12, \H
add w9, w9, w13
ror w9, w9, #25
add w12, w12, w9
eor w10, w10, w9
add w12, w12, \W1
and w11, \B, \C
ror \B, \B, #23
orr w11, w11, w14
eor w9, \W1, \W2
add w11, w11, \D
add w11, w11, w10
add \D, w11, w9
eor \H, w12, w12, ror #23
ror w9, w12, #15
eor \H, \H, w9
.endm
// void SM3_CompressAsm(uint32_t state[8], const uint8_t *data, uint32_t blockCnt);
.globl SM3_CompressAsm
.type SM3_CompressAsm, %function
.align 4
SM3_CompressAsm:
AARCH64_PACIASP
sub sp, sp, 128
stp x19, x20, [sp]
stp x21, x22, [sp, #16]
stp x23, x24, [sp, #32]
stp x25, x26, [sp, #48]
// According to the calling convention, this function needs to be saved.
stp d8, d9, [sp, #64]
stp d10, d11, [sp, #80]
stp d12, d13, [sp, #96]
stp d14, d15, [sp, #112]
sub sp, sp, 64
mov x25, sp
sub sp, sp, 64
mov x26, sp
mov x22, x0 // x22: state
mov x23, x1 // x23: data
mov w24, w2 // x24: blockCnt
// w0-w7: ABCDEFGH word register in"SM3 cryptographic hash algorithm"
ldp w0, w1, [x22]
ldp w2, w3, [x22, #8]
ldp w4, w5, [x22, #16]
ldp w6, w7, [x22, #24]
prfm pldl1keep, [x23, #64]
blocksloop_1:
subs w24, w24, #1
bmi end
// Due to the SM3 feature, only three messages can be extended in parallel.
// You need to use ext to ensure that the data meets the requirements for calculation.
// To reduce the delay, the message expansion is calculated together with the compression function,
// and the compression function is calculated three times for every three Ws.
// v0-v3 message group w0-w15
ld1 {v0.4s-v3.4s}, [x23]
#ifndef HITLS_BIG_ENDIAN
rev32 v0.16B, v0.16B
rev32 v1.16B, v1.16B
rev32 v2.16B, v2.16B
rev32 v3.16B, v3.16B
#endif
ldp w15, w20, [x23]
ldp w19, w21, [x23, #16]
#ifndef HITLS_BIG_ENDIAN
rev w15, w15
rev w19, w19
rev w20, w20
rev w21, w21
#endif
ext v24.16b, v3.16b, v3.16b, #4 // 13, 14, 15
ext v25.16b, v0.16b, v1.16b, #12 // 3, 4, 5
ext v23.16b, v1.16b, v2.16b, #12 // 7, 8, 9
ext v26.16b, v2.16b, v3.16b, #8 // 10, 11, 12
eor v27.16b, v0.16b, v23.16b
// w13: constant Tj , 0 <= j <= 16
mov w13, #0x228c
movk w13, #0xbce6, lsl #16
// Message grouping: Wj−3 ≪ 15, Wj−13 ≪ 7
shl v21.4s, v24.4s, #15
shl v22.4s, v25.4s, #7
sri v21.4s, v24.4s, #17 // 13, 14, 15<<<15
sri v22.4s, v25.4s, #25 // 3, 4, 5<<<7
first16 w0 w1 w2 w3 w4 w5 w6 w7 w15 w19
eor v27.16b, v21.16b, v27.16b
eor v28.16b, v22.16b, v26.16b
first16 w3 w0 w1 w2 w7 w4 w5 w6 w20 w21
// permutation function P1: X ^ (X ≪ 15) ^ (X ≪ 23)
shl v29.4s, v27.4s, #15
shl v30.4s, v27.4s, #23
sri v29.4s, v27.4s, #17
sri v30.4s, v27.4s, #9
eor v27.16b, v27.16b, v29.16b
ldp w15, w20, [x23, #8]
ldp w19, w21, [x23, #24]
#ifndef HITLS_BIG_ENDIAN
rev w15, w15
rev w19, w19
rev w20, w20
rev w21, w21
#endif
eor v27.16b, v27.16b, v30.16b
first16 w2 w3 w0 w1 w6 w7 w4 w5 w15 w19
eor v4.16b, v27.16b, v28.16b
// 2:19, 20, 21
ext v23.16b, v1.16b, v2.16b, #8 // 6, 7, 8
eor v27.16b, v25.16b, v26.16b
first16 w1 w2 w3 w0 w5 w6 w7 w4 w20 w21
shl v21.4s, v4.4s, #15
shl v22.4s, v23.4s, #7
sri v21.4s, v4.4s, #17 // 16, 17, 18<<<15
sri v22.4s, v23.4s, #25 // 6, 7, 8<<<7
ldp w15, w20, [x23, #16]
ldp w19, w21, [x23, #32]
#ifndef HITLS_BIG_ENDIAN
rev w15, w15
rev w19, w19
rev w20, w20
rev w21, w21
#endif
eor v27.16b, v21.16b, v27.16b
eor v28.16b, v22.16b, v24.16b
first16 w0 w1 w2 w3 w4 w5 w6 w7 w15 w19
shl v29.4s, v27.4s, #15
shl v30.4s, v27.4s, #23
sri v29.4s, v27.4s, #17
sri v30.4s, v27.4s, #9
eor v27.16b, v27.16b, v29.16b
first16 w3 w0 w1 w2 w7 w4 w5 w6 w20 w21
eor v27.16b, v27.16b, v30.16b
mov v4.s[3], v4.s[2] // Due to ext requirements, to fill s[3]
eor v5.16b, v27.16b, v28.16b
// 3:22, 23, 24
ext v25.16b, v2.16b, v3.16b, #4 // 9, 10, 11
eor v27.16b, v23.16b, v24.16b
ldp w15, w20, [x23, #24]
ldp w19, w21, [x23, #40]
#ifndef HITLS_BIG_ENDIAN
rev w15, w15
rev w19, w19
rev w20, w20
rev w21, w21
#endif
shl v21.4s, v5.4s, #15
shl v22.4s, v25.4s, #7
sri v21.4s, v5.4s, #17 // 19, 20, 21<<<15
sri v22.4s, v25.4s, #25 // 9, 10, 11<<<7
first16 w2 w3 w0 w1 w6 w7 w4 w5 w15 w19
eor v27.16b, v21.16b, v27.16b
eor v28.16b, v22.16b, v4.16b
first16 w1 w2 w3 w0 w5 w6 w7 w4 w20 w21
shl v29.4s, v27.4s, #15
shl v30.4s, v27.4s, #23
sri v29.4s, v27.4s, #17
sri v30.4s, v27.4s, #9
eor v27.16b, v27.16b, v29.16b
ldp w15, w20, [x23, #32]
ldp w19, w21, [x23, #48]
#ifndef HITLS_BIG_ENDIAN
rev w15, w15
rev w19, w19
rev w20, w20
rev w21, w21
#endif
first16 w0 w1 w2 w3 w4 w5 w6 w7 w15 w19
eor v27.16b, v27.16b, v30.16b
mov v5.s[3], v5.s[2] // Due to ext requirements, to fill s[3]
eor v6.16b, v27.16b, v28.16b
// 4:25, 26, 27
eor v27.16b, v25.16b, v4.16b
shl v21.4s, v6.4s, #15
shl v22.4s, v3.4s, #7
sri v21.4s, v6.4s, #17 // 22, 23, 24<<<15
sri v22.4s, v3.4s, #25 // 12, 13, 14<<<7
first16 w3 w0 w1 w2 w7 w4 w5 w6 w20 w21
eor v27.16b, v21.16b, v27.16b
eor v28.16b, v22.16b, v5.16b
ldp w15, w20, [x23, #40]
ldp w19, w21, [x23, #56]
#ifndef HITLS_BIG_ENDIAN
rev w15, w15
rev w19, w19
rev w20, w20
rev w21, w21
#endif
shl v29.4s, v27.4s, #15
shl v30.4s, v27.4s, #23
sri v29.4s, v27.4s, #17
sri v30.4s, v27.4s, #9
first16 w2 w3 w0 w1 w6 w7 w4 w5 w15 w19
eor v27.16b, v27.16b, v29.16b
first16 w1 w2 w3 w0 w5 w6 w7 w4 w20 w21
eor v27.16b, v27.16b, v30.16b
mov v6.s[3], v6.s[2] // Due to ext requirements, to fill s[3]
eor v7.16b, v27.16b, v28.16b
// 5:28, 29, 30
ext v23.16b, v3.16b, v4.16b, #12 // 15, 16, 17
eor v27.16b, v3.16b, v5.16b
st1 {v4.4s-v7.4s}, [x25] // There is a redundant data for every four 32-bit bits of the stored data.
// The data needs to be read in a skip manner.
shl v21.4s, v7.4s, #15
shl v22.4s, v23.4s, #7
sri v21.4s, v7.4s, #17 // 25, 26, 27<<<15
sri v22.4s, v23.4s, #25 // 15, 16, 17<<<7
ldp w15, w20, [x23, #48]
ldp w19, w21, [x25]
#ifndef HITLS_BIG_ENDIAN
rev w15, w15
rev w20, w20
#endif
first16 w0 w1 w2 w3 w4 w5 w6 w7 w15 w19
eor v27.16b, v21.16b, v27.16b
eor v28.16b, v22.16b, v6.16b
shl v29.4s, v27.4s, #15
shl v30.4s, v27.4s, #23
sri v29.4s, v27.4s, #17
sri v30.4s, v27.4s, #9
eor v27.16b, v27.16b, v29.16b
first16 w3 w0 w1 w2 w7 w4 w5 w6 w20 w21
ldp w15, w20, [x23, #56]
#ifndef HITLS_BIG_ENDIAN
rev w15, w15
rev w20, w20
#endif
add x23, x23, #64
prfm pldl1keep, [x23, #64]
ldr w19, [x25, #8]
ldr w21, [x25, #16]
eor v27.16b, v27.16b, v30.16b
first16 w2 w3 w0 w1 w6 w7 w4 w5 w15 w19
mov v7.s[3], v7.s[2] // Due to ext requirements, to fill s[3]
eor v8.16b, v27.16b, v28.16b
// Message extension completed. Continue with the next 48 compression.
ext v24.16b, v4.16b, v5.16b, #12 // 18, 19, 20
eor v27.16b, v23.16b, v6.16b
first16 w1 w2 w3 w0 w5 w6 w7 w4 w20 w21
shl v21.4s, v8.4s, #15
shl v22.4s, v24.4s, #7
sri v21.4s, v8.4s, #17 // 28, 29, 30<<<15
sri v22.4s, v24.4s, #25 // 18, 19, 20<<<7
ldp w15, w20, [x25]
ldp w19, w21, [x25, #20]
eor v27.16b, v21.16b, v27.16b
eor v28.16b, v22.16b, v7.16b
// w13: constant Tj , 17 <= j <= 63
mov w13, #0x3d43
movk w13, #0xcec5, lsl #16
second48 w0 w1 w2 w3 w4 w5 w6 w7 w15 w19
shl v29.4s, v27.4s, #15
shl v30.4s, v27.4s, #23
sri v29.4s, v27.4s, #17
sri v30.4s, v27.4s, #9
eor v27.16b, v27.16b, v29.16b
second48 w3 w0 w1 w2 w7 w4 w5 w6 w20 w21
eor v27.16b, v27.16b, v30.16b
mov v8.s[3], v8.s[2] // Due to ext requirements, to fill s[3]
eor v9.16b, v27.16b, v28.16b
// 7:34, 35, 36
ext v23.16b, v5.16b, v6.16b, #12 // 21, 22, 23
eor v27.16b, v24.16b, v7.16b
ldr w15, [x25, #8]
ldr w20, [x25, #16]
ldp w19, w21, [x25, #32]
shl v21.4s, v9.4s, #15
shl v22.4s, v23.4s, #7
sri v21.4s, v9.4s, #17 // 31, 32, 33<<<15
sri v22.4s, v23.4s, #25 // 21, 22, 23<<<7
second48 w2 w3 w0 w1 w6 w7 w4 w5 w15 w19
eor v27.16b, v21.16b, v27.16b
eor v28.16b, v22.16b, v8.16b
second48 w1 w2 w3 w0 w5 w6 w7 w4 w20 w21
shl v29.4s, v27.4s, #15
shl v30.4s, v27.4s, #23
sri v29.4s, v27.4s, #17
sri v30.4s, v27.4s, #9
eor v27.16b, v27.16b, v29.16b
ldp w15, w20, [x25, #20]
ldr w19, [x25, #40]
ldr w21, [x25, #48]
eor v27.16b, v27.16b, v30.16b
second48 w0 w1 w2 w3 w4 w5 w6 w7 w15 w19
mov v9.s[3], v9.s[2] // Due to ext requirements, to fill s[3]
eor v10.16b, v27.16b, v28.16b
// 8:37, 38, 39
ext v24.16b, v6.16b, v7.16b, #12 // 24, 25, 26
eor v27.16b, v23.16b, v8.16b
second48 w3 w0 w1 w2 w7 w4 w5 w6 w20 w21
shl v21.4s, v10.4s, #15
shl v22.4s, v24.4s, #7
sri v21.4s, v10.4s, #17 // 34, 35, 36<<<15
sri v22.4s, v24.4s, #25 // 24, 25, 26<<<7
ldp w15, w20, [x25, #32]
ldp w19, w21, [x25, #52]
eor v27.16b, v21.16b, v27.16b
eor v28.16b, v22.16b, v9.16b
second48 w2 w3 w0 w1 w6 w7 w4 w5 w15 w19
shl v29.4s, v27.4s, #15
shl v30.4s, v27.4s, #23
sri v29.4s, v27.4s, #17
sri v30.4s, v27.4s, #9
eor v27.16b, v27.16b, v29.16b
second48 w1 w2 w3 w0 w5 w6 w7 w4 w20 w21
eor v27.16b, v27.16b, v30.16b
mov v10.s[3], v10.s[2] // Due to ext requirements, to fill s[3]
eor v11.16b, v27.16b, v28.16b
// 9:40, 41, 42
ext v23.16b, v7.16b, v8.16b, #12 // 27, 28, 29
eor v27.16b, v24.16b, v9.16b
st1 {v8.4s-v11.4s}, [x26]
shl v21.4s, v11.4s, #15
shl v22.4s, v23.4s, #7
sri v21.4s, v11.4s, #17 // 37, 38, 39<<<15
sri v22.4s, v23.4s, #25 // 27, 28, 29<<<7
ldr w15, [x25, #40]
ldr w20, [x25, #48]
ldp w19, w21, [x26]
second48 w0 w1 w2 w3 w4 w5 w6 w7 w15 w19
eor v27.16b, v21.16b, v27.16b
eor v28.16b, v22.16b, v10.16b
second48 w3 w0 w1 w2 w7 w4 w5 w6 w20 w21
shl v29.4s, v27.4s, #15
shl v30.4s, v27.4s, #23
sri v29.4s, v27.4s, #17
sri v30.4s, v27.4s, #9
eor v27.16b, v27.16b, v29.16b
ldp w15, w20, [x25, #52]
ldr w19, [x26, #8]
ldr w21, [x26, #16]
eor v27.16b, v27.16b, v30.16b
second48 w2 w3 w0 w1 w6 w7 w4 w5 w15 w19
mov v11.s[3], v11.s[2] // Due to ext requirements, to fill s[3]
eor v12.16b, v27.16b, v28.16b
// 10:43, 44, 45
ext v24.16b, v8.16b, v9.16b, #12 // 30, 31, 32
eor v27.16b, v23.16b, v10.16b
second48 w1 w2 w3 w0 w5 w6 w7 w4 w20 w21
shl v21.4s, v12.4s, #15
shl v22.4s, v24.4s, #7
sri v21.4s, v12.4s, #17 // 40, 41, 42<<<15
sri v22.4s, v24.4s, #25 // 30, 31, 32<<<7
ldp w15, w20, [x26]
ldp w19, w21, [x26, #20]
eor v27.16b, v21.16b, v27.16b
eor v28.16b, v22.16b, v11.16b
second48 w0 w1 w2 w3 w4 w5 w6 w7 w15 w19
shl v29.4s, v27.4s, #15
shl v30.4s, v27.4s, #23
sri v29.4s, v27.4s, #17
sri v30.4s, v27.4s, #9
eor v27.16b, v27.16b, v29.16b
second48 w3 w0 w1 w2 w7 w4 w5 w6 w20 w21
eor v27.16b, v27.16b, v30.16b
mov v12.s[3], v12.s[2] // Due to ext requirements, to fill s[3]
eor v13.16b, v27.16b, v28.16b
// 11:46, 47, 48
ext v23.16b, v9.16b, v10.16b, #12 // 33, 34, 35
eor v27.16b, v24.16b, v11.16b
ldr w15, [x26, #8]
ldr w20, [x26, #16]
ldp w19, w21, [x26, #32]
shl v21.4s, v13.4s, #15
shl v22.4s, v23.4s, #7
sri v21.4s, v13.4s, #17 // 43, 44, 45<<<15
sri v22.4s, v23.4s, #25 // 33, 34, 35<<<7
second48 w2 w3 w0 w1 w6 w7 w4 w5 w15 w19
eor v27.16b, v21.16b, v27.16b
eor v28.16b, v22.16b, v12.16b
second48 w1 w2 w3 w0 w5 w6 w7 w4 w20 w21
shl v29.4s, v27.4s, #15
shl v30.4s, v27.4s, #23
sri v29.4s, v27.4s, #17
sri v30.4s, v27.4s, #9
eor v27.16b, v27.16b, v29.16b
ldp w15, w20, [x26, #20]
ldr w19, [x26, #40]
ldr w21, [x26, #48]
second48 w0 w1 w2 w3 w4 w5 w6 w7 w15 w19
eor v27.16b, v27.16b, v30.16b
mov v13.s[3], v13.s[2] // Due to ext requirements, to fill s[3]
eor v14.16b, v27.16b, v28.16b
// 12:49, 50, 51
ext v24.16b, v10.16b, v11.16b, #12 // 36, 37, 38
eor v27.16b, v23.16b, v12.16b
second48 w3 w0 w1 w2 w7 w4 w5 w6 w20 w21
shl v21.4s, v14.4s, #15
shl v22.4s, v24.4s, #7
sri v21.4s, v14.4s, #17 // 46, 47, 48<<<15
sri v22.4s, v24.4s, #25 // 36, 37, 38<<<7
ldp w15, w20, [x26, #32]
ldp w19, w21, [x26, #52]
eor v27.16b, v21.16b, v27.16b
eor v28.16b, v22.16b, v13.16b
second48 w2 w3 w0 w1 w6 w7 w4 w5 w15 w19
shl v29.4s, v27.4s, #15
shl v30.4s, v27.4s, #23
sri v29.4s, v27.4s, #17
sri v30.4s, v27.4s, #9
eor v27.16b, v27.16b, v29.16b
second48 w1 w2 w3 w0 w5 w6 w7 w4 w20 w21
eor v27.16b, v27.16b, v30.16b
mov v14.s[3], v14.s[2] // Due to ext requirements, to fill s[3]
eor v15.16b, v27.16b, v28.16b
// 13:52, 53, 54
ext v23.16b, v11.16b, v12.16b, #12 // 39, 40, 41
eor v27.16b, v24.16b, v13.16b
st1 {v12.4s-v15.4s}, [x25]
shl v21.4s, v15.4s, #15
shl v22.4s, v23.4s, #7
sri v21.4s, v15.4s, #17 // 49, 50, 51<<<15
sri v22.4s, v23.4s, #25 // 39, 40, 41<<<7
ldr w15, [x26, #40]
ldr w20, [x26, #48]
ldp w19, w21, [x25]
second48 w0 w1 w2 w3 w4 w5 w6 w7 w15 w19
eor v27.16b, v21.16b, v27.16b
eor v28.16b, v22.16b, v14.16b
second48 w3 w0 w1 w2 w7 w4 w5 w6 w20 w21
shl v29.4s, v27.4s, #15
shl v30.4s, v27.4s, #23
sri v29.4s, v27.4s, #17
sri v30.4s, v27.4s, #9
eor v27.16b, v27.16b, v29.16b
ldp w15, w20, [x26, #52]
ldr w19, [x25, #8]
ldr w21, [x25, #16]
second48 w2 w3 w0 w1 w6 w7 w4 w5 w15 w19
eor v27.16b, v27.16b, v30.16b
mov v15.s[3], v15.s[2] // Due to ext requirements, to fill s[3]
eor v16.16b, v27.16b, v28.16b
// 14:55, 56, 57
ext v24.16b, v12.16b, v13.16b, #12 // 42, 43, 44
eor v27.16b, v23.16b, v14.16b
shl v21.4s, v16.4s, #15
shl v22.4s, v24.4s, #7
sri v21.4s, v16.4s, #17 // 52, 53, 54<<<15
sri v22.4s, v24.4s, #25 // 42, 43, 44<<<7
second48 w1 w2 w3 w0 w5 w6 w7 w4 w20 w21
eor v27.16b, v21.16b, v27.16b
eor v28.16b, v22.16b, v15.16b
ldp w15, w20, [x25]
ldp w19, w21, [x25, #20]
shl v29.4s, v27.4s, #15
shl v30.4s, v27.4s, #23
sri v29.4s, v27.4s, #17
sri v30.4s, v27.4s, #9
eor v27.16b, v27.16b, v29.16b
second48 w0 w1 w2 w3 w4 w5 w6 w7 w15 w19
eor v27.16b, v27.16b, v30.16b
second48 w3 w0 w1 w2 w7 w4 w5 w6 w20 w21
mov v16.s[3], v16.s[2] // Due to ext requirements, to fill s[3]
eor v17.16b, v27.16b, v28.16b
// 15:58, 59, 60
ext v23.16b, v13.16b, v14.16b, #12 // 45, 46, 47
eor v27.16b, v24.16b, v15.16b
shl v21.4s, v17.4s, #15
shl v22.4s, v23.4s, #7
sri v21.4s, v17.4s, #17 // 55, 56, 57<<<15
sri v22.4s, v23.4s, #25 // 45, 46, 47<<<7
ldr w15, [x25, #8]
ldr w20, [x25, #16]
ldp w19, w21, [x25, #32]
second48 w2 w3 w0 w1 w6 w7 w4 w5 w15 w19
eor v27.16b, v21.16b, v27.16b
eor v28.16b, v22.16b, v16.16b
second48 w1 w2 w3 w0 w5 w6 w7 w4 w20 w21
shl v29.4s, v27.4s, #15
shl v30.4s, v27.4s, #23
sri v29.4s, v27.4s, #17
sri v30.4s, v27.4s, #9
eor v27.16b, v27.16b, v29.16b
ldp w15, w20, [x25, #20]
ldr w19, [x25, #40]
ldr w21, [x25, #48]
second48 w0 w1 w2 w3 w4 w5 w6 w7 w15 w19
eor v27.16b, v27.16b, v30.16b
eor v18.16b, v27.16b, v28.16b
// 16:61, 62, 63
ext v24.16b, v14.16b, v15.16b, #12 // 48, 49, 50
eor v27.16b, v23.16b, v16.16b
shl v21.4s, v18.4s, #15
shl v22.4s, v24.4s, #7
sri v21.4s, v18.4s, #17 // 58, 59, 60<<<15
sri v22.4s, v24.4s, #25 // 48, 49, 50<<<7
second48 w3 w0 w1 w2 w7 w4 w5 w6 w20 w21
eor v27.16b, v21.16b, v27.16b
eor v28.16b, v22.16b, v17.16b
ldp w15, w20, [x25, #32]
ldp w19, w21, [x25, #52]
shl v29.4s, v27.4s, #15
shl v30.4s, v27.4s, #23
sri v29.4s, v27.4s, #17
sri v30.4s, v27.4s, #9
eor v27.16b, v27.16b, v29.16b
second48 w2 w3 w0 w1 w6 w7 w4 w5 w15 w19
eor v27.16b, v27.16b, v30.16b
second48 w1 w2 w3 w0 w5 w6 w7 w4 w20 w21
eor v19.16b, v27.16b, v28.16b
// 17:64, 65, 66
ext v23.16b, v15.16b, v16.16b, #12 // 51, 52, 53
eor v27.16b, v24.16b, v17.16b
st1 {v16.4s-v19.4s}, [x26]
shl v21.4s, v19.4s, #15
shl v22.4s, v23.4s, #7
sri v21.4s, v19.4s, #17 // 61, 62, 63<<<15
sri v22.4s, v23.4s, #25 // 51, 52, 53<<<7
ldr w15, [x25, #40]
ldr w20, [x25, #48]
ldp w19, w21, [x26]
second48 w0 w1 w2 w3 w4 w5 w6 w7 w15 w19
eor v27.16b, v21.16b, v27.16b
eor v28.16b, v22.16b, v18.16b
second48 w3 w0 w1 w2 w7 w4 w5 w6 w20 w21
shl v29.4s, v27.4s, #15
shl v30.4s, v27.4s, #23
sri v29.4s, v27.4s, #17
sri v30.4s, v27.4s, #9
eor v27.16b, v27.16b, v29.16b
ldp w15, w20, [x25, #52]
ldr w19, [x26, #8]
ldr w21, [x26, #16]
eor v27.16b, v27.16b, v30.16b
second48 w2 w3 w0 w1 w6 w7 w4 w5 w15 w19
eor v20.16b, v27.16b, v28.16b
// 18:67
ext v24.16b, v16.16b, v17.16b, #12 // 54, 55, 56
eor v27.16b, v23.16b, v18.16b
shl v21.4s, v20.4s, #15
shl v22.4s, v24.4s, #7
sri v21.4s, v20.4s, #17 // 64, 65, 66<<<15
sri v22.4s, v24.4s, #25 // 54, 55, 56<<<7
second48 w1 w2 w3 w0 w5 w6 w7 w4 w20 w21
eor v27.16b, v21.16b, v27.16b
eor v28.16b, v22.16b, v19.16b
ldp w15, w20, [x26]
ldp w19, w21, [x26, #20]
shl v29.4s, v27.4s, #15
shl v30.4s, v27.4s, #23
sri v29.4s, v27.4s, #17
sri v30.4s, v27.4s, #9
eor v27.16b, v27.16b, v29.16b
second48 w0 w1 w2 w3 w4 w5 w6 w7 w15 w19
eor v27.16b, v27.16b, v30.16b
second48 w3 w0 w1 w2 w7 w4 w5 w6 w20 w21
eor v21.16b, v27.16b, v28.16b
ldr w15, [x26, #8]
ldr w20, [x26, #16]
ldp w19, w21, [x26, #32]
second48 w2 w3 w0 w1 w6 w7 w4 w5 w15 w19
st1 {v20.4s-v21.4s}, [x25]
second48 w1 w2 w3 w0 w5 w6 w7 w4 w20 w21
ldp w15, w20, [x26, #20]
ldr w19, [x26, #40]
ldr w21, [x26, #48]
second48 w0 w1 w2 w3 w4 w5 w6 w7 w15 w19
second48 w3 w0 w1 w2 w7 w4 w5 w6 w20 w21
ldp w15, w20, [x26, #32]
ldp w19, w21, [x26, #52]
second48 w2 w3 w0 w1 w6 w7 w4 w5 w15 w19
second48 w1 w2 w3 w0 w5 w6 w7 w4 w20 w21
ldr w15, [x26, #40]
ldr w20, [x26, #48]
ldp w19, w21, [x25]
second48 w0 w1 w2 w3 w4 w5 w6 w7 w15 w19
second48 w3 w0 w1 w2 w7 w4 w5 w6 w20 w21
ldp w15, w20, [x26, #52]
ldr w19, [x25, #8]
ldr w21, [x25, #16]
second48 w2 w3 w0 w1 w6 w7 w4 w5 w15 w19
second48 w1 w2 w3 w0 w5 w6 w7 w4 w20 w21
ldp w9, w10, [x22] // XOR with the previous hash result
ldp w11, w12, [x22, #8]
ldp w13, w14, [x22, #16]
ldp w15, w19, [x22, #24]
eor w0, w0, w9
eor w1, w1, w10
eor w2, w2, w11
eor w3, w3, w12
eor w4, w4, w13
eor w5, w5, w14
eor w6, w6, w15
eor w7, w7, w19
stp w0, w1, [x22] // Result saving
stp w2, w3, [x22, #8]
stp w4, w5, [x22, #16]
stp w6, w7, [x22, #24]
b blocksloop_1
end:
add sp, sp, 128
ldp x19, x20, [sp]
ldp x21, x22, [sp, #16]
ldp x23, x24, [sp, #32]
ldp x25, x26, [sp, #48]
ldp d8, d9, [sp, #64]
ldp d10, d11, [sp, #80]
ldp d12, d13, [sp, #96]
ldp d14, d15, [sp, #112]
add sp, sp, 128
AARCH64_AUTIASP
ret
.size SM3_CompressAsm,.-SM3_CompressAsm
#endif
| 2302_82127028/openHiTLS-examples_1508 | crypto/sm3/src/asm/sm3_armv8.S | Motorola 68K Assembly | unknown | 21,152 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SM3
.file "sm3_x86_64.s"
.text
.set A,%r8d
.set B,%r9d
.set C,%r10d
.set D,%r11d
.set E,%r12d
.set F,%r13d
.set G,%r14d
.set H,%r15d
.set STATE,%rdi
.set DATA,%rsi
.set NUM,%rdx
.set ADDR,%rax
.set BOOL_OUT,%eax
.set SS1,%ebx
.set SS2,%eax
.set X0,%xmm0
.set X1,%xmm1
.set X2,%xmm2
.set X3,%xmm3
.set X4,%xmm4
.set X5,%xmm5
.set X6,%xmm6
.set X7,%xmm7
.set R16,%xmm13
.set R24,%xmm14
.set SHUFFLEMASK,%xmm15
.macro FF0 X Y Z
# X ^ Y ^ Z
movl \X,%eax
xorl \Y,%eax
xorl \Z,%eax
.endm
.macro FF1 X Y Z
# (X & Y) | (X & Z) | (Y & Z)
# = (X & (Y | Z)) | (Y & Z)
movl \Y,%eax
movl %eax,%ebx
orl \Z,%eax
andl \Z,%ebx
andl \X,%eax
orl %ebx,%eax
.endm
.macro GG0 X Y Z
FF0 \X \Y \Z
.endm
.macro GG1 X Y Z
# (X & Y) | (~X & Z)
movl \X,%ebx
andn \Z,%ebx,%eax
andl \Y,%ebx
orl %ebx,%eax
.endm
.macro P0 X
rorx $15,\X,%eax
rorx $23,\X,%ebx
xorl %eax,\X
xorl %ebx,\X
.endm
.macro P1 X
rorx $9,\X,%eax
rorx $17,\X,%ebx
xorl %eax,\X
xorl %ebx,\X
.endm
.macro ROUND FF GG Ar Br Cr Dr Er Fr Gr Hr TJ
# A <<< 12
rorx $20,\Ar,%eax
# SS1 (%ebx) <- ((A <<< 12) + E + (Tj <<< (jmod32))) <<< 7
# pre-computed TJ = Tj <<< (jmod32)
movl %eax,%ebx
addl \Er,%ebx
addl $\TJ,%ebx
rorx $25,%ebx,SS1
# SS2 (%eax) <- SS1 ^ (A <<< 12)
xorl SS1,SS2
# TT1 (D) <- FF(A,B,C) + D + SS2 + W(i)'
# TT2 (H) <- GG(E,F,G) + H + SS1 + W(i)
addl SS2,\Dr
addl SS1,\Hr
# FF(A,B,C)
\FF \Ar \Br \Cr
addl BOOL_OUT,\Dr
# GG(E,F,G)
\GG \Er \Fr \Gr
addl BOOL_OUT,\Hr
# B <- B <<< 9
rorx $23,\Br,\Br
# F <- F <<< 19
rorx $13,\Fr,\Fr
# P0(TT2)
P0 \Hr
.endm
.macro ROUND_00_15 Ar Br Cr Dr Er Fr Gr Hr TJ WADDR WPADDR
# H <- H + W(i)
# D <- D + W(i)'
addl \WADDR(%rsp),\Hr
addl \WPADDR(%rsp),\Dr
ROUND FF0 GG0 \Ar \Br \Cr \Dr \Er \Fr \Gr \Hr \TJ
.endm
.macro ROUND_16_63 Ar Br Cr Dr Er Fr Gr Hr TJ WADDR WPADDR
# H <- H + W(i)
# D <- D + W(i)'
addl \WADDR(%rsp),\Hr
addl \WPADDR(%rsp),\Dr
ROUND FF1 GG1 \Ar \Br \Cr \Dr \Er \Fr \Gr \Hr \TJ
.endm
.macro ROTATE IN OUT LEFT RIGHT
vpslld $\LEFT,\IN,%xmm6
vpsrld $\RIGHT,\IN,%xmm7
vpxor %xmm6,%xmm7,\OUT
.endm
.macro WORD_SCHEDULER_00_11 I
# W'(i) <- W(i) ^ W(i+4)
# i = 0, ... ,11
movl \I(%rsp), %ecx # load W(i)
xorl \I+4*4(%rsp),%ecx # W'(i) <- W(i) ^ W(i+4)
movl %ecx,284(%rsp) # store W(i)'
.endm
.macro WORD_SCHEDULER_12_63 I
# W(i) <- P1( W(i-16) ^ W(i-9) ^ ( W(i-3) <<< 15 ) ) ^ ( W(i-13) <<< 7 ) ^ W(i-6)
# i = 12, ... ,63
rorx $17,\I+13*4(%rsp),%ecx # W(i-3)
xorl \I(%rsp),%ecx # W(i-16)
xorl \I+7*4(%rsp),%ecx # W(i-9)
P1 %ecx
rorx $25,\I+3*4(%rsp),%eax # W(i-13)
xorl \I+10*4(%rsp),%eax # W(i-6)
xorl %eax,%ecx
# Store W(i) and W'(i)
movl %ecx,\I+16*4(%rsp) # store W(i)
xorl \I+12*4(%rsp),%ecx # W'(i) <- W(i) ^ W(i+4)
movl %ecx,284(%rsp) # store W(i)'
.endm
.macro LOAD_WORD_FOR_SCHEDULER START
vmovdqu \START(%rsp),X0
vmovdqu \START+12(%rsp),X1
vmovdqu \START+28(%rsp),X2
vmovdqu \START+40(%rsp),X3
vmovdqu \START+48(%rsp),X4
vmovdqu \START+52(%rsp),X5
.endm
.macro LOAD_WORD_FOR_SCHEDULER_FAST START W0 W1 W2 W3 W4 W5
vmovdqu \START+12(%rsp),\W1
vmovdqu \START+48(%rsp),\W4
vmovdqu \START+52(%rsp),\W5
.endm
.macro MESSAGE_SCHEDULER START W0 W1 W2 W3 W4 W5
vpxor \W2,\W0,\W0
ROTATE \W5,\W2,15,17
vpxor \W2,\W0,\W0
# P1
vpshufb R16,\W0,X6
vpshufb R24,\W0,X7
vpxor X6,X7,X7
ROTATE X7,X7,31,1
vpxor X7,\W0,\W0
ROTATE \W1,\W2,7,25
vpxor \W2,\W0,\W0
vpxor \W3,\W0,\W0
# W'(i) <- W(i) ^ W(i+4)
vpxor \W0,\W4,\W4
vmovdqu \W0,\START+64(%rsp)
vmovdqu \W4,284(%rsp)
.endm
.macro MESSAGE_SCHEDULER_FAST START W0 W1 W2 W3 W4 W5
LOAD_WORD_FOR_SCHEDULER_FAST \START \W0 \W1 \W2 \W3 \W4 \W5
MESSAGE_SCHEDULER \START \W0 \W1 \W2 \W3 \W4 \W5
.endm
##### SM3 #####
# void SM3_CompressSIMD(uint32_t state[8], const uint8_t *data, uint32_t blockCnt)
# state|out %rdi 32 bytes
# p %rsi
# num %rdx
.globl SM3_CompressSIMD
.type SM3_CompressSIMD, @function
.align 64
SM3_CompressSIMD:
testq NUM,NUM
jz .Lsm3_avx_ret
# Store Registers
subq $348,%rsp
movq %rbx,300(%rsp)
movq %rbp,8+300(%rsp)
movq %r12,16+300(%rsp)
movq %r13,24+300(%rsp)
movq %r14,32+300(%rsp)
movq %r15,40+300(%rsp)
.Lsm3_avx_init:
leaq MASKS(%rip),ADDR
vmovdqa (ADDR),SHUFFLEMASK
vmovdqa 16(ADDR),R16
vmovdqa 32(ADDR),R24
.Lsm3_avx_update:
# Load Data (Big Endian)
vmovdqu (DATA),%xmm0
vmovdqu 16(DATA),%xmm1
vmovdqu 32(DATA),%xmm2
vmovdqu 48(DATA),%xmm3
vpshufb SHUFFLEMASK,%xmm0,%xmm0
vpshufb SHUFFLEMASK,%xmm1,%xmm1
vpshufb SHUFFLEMASK,%xmm2,%xmm2
vpshufb SHUFFLEMASK,%xmm3,%xmm3
vmovdqu %xmm0,(%rsp)
vmovdqu %xmm1,16(%rsp)
vmovdqu %xmm2,32(%rsp)
vmovdqu %xmm3,48(%rsp)
vpxor %xmm1,%xmm0,%xmm0
vpxor %xmm2,%xmm1,%xmm1
vpxor %xmm3,%xmm2,%xmm2
# Load State
movl (STATE),A
movl 4(STATE),B
movl 8(STATE),C
movl 12(STATE),D
movl 16(STATE),E
movl 20(STATE),F
movl 24(STATE),G
movl 28(STATE),H
# ROUND 0-11
vmovdqu %xmm0,284(%rsp)
ROUND_00_15 A B C D E F G H 0x79CC4519 0 284
ROUND_00_15 D A B C H E F G 0xF3988A32 4 288
ROUND_00_15 C D A B G H E F 0xE7311465 8 292
ROUND_00_15 B C D A F G H E 0xCE6228CB 12 296
vmovdqu %xmm1,284(%rsp)
ROUND_00_15 A B C D E F G H 0x9CC45197 16 284
ROUND_00_15 D A B C H E F G 0x3988A32F 20 288
ROUND_00_15 C D A B G H E F 0x7311465E 24 292
ROUND_00_15 B C D A F G H E 0xE6228CBC 28 296
vmovdqu %xmm2,284(%rsp)
ROUND_00_15 A B C D E F G H 0xCC451979 32 284
ROUND_00_15 D A B C H E F G 0x988A32F3 36 288
ROUND_00_15 C D A B G H E F 0x311465E7 40 292
ROUND_00_15 B C D A F G H E 0x6228CBCE 44 296
# ROUND 12-15
LOAD_WORD_FOR_SCHEDULER 0
MESSAGE_SCHEDULER 0 X0 X1 X2 X3 X4 X5
ROUND_00_15 A B C D E F G H 0xC451979C 48 284
ROUND_00_15 D A B C H E F G 0x88A32F39 52 288
ROUND_00_15 C D A B G H E F 0x11465E73 56 292
MESSAGE_SCHEDULER_FAST 12 X1 X0 X3 X5 X4 X2
ROUND_00_15 B C D A F G H E 0x228CBCE6 60 284
# ROUND 16-63
ROUND_16_63 A B C D E F G H 0x9D8A7A87 64 288
ROUND_16_63 D A B C H E F G 0x3B14F50F 68 292
MESSAGE_SCHEDULER_FAST 24 X0 X1 X5 X2 X4 X3
ROUND_16_63 C D A B G H E F 0x7629EA1E 72 284
ROUND_16_63 B C D A F G H E 0xEC53D43C 76 288
ROUND_16_63 A B C D E F G H 0xD8A7A879 80 292
MESSAGE_SCHEDULER_FAST 36 X1 X0 X2 X3 X4 X5
ROUND_16_63 D A B C H E F G 0xB14F50F3 84 284
ROUND_16_63 C D A B G H E F 0x629EA1E7 88 288
ROUND_16_63 B C D A F G H E 0xC53D43CE 92 292
MESSAGE_SCHEDULER_FAST 48 X0 X1 X3 X5 X4 X2
ROUND_16_63 A B C D E F G H 0x8A7A879D 96 284
ROUND_16_63 D A B C H E F G 0x14F50F3B 100 288
ROUND_16_63 C D A B G H E F 0x29EA1E76 104 292
MESSAGE_SCHEDULER_FAST 60 X1 X0 X5 X2 X4 X3
ROUND_16_63 B C D A F G H E 0x53D43CEC 108 284
ROUND_16_63 A B C D E F G H 0xA7A879D8 112 288
ROUND_16_63 D A B C H E F G 0x4F50F3B1 116 292
MESSAGE_SCHEDULER_FAST 72 X0 X1 X2 X3 X4 X5
ROUND_16_63 C D A B G H E F 0x9EA1E762 120 284
ROUND_16_63 B C D A F G H E 0x3D43CEC5 124 288
ROUND_16_63 A B C D E F G H 0x7A879D8A 128 292
MESSAGE_SCHEDULER_FAST 84 X1 X0 X3 X5 X4 X2
ROUND_16_63 D A B C H E F G 0xF50F3B14 132 284
ROUND_16_63 C D A B G H E F 0xEA1E7629 136 288
ROUND_16_63 B C D A F G H E 0xD43CEC53 140 292
MESSAGE_SCHEDULER_FAST 96 X0 X1 X5 X2 X4 X3
ROUND_16_63 A B C D E F G H 0xA879D8A7 144 284
ROUND_16_63 D A B C H E F G 0x50F3B14F 148 288
ROUND_16_63 C D A B G H E F 0xA1E7629E 152 292
MESSAGE_SCHEDULER_FAST 108 X1 X0 X2 X3 X4 X5
ROUND_16_63 B C D A F G H E 0x43CEC53D 156 284
ROUND_16_63 A B C D E F G H 0x879D8A7A 160 288
ROUND_16_63 D A B C H E F G 0x0F3B14F5 164 292
MESSAGE_SCHEDULER_FAST 120 X0 X1 X3 X5 X4 X2
ROUND_16_63 C D A B G H E F 0x1E7629EA 168 284
ROUND_16_63 B C D A F G H E 0x3CEC53D4 172 288
ROUND_16_63 A B C D E F G H 0x79D8A7A8 176 292
MESSAGE_SCHEDULER_FAST 132 X1 X0 X5 X2 X4 X3
ROUND_16_63 D A B C H E F G 0xF3B14F50 180 284
ROUND_16_63 C D A B G H E F 0xE7629EA1 184 288
ROUND_16_63 B C D A F G H E 0xCEC53D43 188 292
MESSAGE_SCHEDULER_FAST 144 X0 X1 X2 X3 X4 X5
ROUND_16_63 A B C D E F G H 0x9D8A7A87 192 284
ROUND_16_63 D A B C H E F G 0x3B14F50F 196 288
ROUND_16_63 C D A B G H E F 0x7629EA1E 200 292
MESSAGE_SCHEDULER_FAST 156 X1 X0 X3 X5 X4 X2
ROUND_16_63 B C D A F G H E 0xEC53D43C 204 284
ROUND_16_63 A B C D E F G H 0xD8A7A879 208 288
ROUND_16_63 D A B C H E F G 0xB14F50F3 212 292
MESSAGE_SCHEDULER_FAST 168 X0 X1 X5 X2 X4 X3
ROUND_16_63 C D A B G H E F 0x629EA1E7 216 284
ROUND_16_63 B C D A F G H E 0xC53D43CE 220 288
ROUND_16_63 A B C D E F G H 0x8A7A879D 224 292
MESSAGE_SCHEDULER_FAST 180 X1 X0 X2 X3 X4 X5
ROUND_16_63 D A B C H E F G 0x14F50F3B 228 284
ROUND_16_63 C D A B G H E F 0x29EA1E76 232 288
ROUND_16_63 B C D A F G H E 0x53D43CEC 236 292
MESSAGE_SCHEDULER_FAST 192 X0 X1 X3 X5 X4 X2
ROUND_16_63 A B C D E F G H 0xA7A879D8 240 284
ROUND_16_63 D A B C H E F G 0x4F50F3B1 244 288
ROUND_16_63 C D A B G H E F 0x9EA1E762 248 292
WORD_SCHEDULER_12_63 204
ROUND_16_63 B C D A F G H E 0x3D43CEC5 252 284
xorl A,(STATE)
xorl B,4(STATE)
xorl C,8(STATE)
xorl D,12(STATE)
xorl E,16(STATE)
xorl F,20(STATE)
xorl G,24(STATE)
xorl H,28(STATE)
leaq 64(DATA),DATA
decq NUM
jz .Lsm3_avx_final
jmp .Lsm3_avx_update
.Lsm3_avx_final:
vzeroall
# Clear Context
xorq %r8,%r8
xorq %r9,%r9
xorq %r10,%r10
xorq %r11,%r11
# Restore Registers
movq 300(%rsp),%rbx
movq 8+300(%rsp),%rbp
movq 16+300(%rsp),%r12
movq 24+300(%rsp),%r13
movq 32+300(%rsp),%r14
movq 40+300(%rsp),%r15
addq $348,%rsp
.Lsm3_avx_ret:
ret
.size SM3_CompressSIMD, .-SM3_CompressSIMD
##### SM3 #####
# void SM3_CompressAsm(uint32_t state[8], const uint8_t *data, uint32_t blockCnt)
# state|out %rdi 32 bytes
# p %rsi
# num %rdx
.globl SM3_CompressAsm
.type SM3_CompressAsm, @function
.align 64
SM3_CompressAsm:
testq NUM,NUM
jz .Lsm3_ret
# Store Registers
subq $348,%rsp
movq %rbx,300(%rsp)
movq %rbp,8+300(%rsp)
movq %r12,16+300(%rsp)
movq %r13,24+300(%rsp)
movq %r14,32+300(%rsp)
movq %r15,40+300(%rsp)
.Lsm3_loop:
# Load Data (Big Endian)
movl (DATA),%r8d
movl 4(DATA),%r9d
movl 8(DATA),%r10d
movl 12(DATA),%r11d
movbe %r8d,(%rsp)
movbe %r9d,4(%rsp)
movbe %r10d,8(%rsp)
movbe %r11d,12(%rsp)
movl 16(DATA),%r8d
movl 20(DATA),%r9d
movl 24(DATA),%r10d
movl 28(DATA),%r11d
movbe %r8d,16(%rsp)
movbe %r9d,20(%rsp)
movbe %r10d,24(%rsp)
movbe %r11d,28(%rsp)
movl 32(DATA),%r8d
movl 36(DATA),%r9d
movl 40(DATA),%r10d
movl 44(DATA),%r11d
movbe %r8d,32(%rsp)
movbe %r9d,36(%rsp)
movbe %r10d,40(%rsp)
movbe %r11d,44(%rsp)
movl 48(DATA),%r8d
movl 52(DATA),%r9d
movl 56(DATA),%r10d
movl 60(DATA),%r11d
movbe %r8d,48(%rsp)
movbe %r9d,52(%rsp)
movbe %r10d,56(%rsp)
movbe %r11d,60(%rsp)
# Load State
movl (STATE),A
movl 4(STATE),B
movl 8(STATE),C
movl 12(STATE),D
movl 16(STATE),E
movl 20(STATE),F
movl 24(STATE),G
movl 28(STATE),H
# ROUND 0-11
WORD_SCHEDULER_00_11 0
ROUND_00_15 A B C D E F G H 0x79CC4519 0 284
WORD_SCHEDULER_00_11 4
ROUND_00_15 D A B C H E F G 0xF3988A32 4 284
WORD_SCHEDULER_00_11 8
ROUND_00_15 C D A B G H E F 0xE7311465 8 284
WORD_SCHEDULER_00_11 12
ROUND_00_15 B C D A F G H E 0xCE6228CB 12 284
WORD_SCHEDULER_00_11 16
ROUND_00_15 A B C D E F G H 0x9CC45197 16 284
WORD_SCHEDULER_00_11 20
ROUND_00_15 D A B C H E F G 0x3988A32F 20 284
WORD_SCHEDULER_00_11 24
ROUND_00_15 C D A B G H E F 0x7311465E 24 284
WORD_SCHEDULER_00_11 28
ROUND_00_15 B C D A F G H E 0xE6228CBC 28 284
WORD_SCHEDULER_00_11 32
ROUND_00_15 A B C D E F G H 0xCC451979 32 284
WORD_SCHEDULER_00_11 36
ROUND_00_15 D A B C H E F G 0x988A32F3 36 284
WORD_SCHEDULER_00_11 40
ROUND_00_15 C D A B G H E F 0x311465E7 40 284
WORD_SCHEDULER_00_11 44
ROUND_00_15 B C D A F G H E 0x6228CBCE 44 284
# ROUND 12-15
WORD_SCHEDULER_12_63 0
ROUND_00_15 A B C D E F G H 0xC451979C 48 284
WORD_SCHEDULER_12_63 4
ROUND_00_15 D A B C H E F G 0x88A32F39 52 284
WORD_SCHEDULER_12_63 8
ROUND_00_15 C D A B G H E F 0x11465E73 56 284
WORD_SCHEDULER_12_63 12
ROUND_00_15 B C D A F G H E 0x228CBCE6 60 284
# ROUND 16-63
WORD_SCHEDULER_12_63 16
ROUND_16_63 A B C D E F G H 0x9D8A7A87 64 284
WORD_SCHEDULER_12_63 20
ROUND_16_63 D A B C H E F G 0x3B14F50F 68 284
WORD_SCHEDULER_12_63 24
ROUND_16_63 C D A B G H E F 0x7629EA1E 72 284
WORD_SCHEDULER_12_63 28
ROUND_16_63 B C D A F G H E 0xEC53D43C 76 284
WORD_SCHEDULER_12_63 32
ROUND_16_63 A B C D E F G H 0xD8A7A879 80 284
WORD_SCHEDULER_12_63 36
ROUND_16_63 D A B C H E F G 0xB14F50F3 84 284
WORD_SCHEDULER_12_63 40
ROUND_16_63 C D A B G H E F 0x629EA1E7 88 284
WORD_SCHEDULER_12_63 44
ROUND_16_63 B C D A F G H E 0xC53D43CE 92 284
WORD_SCHEDULER_12_63 48
ROUND_16_63 A B C D E F G H 0x8A7A879D 96 284
WORD_SCHEDULER_12_63 52
ROUND_16_63 D A B C H E F G 0x14F50F3B 100 284
WORD_SCHEDULER_12_63 56
ROUND_16_63 C D A B G H E F 0x29EA1E76 104 284
WORD_SCHEDULER_12_63 60
ROUND_16_63 B C D A F G H E 0x53D43CEC 108 284
WORD_SCHEDULER_12_63 64
ROUND_16_63 A B C D E F G H 0xA7A879D8 112 284
WORD_SCHEDULER_12_63 68
ROUND_16_63 D A B C H E F G 0x4F50F3B1 116 284
WORD_SCHEDULER_12_63 72
ROUND_16_63 C D A B G H E F 0x9EA1E762 120 284
WORD_SCHEDULER_12_63 76
ROUND_16_63 B C D A F G H E 0x3D43CEC5 124 284
WORD_SCHEDULER_12_63 80
ROUND_16_63 A B C D E F G H 0x7A879D8A 128 284
WORD_SCHEDULER_12_63 84
ROUND_16_63 D A B C H E F G 0xF50F3B14 132 284
WORD_SCHEDULER_12_63 88
ROUND_16_63 C D A B G H E F 0xEA1E7629 136 284
WORD_SCHEDULER_12_63 92
ROUND_16_63 B C D A F G H E 0xD43CEC53 140 284
WORD_SCHEDULER_12_63 96
ROUND_16_63 A B C D E F G H 0xA879D8A7 144 284
WORD_SCHEDULER_12_63 100
ROUND_16_63 D A B C H E F G 0x50F3B14F 148 284
WORD_SCHEDULER_12_63 104
ROUND_16_63 C D A B G H E F 0xA1E7629E 152 284
WORD_SCHEDULER_12_63 108
ROUND_16_63 B C D A F G H E 0x43CEC53D 156 284
WORD_SCHEDULER_12_63 112
ROUND_16_63 A B C D E F G H 0x879D8A7A 160 284
WORD_SCHEDULER_12_63 116
ROUND_16_63 D A B C H E F G 0x0F3B14F5 164 284
WORD_SCHEDULER_12_63 120
ROUND_16_63 C D A B G H E F 0x1E7629EA 168 284
WORD_SCHEDULER_12_63 124
ROUND_16_63 B C D A F G H E 0x3CEC53D4 172 284
WORD_SCHEDULER_12_63 128
ROUND_16_63 A B C D E F G H 0x79D8A7A8 176 284
WORD_SCHEDULER_12_63 132
ROUND_16_63 D A B C H E F G 0xF3B14F50 180 284
WORD_SCHEDULER_12_63 136
ROUND_16_63 C D A B G H E F 0xE7629EA1 184 284
WORD_SCHEDULER_12_63 140
ROUND_16_63 B C D A F G H E 0xCEC53D43 188 284
WORD_SCHEDULER_12_63 144
ROUND_16_63 A B C D E F G H 0x9D8A7A87 192 284
WORD_SCHEDULER_12_63 148
ROUND_16_63 D A B C H E F G 0x3B14F50F 196 284
WORD_SCHEDULER_12_63 152
ROUND_16_63 C D A B G H E F 0x7629EA1E 200 284
WORD_SCHEDULER_12_63 156
ROUND_16_63 B C D A F G H E 0xEC53D43C 204 284
WORD_SCHEDULER_12_63 160
ROUND_16_63 A B C D E F G H 0xD8A7A879 208 284
WORD_SCHEDULER_12_63 164
ROUND_16_63 D A B C H E F G 0xB14F50F3 212 284
WORD_SCHEDULER_12_63 168
ROUND_16_63 C D A B G H E F 0x629EA1E7 216 284
WORD_SCHEDULER_12_63 172
ROUND_16_63 B C D A F G H E 0xC53D43CE 220 284
WORD_SCHEDULER_12_63 176
ROUND_16_63 A B C D E F G H 0x8A7A879D 224 284
WORD_SCHEDULER_12_63 180
ROUND_16_63 D A B C H E F G 0x14F50F3B 228 284
WORD_SCHEDULER_12_63 184
ROUND_16_63 C D A B G H E F 0x29EA1E76 232 284
WORD_SCHEDULER_12_63 188
ROUND_16_63 B C D A F G H E 0x53D43CEC 236 284
WORD_SCHEDULER_12_63 192
ROUND_16_63 A B C D E F G H 0xA7A879D8 240 284
WORD_SCHEDULER_12_63 196
ROUND_16_63 D A B C H E F G 0x4F50F3B1 244 284
WORD_SCHEDULER_12_63 200
ROUND_16_63 C D A B G H E F 0x9EA1E762 248 284
WORD_SCHEDULER_12_63 204
ROUND_16_63 B C D A F G H E 0x3D43CEC5 252 284
xorl A,(STATE)
xorl B,4(STATE)
xorl C,8(STATE)
xorl D,12(STATE)
xorl E,16(STATE)
xorl F,20(STATE)
xorl G,24(STATE)
xorl H,28(STATE)
leaq 64(DATA),DATA
decq NUM
jz .Lsm3_final
jmp .Lsm3_loop
.Lsm3_final:
# Clear Context
xorq %r8,%r8
xorq %r9,%r9
xorq %r10,%r10
xorq %r11,%r11
# Restore Registers
movq 300(%rsp),%rbx
movq 8+300(%rsp),%rbp
movq 16+300(%rsp),%r12
movq 24+300(%rsp),%r13
movq 32+300(%rsp),%r14
movq 40+300(%rsp),%r15
addq $348,%rsp
.Lsm3_ret:
ret
.size SM3_CompressAsm, .-SM3_CompressAsm
.section .rodata
.align 64
MASKS:
# .shuffle_mask: (%rax)
.byte 3,2,1,0,7,6,5,4,11,10,9,8,15,14,13,12
# left rotations
# .r16: 16(%rax)
.byte 2,3,0,1,6,7,4,5,10,11,8,9,14,15,12,13
# .r24: 32(%rax)
.byte 1,2,3,0,5,6,7,4,9,10,11,8,13,14,15,12
#endif
| 2302_82127028/openHiTLS-examples_1508 | crypto/sm3/src/asm/sm3_x86_64.s | Motorola 68K Assembly | unknown | 16,809 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SM3
#include "sm3_local.h"
#include "crypt_utils.h"
void SM3_Compress(uint32_t state[8], const uint8_t *data, uint32_t blockCnt)
{
return SM3_CompressAsm(state, data, blockCnt);
}
#endif // HITLS_CRYPTO_SM3
| 2302_82127028/openHiTLS-examples_1508 | crypto/sm3/src/asm_sm3.c | C | unknown | 802 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SM3
#include <stdint.h>
#include "crypt_utils.h"
#include "bsl_sal.h"
#include "crypt_sm3.h"
#define K0 0x79cc4519U
#define K1 0xf3988a32U
#define K2 0xe7311465U
#define K3 0xce6228cbU
#define K4 0x9cc45197U
#define K5 0x3988a32fU
#define K6 0x7311465eU
#define K7 0xe6228cbcU
#define K8 0xcc451979U
#define K9 0x988a32f3U
#define K10 0x311465e7U
#define K11 0x6228cbceU
#define K12 0xc451979cU
#define K13 0x88a32f39U
#define K14 0x11465e73U
#define K15 0x228cbce6U
#define K16 0x9d8a7a87U
#define K17 0x3b14f50fU
#define K18 0x7629ea1eU
#define K19 0xec53d43cU
#define K20 0xd8a7a879U
#define K21 0xb14f50f3U
#define K22 0x629ea1e7U
#define K23 0xc53d43ceU
#define K24 0x8a7a879dU
#define K25 0x14f50f3bU
#define K26 0x29ea1e76U
#define K27 0x53d43cecU
#define K28 0xa7a879d8U
#define K29 0x4f50f3b1U
#define K30 0x9ea1e762U
#define K31 0x3d43cec5U
#define K32 0x7a879d8aU
#define K33 0xf50f3b14U
#define K34 0xea1e7629U
#define K35 0xd43cec53U
#define K36 0xa879d8a7U
#define K37 0x50f3b14fU
#define K38 0xa1e7629eU
#define K39 0x43cec53dU
#define K40 0x879d8a7aU
#define K41 0x0f3b14f5U
#define K42 0x1e7629eaU
#define K43 0x3cec53d4U
#define K44 0x79d8a7a8U
#define K45 0xf3b14f50U
#define K46 0xe7629ea1U
#define K47 0xcec53d43U
#define K48 0x9d8a7a87U
#define K49 0x3b14f50fU
#define K50 0x7629ea1eU
#define K51 0xec53d43cU
#define K52 0xd8a7a879U
#define K53 0xb14f50f3U
#define K54 0x629ea1e7U
#define K55 0xc53d43ceU
#define K56 0x8a7a879dU
#define K57 0x14f50f3bU
#define K58 0x29ea1e76U
#define K59 0x53d43cecU
#define K60 0xa7a879d8U
#define K61 0x4f50f3b1U
#define K62 0x9ea1e762U
#define K63 0x3d43cec5U
#define P0(x) ((x) ^ ROTL32((x), 9) ^ ROTL32((x), 17))
#define P1(x) ((x) ^ ROTL32((x), 15) ^ ROTL32((x), 23))
#define FF0(x, y, z) ((x) ^ (y) ^ (z))
#define FF1(x, y, z) (((x) & (y)) | ((x) & (z)) | ((y) & (z)))
#define GG0(x, y, z) ((x) ^ (y) ^ (z))
#define GG1(x, y, z) (((x) & (y)) | (~(x) & (z)))
#define ROUND(A, B, C, D, E, F, G, H, K, FF, GG, Wj, Wi) do { \
uint32_t a12 = ROTL32((A), 12); \
uint32_t ss1 = ROTL32(a12 + (E) + (K), 7); \
uint32_t ss2 = ss1 ^ a12; \
uint32_t tt1 = FF((A), (B), (C)) + (D) + ss2 + (Wi); \
uint32_t tt2 = GG((E), (F), (G)) + (H) + ss1 + (Wj); \
(H) = tt1; (D) = P0(tt2); \
(B) = ROTL32((B), 9); (F) = ROTL32((F), 19); \
} while (0)
#define ROUND00_15(A, B, C, D, E, F, G, H, K, Wj, Wi) \
ROUND(A, B, C, D, E, F, G, H, K, FF0, GG0, Wj, Wi)
#define ROUND16_63(A, B, C, D, E, F, G, H, K, Wj, Wi) \
ROUND(A, B, C, D, E, F, G, H, K, FF1, GG1, Wj, Wi)
#define EXPAND(W1, W2, W3, W4, W5) \
(P1((W1) ^ (W2) ^ ROTL32((W3), 15)) ^ ROTL32((W4), 7) ^ (W5))
/* see the GM standard document GM/T 0004-2012 chapter 5.3.3 */
void SM3_Compress(uint32_t state[8], const uint8_t *data, uint32_t blockCnt)
{
uint32_t w[16] = {0};
const uint8_t *input = data;
uint32_t count = blockCnt;
while (count > 0) {
/* converts data to 32 bits for calculation */
w[0] = GET_UINT32_BE(input, 0);
w[1] = GET_UINT32_BE(input, 4);
w[2] = GET_UINT32_BE(input, 8);
w[3] = GET_UINT32_BE(input, 12);
w[4] = GET_UINT32_BE(input, 16);
w[5] = GET_UINT32_BE(input, 20);
w[6] = GET_UINT32_BE(input, 24);
w[7] = GET_UINT32_BE(input, 28);
w[8] = GET_UINT32_BE(input, 32);
w[9] = GET_UINT32_BE(input, 36);
w[10] = GET_UINT32_BE(input, 40);
w[11] = GET_UINT32_BE(input, 44);
w[12] = GET_UINT32_BE(input, 48);
w[13] = GET_UINT32_BE(input, 52);
w[14] = GET_UINT32_BE(input, 56);
w[15] = GET_UINT32_BE(input, 60);
uint32_t a = state[0];
uint32_t b = state[1];
uint32_t c = state[2];
uint32_t d = state[3];
uint32_t e = state[4];
uint32_t f = state[5];
uint32_t g = state[6];
uint32_t h = state[7];
// 0 ~ 15 round
ROUND00_15(a, b, c, d, e, f, g, h, K0, w[0], w[0] ^ w[4]);
ROUND00_15(h, a, b, c, d, e, f, g, K1, w[1], w[1] ^ w[5]);
ROUND00_15(g, h, a, b, c, d, e, f, K2, w[2], w[2] ^ w[6]);
ROUND00_15(f, g, h, a, b, c, d, e, K3, w[3], w[3] ^ w[7]);
ROUND00_15(e, f, g, h, a, b, c, d, K4, w[4], w[4] ^ w[8]);
ROUND00_15(d, e, f, g, h, a, b, c, K5, w[5], w[5] ^ w[9]);
ROUND00_15(c, d, e, f, g, h, a, b, K6, w[6], w[6] ^ w[10]);
ROUND00_15(b, c, d, e, f, g, h, a, K7, w[7], w[7] ^ w[11]);
ROUND00_15(a, b, c, d, e, f, g, h, K8, w[8], w[8] ^ w[12]);
ROUND00_15(h, a, b, c, d, e, f, g, K9, w[9], w[9] ^ w[13]);
ROUND00_15(g, h, a, b, c, d, e, f, K10, w[10], w[10] ^ w[14]);
ROUND00_15(f, g, h, a, b, c, d, e, K11, w[11], w[11] ^ w[15]);
w[0] = EXPAND(w[0], w[7], w[13], w[3], w[10]);
ROUND00_15(e, f, g, h, a, b, c, d, K12, w[12], w[12] ^ w[0]);
w[1] = EXPAND(w[1], w[8], w[14], w[4], w[11]);
ROUND00_15(d, e, f, g, h, a, b, c, K13, w[13], w[13] ^ w[1]);
w[2] = EXPAND(w[2], w[9], w[15], w[5], w[12]);
ROUND00_15(c, d, e, f, g, h, a, b, K14, w[14], w[14] ^ w[2]);
w[3] = EXPAND(w[3], w[10], w[0], w[6], w[13]);
ROUND00_15(b, c, d, e, f, g, h, a, K15, w[15], w[15] ^ w[3]);
// 16 ~ 63 round
w[4] = EXPAND(w[4], w[11], w[1], w[7], w[14]);
ROUND16_63(a, b, c, d, e, f, g, h, K16, w[0], w[0] ^ w[4]);
w[5] = EXPAND(w[5], w[12], w[2], w[8], w[15]);
ROUND16_63(h, a, b, c, d, e, f, g, K17, w[1], w[1] ^ w[5]);
w[6] = EXPAND(w[6], w[13], w[3], w[9], w[0]);
ROUND16_63(g, h, a, b, c, d, e, f, K18, w[2], w[2] ^ w[6]);
w[7] = EXPAND(w[7], w[14], w[4], w[10], w[1]);
ROUND16_63(f, g, h, a, b, c, d, e, K19, w[3], w[3] ^ w[7]);
w[8] = EXPAND(w[8], w[15], w[5], w[11], w[2]);
ROUND16_63(e, f, g, h, a, b, c, d, K20, w[4], w[4] ^ w[8]);
w[9] = EXPAND(w[9], w[0], w[6], w[12], w[3]);
ROUND16_63(d, e, f, g, h, a, b, c, K21, w[5], w[5] ^ w[9]);
w[10] = EXPAND(w[10], w[1], w[7], w[13], w[4]);
ROUND16_63(c, d, e, f, g, h, a, b, K22, w[6], w[6] ^ w[10]);
w[11] = EXPAND(w[11], w[2], w[8], w[14], w[5]);
ROUND16_63(b, c, d, e, f, g, h, a, K23, w[7], w[7] ^ w[11]);
w[12] = EXPAND(w[12], w[3], w[9], w[15], w[6]);
ROUND16_63(a, b, c, d, e, f, g, h, K24, w[8], w[8] ^ w[12]);
w[13] = EXPAND(w[13], w[4], w[10], w[0], w[7]);
ROUND16_63(h, a, b, c, d, e, f, g, K25, w[9], w[9] ^ w[13]);
w[14] = EXPAND(w[14], w[5], w[11], w[1], w[8]);
ROUND16_63(g, h, a, b, c, d, e, f, K26, w[10], w[10] ^ w[14]);
w[15] = EXPAND(w[15], w[6], w[12], w[2], w[9]);
ROUND16_63(f, g, h, a, b, c, d, e, K27, w[11], w[11] ^ w[15]);
w[0] = EXPAND(w[0], w[7], w[13], w[3], w[10]);
ROUND16_63(e, f, g, h, a, b, c, d, K28, w[12], w[12] ^ w[0]);
w[1] = EXPAND(w[1], w[8], w[14], w[4], w[11]);
ROUND16_63(d, e, f, g, h, a, b, c, K29, w[13], w[13] ^ w[1]);
w[2] = EXPAND(w[2], w[9], w[15], w[5], w[12]);
ROUND16_63(c, d, e, f, g, h, a, b, K30, w[14], w[14] ^ w[2]);
w[3] = EXPAND(w[3], w[10], w[0], w[6], w[13]);
ROUND16_63(b, c, d, e, f, g, h, a, K31, w[15], w[15] ^ w[3]);
w[4] = EXPAND(w[4], w[11], w[1], w[7], w[14]);
ROUND16_63(a, b, c, d, e, f, g, h, K32, w[0], w[0] ^ w[4]);
w[5] = EXPAND(w[5], w[12], w[2], w[8], w[15]);
ROUND16_63(h, a, b, c, d, e, f, g, K33, w[1], w[1] ^ w[5]);
w[6] = EXPAND(w[6], w[13], w[3], w[9], w[0]);
ROUND16_63(g, h, a, b, c, d, e, f, K34, w[2], w[2] ^ w[6]);
w[7] = EXPAND(w[7], w[14], w[4], w[10], w[1]);
ROUND16_63(f, g, h, a, b, c, d, e, K35, w[3], w[3] ^ w[7]);
w[8] = EXPAND(w[8], w[15], w[5], w[11], w[2]);
ROUND16_63(e, f, g, h, a, b, c, d, K36, w[4], w[4] ^ w[8]);
w[9] = EXPAND(w[9], w[0], w[6], w[12], w[3]);
ROUND16_63(d, e, f, g, h, a, b, c, K37, w[5], w[5] ^ w[9]);
w[10] = EXPAND(w[10], w[1], w[7], w[13], w[4]);
ROUND16_63(c, d, e, f, g, h, a, b, K38, w[6], w[6] ^ w[10]);
w[11] = EXPAND(w[11], w[2], w[8], w[14], w[5]);
ROUND16_63(b, c, d, e, f, g, h, a, K39, w[7], w[7] ^ w[11]);
w[12] = EXPAND(w[12], w[3], w[9], w[15], w[6]);
ROUND16_63(a, b, c, d, e, f, g, h, K40, w[8], w[8] ^ w[12]);
w[13] = EXPAND(w[13], w[4], w[10], w[0], w[7]);
ROUND16_63(h, a, b, c, d, e, f, g, K41, w[9], w[9] ^ w[13]);
w[14] = EXPAND(w[14], w[5], w[11], w[1], w[8]);
ROUND16_63(g, h, a, b, c, d, e, f, K42, w[10], w[10] ^ w[14]);
w[15] = EXPAND(w[15], w[6], w[12], w[2], w[9]);
ROUND16_63(f, g, h, a, b, c, d, e, K43, w[11], w[11] ^ w[15]);
w[0] = EXPAND(w[0], w[7], w[13], w[3], w[10]);
ROUND16_63(e, f, g, h, a, b, c, d, K44, w[12], w[12] ^ w[0]);
w[1] = EXPAND(w[1], w[8], w[14], w[4], w[11]);
ROUND16_63(d, e, f, g, h, a, b, c, K45, w[13], w[13] ^ w[1]);
w[2] = EXPAND(w[2], w[9], w[15], w[5], w[12]);
ROUND16_63(c, d, e, f, g, h, a, b, K46, w[14], w[14] ^ w[2]);
w[3] = EXPAND(w[3], w[10], w[0], w[6], w[13]);
ROUND16_63(b, c, d, e, f, g, h, a, K47, w[15], w[15] ^ w[3]);
w[4] = EXPAND(w[4], w[11], w[1], w[7], w[14]);
ROUND16_63(a, b, c, d, e, f, g, h, K48, w[0], w[0] ^ w[4]);
w[5] = EXPAND(w[5], w[12], w[2], w[8], w[15]);
ROUND16_63(h, a, b, c, d, e, f, g, K49, w[1], w[1] ^ w[5]);
w[6] = EXPAND(w[6], w[13], w[3], w[9], w[0]);
ROUND16_63(g, h, a, b, c, d, e, f, K50, w[2], w[2] ^ w[6]);
w[7] = EXPAND(w[7], w[14], w[4], w[10], w[1]);
ROUND16_63(f, g, h, a, b, c, d, e, K51, w[3], w[3] ^ w[7]);
w[8] = EXPAND(w[8], w[15], w[5], w[11], w[2]);
ROUND16_63(e, f, g, h, a, b, c, d, K52, w[4], w[4] ^ w[8]);
w[9] = EXPAND(w[9], w[0], w[6], w[12], w[3]);
ROUND16_63(d, e, f, g, h, a, b, c, K53, w[5], w[5] ^ w[9]);
w[10] = EXPAND(w[10], w[1], w[7], w[13], w[4]);
ROUND16_63(c, d, e, f, g, h, a, b, K54, w[6], w[6] ^ w[10]);
w[11] = EXPAND(w[11], w[2], w[8], w[14], w[5]);
ROUND16_63(b, c, d, e, f, g, h, a, K55, w[7], w[7] ^ w[11]);
w[12] = EXPAND(w[12], w[3], w[9], w[15], w[6]);
ROUND16_63(a, b, c, d, e, f, g, h, K56, w[8], w[8] ^ w[12]);
w[13] = EXPAND(w[13], w[4], w[10], w[0], w[7]);
ROUND16_63(h, a, b, c, d, e, f, g, K57, w[9], w[9] ^ w[13]);
w[14] = EXPAND(w[14], w[5], w[11], w[1], w[8]);
ROUND16_63(g, h, a, b, c, d, e, f, K58, w[10], w[10] ^ w[14]);
w[15] = EXPAND(w[15], w[6], w[12], w[2], w[9]);
ROUND16_63(f, g, h, a, b, c, d, e, K59, w[11], w[11] ^ w[15]);
w[0] = EXPAND(w[0], w[7], w[13], w[3], w[10]);
ROUND16_63(e, f, g, h, a, b, c, d, K60, w[12], w[12] ^ w[0]);
w[1] = EXPAND(w[1], w[8], w[14], w[4], w[11]);
ROUND16_63(d, e, f, g, h, a, b, c, K61, w[13], w[13] ^ w[1]);
w[2] = EXPAND(w[2], w[9], w[15], w[5], w[12]);
ROUND16_63(c, d, e, f, g, h, a, b, K62, w[14], w[14] ^ w[2]);
w[3] = EXPAND(w[3], w[10], w[0], w[6], w[13]);
ROUND16_63(b, c, d, e, f, g, h, a, K63, w[15], w[15] ^ w[3]);
state[0] ^= a;
state[1] ^= b;
state[2] ^= c;
state[3] ^= d;
state[4] ^= e;
state[5] ^= f;
state[6] ^= g;
state[7] ^= h;
input += CRYPT_SM3_BLOCKSIZE;
count--;
}
}
#endif // HITLS_CRYPTO_SM3
| 2302_82127028/openHiTLS-examples_1508 | crypto/sm3/src/noasm_sm3.c | C | unknown | 12,340 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef SM3_LOCAL_H
#define SM3_LOCAL_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SM3
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
void SM3_Compress(uint32_t state[8], const uint8_t *data, uint32_t blockCnt);
/* assembly interface */
void SM3_CompressAsm(uint32_t state[8], const uint8_t *data, uint32_t blockCnt);
#ifdef __cplusplus
}
#endif /* __cpluscplus */
#endif // HITLS_CRYPTO_SM3
#endif // SM3_LOCAL_H
| 2302_82127028/openHiTLS-examples_1508 | crypto/sm3/src/sm3_local.h | C | unknown | 1,000 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SM3
#include <stdlib.h>
#include <stdint.h>
#include "securec.h"
#include "crypt_errno.h"
#include "crypt_utils.h"
#include "bsl_err_internal.h"
#include "crypt_sm3.h"
#include "sm3_local.h"
#include "bsl_sal.h"
#include "crypt_types.h"
struct CryptSm3Ctx {
uint32_t h[CRYPT_SM3_DIGESTSIZE / sizeof(uint32_t)]; /* store the intermediate data of the hash value */
uint32_t hNum, lNum; /* input data counter, maximum value 2 ^ 64 bits */
uint8_t block[CRYPT_SM3_BLOCKSIZE]; /* store the remaining data which less than one block */
/* Number of remaining bytes in 'block' arrary that are stored less than one block */
uint32_t num;
};
CRYPT_SM3_Ctx *CRYPT_SM3_NewCtx(void)
{
return BSL_SAL_Calloc(1, sizeof(CRYPT_SM3_Ctx));
}
CRYPT_SM3_Ctx *CRYPT_SM3_NewCtxEx(void *libCtx, int32_t algId)
{
(void)libCtx;
(void)algId;
return BSL_SAL_Calloc(1, sizeof(CRYPT_SM3_Ctx));
}
void CRYPT_SM3_FreeCtx(CRYPT_SM3_Ctx *ctx)
{
BSL_SAL_ClearFree(ctx, sizeof(CRYPT_SM3_Ctx));
}
int32_t CRYPT_SM3_Init(CRYPT_SM3_Ctx *ctx, BSL_Param *param)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
(void) param;
(void)memset_s(ctx, sizeof(CRYPT_SM3_Ctx), 0, sizeof(CRYPT_SM3_Ctx));
/* GM/T 0004-2012 chapter 4.1 */
ctx->h[0] = 0x7380166F;
ctx->h[1] = 0x4914B2B9;
ctx->h[2] = 0x172442D7;
ctx->h[3] = 0xDA8A0600;
ctx->h[4] = 0xA96F30BC;
ctx->h[5] = 0x163138AA;
ctx->h[6] = 0xE38DEE4D;
ctx->h[7] = 0xB0FB0E4E;
return CRYPT_SUCCESS;
}
int32_t CRYPT_SM3_Deinit(CRYPT_SM3_Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
(void)memset_s(ctx, sizeof(CRYPT_SM3_Ctx), 0, sizeof(CRYPT_SM3_Ctx));
return CRYPT_SUCCESS;
}
static uint32_t IsInputOverflow(CRYPT_SM3_Ctx *ctx, uint32_t nbytes)
{
uint32_t cnt0 = ctx->lNum + (nbytes << SHIFTS_PER_BYTE);
if (cnt0 < ctx->lNum) {
if (++ctx->hNum == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_SM3_INPUT_OVERFLOW);
return CRYPT_SM3_INPUT_OVERFLOW;
}
}
uint32_t cnt1 = ctx->hNum + (uint32_t)(nbytes >> (BITSIZE(uint32_t) - SHIFTS_PER_BYTE));
if (cnt1 < ctx->hNum) {
BSL_ERR_PUSH_ERROR(CRYPT_SM3_INPUT_OVERFLOW);
return CRYPT_SM3_INPUT_OVERFLOW;
}
ctx->hNum = cnt1;
ctx->lNum = cnt0;
return CRYPT_SUCCESS;
}
static int32_t IsUpdateParamValid(CRYPT_SM3_Ctx *ctx, const uint8_t *in, uint32_t len)
{
if ((ctx == NULL) || (in == NULL && len != 0)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (IsInputOverflow(ctx, len) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_SM3_INPUT_OVERFLOW);
return CRYPT_SM3_INPUT_OVERFLOW;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_SM3_Update(CRYPT_SM3_Ctx *ctx, const uint8_t *in, uint32_t len)
{
int32_t ret = IsUpdateParamValid(ctx, in, len);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if (len == 0) {
return CRYPT_SUCCESS;
}
const uint8_t *data = in;
uint32_t dataLen = len;
uint32_t left = CRYPT_SM3_BLOCKSIZE - ctx->num;
if (ctx->num != 0) {
if (dataLen < left) {
(void)memcpy_s(ctx->block + ctx->num, left, data, dataLen);
ctx->num += dataLen;
return CRYPT_SUCCESS;
}
// When the external input data is greater than the remaining space of the block,
// copy the data which is the same length as the remaining space.
(void)memcpy_s(ctx->block + ctx->num, left, data, left);
SM3_Compress(ctx->h, ctx->block, 1);
dataLen -= left;
data += left;
ctx->num = 0;
}
uint32_t blockCnt = dataLen / CRYPT_SM3_BLOCKSIZE;
if (blockCnt > 0) {
SM3_Compress(ctx->h, data, blockCnt);
blockCnt *= CRYPT_SM3_BLOCKSIZE;
data += blockCnt;
dataLen -= blockCnt;
}
if (dataLen != 0) {
// copy the remaining data to the cache array
(void)memcpy_s(ctx->block, CRYPT_SM3_BLOCKSIZE, data, dataLen);
ctx->num = dataLen;
}
return CRYPT_SUCCESS;
}
static int32_t IsFinalParamValid(const CRYPT_SM3_Ctx *ctx, const uint8_t *out, const uint32_t *outLen)
{
if ((ctx == NULL) || (out == NULL) || (outLen == NULL)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (*outLen < CRYPT_SM3_DIGESTSIZE) {
BSL_ERR_PUSH_ERROR(CRYPT_SM3_OUT_BUFF_LEN_NOT_ENOUGH);
return CRYPT_SM3_OUT_BUFF_LEN_NOT_ENOUGH;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_SM3_Final(CRYPT_SM3_Ctx *ctx, uint8_t *out, uint32_t *outLen)
{
int32_t ret = IsFinalParamValid(ctx, out, outLen);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ctx->block[ctx->num++] = 0x80; /* 0x80 means add '1' to the end of the message */
uint8_t *block = ctx->block;
uint32_t num = ctx->num;
uint32_t left = CRYPT_SM3_BLOCKSIZE - num;
if (left < 8) { /* less than 8 bytes which insufficient for storing data length data */
(void)memset_s(block + num, left, 0, left);
SM3_Compress(ctx->h, ctx->block, 1);
num = 0;
left = CRYPT_SM3_BLOCKSIZE;
}
(void)memset_s(block + num, left - 8, 0, left - 8);
block += CRYPT_SM3_BLOCKSIZE - 8;
PUT_UINT32_BE(ctx->hNum, block, 0);
block += sizeof(uint32_t);
PUT_UINT32_BE(ctx->lNum, block, 0);
SM3_Compress(ctx->h, ctx->block, 1);
ctx->num = 0;
PUT_UINT32_BE(ctx->h[0], out, 0);
PUT_UINT32_BE(ctx->h[1], out, 4);
PUT_UINT32_BE(ctx->h[2], out, 8);
PUT_UINT32_BE(ctx->h[3], out, 12);
PUT_UINT32_BE(ctx->h[4], out, 16);
PUT_UINT32_BE(ctx->h[5], out, 20);
PUT_UINT32_BE(ctx->h[6], out, 24);
PUT_UINT32_BE(ctx->h[7], out, 28);
*outLen = CRYPT_SM3_DIGESTSIZE;
return CRYPT_SUCCESS;
}
int32_t CRYPT_SM3_CopyCtx(CRYPT_SM3_Ctx *dst, const CRYPT_SM3_Ctx *src)
{
if (dst == NULL || src == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
(void)memcpy_s(dst, sizeof(CRYPT_SM3_Ctx), src, sizeof(CRYPT_SM3_Ctx));
return CRYPT_SUCCESS;
}
CRYPT_SM3_Ctx *CRYPT_SM3_DupCtx(const CRYPT_SM3_Ctx *src)
{
if (src == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return NULL;
}
CRYPT_SM3_Ctx *newCtx = CRYPT_SM3_NewCtx();
if (newCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
(void)memcpy_s(newCtx, sizeof(CRYPT_SM3_Ctx), src, sizeof(CRYPT_SM3_Ctx));
return newCtx;
}
#ifdef HITLS_CRYPTO_PROVIDER
int32_t CRYPT_SM3_GetParam(CRYPT_SM3_Ctx *ctx, BSL_Param *param)
{
(void)ctx;
return CRYPT_MdCommonGetParam(CRYPT_SM3_DIGESTSIZE, CRYPT_SM3_BLOCKSIZE, param);
}
#endif // HITLS_CRYPTO_PROVIDER
#endif /* HITLS_CRYPTO_SM3 */
| 2302_82127028/openHiTLS-examples_1508 | crypto/sm3/src/sm3_public.c | C | unknown | 7,524 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef CRYPT_SM4_H
#define CRYPT_SM4_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SM4
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include "crypt_types.h"
#include "crypt_local_types.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#define CRYPT_SM4_BLOCKSIZE 16
#define CRYPT_SM4_BLOCKSIZE_16 256
#define CRYPT_SM4_ROUNDS 32
typedef struct {
uint8_t iv[CRYPT_SM4_BLOCKSIZE];
uint32_t rk[CRYPT_SM4_ROUNDS];
} CRYPT_SM4_Ctx;
/**
* @brief SM4 Set the encryption and decryption key.
*
* @param [IN] ctx SM4 context
* @param [IN] key Key
* @param [IN] keyLen Key length
* @return Success: CRYPT_SUCCESS
* Other error codes are returned if the operation fails.
*/
int32_t CRYPT_SM4_SetKey(CRYPT_SM4_Ctx *ctx, const uint8_t *key, uint32_t keyLen);
/**
* @brief SM4 encryption. The data length must be an integer multiple of 16.
*
* @param [IN] ctx SM4 context
* @param [IN] in Data to be encrypted
* @param [OUT] out Encrypted data
* @param [IN] length Data length
* @return Success: CRYPT_SUCCESS
* Other error codes are returned if the operation fails.
*/
int32_t CRYPT_SM4_Encrypt(CRYPT_SM4_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t length);
/**
* @brief SM4 decryption. The data length must be an integer multiple of 16.
*
* @param [IN] ctx SM4 context
* @param [IN] in Data to be decrypted
* @param [OUT] out Decrypted Data
* @param [IN] length Data length
* @return Success: CRYPT_SUCCESS
* Other error codes are returned if the operation fails.
*/
int32_t CRYPT_SM4_Decrypt(CRYPT_SM4_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t length);
/**
* @brief Clear the SM4 context
*
* @param [IN] ctx sm4 context
*/
void CRYPT_SM4_Clean(CRYPT_SM4_Ctx *ctx);
#ifdef HITLS_CRYPTO_XTS
/**
* @brief SM4 Set the encryption key.
*
* @param ctx [IN] sm4 Context
* @param key [IN] Key. The first 16 bytes are data_key, and the last 16 bytes are tweak_key.
* @param keyLen [IN] Key length
*
* @retval #CRYPT_SUCCESS succeeded.
* @retval #CRYPT_NULL_INPUT ctx or key is NULL.
* @retval #CRYPT_SM4_ERR_KEY_LEN The key length is not equal to 32.
*/
int32_t CRYPT_SM4_XTS_SetEncryptKey(CRYPT_SM4_Ctx *ctx, const uint8_t *key, uint32_t len);
/**
* @brief SM4 Set the decryption key.
*
* @param ctx [IN] sm4 Context
* @param key [IN] Key
* @param keyLen [IN] Key length
* @return Success: CRYPT_SUCCESS
* Other error codes are returned if the operation fails.
*/
int32_t CRYPT_SM4_XTS_SetDecryptKey(CRYPT_SM4_Ctx *ctx, const uint8_t *key, uint32_t len);
/**
* @brief Clear SM4_xts context
*
* @param [IN] ctx sm4 context
*/
void CRYPT_SM4_XTS_Clean(CRYPT_SM4_Ctx *ctx);
/**
* @brief SM4 XTS mode encryption
* @param ctx [IN] sm4 Context
* @param in [IN] Data to be decrypted
* @param out [OUT] Decrypted data
* @param len [IN] Length of the decrypted data
* @param iv [IN] Set IV
*
* @retval #CRYPT_SUCCESS succeeded.
* @retval #CRYPT_NULL_INPUT ctx,in,out is NULL
* @retval #CRYPT_SM4_DATALEN_ERROR The length of the decrypted data is less than 16 bytes.
*/
int32_t CRYPT_SM4_XTS_Decrypt(CRYPT_SM4_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len, uint8_t *iv);
/**
* @brief SM4 XTS mode encryption
* @param ctx [IN] sm4 Context
* @param in [IN] Data to be encrypted
* @param out [OUT] Encrypted data
* @param len [IN] Length of the encrypted data
* @param iv [IN] Set IV
*
* @retval #CRYPT_SUCCESS succeeded.
* @retval #CRYPT_NULL_INPUT ctx/in/out is NULL
* @retval #CRYPT_SM4_DATALEN_ERROR The length of the encrypted data is less than 16.
*/
int32_t CRYPT_SM4_XTS_Encrypt(CRYPT_SM4_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len, uint8_t *iv);
#endif
/**
* @brief SM4 Set the encryption key (optimized).
*
* @param [IN] ctx SM4 context
* @param [IN] key Key
* @param [IN] len Key length
* @return Success: CRYPT_SUCCESS
* Other error codes are returned if the operation fails.
*/
int32_t CRYPT_SM4_SetEncryptKey(CRYPT_SM4_Ctx *ctx, const uint8_t *key, uint32_t len);
/**
* @brief SM4 Set the decryption key (optimized).
*
* @param [IN] ctx SM4 context
* @param [IN] key Key
* @param [IN] len Key length
* @return Success: CRYPT_SUCCESS
* Other error codes are returned if the operation fails.
*/
int32_t CRYPT_SM4_SetDecryptKey(CRYPT_SM4_Ctx *ctx, const uint8_t *key, uint32_t len);
#ifdef HITLS_CRYPTO_ECB
/**
* @brief SM4 ECB mode encryption (optimized).
* @param ctx [IN] sm4 Context
* @param in [IN] Data to be encrypted
* @param out [OUT] Encrypted data
* @param len [IN] Length of the encrypted data
*
* @return Success: CRYPT_SUCCESS
* Other error codes are returned if the operation fails.
*/
int32_t CRYPT_SM4_ECB_Encrypt(CRYPT_SM4_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len);
/**
* @brief SM4 ECB mode decryption (optimized).
* @param ctx [IN] sm4 Context
* @param in [IN] Data to be decrypted
* @param out [OUT] Decrypted data
* @param len [IN] Length of the decrypted data
*
* @return Success: CRYPT_SUCCESS
* Other error codes are returned if the operation fails.
*/
int32_t CRYPT_SM4_ECB_Decrypt(CRYPT_SM4_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len);
#endif
#ifdef HITLS_CRYPTO_CBC
/**
* @brief SM4 CBC mode encryption (optimized).
* @param ctx [IN] sm4 Context
* @param in [IN] Data to be encrypted
* @param out [OUT] Encrypted data
* @param len [IN] Length of the encrypted data
* @param iv [IN] Set IV
*
* @return Success: CRYPT_SUCCESS
* Other error codes are returned if the operation fails.
*/
int32_t CRYPT_SM4_CBC_Encrypt(CRYPT_SM4_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len, uint8_t *iv);
/**
* @brief SM4 CBC mode decryption (optimized).
* @param ctx [IN] sm4 Context
* @param in [IN] Data to be decrypted
* @param out [OUT] decrypted data
* @param len [IN] Length of the decrypted data
* @param iv [IN] Set IV
*
* @return Success: CRYPT_SUCCESS
* Other error codes are returned if the operation fails.
*/
int32_t CRYPT_SM4_CBC_Decrypt(CRYPT_SM4_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len, uint8_t *iv);
#endif
#if defined(HITLS_CRYPTO_CTR) || defined(HITLS_CRYPTO_GCM)
/**
* @brief SM4 CTR mode encryption (optimized).
* @param ctx [IN] sm4 Context
* @param in [IN] Data to be encrypted
* @param out [OUT] Encrypted data
* @param len [IN] Length of the encrypted data
* @param iv [IN] Set IV
*
* @return Success: CRYPT_SUCCESS
* Other error codes are returned if the operation fails.
*/
int32_t CRYPT_SM4_CTR_Encrypt(CRYPT_SM4_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len, uint8_t *iv);
/**
* @brief SM4 CTR mode decryption (optimized).
* @param ctx [IN] sm4 Context
* @param in [IN] Data to be decrypted
* @param out [OUT] decrypted data
* @param len [IN] Length of the decrypted data
* @param iv [IN] Set IV
*
* @return Success: CRYPT_SUCCESS
* Other error codes are returned if the operation fails.
*/
int32_t CRYPT_SM4_CTR_Decrypt(CRYPT_SM4_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len, uint8_t *iv);
#endif
#ifdef HITLS_CRYPTO_OFB
/**
* @brief SM4 OFB mode encryption (optimized).
* @param ctx [IN] sm4 Context
* @param in [IN] Data to be encrypted
* @param out [OUT] Encrypted data
* @param len [IN] Length of the encrypted data
* @param iv [IN] Set IV
* @param offset [OUT] Length of less than one block
*
* @return Success: CRYPT_SUCCESS
* Other error codes are returned if the operation fails.
*/
int32_t CRYPT_SM4_OFB_Encrypt(CRYPT_SM4_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len, uint8_t *iv, uint8_t *offset);
/**
* @brief SM4 OFB mode decryption (optimized).
* @param ctx [IN] sm4 Context
* @param in [IN] Data to be decrypted
* @param out [OUT] decrypted data
* @param len [IN] Length of the decrypted data
* @param iv [IN] Set IV
* @param offset [OUT] Length of less than one block
*
* @return Success: CRYPT_SUCCESS
* Other error codes are returned if the operation fails.
*/
int32_t CRYPT_SM4_OFB_Decrypt(CRYPT_SM4_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len, uint8_t *iv, uint8_t *offset);
#endif
#ifdef HITLS_CRYPTO_CFB
/**
* @brief SM4 CFB mode encryption (optimized).
* @param ctx [IN] sm4 Context
* @param in [IN] Data to be encrypted
* @param out [OUT] Encrypted data
* @param len [IN] Length of the encrypted data
* @param iv [IN] Set IV
* @param offset [OUT] Length of less than one block.
*
* @return Success: CRYPT_SUCCESS
* Other error codes are returned if the operation fails.
*/
int32_t CRYPT_SM4_CFB_Encrypt(CRYPT_SM4_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len, uint8_t *iv, uint8_t *offset);
/**
* @brief SM4 CFB mode decryption (optimized).
* @param ctx [IN] sm4 Context
* @param in [IN] Data to be decrypted
* @param out [OUT] decrypted data
* @param len [IN] Length of the decrypted data
* @param iv [IN] Set IV
* @param offset [OUT] Length of less than one block.
*
* @return Success: CRYPT_SUCCESS
* Other error codes are returned if the operation fails.
*/
int32_t CRYPT_SM4_CFB_Decrypt(CRYPT_SM4_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len, uint8_t *iv, uint8_t *offset);
#endif
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif // HITLS_CRYPTO_SM4
#endif // CRYPT_SM4_H | 2302_82127028/openHiTLS-examples_1508 | crypto/sm4/include/crypt_sm4.h | C | unknown | 10,045 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SM4
#include "crypt_arm.h"
.arch armv8-a+crypto
rk0 .req v12
rk1 .req v13
rka .req v14
rkb .req v15
rk2 .req v20
rkc .req v21
vtmp0 .req v0
vtmp1 .req v1
vtmp2 .req v2
vtmp3 .req v3
vtmp4 .req v24
vtmp5 .req v25
vtmp6 .req v22
vtmp7 .req v23
data0 .req v4
data1 .req v5
data2 .req v6
data3 .req v7
datax0 .req v8
datax1 .req v9
datax2 .req v10
datax3 .req v11
vtmpx0 .req v12
vtmpx1 .req v13
vtmpx2 .req v14
vtmpx3 .req v15
data10 .req v16
data11 .req v17
data12 .req v18
data13 .req v19
MaskV .req v26
TAHMatV .req v27
TALMatV .req v28
ATAHMatV .req v29
ATALMatV .req v30
ANDMaskV .req v31
MaskQ .req q26
TAHMatQ .req q27
TALMatQ .req q28
ATAHMatQ .req q29
ATALMatQ .req q30
ANDMaskQ .req q31
vtmp5q .req q25
vtmp6q .req q22
vtmp7q .req q23
inp .req x0
outp .req x1
blocks .req w2
rks .req x3
wtmp0 .req w7
wtmp1 .req w8
wtmp2 .req w9
ptr .req x10
counter .req w11
word0 .req w12
word1 .req w13
word2 .req w14
word3 .req w15
xword1 .req x13
tbox0 .req x19
tbox1 .req x20
tbox2 .req x21
tbox3 .req x22
len .req x2
ivp .req x4
ctr .req w5
ivec .req v3
ivec1 .req v15
.section .rodata
.align 4
.Ltbox1:
.word 0xd55b5b8e, 0x924242d0, 0xeaa7a74d, 0xfdfbfb06, 0xcf3333fc, 0xe2878765, 0x3df4f4c9, 0xb5dede6b, 0x1658584e
.word 0xb4dada6e, 0x14505044, 0xc10b0bca, 0x28a0a088, 0xf8efef17, 0x2cb0b09c, 0x05141411, 0x2bacac87, 0x669d9dfb
.word 0x986a6af2, 0x77d9d9ae, 0x2aa8a882, 0xbcfafa46, 0x04101014, 0xc00f0fcf, 0xa8aaaa02, 0x45111154, 0x134c4c5f
.word 0x269898be, 0x4825256d, 0x841a1a9e, 0x0618181e, 0x9b6666fd, 0x9e7272ec, 0x4309094a, 0x51414110, 0xf7d3d324
.word 0x934646d5, 0xecbfbf53, 0x9a6262f8, 0x7be9e992, 0x33ccccff, 0x55515104, 0x0b2c2c27, 0x420d0d4f, 0xeeb7b759
.word 0xcc3f3ff3, 0xaeb2b21c, 0x638989ea, 0xe7939374, 0xb1cece7f, 0x1c70706c, 0xaba6a60d, 0xca2727ed, 0x08202028
.word 0xeba3a348, 0x975656c1, 0x82020280, 0xdc7f7fa3, 0x965252c4, 0xf9ebeb12, 0x74d5d5a1, 0x8d3e3eb3, 0x3ffcfcc3
.word 0xa49a9a3e, 0x461d1d5b, 0x071c1c1b, 0xa59e9e3b, 0xfff3f30c, 0xf0cfcf3f, 0x72cdcdbf, 0x175c5c4b, 0xb8eaea52
.word 0x810e0e8f, 0x5865653d, 0x3cf0f0cc, 0x1964647d, 0xe59b9b7e, 0x87161691, 0x4e3d3d73, 0xaaa2a208, 0x69a1a1c8
.word 0x6aadadc7, 0x83060685, 0xb0caca7a, 0x70c5c5b5, 0x659191f4, 0xd96b6bb2, 0x892e2ea7, 0xfbe3e318, 0xe8afaf47
.word 0x0f3c3c33, 0x4a2d2d67, 0x71c1c1b0, 0x5759590e, 0x9f7676e9, 0x35d4d4e1, 0x1e787866, 0x249090b4, 0x0e383836
.word 0x5f797926, 0x628d8def, 0x59616138, 0xd2474795, 0xa08a8a2a, 0x259494b1, 0x228888aa, 0x7df1f18c, 0x3bececd7
.word 0x01040405, 0x218484a5, 0x79e1e198, 0x851e1e9b, 0xd7535384, 0x00000000, 0x4719195e, 0x565d5d0b, 0x9d7e7ee3
.word 0xd04f4f9f, 0x279c9cbb, 0x5349491a, 0x4d31317c, 0x36d8d8ee, 0x0208080a, 0xe49f9f7b, 0xa2828220, 0xc71313d4
.word 0xcb2323e8, 0x9c7a7ae6, 0xe9abab42, 0xbdfefe43, 0x882a2aa2, 0xd14b4b9a, 0x41010140, 0xc41f1fdb, 0x38e0e0d8
.word 0xb7d6d661, 0xa18e8e2f, 0xf4dfdf2b, 0xf1cbcb3a, 0xcd3b3bf6, 0xfae7e71d, 0x608585e5, 0x15545441, 0xa3868625
.word 0xe3838360, 0xacbaba16, 0x5c757529, 0xa6929234, 0x996e6ef7, 0x34d0d0e4, 0x1a686872, 0x54555501, 0xafb6b619
.word 0x914e4edf, 0x32c8c8fa, 0x30c0c0f0, 0xf6d7d721, 0x8e3232bc, 0xb3c6c675, 0xe08f8f6f, 0x1d747469, 0xf5dbdb2e
.word 0xe18b8b6a, 0x2eb8b896, 0x800a0a8a, 0x679999fe, 0xc92b2be2, 0x618181e0, 0xc30303c0, 0x29a4a48d, 0x238c8caf
.word 0xa9aeae07, 0x0d343439, 0x524d4d1f, 0x4f393976, 0x6ebdbdd3, 0xd6575781, 0xd86f6fb7, 0x37dcdceb, 0x44151551
.word 0xdd7b7ba6, 0xfef7f709, 0x8c3a3ab6, 0x2fbcbc93, 0x030c0c0f, 0xfcffff03, 0x6ba9a9c2, 0x73c9c9ba, 0x6cb5b5d9
.word 0x6db1b1dc, 0x5a6d6d37, 0x50454515, 0x8f3636b9, 0x1b6c6c77, 0xadbebe13, 0x904a4ada, 0xb9eeee57, 0xde7777a9
.word 0xbef2f24c, 0x7efdfd83, 0x11444455, 0xda6767bd, 0x5d71712c, 0x40050545, 0x1f7c7c63, 0x10404050, 0x5b696932
.word 0xdb6363b8, 0x0a282822, 0xc20707c5, 0x31c4c4f5, 0x8a2222a8, 0xa7969631, 0xce3737f9, 0x7aeded97, 0xbff6f649
.word 0x2db4b499, 0x75d1d1a4, 0xd3434390, 0x1248485a, 0xbae2e258, 0xe6979771, 0xb6d2d264, 0xb2c2c270, 0x8b2626ad
.word 0x68a5a5cd, 0x955e5ecb, 0x4b292962, 0x0c30303c, 0x945a5ace, 0x76ddddab, 0x7ff9f986, 0x649595f1, 0xbbe6e65d
.word 0xf2c7c735, 0x0924242d, 0xc61717d1, 0x6fb9b9d6, 0xc51b1bde, 0x86121294, 0x18606078, 0xf3c3c330, 0x7cf5f589
.word 0xefb3b35c, 0x3ae8e8d2, 0xdf7373ac, 0x4c353579, 0x208080a0, 0x78e5e59d, 0xedbbbb56, 0x5e7d7d23, 0x3ef8f8c6
.word 0xd45f5f8b, 0xc82f2fe7, 0x39e4e4dd, 0x49212168
.Ltbox2:
.word 0x5b5b8ed5, 0x4242d092, 0xa7a74dea, 0xfbfb06fd, 0x3333fccf, 0x878765e2, 0xf4f4c93d, 0xdede6bb5, 0x58584e16
.word 0xdada6eb4, 0x50504414, 0x0b0bcac1, 0xa0a08828, 0xefef17f8, 0xb0b09c2c, 0x14141105, 0xacac872b, 0x9d9dfb66
.word 0x6a6af298, 0xd9d9ae77, 0xa8a8822a, 0xfafa46bc, 0x10101404, 0x0f0fcfc0, 0xaaaa02a8, 0x11115445, 0x4c4c5f13
.word 0x9898be26, 0x25256d48, 0x1a1a9e84, 0x18181e06, 0x6666fd9b, 0x7272ec9e, 0x09094a43, 0x41411051, 0xd3d324f7
.word 0x4646d593, 0xbfbf53ec, 0x6262f89a, 0xe9e9927b, 0xccccff33, 0x51510455, 0x2c2c270b, 0xd0d4f42, 0xb7b759ee
.word 0x3f3ff3cc, 0xb2b21cae, 0x8989ea63, 0x939374e7, 0xcece7fb1, 0x70706c1c, 0xa6a60dab, 0x2727edca, 0x20202808
.word 0xa3a348eb, 0x5656c197, 0x02028082, 0x7f7fa3dc, 0x5252c496, 0xebeb12f9, 0xd5d5a174, 0x3e3eb38d, 0xfcfcc33f
.word 0x9a9a3ea4, 0x1d1d5b46, 0x1c1c1b07, 0x9e9e3ba5, 0xf3f30cff, 0xcfcf3ff0, 0xcdcdbf72, 0x5c5c4b17, 0xeaea52b8
.word 0x0e0e8f81, 0x65653d58, 0xf0f0cc3c, 0x64647d19, 0x9b9b7ee5, 0x16169187, 0x3d3d734e, 0xa2a208aa, 0xa1a1c869
.word 0xadadc76a, 0x06068583, 0xcaca7ab0, 0xc5c5b570, 0x9191f465, 0x6b6bb2d9, 0x2e2ea789, 0xe3e318fb, 0xafaf47e8
.word 0x3c3c330f, 0x2d2d674a, 0xc1c1b071, 0x59590e57, 0x7676e99f, 0xd4d4e135, 0x7878661e, 0x9090b424, 0x3838360e
.word 0x7979265f, 0x8d8def62, 0x61613859, 0x474795d2, 0x8a8a2aa0, 0x9494b125, 0x8888aa22, 0xf1f18c7d, 0xececd73b
.word 0x04040501, 0x8484a521, 0xe1e19879, 0x1e1e9b85, 0x535384d7, 0x00000000, 0x19195e47, 0x5d5d0b56, 0x7e7ee39d
.word 0x4f4f9fd0, 0x9c9cbb27, 0x49491a53, 0x31317c4d, 0xd8d8ee36, 0x08080a02, 0x9f9f7be4, 0x828220a2, 0x1313d4c7
.word 0x2323e8cb, 0x7a7ae69c, 0xabab42e9, 0xfefe43bd, 0x2a2aa288, 0x4b4b9ad1, 0x01014041, 0x1f1fdbc4, 0xe0e0d838
.word 0xd6d661b7, 0x8e8e2fa1, 0xdfdf2bf4, 0xcbcb3af1, 0x3b3bf6cd, 0xe7e71dfa, 0x8585e560, 0x54544115, 0x868625a3
.word 0x838360e3, 0xbaba16ac, 0x7575295c, 0x929234a6, 0x6e6ef799, 0xd0d0e434, 0x6868721a, 0x55550154, 0xb6b619af
.word 0x4e4edf91, 0xc8c8fa32, 0xc0c0f030, 0xd7d721f6, 0x3232bc8e, 0xc6c675b3, 0x8f8f6fe0, 0x7474691d, 0xdbdb2ef5
.word 0x8b8b6ae1, 0xb8b8962e, 0x0a0a8a80, 0x9999fe67, 0x2b2be2c9, 0x8181e061, 0x0303c0c3, 0xa4a48d29, 0x8c8caf23
.word 0xaeae07a9, 0x3434390d, 0x4d4d1f52, 0x3939764f, 0xbdbdd36e, 0x575781d6, 0x6f6fb7d8, 0xdcdceb37, 0x15155144
.word 0x7b7ba6dd, 0xf7f709fe, 0x3a3ab68c, 0xbcbc932f, 0x0c0c0f03, 0xffff03fc, 0xa9a9c26b, 0xc9c9ba73, 0xb5b5d96c
.word 0xb1b1dc6d, 0x6d6d375a, 0x45451550, 0x3636b98f, 0x6c6c771b, 0xbebe13ad, 0x4a4ada90, 0xeeee57b9, 0x7777a9de
.word 0xf2f24cbe, 0xfdfd837e, 0x44445511, 0x6767bdda, 0x71712c5d, 0x05054540, 0x7c7c631f, 0x40405010, 0x6969325b
.word 0x6363b8db, 0x2828220a, 0x0707c5c2, 0xc4c4f531, 0x2222a88a, 0x969631a7, 0x3737f9ce, 0xeded977a, 0xf6f649bf
.word 0xb4b4992d, 0xd1d1a475, 0x434390d3, 0x48485a12, 0xe2e258ba, 0x979771e6, 0xd2d264b6, 0xc2c270b2, 0x2626ad8b
.word 0xa5a5cd68, 0x5e5ecb95, 0x2929624b, 0x30303c0c, 0x5a5ace94, 0xddddab76, 0xf9f9867f, 0x9595f164, 0xe6e65dbb
.word 0xc7c735f2, 0x24242d09, 0x1717d1c6, 0xb9b9d66f, 0x1b1bdec5, 0x12129486, 0x60607818, 0xc3c330f3, 0xf5f5897c
.word 0xb3b35cef, 0xe8e8d23a, 0x7373acdf, 0x3535794c, 0x8080a020, 0xe5e59d78, 0xbbbb56ed, 0x7d7d235e, 0xf8f8c63e
.word 0x5f5f8bd4, 0x2f2fe7c8, 0xe4e4dd39, 0x21216849
.Ltbox3:
.word 0x5b8ed55b, 0x42d09242, 0xa74deaa7, 0xfb06fdfb, 0x33fccf33, 0x8765e287, 0xf4c93df4, 0xde6bb5de, 0x584e1658
.word 0xda6eb4da, 0x50441450, 0x0bcac10b, 0xa08828a0, 0xef17f8ef, 0xb09c2cb0, 0x14110514, 0xac872bac, 0x9dfb669d
.word 0x6af2986a, 0xd9ae77d9, 0xa8822aa8, 0xfa46bcfa, 0x10140410, 0x0fcfc00f, 0xaa02a8aa, 0x11544511, 0x4c5f134c
.word 0x98be2698, 0x256d4825, 0x1a9e841a, 0x181e0618, 0x66fd9b66, 0x72ec9e72, 0x094a4309, 0x41105141, 0xd324f7d3
.word 0x46d59346, 0xbf53ecbf, 0x62f89a62, 0xe9927be9, 0xccff33cc, 0x51045551, 0x2c270b2c, 0x0d4f420d, 0xb759eeb7
.word 0x3ff3cc3f, 0xb21caeb2, 0x89ea6389, 0x9374e793, 0xce7fb1ce, 0x706c1c70, 0xa60daba6, 0x27edca27, 0x20280820
.word 0xa348eba3, 0x56c19756, 0x02808202, 0x7fa3dc7f, 0x52c49652, 0xeb12f9eb, 0xd5a174d5, 0x3eb38d3e, 0xfcc33ffc
.word 0x9a3ea49a, 0x1d5b461d, 0x1c1b071c, 0x9e3ba59e, 0xf30cfff3, 0xcf3ff0cf, 0xcdbf72cd, 0x5c4b175c, 0xea52b8ea
.word 0x0e8f810e, 0x653d5865, 0xf0cc3cf0, 0x647d1964, 0x9b7ee59b, 0x16918716, 0x3d734e3d, 0xa208aaa2, 0xa1c869a1
.word 0xadc76aad, 0x06858306, 0xca7ab0ca, 0xc5b570c5, 0x91f46591, 0x6bb2d96b, 0x2ea7892e, 0xe318fbe3, 0xaf47e8af
.word 0x3c330f3c, 0x2d674a2d, 0xc1b071c1, 0x590e5759, 0x76e99f76, 0xd4e135d4, 0x78661e78, 0x90b42490, 0x38360e38
.word 0x79265f79, 0x8def628d, 0x61385961, 0x4795d247, 0x8a2aa08a, 0x94b12594, 0x88aa2288, 0xf18c7df1, 0xecd73bec
.word 0x04050104, 0x84a52184, 0xe19879e1, 0x1e9b851e, 0x5384d753, 0x00000000, 0x195e4719, 0x5d0b565d, 0x7ee39d7e
.word 0x4f9fd04f, 0x9cbb279c, 0x491a5349, 0x317c4d31, 0xd8ee36d8, 0x080a0208, 0x9f7be49f, 0x8220a282, 0x13d4c713
.word 0x23e8cb23, 0x7ae69c7a, 0xab42e9ab, 0xfe43bdfe, 0x2aa2882a, 0x4b9ad14b, 0x01404101, 0x1fdbc41f, 0xe0d838e0
.word 0xd661b7d6, 0x8e2fa18e, 0xdf2bf4df, 0xcb3af1cb, 0x3bf6cd3b, 0xe71dfae7, 0x85e56085, 0x54411554, 0x8625a386
.word 0x8360e383, 0xba16acba, 0x75295c75, 0x9234a692, 0x6ef7996e, 0xd0e434d0, 0x68721a68, 0x55015455, 0xb619afb6
.word 0x4edf914e, 0xc8fa32c8, 0xc0f030c0, 0xd721f6d7, 0x32bc8e32, 0xc675b3c6, 0x8f6fe08f, 0x74691d74, 0xdb2ef5db
.word 0x8b6ae18b, 0xb8962eb8, 0x0a8a800a, 0x99fe6799, 0x2be2c92b, 0x81e06181, 0x03c0c303, 0xa48d29a4, 0x8caf238c
.word 0xae07a9ae, 0x34390d34, 0x4d1f524d, 0x39764f39, 0xbdd36ebd, 0x5781d657, 0x6fb7d86f, 0xdceb37dc, 0x15514415
.word 0x7ba6dd7b, 0xf709fef7, 0x3ab68c3a, 0xbc932fbc, 0x0c0f030c, 0xff03fcff, 0xa9c26ba9, 0xc9ba73c9, 0xb5d96cb5
.word 0xb1dc6db1, 0x6d375a6d, 0x45155045, 0x36b98f36, 0x6c771b6c, 0xbe13adbe, 0x4ada904a, 0xee57b9ee, 0x77a9de77
.word 0xf24cbef2, 0xfd837efd, 0x44551144, 0x67bdda67, 0x712c5d71, 0x05454005, 0x7c631f7c, 0x40501040, 0x69325b69
.word 0x63b8db63, 0x28220a28, 0x07c5c207, 0xc4f531c4, 0x22a88a22, 0x9631a796, 0x37f9ce37, 0xed977aed, 0xf649bff6
.word 0xb4992db4, 0xd1a475d1, 0x4390d343, 0x485a1248, 0xe258bae2, 0x9771e697, 0xd264b6d2, 0xc270b2c2, 0x26ad8b26
.word 0xa5cd68a5, 0x5ecb955e, 0x29624b29, 0x303c0c30, 0x5ace945a, 0xddab76dd, 0xf9867ff9, 0x95f16495, 0xe65dbbe6
.word 0xc735f2c7, 0x242d0924, 0x17d1c617, 0xb9d66fb9, 0x1bdec51b, 0x12948612, 0x60781860, 0xc330f3c3, 0xf5897cf5
.word 0xb35cefb3, 0xe8d23ae8, 0x73acdf73, 0x35794c35, 0x80a02080, 0xe59d78e5, 0xbb56edbb, 0x7d235e7d, 0xf8c63ef8
.word 0x5f8bd45f, 0x2fe7c82f, 0xe4dd39e4, 0x21684921
.Ltbox4:
.word 0x8ed55b5b, 0xd0924242, 0x4deaa7a7, 0x06fdfbfb, 0xfccf3333, 0x65e28787, 0xc93df4f4, 0x6bb5dede, 0x4e165858
.word 0x6eb4dada, 0x44145050, 0xcac10b0b, 0x8828a0a0, 0x17f8efef, 0x9c2cb0b0, 0x11051414, 0x872bacac, 0xfb669d9d
.word 0xf2986a6a, 0xae77d9d9, 0x822aa8a8, 0x46bcfafa, 0x14041010, 0xcfc00f0f, 0x02a8aaaa, 0x54451111, 0x5f134c4c
.word 0xbe269898, 0x6d482525, 0x9e841a1a, 0x1e061818, 0xfd9b6666, 0xec9e7272, 0x4a430909, 0x10514141, 0x24f7d3d3
.word 0xd5934646, 0x53ecbfbf, 0xf89a6262, 0x927be9e9, 0xff33cccc, 0x04555151, 0x270b2c2c, 0x4f420d0d, 0x59eeb7b7
.word 0xf3cc3f3f, 0x1caeb2b2, 0xea638989, 0x74e79393, 0x7fb1cece, 0x6c1c7070, 0x0daba6a6, 0xedca2727, 0x28082020
.word 0x48eba3a3, 0xc1975656, 0x80820202, 0xa3dc7f7f, 0xc4965252, 0x12f9ebeb, 0xa174d5d5, 0xb38d3e3e, 0xc33ffcfc
.word 0x3ea49a9a, 0x5b461d1d, 0x1b071c1c, 0x3ba59e9e, 0x0cfff3f3, 0x3ff0cfcf, 0xbf72cdcd, 0x4b175c5c, 0x52b8eaea
.word 0x8f810e0e, 0x3d586565, 0xcc3cf0f0, 0x7d196464, 0x7ee59b9b, 0x91871616, 0x734e3d3d, 0x08aaa2a2, 0xc869a1a1
.word 0xc76aadad, 0x85830606, 0x7ab0caca, 0xb570c5c5, 0xf4659191, 0xb2d96b6b, 0xa7892e2e, 0x18fbe3e3, 0x47e8afaf
.word 0x330f3c3c, 0x674a2d2d, 0xb071c1c1, 0x0e575959, 0xe99f7676, 0xe135d4d4, 0x661e7878, 0xb4249090, 0x360e3838
.word 0x265f7979, 0xef628d8d, 0x38596161, 0x95d24747, 0x2aa08a8a, 0xb1259494, 0xaa228888, 0x8c7df1f1, 0xd73becec
.word 0x05010404, 0xa5218484, 0x9879e1e1, 0x9b851e1e, 0x84d75353, 0x00000000, 0x5e471919, 0x0b565d5d, 0xe39d7e7e
.word 0x9fd04f4f, 0xbb279c9c, 0x1a534949, 0x7c4d3131, 0xee36d8d8, 0x0a020808, 0x7be49f9f, 0x20a28282, 0xd4c71313
.word 0xe8cb2323, 0xe69c7a7a, 0x42e9abab, 0x43bdfefe, 0xa2882a2a, 0x9ad14b4b, 0x40410101, 0xdbc41f1f, 0xd838e0e0
.word 0x61b7d6d6, 0x2fa18e8e, 0x2bf4dfdf, 0x3af1cbcb, 0xf6cd3b3b, 0x1dfae7e7, 0xe5608585, 0x41155454, 0x25a38686
.word 0x60e38383, 0x16acbaba, 0x295c7575, 0x34a69292, 0xf7996e6e, 0xe434d0d0, 0x721a6868, 0x01545555, 0x19afb6b6
.word 0xdf914e4e, 0xfa32c8c8, 0xf030c0c0, 0x21f6d7d7, 0xbc8e3232, 0x75b3c6c6, 0x6fe08f8f, 0x691d7474, 0x2ef5dbdb
.word 0x6ae18b8b, 0x962eb8b8, 0x8a800a0a, 0xfe679999, 0xe2c92b2b, 0xe0618181, 0xc0c30303, 0x8d29a4a4, 0xaf238c8c
.word 0x07a9aeae, 0x390d3434, 0x1f524d4d, 0x764f3939, 0xd36ebdbd, 0x81d65757, 0xb7d86f6f, 0xeb37dcdc, 0x51441515
.word 0xa6dd7b7b, 0x09fef7f7, 0xb68c3a3a, 0x932fbcbc, 0x0f030c0c, 0x03fcffff, 0xc26ba9a9, 0xba73c9c9, 0xd96cb5b5
.word 0xdc6db1b1, 0x375a6d6d, 0x15504545, 0xb98f3636, 0x771b6c6c, 0x13adbebe, 0xda904a4a, 0x57b9eeee, 0xa9de7777
.word 0x4cbef2f2, 0x837efdfd, 0x55114444, 0xbdda6767, 0x2c5d7171, 0x45400505, 0x631f7c7c, 0x50104040, 0x325b6969
.word 0xb8db6363, 0x220a2828, 0xc5c20707, 0xf531c4c4, 0xa88a2222, 0x31a79696, 0xf9ce3737, 0x977aeded, 0x49bff6f6
.word 0x992db4b4, 0xa475d1d1, 0x90d34343, 0x5a124848, 0x58bae2e2, 0x71e69797, 0x64b6d2d2, 0x70b2c2c2, 0xad8b2626
.word 0xcd68a5a5, 0xcb955e5e, 0x624b2929, 0x3c0c3030, 0xce945a5a, 0xab76dddd, 0x867ff9f9, 0xf1649595, 0x5dbbe6e6
.word 0x35f2c7c7, 0x2d092424, 0xd1c61717, 0xd66fb9b9, 0xdec51b1b, 0x94861212, 0x78186060, 0x30f3c3c3, 0x897cf5f5
.word 0x5cefb3b3, 0xd23ae8e8, 0xacdf7373, 0x794c3535, 0xa0208080, 0x9d78e5e5, 0x56edbbbb, 0x235e7d7d, 0xc63ef8f8
.word 0x8bd45f5f, 0xe7c82f2f, 0xdd39e4e4, 0x68492121
#ifdef HITLS_BIG_ENDIAN
.Lxts_magic:
.quad 0x0101010101010101,0x0101010101010187
.Lsbox_magic:
.quad 0x0306090c0f020508,0x0b0e0104070a0d00
.quad 0x22581a6002783a40,0x62185a2042387a00
.quad 0xc10bb67c4a803df7,0x15df62a89e54e923
.quad 0x1407c6d56c7fbead,0xb9aa6b78c1d21300
.quad 0xe383c1a1fe9edcbc,0x6404462679195b3b
.quad 0x0E0D0C0F0A09080B,0x0605040702010003
.quad 0x0D0C0F0E09080B0A,0x0504070601000302
.quad 0x0C0F0E0D080B0A09,0x0407060500030201
#else
.Lxts_magic:
.quad 0x0101010101010187,0x0101010101010101
.Lsbox_magic:
.quad 0x0b0e0104070a0d00,0x0306090c0f020508
.quad 0x62185a2042387a00,0x22581a6002783a40
.quad 0x15df62a89e54e923,0xc10bb67c4a803df7
.quad 0xb9aa6b78c1d21300,0x1407c6d56c7fbead
.quad 0x6404462679195b3b,0xe383c1a1fe9edcbc
.quad 0x0605040702010003,0x0E0D0C0F0A09080B
.quad 0x0504070601000302,0x0D0C0F0E09080B0A
.quad 0x0407060500030201,0x0C0F0E0D080B0A09
#endif
.macro LoadSbox
adrp x15,.Lsbox_magic
add x15,x15,:lo12:.Lsbox_magic
ldr MaskQ, [x15]
ldr TAHMatQ, [x15, #16]
ldr TALMatQ, [x15, #32]
ldr ATAHMatQ, [x15, #48]
ldr ATALMatQ, [x15, #64]
ldr vtmp5q, [x15, #80]
ldr vtmp6q, [x15, #96]
ldr vtmp7q, [x15, #112]
.endm
.macro round x1, x2, x3, x4, rk
eor word0,\x2, \x3
eor word0, word0, \rk
eor word0, word0, \x4
and word1, word0, #0xff
ldr word1, [tbox0,xword1,lsl #2]
eor \x1, word1, \x1
ubfx word1, word0,#8,#8
ldr word1, [tbox1, xword1, lsl #2]
eor \x1, word1, \x1
ubfx word1, word0, #16, #8
ldr word1,[tbox2, xword1, lsl #2]
eor \x1, word1, \x1
lsr word1, word0, #24
ldr word1, [tbox3, xword1, lsl #2]
eor \x1, word1, \x1
.endm
.macro EncRound4 offset1, offset2
ldp word2, word3,[rks, \offset1]
round w8, w9, w10, w11, word2
round w9, w10, w11, w8, word3
ldp word2, word3,[rks, \offset2]
round w10, w11, w8, w9, word2
round w11, w8, w9, w10, word3
.endm
.macro EncRound
EncRound4 0, 8
EncRound4 16, 24
EncRound4 32, 40
EncRound4 48, 56
EncRound4 64, 72
EncRound4 80, 88
EncRound4 96, 104
EncRound4 112, 120
.endm
.macro transpose dat0s, dat1s, dat2s, dat3s, dat0d, dat1d, dat2d, dat3d, vt0s, vt1s, vt2s, vt3s, vt0d, vt1d, vt2d, vt3d
zip1 \vt0s, \dat0s, \dat1s
zip2 \vt1s, \dat0s, \dat1s
zip1 \vt2s, \dat2s, \dat3s
zip2 \vt3s, \dat2s, \dat3s
zip1 \dat0d, \vt0d, \vt2d
zip2 \dat1d, \vt0d, \vt2d
zip1 \dat2d, \vt1d, \vt3d
zip2 \dat3d, \vt1d, \vt3d
.endm
.macro Encrypt1blkNorevCtr
mov w8,ivec.s[0]
mov w9,ivec.s[1]
mov w10,ivec.s[2]
mov w11,ivec.s[3]
EncRound
mov ivec.s[0],w11
mov ivec.s[1],w10
mov ivec.s[2],w9
mov ivec.s[3],w8
#ifndef HITLS_BIG_ENDIAN
rev32 v3.16b,v3.16b
#endif
.endm
# matrix multiplication Mat*x = (lowerMat*x) ^ (higherMat*x)
.macro MulMatrix x, higherMat, lowerMat, tmp
ushr \tmp, \x, 4
and \x, \x, ANDMaskV.16b
tbl \x, {\lowerMat}, \x
tbl \tmp, {\higherMat}, \tmp
eor \x, \x, \tmp
.endm
# matrix multiplication Mat*x = (lowerMat*x) ^ (higherMat*x)
.macro MulMatrixOut x, higherMat, lowerMat, tmp, out
ushr \tmp, \x, 4
and \x, \x, ANDMaskV.16b
tbl \x, {\lowerMat}, \x
tbl \tmp, {\higherMat}, \tmp
eor \out, \x, \tmp
.endm
# Sbox operations for 4-lane of words
.macro Sbox dat, dat2
movi ANDMaskV.16b, #0x0f
// optimize Sbox using AESE instruction
tbl v0.16b, {\dat}, MaskV.16b
MulMatrix v0.16b, TAHMatV.16b, TALMatV.16b, v24.16b
eor v1.16b, v1.16b, v1.16b
aese v0.16b, v1.16b
MulMatrix v0.16b, ATAHMatV.16b, ATALMatV.16b, v24.16b
mov \dat, v0.16b
// linear transformation
ushr v0.4s, \dat2,32-2
ushr v1.4s, \dat2,32-10
ushr v2.4s, \dat2,32-18
ushr v3.4s, \dat2,32-24
sli v0.4s, \dat2,2
sli v1.4s, \dat2,10
sli v2.4s, \dat2,18
sli v3.4s, \dat2,24
eor v24.16b, v0.16b, \dat
eor v24.16b, v24.16b, v1.16b
eor \dat, v2.16b, v3.16b
eor \dat, \dat, v24.16b
.endm
# sm4 for 4-lanes of data, in neon registers data0/data1/data2/data3
.macro Sm44blks kptr
ldp wtmp0, wtmp1,[\kptr],8
dup rk0.4s, wtmp0
dup rk1.4s, wtmp1
// B0 ^= SBOX(B1 ^ B2 ^ B3 ^ RK0)
eor rka.16b, v6.16b, v7.16b
eor rk0.16b, v5.16b, rk0.16b
eor rk0.16b, rka.16b, rk0.16b
Sbox rk0.16b, rk0.4s
eor v4.16b, v4.16b, rk0.16b
// B1 ^= SBOX(B0 ^ B2 ^ B3 ^ RK1)
eor rka.16b, rka.16b, v4.16b
eor rk1.16b, rka.16b, rk1.16b
Sbox rk1.16b, rk1.4s
ldp wtmp0, wtmp1,[\kptr],8
eor v5.16b,v5.16b, rk1.16b
dup rk0.4s, wtmp0
dup rk1.4s, wtmp1
// B2 ^= SBOX(B0 ^ B1 ^ B3 ^ RK2)
eor rka.16b, v4.16b, v5.16b
eor rk0.16b, v7.16b, rk0.16b
eor rk0.16b, rka.16b, rk0.16b
Sbox rk0.16b, rk0.4s
eor v6.16b, v6.16b, rk0.16b
// B3 ^= SBOX(B0 ^ B1 ^ B2 ^ RK3)
eor rka.16b, rka.16b, v6.16b
eor rk1.16b, rka.16b, rk1.16b
Sbox rk1.16b, rk1.4s
eor v7.16b, v7.16b, rk1.16b
.endm
.macro Encrypt4blks
mov ptr, rks
mov counter,#8
10:
Sm44blks ptr
subs counter, counter,#1
b.ne 10b
#ifndef HITLS_BIG_ENDIAN
rev32 v3.16b,v4.16b
rev32 v2.16b,v5.16b
rev32 v1.16b,v6.16b
rev32 v0.16b,v7.16b
#else
mov v3.16b,v4.16b
mov v2.16b,v5.16b
mov v1.16b,v6.16b
mov v0.16b,v7.16b
#endif
.endm
# Sbox operation for 8-lane of words
.macro SboxDouble dat datx
movi ANDMaskV.16b, #0x0f
// optimize Sbox using AESE instruction
tbl v0.16b, {rk0.16b}, MaskV.16b
tbl v1.16b, {rk1.16b}, MaskV.16b
MulMatrix v0.16b, TAHMatV.16b, TALMatV.16b, v24.16b
MulMatrix v1.16b, TAHMatV.16b, TALMatV.16b, v24.16b
eor vtmp5.16b, vtmp5.16b, vtmp5.16b
aese v0.16b,vtmp5.16b
aese v1.16b,vtmp5.16b
MulMatrixOut v0.16b, ATAHMatV.16b, ATALMatV.16b, v24.16b, rk0.16b
MulMatrixOut v1.16b, ATAHMatV.16b, ATALMatV.16b, v24.16b, rk1.16b
// linear transformation
ushr v0.4s,rk0.4s,32-2
ushr vtmp5.4s,rk1.4s,32-2
ushr v1.4s,rk0.4s,32-10
ushr v2.4s,rk0.4s,32-18
ushr v3.4s,rk0.4s,32-24
sli v0.4s,rk0.4s,2
sli vtmp5.4s,rk1.4s,2
sli v1.4s,rk0.4s,10
sli v2.4s,rk0.4s,18
sli v3.4s,rk0.4s,24
eor v24.16b,v0.16b,rk0.16b
eor v24.16b,v24.16b,v1.16b
eor rk0.16b,v2.16b,v3.16b
eor rk0.16b,rk0.16b,v24.16b
ushr v1.4s,rk1.4s,32-10
ushr v2.4s,rk1.4s,32-18
ushr v3.4s,rk1.4s,32-24
sli v1.4s,rk1.4s,10
sli v2.4s,rk1.4s,18
sli v3.4s,rk1.4s,24
eor v24.16b,vtmp5.16b,rk1.16b
eor v24.16b,v24.16b,v1.16b
eor rk1.16b,v2.16b,v3.16b
eor rk1.16b,rk1.16b,v24.16b
.endm
.macro SboxThree dat, datx, dat1
movi ANDMaskV.16b, #0x0f
// optimize sbox using AESE instruction
tbl v0.16b, {\dat}, MaskV.16b
tbl v1.16b, {\datx}, MaskV.16b
tbl v2.16b, {\dat1}, MaskV.16b
eor v3.16b, v3.16b, v3.16b
MulMatrix v0.16b, TAHMatV.16b, TALMatV.16b, v24.16b
MulMatrix v1.16b, TAHMatV.16b, TALMatV.16b, v24.16b
aese v0.16b, v3.16b
MulMatrix v2.16b, TAHMatV.16b, TALMatV.16b, v24.16b
aese v1.16b, v3.16b
aese v2.16b, v3.16b
MulMatrixOut v0.16b, ATAHMatV.16b, ATALMatV.16b, v24.16b, \dat
MulMatrixOut v1.16b, ATAHMatV.16b, ATALMatV.16b, v24.16b, \datx
MulMatrixOut v2.16b, ATAHMatV.16b, ATALMatV.16b, v24.16b, \dat1
// linear transformation
tbl v0.16b, {\dat}, vtmp5.16b // shitf left 8
tbl v1.16b, {\datx}, vtmp5.16b
tbl v2.16b, {\dat1}, vtmp5.16b
tbl v3.16b, {\dat}, v22.16b // shitf left 16
tbl v24.16b, {\datx}, v22.16b
tbl ANDMaskV.16b, {\dat1}, v22.16b
eor v0.16b, v0.16b, \dat
eor v1.16b, v1.16b, \datx
eor v2.16b, v2.16b, \dat1
eor v0.16b, v0.16b, v3.16b
eor v1.16b, v1.16b, v24.16b
eor v2.16b, v2.16b, ANDMaskV.16b
shl v3.4s, v0.4s, #2 // shift left by 2 bits, equivalent to v12<<2 xor v12<<10 xor v12<<18
sri v3.4s, v0.4s, #30
shl v24.4s, v1.4s, #2
sri v24.4s, v1.4s, #30
shl ANDMaskV.4s, v2.4s, #2
sri ANDMaskV.4s, v2.4s, #30
tbl v0.16b, {\dat}, v23.16b // shitf left 24
tbl v1.16b, {\datx}, v23.16b
tbl v2.16b, {\dat1}, v23.16b
eor \dat, \dat, v3.16b
eor \datx, \datx, v24.16b
eor \dat1, \dat1, ANDMaskV.16b
eor \dat, v0.16b, \dat
eor \datx, v1.16b, \datx
eor \dat1, v2.16b, \dat1
.endm
.macro Sm48blks kptr
ldp wtmp0, wtmp1,[\kptr],8
// B0 ^= SBOX(B1 ^ B2 ^ B3 ^ RK0)
dup rk0.4s, wtmp0
eor rka.16b,v6.16b,v7.16b
eor rkb.16b,v10.16b,v11.16b
eor v0.16b,v5.16b,rk0.16b
eor v1.16b,v9.16b,rk0.16b
eor rk0.16b, rka.16b,v0.16b
eor rk1.16b, rkb.16b,v1.16b
SboxDouble
eor v4.16b, v4.16b, rk0.16b
eor v8.16b,v8.16b, rk1.16b
// B1 ^= SBOX(B0 ^ B2 ^ B3 ^ RK1)
dup rk1.4s, wtmp1
eor rka.16b,rka.16b,v4.16b
eor rkb.16b,rkb.16b,v8.16b
eor rk0.16b,rka.16b,rk1.16b
eor rk1.16b,rkb.16b,rk1.16b
SboxDouble
ldp wtmp0, wtmp1,[\kptr],8
eor v5.16b,v5.16b,rk0.16b
eor v9.16b,v9.16b,rk1.16b
// B2 ^= SBOX(B0 ^ B1 ^ B3 ^ RK2)
dup rk0.4s, wtmp0
eor rka.16b,v4.16b,v5.16b
eor rkb.16b,v8.16b,v9.16b
eor v0.16b,v7.16b,rk0.16b
eor v1.16b,v11.16b,rk0.16b
eor rk0.16b,rka.16b,v0.16b
eor rk1.16b,rkb.16b,v1.16b
SboxDouble
eor v6.16b,v6.16b,rk0.16b
eor v10.16b,v10.16b,rk1.16b
// B3 ^= SBOX(B0 ^ B1 ^ B2 ^ RK3)
dup rk1.4s, wtmp1
eor rka.16b,rka.16b,v6.16b
eor rkb.16b,rkb.16b,v10.16b
eor rk0.16b,rka.16b,rk1.16b
eor rk1.16b,rkb.16b,rk1.16b
SboxDouble
eor v7.16b,v7.16b,rk0.16b
eor v11.16b,v11.16b,rk1.16b
.endm
.macro Sm412blks kptr
ldp wtmp0,wtmp1,[\kptr],8
// B0 ^= SBOX(B1 ^ B2 ^ B3 ^ RK0)
dup rk0.4s,wtmp0
eor rka.16b,v6.16b,v7.16b
eor rkb.16b,v10.16b,v11.16b
eor rkc.16b,v18.16b,v19.16b
eor v0.16b,v5.16b,rk0.16b
eor v1.16b,v9.16b,rk0.16b
eor v2.16b,v17.16b,rk0.16b
eor rk0.16b,rka.16b,v0.16b
eor rk1.16b,rkb.16b,v1.16b
eor rk2.16b,rkc.16b,v2.16b
SboxThree rk0.16b, rk1.16b, rk2.16b
eor v4.16b,v4.16b,rk0.16b
eor v8.16b,v8.16b,rk1.16b
eor v16.16b,v16.16b,rk2.16b
// B1 ^= SBOX(B0 ^ B2 ^ B3 ^ RK1)
dup rk1.4s,wtmp1
eor rka.16b,rka.16b,v4.16b
eor rkb.16b,rkb.16b,v8.16b
eor rkc.16b,rkc.16b,v16.16b
eor rk0.16b,rka.16b,rk1.16b
eor rk2.16b,rkc.16b,rk1.16b
eor rk1.16b,rkb.16b,rk1.16b
SboxThree rk0.16b, rk1.16b, rk2.16b
ldp wtmp0,wtmp1,[\kptr],8
eor v5.16b,v5.16b,rk0.16b
eor v9.16b,v9.16b,rk1.16b
eor v17.16b,v17.16b,rk2.16b
// B2 ^= SBOX(B0 ^ B1 ^ B3 ^ RK2)
dup rk0.4s,wtmp0
eor rka.16b,v4.16b,v5.16b
eor rkb.16b,v8.16b,v9.16b
eor rkc.16b,v16.16b,v17.16b
eor v0.16b,v7.16b,rk0.16b
eor v1.16b,v11.16b,rk0.16b
eor v2.16b,v19.16b,rk0.16b
eor rk0.16b,rka.16b,v0.16b
eor rk1.16b,rkb.16b,v1.16b
eor rk2.16b,rkc.16b,v2.16b
SboxThree rk0.16b, rk1.16b, rk2.16b
eor v6.16b,v6.16b,rk0.16b
eor v10.16b,v10.16b,rk1.16b
eor v18.16b,v18.16b,rk2.16b
// B3 ^= SBOX(B0 ^ B1 ^ B2 ^ RK3)
dup rk1.4s,wtmp1
eor rka.16b,rka.16b,v6.16b
eor rkb.16b,rkb.16b,v10.16b
eor rkc.16b,rkc.16b,v18.16b
eor rk0.16b,rka.16b,rk1.16b
eor rk2.16b,rkc.16b,rk1.16b
eor rk1.16b,rkb.16b,rk1.16b
SboxThree rk0.16b, rk1.16b, rk2.16b
eor v7.16b,v7.16b,rk0.16b
eor v11.16b,v11.16b,rk1.16b
eor v19.16b,v19.16b,rk2.16b
.endm
.macro Encrypt8blks
mov ptr, rks
mov counter, #8
10:
Sm48blks ptr
subs counter, counter,#1
b.ne 10b
#ifndef HITLS_BIG_ENDIAN
rev32 v3.16b,v4.16b
rev32 v2.16b,v5.16b
rev32 v1.16b,v6.16b
rev32 v0.16b,v7.16b
rev32 v7.16b,v8.16b
rev32 v6.16b,v9.16b
rev32 v5.16b,v10.16b
rev32 v4.16b,v11.16b
#else
mov v3.16b,v4.16b
mov v2.16b,v5.16b
mov v1.16b,v6.16b
mov v0.16b,v7.16b
mov v7.16b,v8.16b
mov v6.16b,v9.16b
mov v5.16b,v10.16b
mov v4.16b,v11.16b
#endif
.endm
.macro Encrypt12blks
mov ptr, rks
mov counter, #8
10:
Sm412blks ptr
subs counter,counter,#1
b.ne 10b
// last reverse transform
#ifndef HITLS_BIG_ENDIAN
rev32 v3.16b,v4.16b
rev32 v2.16b,v5.16b
rev32 v1.16b,v6.16b
rev32 v0.16b,v7.16b
rev32 v7.16b,v8.16b
rev32 v6.16b,v9.16b
rev32 v5.16b,v10.16b
rev32 v4.16b,v11.16b
rev32 v11.16b,v16.16b
rev32 v10.16b,v17.16b
rev32 v9.16b,v18.16b
rev32 v8.16b,v19.16b
#else
mov v3.16b,v4.16b
mov v2.16b,v5.16b
mov v1.16b,v6.16b
mov v0.16b,v7.16b
mov v7.16b,v8.16b
mov v6.16b,v9.16b
mov v5.16b,v10.16b
mov v4.16b,v11.16b
mov v11.16b,v16.16b
mov v10.16b,v17.16b
mov v9.16b,v18.16b
mov v8.16b,v19.16b
#endif
.endm
.text
.type Sm4Enc4blks,%function
.align 4
Sm4Enc4blks:
AARCH64_PACIASP
Encrypt4blks
AARCH64_AUTIASP
ret
.size Sm4Enc4blks,.-Sm4Enc4blks
.type Sm4Enc8blks,%function
.align 4
Sm4Enc8blks:
AARCH64_PACIASP
Encrypt8blks
AARCH64_AUTIASP
ret
.size Sm4Enc8blks,.-Sm4Enc8blks
.type Sm4Enc12blks,%function
.align 4
Sm4Enc12blks:
AARCH64_PACIASP
Encrypt12blks
AARCH64_AUTIASP
ret
.size Sm4Enc12blks,.-Sm4Enc12blks
.globl Vpsm4EcbEncrypt
.type Vpsm4EcbEncrypt,%function
.align 5
Vpsm4EcbEncrypt:
AARCH64_PACIASP
// convert length into blocks
lsr x2,x2,4
stp d8,d9,[sp,#-112]!
stp d10,d11,[sp,#16]
stp d12,d13,[sp,#32]
stp d14,d15,[sp,#48]
stp x29,x30,[sp,#64]
stp x19,x20,[sp,#80]
stp x21,x22,[sp,#96]
LoadSbox
.Lecb_12_blocks_process:
cmp blocks,#12
b.lt .Lecb_8_blocks_process
ld4 {v4.4s,v5.4s,v6.4s,v7.4s},[inp],#64
ld4 {v8.4s,v9.4s,v10.4s,v11.4s},[inp],#64
ld4 {v16.4s,v17.4s,v18.4s,v19.4s},[inp],#64
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
rev32 v5.16b,v5.16b
rev32 v6.16b,v6.16b
rev32 v7.16b,v7.16b
rev32 v8.16b,v8.16b
rev32 v9.16b,v9.16b
rev32 v10.16b,v10.16b
rev32 v11.16b,v11.16b
rev32 v16.16b,v16.16b
rev32 v17.16b,v17.16b
rev32 v18.16b,v18.16b
rev32 v19.16b,v19.16b
#endif
bl Sm4Enc12blks
st4 {v0.4s,v1.4s,v2.4s,v3.4s},[outp],#64
st4 {v4.4s,v5.4s,v6.4s,v7.4s},[outp],#64
st4 {v8.4s,v9.4s,v10.4s,v11.4s},[outp],#64
subs blocks,blocks,#12
b.gt .Lecb_12_blocks_process
b 100f
.Lecb_8_blocks_process:
cmp blocks, #8
b.lt .Lecb_4_blocks_process
ld4 {v4.4s,v5.4s,v6.4s,v7.4s},[x0],#64
ld4 {v8.4s,v9.4s,v10.4s,v11.4s},[x0],#64
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
rev32 v5.16b,v5.16b
rev32 v6.16b,v6.16b
rev32 v7.16b,v7.16b
rev32 v8.16b,v8.16b
rev32 v9.16b,v9.16b
rev32 v10.16b,v10.16b
rev32 v11.16b,v11.16b
#endif
bl Sm4Enc8blks
st4 {v0.4s,v1.4s,v2.4s,v3.4s},[x1],#64
st4 {v4.4s,v5.4s,v6.4s,v7.4s},[x1],#64
subs blocks,blocks,#8
b.gt .Lecb_8_blocks_process
b 100f
.Lecb_4_blocks_process:
cmp blocks,#4
b.lt 1f
ld4 {v4.4s,v5.4s,v6.4s,v7.4s},[x0],#64
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b, v4.16b
rev32 v5.16b, v5.16b
rev32 v6.16b, v6.16b
rev32 v7.16b, v7.16b
#endif
bl Sm4Enc4blks
st4 {v0.4s,v1.4s,v2.4s,v3.4s},[x1],#64
sub blocks,blocks,#4
1:
// process last block
cmp blocks,#1
b.lt 100f
b.gt 1f
adrp x19, .Ltbox1
add x19,x19,:lo12:.Ltbox1
adrp x20, .Ltbox2
add x20,x20,:lo12:.Ltbox2
adrp x21, .Ltbox3
add x21,x21,:lo12:.Ltbox3
adrp x22, .Ltbox4
add x22,x22,:lo12:.Ltbox4
ldp w8,w9,[inp],#8
ldp w10,w11,[inp],#8
#ifndef HITLS_BIG_ENDIAN
rev w8,w8
rev w9,w9
rev w10,w10
rev w11,w11
#endif
EncRound
#ifndef HITLS_BIG_ENDIAN
rev w8,w8
rev w9,w9
rev w10,w10
rev w11,w11
#endif
stp w11,w10,[outp]
stp w9,w8,[outp,#8]
b 100f
1: // process last 2 blocks
ld4 {v4.s,v5.s,v6.s,v7.s}[0],[inp],#16
ld4 {v4.s,v5.s,v6.s,v7.s}[1],[inp],#16
cmp blocks,#2
b.gt 1f
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
rev32 v5.16b,v5.16b
rev32 v6.16b,v6.16b
rev32 v7.16b,v7.16b
#endif
bl Sm4Enc4blks
st4 {v0.s,v1.s,v2.s,v3.s}[0],[outp],#16
st4 {v0.s,v1.s,v2.s,v3.s}[1],[outp]
b 100f //
1: // process last 3 blocks
ld4 {v4.s,v5.s,v6.s,v7.s}[2],[inp],#16
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
rev32 v5.16b,v5.16b
rev32 v6.16b,v6.16b
rev32 v7.16b,v7.16b
#endif
bl Sm4Enc4blks
st4 {v0.s,v1.s,v2.s,v3.s}[0],[outp],#16
st4 {v0.s,v1.s,v2.s,v3.s}[1],[outp],#16
st4 {v0.s,v1.s,v2.s,v3.s}[2],[outp]
100:
ldp d10,d11,[sp,#16]
ldp d12,d13,[sp,#32]
ldp d14,d15,[sp,#48]
ldp x29,x30,[sp,#64]
ldp x19,x20,[sp,#80]
ldp x21,x22,[sp,#96]
ldp d8,d9,[sp],#112
AARCH64_AUTIASP
ret
.size Vpsm4EcbEncrypt,.-Vpsm4EcbEncrypt
.globl Vpsm4CbcEncrypt
.type Vpsm4CbcEncrypt,%function
.align 5
Vpsm4CbcEncrypt:
AARCH64_PACIASP
lsr len,len,4
stp x29,x30,[sp,#-48]!
stp x19,x20,[sp,#16]
stp x21,x22,[sp,#32]
// load tbox
adrp x19, .Ltbox1
add x19,x19,:lo12:.Ltbox1
adrp x20, .Ltbox2
add x20,x20,:lo12:.Ltbox2
adrp x21, .Ltbox3
add x21,x21,:lo12:.Ltbox3
adrp x22, .Ltbox4
add x22,x22,:lo12:.Ltbox4
cbz w5,.Ldec
// load iv
ldp w8,w9,[ivp]
ldp w10,w11,[ivp,#8]
.Lcbc_1_block_enc:
subs blocks,blocks,#1
b.lt 2f
ldp w6,w7,[inp],#8
ldp w16,w17,[inp],#8
eor w8,w8,w6
eor w9,w9,w7
eor w10,w10,w16
eor w11,w11,w17
#ifndef HITLS_BIG_ENDIAN
rev w8,w8
rev w9,w9
rev w10,w10
rev w11,w11
#endif
EncRound
#ifndef HITLS_BIG_ENDIAN
rev w8,w8
rev w9,w9
rev w10,w10
rev w11,w11
#endif
// reverse to store
mov w6,w8
mov w8,w11
mov w11,w6
mov w7,w9
mov w9,w10
mov w10,w7
stp w8,w9,[outp],#8
stp w10,w11,[outp],#8
b .Lcbc_1_block_enc
2:
// save back IV
stp w8,w9,[ivp]
stp w10,w11,[ivp,#8]
ldp x19,x20,[sp,#16]
ldp x21,x22,[sp,#32]
ldp x29,x30,[sp],#48
AARCH64_AUTIASP
ret
.Ldec:
LoadSbox
// decryption mode starts
stp d8,d9,[sp,#-64]!
stp d10,d11,[sp,#16]
stp d12,d13,[sp,#32]
stp d14,d15,[sp,#48]
.Lcbc_12_blocks_dec:
cmp w2,#12
b.lt .Lcbc_8_blocks_dec
ld4 {v4.4s,v5.4s,v6.4s,v7.4s},[x0]
add x10,x0,#64
ld4 {v8.4s,v9.4s,v10.4s,v11.4s},[x10]
add x10,x10,#64
ld4 {v16.4s,v17.4s,v18.4s,v19.4s},[x10]
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
rev32 v5.16b,v5.16b
rev32 v6.16b,v6.16b
rev32 v7.16b,v7.16b
rev32 v8.16b,v8.16b
rev32 v9.16b,v9.16b
rev32 v10.16b,v10.16b
rev32 v11.16b,v11.16b
rev32 v16.16b,v16.16b
rev32 v17.16b,v17.16b
rev32 v18.16b,v18.16b
rev32 v19.16b,v19.16b
#endif
bl Sm4Enc12blks
// transpose to xor iv
transpose v0.4s,v1.4s,v2.4s,v3.4s,v0.2d,v1.2d,v2.2d,v3.2d,v16.4s,v17.4s,v18.4s,v19.4s,v16.2d,v17.2d,v18.2d,v19.2d
transpose v4.4s,v5.4s,v6.4s,v7.4s,v4.2d,v5.2d,v6.2d,v7.2d,v16.4s,v17.4s,v18.4s,v19.4s,v16.2d,v17.2d,v18.2d,v19.2d
transpose v8.4s,v9.4s,v10.4s,v11.4s,v8.2d,v9.2d,v10.2d,v11.2d,v16.4s,v17.4s,v18.4s,v19.4s,v16.2d,v17.2d,v18.2d,v19.2d
ld1 {ivec1.4s},[ivp]
ld1 {v16.4s,v17.4s,v18.4s,v19.4s},[inp],#64
eor v0.16b,v0.16b,ivec1.16b
ld1 {v12.4s,v13.4s,v14.4s,v15.4s},[inp],#64
eor v1.16b,v1.16b,v16.16b
eor v2.16b,v2.16b,v17.16b
eor v3.16b,v3.16b,v18.16b
st1 {v0.4s,v1.4s,v2.4s,v3.4s},[outp],#64
eor v4.16b,v4.16b,v19.16b
eor v5.16b,v5.16b,v12.16b
eor v6.16b,v6.16b,v13.16b
eor v7.16b,v7.16b,v14.16b
st1 {v4.4s,v5.4s,v6.4s,v7.4s},[outp],#64
ld1 {v16.4s,v17.4s,v18.4s,v19.4s},[inp],#64
eor v8.16b,v8.16b,v15.16b
eor v9.16b,v9.16b,v16.16b
eor v10.16b,v10.16b,v17.16b
eor v11.16b,v11.16b,v18.16b
st1 {v8.4s,v9.4s,v10.4s,v11.4s},[outp],#64
// save back iv
st1 {v19.4s}, [ivp]
subs blocks,blocks,#12
b.gt .Lcbc_12_blocks_dec
b 100f
.Lcbc_8_blocks_dec:
cmp blocks,#8
b.lt 1f
ld4 {v4.4s,v5.4s,v6.4s,v7.4s},[inp]
add ptr, inp, #64
ld4 {v8.4s,v9.4s,v10.4s,v11.4s},[ptr]
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
rev32 v5.16b,v5.16b
rev32 v6.16b,v6.16b
rev32 v7.16b,v7.16b
rev32 v8.16b,v8.16b
rev32 v9.16b,v9.16b
rev32 v10.16b,v10.16b
rev32 v11.16b,v11.16b
#endif
bl Sm4Enc8blks
transpose v0.4s,v1.4s,v2.4s,v3.4s,v0.2d,v1.2d,v2.2d,v3.2d,v8.4s,v9.4s,v10.4s,v11.4s,v8.2d,v9.2d,v10.2d,v11.2d
transpose v4.4s,v5.4s,v6.4s,v7.4s,v4.2d,v5.2d,v6.2d,v7.2d,v8.4s,v9.4s,v10.4s,v11.4s,v8.2d,v9.2d,v10.2d,v11.2d
ld1 {ivec1.4s},[ivp]
ld1 {v8.4s,v9.4s,v10.4s,v11.4s},[inp],#64
// note ivec1 and v15 are resuing the same register
// care needs to be taken to avoid conflict
eor v0.16b,v0.16b,ivec1.16b
ld1 {v12.4s,v13.4s,v14.4s,v15.4s},[inp],#64
eor v1.16b,v1.16b,v8.16b
eor v2.16b,v2.16b,v9.16b
eor v3.16b,v3.16b,v10.16b
// save back IV
st1 {v15.4s}, [ivp]
eor v4.16b,v4.16b,v11.16b
eor v5.16b,v5.16b,v12.16b
eor v6.16b,v6.16b,v13.16b
eor v7.16b,v7.16b,v14.16b
st1 {v0.4s,v1.4s,v2.4s,v3.4s},[outp],#64
st1 {v4.4s,v5.4s,v6.4s,v7.4s},[outp],#64
subs blocks,blocks,#8
b.gt .Lcbc_8_blocks_dec
b.eq 100f
1:
ld1 {ivec1.4s},[ivp]
.Lcbc_4_blocks_dec:
cmp blocks,#4
b.lt 1f
ld4 {v4.4s,v5.4s,v6.4s,v7.4s},[inp]
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
rev32 v5.16b,v5.16b
rev32 v6.16b,v6.16b
rev32 v7.16b,v7.16b
#endif
bl Sm4Enc4blks
ld1 {v4.4s,v5.4s,v6.4s,v7.4s},[inp],#64
transpose v0.4s,v1.4s,v2.4s,v3.4s,v0.2d,v1.2d,v2.2d,v3.2d,v8.4s,v9.4s,v10.4s,v11.4s,v8.2d,v9.2d,v10.2d,v11.2d
eor v0.16b,v0.16b,ivec1.16b
eor v1.16b,v1.16b,v4.16b
orr v15.16b,v7.16b,v7.16b
eor v2.16b,v2.16b,v5.16b
eor v3.16b,v3.16b,v6.16b
st1 {v0.4s,v1.4s,v2.4s,v3.4s},[outp],#64
// save back IV
st1 {v7.4s}, [ivp]
subs blocks,blocks,#4
b.gt .Lcbc_4_blocks_dec
b 100f
1: // last block
subs blocks,blocks,#1
b.lt 100f
b.gt 1f
// load iv
ldp w6,w7,[ivp]
ldp w16,w17,[ivp,#8]
ldp w8,w9,[inp]
ldp w10,w11,[inp,#8]
// store back iv
stp w8,w9,[ivp]
stp w10,w11,[ivp,#8]
#ifndef HITLS_BIG_ENDIAN
rev w8,w8
rev w9,w9
rev w10,w10
rev w11,w11
#endif
EncRound
#ifndef HITLS_BIG_ENDIAN
rev w8,w8
rev w9,w9
rev w10,w10
rev w11,w11
#endif
eor w11,w11,w6
eor w10,w10,w7
eor w9,w9,w16
eor w8,w8,w17
stp w11,w10,[outp],#8
stp w9,w8,[outp],#8
b 100f
1: // last two blocks
ld4 {v4.s,v5.s,v6.s,v7.s}[0], [inp]
add ptr,inp,#16
ld4 {v4.s,v5.s,v6.s,v7.s}[1],[ptr],#16
subs blocks,blocks,1
b.gt 1f
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
rev32 v5.16b,v5.16b
rev32 v6.16b,v6.16b
rev32 v7.16b,v7.16b
#endif
bl Sm4Enc4blks
ld1 {v4.4s,v5.4s},[inp],#32
transpose v0.4s,v1.4s,v2.4s,v3.4s,v0.2d,v1.2d,v2.2d,v3.2d,v8.4s,v9.4s,v10.4s,v11.4s,v8.2d,v9.2d,v10.2d,v11.2d
eor v0.16b,v0.16b,ivec1.16b
eor v1.16b,v1.16b,v4.16b
st1 {v0.4s,v1.4s},[outp],#32
// save back IV
st1 {v5.4s}, [ivp]
b 100f
1: // last 3 blocks
ld4 {v4.s,v5.s,v6.s,v7.s}[2],[ptr]
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
rev32 v5.16b,v5.16b
rev32 v6.16b,v6.16b
rev32 v7.16b,v7.16b
#endif
bl Sm4Enc4blks
ld1 {v4.4s,v5.4s,v6.4s},[inp],#48
transpose v0.4s,v1.4s,v2.4s,v3.4s,v0.2d,v1.2d,v2.2d,v3.2d,v8.4s,v9.4s,v10.4s,v11.4s,v8.2d,v9.2d,v10.2d,v11.2d
eor v0.16b,v0.16b,ivec1.16b
eor v1.16b,v1.16b,v4.16b
eor v2.16b,v2.16b,v5.16b
st1 {v0.4s,v1.4s,v2.4s},[outp],#48
// save back IV
st1 {v6.4s}, [ivp]
100:
ldp d10,d11,[sp,#16]
ldp d12,d13,[sp,#32]
ldp d14,d15,[sp,#48]
ldp d8,d9,[sp],#64
ldp x19,x20,[sp,#16]
ldp x21,x22,[sp,#32]
ldp x29,x30,[sp],#48
AARCH64_AUTIASP
ret
.size Vpsm4CbcEncrypt,.-Vpsm4CbcEncrypt
# void Vpsm4Ctr32EncryptBlocks(const uint8_t *in, uint8_t *out, uint64_t blocks, const uint32_t *key, uint8_t *iv);
.globl Vpsm4Ctr32EncryptBlocks
.type Vpsm4Ctr32EncryptBlocks,%function
.align 5
Vpsm4Ctr32EncryptBlocks:
AARCH64_PACIASP
ld1 {ivec.4s},[ivp]
#ifndef HITLS_BIG_ENDIAN
rev32 v3.16b,v3.16b
#endif
LoadSbox
cmp blocks,#1
b.ne 1f
// fast processing for one single block without
// context saving overhead
stp x19,x20,[sp,#-32]!
stp x21,x22,[sp,#16]
adrp x19, .Ltbox1
add x19,x19,:lo12:.Ltbox1
adrp x20, .Ltbox2
add x20,x20,:lo12:.Ltbox2
adrp x21, .Ltbox3
add x21,x21,:lo12:.Ltbox3
adrp x22, .Ltbox4
add x22,x22,:lo12:.Ltbox4
Encrypt1blkNorevCtr
ld1 {v4.4s},[inp]
eor v4.16b,v4.16b,ivec.16b
st1 {v4.4s},[outp]
ldp x21,x22,[sp,#16]
ldp x19,x20,[sp],#32
ldr ctr,[ivp,#12]
#ifndef HITLS_BIG_ENDIAN
rev ctr,ctr
#endif
add ctr,ctr,#1
#ifndef HITLS_BIG_ENDIAN
rev ctr,ctr
#endif
str ctr,[ivp,#12]
AARCH64_AUTIASP
ret
1:
stp d8,d9,[sp,#-112]!
stp d10,d11,[sp,#16]
stp d12,d13,[sp,#32]
stp d14,d15,[sp,#48]
stp x29,x30,[sp,#64]
stp x19,x20,[sp,#80]
stp x21,x22,[sp,#96]
mov word0, ivec.s[0]
mov word1, ivec.s[1]
mov word2, ivec.s[2]
mov ctr, ivec.s[3]
.Lctr32_4_blocks_process:
cmp blocks,#4
b.lt 1f
dup v4.4s,word0
dup v5.4s,word1
dup v6.4s,word2
mov v7.s[0],w5
add ctr,ctr,#1
mov v7.s[1],ctr
add ctr,ctr,#1
mov v7.s[2],ctr
add ctr,ctr,#1
mov v7.s[3],ctr
add ctr,ctr,#1
cmp blocks,#8
b.ge .Lctr32_8_blocks_process
bl Sm4Enc4blks
ld4 {v12.4s,v13.4s,v14.4s,v15.4s},[inp],#64
eor v0.16b,v0.16b,v12.16b
eor v1.16b,v1.16b,v13.16b
eor v2.16b,v2.16b,v14.16b
eor v3.16b,v3.16b,v15.16b
st4 {v0.4s,v1.4s,v2.4s,v3.4s},[outp],#64
subs blocks,blocks,#4
b.ne .Lctr32_4_blocks_process
b 100f
.Lctr32_8_blocks_process:
dup v8.4s,word0
dup v9.4s,word1
dup v10.4s,word2
mov v11.s[0],ctr
add ctr,ctr,#1
mov v11.s[1],ctr
add ctr,ctr,#1
mov v11.s[2],ctr
add ctr,ctr,#1
mov v11.s[3],ctr
add ctr,ctr,#1
cmp blocks,#12
b.ge .Lctr32_12_blocks_process
bl Sm4Enc8blks
ld4 {v12.4s,v13.4s,v14.4s,v15.4s},[inp],#64
ld4 {v8.4s,v9.4s,v10.4s,v11.4s},[inp],#64
eor v0.16b,v0.16b,v12.16b
eor v1.16b,v1.16b,v13.16b
eor v2.16b,v2.16b,v14.16b
eor v3.16b,v3.16b,v15.16b
eor v4.16b,v4.16b,v8.16b
eor v5.16b,v5.16b,v9.16b
eor v6.16b,v6.16b,v10.16b
eor v7.16b,v7.16b,v11.16b
st4 {v0.4s,v1.4s,v2.4s,v3.4s},[outp],#64
st4 {v4.4s,v5.4s,v6.4s,v7.4s},[outp],#64
subs blocks,blocks,#8
b.ne .Lctr32_4_blocks_process
b 100f
.Lctr32_12_blocks_process:
dup v16.4s,word0
dup v17.4s,word1
dup v18.4s,word2
mov v19.s[0],ctr
add ctr,ctr,#1
mov v19.s[1],ctr
add ctr,ctr,#1
mov v19.s[2],ctr
add ctr,ctr,#1
mov v19.s[3],ctr
add ctr,ctr,#1
bl Sm4Enc12blks
ld4 {v12.4s,v13.4s,v14.4s,v15.4s},[inp],#64
eor v0.16b,v0.16b,v12.16b
eor v1.16b,v1.16b,v13.16b
eor v2.16b,v2.16b,v14.16b
eor v3.16b,v3.16b,v15.16b
st4 {v0.4s,v1.4s,v2.4s,v3.4s},[outp],#64
ld4 {v12.4s,v13.4s,v14.4s,v15.4s},[inp],#64
eor v4.16b,v4.16b,v12.16b
eor v5.16b,v5.16b,v13.16b
eor v6.16b,v6.16b,v14.16b
eor v7.16b,v7.16b,v15.16b
st4 {v4.4s,v5.4s,v6.4s,v7.4s},[outp],#64
ld4 {v12.4s,v13.4s,v14.4s,v15.4s},[inp],#64
eor v8.16b,v8.16b,v12.16b
eor v9.16b,v9.16b,v13.16b
eor v10.16b,v10.16b,v14.16b
eor v11.16b,v11.16b,v15.16b
st4 {v8.4s,v9.4s,v10.4s,v11.4s},[outp],#64
subs blocks,blocks,#12
b.ne .Lctr32_4_blocks_process
b 100f
1: // last block processing
subs blocks,blocks,#1
b.lt 100f
b.gt 1f
mov ivec.s[0],word0
mov ivec.s[1],word1
mov ivec.s[2],word2
mov ivec.s[3],ctr
add ctr,ctr,#1
adrp x19, .Ltbox1
add x19,x19,:lo12:.Ltbox1
adrp x20, .Ltbox2
add x20,x20,:lo12:.Ltbox2
adrp x21, .Ltbox3
add x21,x21,:lo12:.Ltbox3
adrp x22, .Ltbox4
add x22,x22,:lo12:.Ltbox4
Encrypt1blkNorevCtr
ld1 {v4.4s},[inp]
eor v4.16b,v4.16b,ivec.16b
st1 {v4.4s},[outp]
b 100f
1: // last 2 blocks processing
dup v4.4s,word0
dup v5.4s,word1
dup v6.4s,word2
mov v7.s[0],ctr
add ctr,ctr,#1
mov v7.s[1],ctr
subs blocks,blocks,#1
b.ne 1f
add ctr,ctr,#1
bl Sm4Enc4blks
ld4 {v12.s,v13.s,v14.s,v15.s}[0],[inp],#16
ld4 {v12.s,v13.s,v14.s,v15.s}[1],[inp],#16
eor v0.16b,v0.16b,v12.16b
eor v1.16b,v1.16b,v13.16b
eor v2.16b,v2.16b,v14.16b
eor v3.16b,v3.16b,v15.16b
st4 {v0.s,v1.s,v2.s,v3.s}[0],[outp],#16
st4 {v0.s,v1.s,v2.s,v3.s}[1],[outp],#16
b 100f
1: // last 3 blocks processing
add ctr,ctr,#1
mov v7.s[2],ctr
add ctr,ctr,#1
bl Sm4Enc4blks
ld4 {v12.s,v13.s,v14.s,v15.s}[0],[inp],#16
ld4 {v12.s,v13.s,v14.s,v15.s}[1],[inp],#16
ld4 {v12.s,v13.s,v14.s,v15.s}[2],[inp],#16
eor v0.16b,v0.16b,v12.16b
eor v1.16b,v1.16b,v13.16b
eor v2.16b,v2.16b,v14.16b
eor v3.16b,v3.16b,v15.16b
st4 {v0.s,v1.s,v2.s,v3.s}[0],[outp],#16
st4 {v0.s,v1.s,v2.s,v3.s}[1],[outp],#16
st4 {v0.s,v1.s,v2.s,v3.s}[2],[outp],#16
100:
ldp d10,d11,[sp,#16]
ldp d12,d13,[sp,#32]
ldp d14,d15,[sp,#48]
ldp x29,x30,[sp,#64]
ldp x19,x20,[sp,#80]
ldp x21,x22,[sp,#96]
ldp d8,d9,[sp],#112
#ifndef HITLS_BIG_ENDIAN
rev ctr, ctr
#endif
str ctr, [ivp,#12]
AARCH64_AUTIASP
ret
.size Vpsm4Ctr32EncryptBlocks,.-Vpsm4Ctr32EncryptBlocks
.globl Vpsm4XtsCipher
.type Vpsm4XtsCipher,%function
.align 5
Vpsm4XtsCipher:
AARCH64_PACIASP
stp x19, x20, [sp, #-0x10]!
stp x21, x22, [sp, #-0x10]!
stp x23, x24, [sp, #-0x10]!
stp x25, x26, [sp, #-0x10]!
stp x27, x28, [sp, #-0x10]!
stp x29, x30, [sp, #-0x10]!
stp d8, d9, [sp, #-0x10]!
stp d10, d11, [sp, #-0x10]!
stp d12, d13, [sp, #-0x10]!
stp d14, d15, [sp, #-0x10]!
sub sp, sp, #192
mov x24, sp
mov x26,x3
mov x27,x4
mov w28,w6
ld1 {v16.4s}, [x5]
LoadSbox
and x29,x2,#0x0F
// convert length into blocks
lsr x2,x2,4
cmp x2,#1
b.lt .Lxts_cipher_return
cmp x29,0
// If the encryption/decryption Length is N times of 16,
// the all blocks are encrypted/decrypted in .xts_encrypt_blocks
b.eq .xts_encrypt_blocks
// If the encryption/decryption length is not N times of 16,
// the last two blocks are encrypted/decrypted in .last_2blks_tweak or .only_2blks_tweak
// the other blocks are encrypted/decrypted in .xts_encrypt_blocks
subs x2,x2,#1
b.eq .only_2blks_tweak
.xts_encrypt_blocks:
rbit v16.16b,v16.16b
#ifdef HITLS_BIG_ENDIAN
rev32 v16.16b,v16.16b
#endif
mov x12,v16.d[0]
mov x13,v16.d[1]
mov w7,0x87
extr x9,x13,x13,#32
extr x15,x13,x12,#63
and w8,w7,w9,asr#31
eor x14,x8,x12,lsl#1
mov w7,0x87
extr x9,x15,x15,#32
extr x17,x15,x14,#63
and w8,w7,w9,asr#31
eor x16,x8,x14,lsl#1
mov w7,0x87
extr x9,x17,x17,#32
extr x19,x17,x16,#63
and w8,w7,w9,asr#31
eor x18,x8,x16,lsl#1
.Lxts_12_blocks_process:
mov x24, sp
cmp x2,#12
b.lt .Lxts_8_blocks_process
mov v16.d[0],x12
mov v16.d[1],x13
#ifdef HITLS_BIG_ENDIAN
rev32 v16.16b,v16.16b
#endif
mov w7,0x87
extr x9,x19,x19,#32
extr x13,x19,x18,#63
and w8,w7,w9,asr#31
eor x12,x8,x18,lsl#1
mov v17.d[0],x14
mov v17.d[1],x15
#ifdef HITLS_BIG_ENDIAN
rev32 v17.16b,v17.16b
#endif
mov w7,0x87
extr x9,x13,x13,#32
extr x15,x13,x12,#63
and w8,w7,w9,asr#31
eor x14,x8,x12,lsl#1
mov v18.d[0],x16
mov v18.d[1],x17
#ifdef HITLS_BIG_ENDIAN
rev32 v18.16b,v18.16b
#endif
mov w7,0x87
extr x9,x15,x15,#32
extr x17,x15,x14,#63
and w8,w7,w9,asr#31
eor x16,x8,x14,lsl#1
mov v19.d[0],x18
mov v19.d[1],x19
#ifdef HITLS_BIG_ENDIAN
rev32 v19.16b,v19.16b
#endif
mov w7,0x87
extr x9,x17,x17,#32
extr x19,x17,x16,#63
and w8,w7,w9,asr#31
eor x18,x8,x16,lsl#1
ld1 {v4.4s,v5.4s,v6.4s,v7.4s},[x0],#64
rbit v16.16b,v16.16b
rbit v17.16b,v17.16b
rbit v18.16b,v18.16b
rbit v19.16b,v19.16b
eor v4.16b, v4.16b, v16.16b
eor v5.16b, v5.16b, v17.16b
eor v6.16b, v6.16b, v18.16b
eor v7.16b, v7.16b, v19.16b
ld1 {v8.4s,v9.4s,v10.4s,v11.4s},[x0],#64
st1 {v16.4s,v17.4s,v18.4s,v19.4s},[x24],#64
mov v16.d[0],x12
mov v16.d[1],x13
#ifdef HITLS_BIG_ENDIAN
rev32 v16.16b,v16.16b
#endif
mov w7,0x87
extr x9,x19,x19,#32
extr x13,x19,x18,#63
and w8,w7,w9,asr#31
eor x12,x8,x18,lsl#1
mov v17.d[0],x14
mov v17.d[1],x15
#ifdef HITLS_BIG_ENDIAN
rev32 v17.16b,v17.16b
#endif
mov w7,0x87
extr x9,x13,x13,#32
extr x15,x13,x12,#63
and w8,w7,w9,asr#31
eor x14,x8,x12,lsl#1
mov v18.d[0],x16
mov v18.d[1],x17
#ifdef HITLS_BIG_ENDIAN
rev32 v18.16b,v18.16b
#endif
mov w7,0x87
extr x9,x15,x15,#32
extr x17,x15,x14,#63
and w8,w7,w9,asr#31
eor x16,x8,x14,lsl#1
mov v19.d[0],x18
mov v19.d[1],x19
#ifdef HITLS_BIG_ENDIAN
rev32 v19.16b,v19.16b
#endif
mov w7,0x87
extr x9,x17,x17,#32
extr x19,x17,x16,#63
and w8,w7,w9,asr#31
eor x18,x8,x16,lsl#1
rbit v16.16b,v16.16b
rbit v17.16b,v17.16b
rbit v18.16b,v18.16b
rbit v19.16b,v19.16b
eor v8.16b, v8.16b, v16.16b
eor v9.16b, v9.16b, v17.16b
eor v10.16b, v10.16b, v18.16b
eor v11.16b, v11.16b, v19.16b
ld1 {v0.4s,v1.4s,v2.4s,v3.4s},[x0],#64
st1 {v16.4s,v17.4s,v18.4s,v19.4s},[x24],#64
mov v16.d[0],x12
mov v16.d[1],x13
#ifdef HITLS_BIG_ENDIAN
rev32 v16.16b,v16.16b
#endif
mov w7,0x87
extr x9,x19,x19,#32
extr x13,x19,x18,#63
and w8,w7,w9,asr#31
eor x12,x8,x18,lsl#1
mov v17.d[0],x14
mov v17.d[1],x15
#ifdef HITLS_BIG_ENDIAN
rev32 v17.16b,v17.16b
#endif
mov w7,0x87
extr x9,x13,x13,#32
extr x15,x13,x12,#63
and w8,w7,w9,asr#31
eor x14,x8,x12,lsl#1
mov v18.d[0],x16
mov v18.d[1],x17
#ifdef HITLS_BIG_ENDIAN
rev32 v18.16b,v18.16b
#endif
mov w7,0x87
extr x9,x15,x15,#32
extr x17,x15,x14,#63
and w8,w7,w9,asr#31
eor x16,x8,x14,lsl#1
mov v19.d[0],x18
mov v19.d[1],x19
#ifdef HITLS_BIG_ENDIAN
rev32 v19.16b,v19.16b
#endif
mov w7,0x87
extr x9,x17,x17,#32
extr x19,x17,x16,#63
and w8,w7,w9,asr#31
eor x18,x8,x16,lsl#1
rbit v16.16b,v16.16b
rbit v17.16b,v17.16b
rbit v18.16b,v18.16b
rbit v19.16b,v19.16b
eor v0.16b, v0.16b, v16.16b
eor v1.16b, v1.16b, v17.16b
eor v2.16b, v2.16b, v18.16b
eor v3.16b, v3.16b, v19.16b
st1 {v16.4s,v17.4s,v18.4s,v19.4s},[x24],#64
mov v16.16b,v0.16b
mov v17.16b,v1.16b
mov v18.16b,v2.16b
mov v19.16b,v3.16b
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
rev32 v5.16b,v5.16b
rev32 v6.16b,v6.16b
rev32 v7.16b,v7.16b
rev32 v8.16b,v8.16b
rev32 v9.16b,v9.16b
rev32 v10.16b,v10.16b
rev32 v11.16b,v11.16b
rev32 v16.16b,v16.16b
rev32 v17.16b,v17.16b
rev32 v18.16b,v18.16b
rev32 v19.16b,v19.16b
#endif
zip1 v0.4s,v4.4s,v5.4s
zip2 v1.4s,v4.4s,v5.4s
zip1 v2.4s,v6.4s,v7.4s
zip2 v3.4s,v6.4s,v7.4s
zip1 v4.2d,v0.2d,v2.2d
zip2 v5.2d,v0.2d,v2.2d
zip1 v6.2d,v1.2d,v3.2d
zip2 v7.2d,v1.2d,v3.2d
zip1 v0.4s,v8.4s,v9.4s
zip2 v1.4s,v8.4s,v9.4s
zip1 v2.4s,v10.4s,v11.4s
zip2 v3.4s,v10.4s,v11.4s
zip1 v8.2d,v0.2d,v2.2d
zip2 v9.2d,v0.2d,v2.2d
zip1 v10.2d,v1.2d,v3.2d
zip2 v11.2d,v1.2d,v3.2d
zip1 v0.4s,v16.4s,v17.4s
zip2 v1.4s,v16.4s,v17.4s
zip1 v2.4s,v18.4s,v19.4s
zip2 v3.4s,v18.4s,v19.4s
zip1 v16.2d,v0.2d,v2.2d
zip2 v17.2d,v0.2d,v2.2d
zip1 v18.2d,v1.2d,v3.2d
zip2 v19.2d,v1.2d,v3.2d
bl Sm4Enc12blks
zip1 v16.4s,v0.4s,v1.4s
zip2 v17.4s,v0.4s,v1.4s
zip1 v18.4s,v2.4s,v3.4s
zip2 v19.4s,v2.4s,v3.4s
zip1 v0.2d,v16.2d,v18.2d
zip2 v1.2d,v16.2d,v18.2d
zip1 v2.2d,v17.2d,v19.2d
zip2 v3.2d,v17.2d,v19.2d
zip1 v16.4s,v4.4s,v5.4s
zip2 v17.4s,v4.4s,v5.4s
zip1 v18.4s,v6.4s,v7.4s
zip2 v19.4s,v6.4s,v7.4s
zip1 v4.2d,v16.2d,v18.2d
zip2 v5.2d,v16.2d,v18.2d
zip1 v6.2d,v17.2d,v19.2d
zip2 v7.2d,v17.2d,v19.2d
zip1 v16.4s,v8.4s,v9.4s
zip2 v17.4s,v8.4s,v9.4s
zip1 v18.4s,v10.4s,v11.4s
zip2 v19.4s,v10.4s,v11.4s
zip1 v8.2d,v16.2d,v18.2d
zip2 v9.2d,v16.2d,v18.2d
zip1 v10.2d,v17.2d,v19.2d
zip2 v11.2d,v17.2d,v19.2d
mov x24, sp
ld1 {v16.4s,v17.4s,v18.4s,v19.4s},[x24],#64
eor v0.16b, v0.16b, v16.16b
eor v1.16b, v1.16b, v17.16b
eor v2.16b, v2.16b, v18.16b
eor v3.16b, v3.16b, v19.16b
ld1 {v16.4s,v17.4s,v18.4s,v19.4s},[x24],#64
eor v4.16b, v4.16b, v16.16b
eor v5.16b, v5.16b, v17.16b
eor v6.16b, v6.16b, v18.16b
eor v7.16b, v7.16b, v19.16b
ld1 {v16.4s,v17.4s,v18.4s,v19.4s},[x24],#64
eor v8.16b, v8.16b, v16.16b
eor v9.16b, v9.16b, v17.16b
eor v10.16b, v10.16b, v18.16b
eor v11.16b, v11.16b, v19.16b
// save the last tweak
mov v24.16b,v19.16b
st1 {v0.4s,v1.4s,v2.4s,v3.4s},[x1],#64
st1 {v4.4s,v5.4s,v6.4s,v7.4s},[x1],#64
st1 {v8.4s,v9.4s,v10.4s,v11.4s},[x1],#64
subs x2,x2,#12
b.gt .Lxts_12_blocks_process
b 100f
.Lxts_8_blocks_process:
mov x24, sp
cmp x2,#8
mov v16.d[0],x12
mov v16.d[1],x13
#ifdef HITLS_BIG_ENDIAN
rev32 v16.16b,v16.16b
#endif
mov w7,0x87
extr x9,x19,x19,#32
extr x13,x19,x18,#63
and w8,w7,w9,asr#31
eor x12,x8,x18,lsl#1
mov v17.d[0],x14
mov v17.d[1],x15
#ifdef HITLS_BIG_ENDIAN
rev32 v17.16b,v17.16b
#endif
mov w7,0x87
extr x9,x13,x13,#32
extr x15,x13,x12,#63
and w8,w7,w9,asr#31
eor x14,x8,x12,lsl#1
mov v18.d[0],x16
mov v18.d[1],x17
#ifdef HITLS_BIG_ENDIAN
rev32 v18.16b,v18.16b
#endif
mov w7,0x87
extr x9,x15,x15,#32
extr x17,x15,x14,#63
and w8,w7,w9,asr#31
eor x16,x8,x14,lsl#1
mov v19.d[0],x18
mov v19.d[1],x19
#ifdef HITLS_BIG_ENDIAN
rev32 v19.16b,v19.16b
#endif
mov w7,0x87
extr x9,x17,x17,#32
extr x19,x17,x16,#63
and w8,w7,w9,asr#31
eor x18,x8,x16,lsl#1
b.lt .Lxts_4_blocks_process
ld1 {v4.4s,v5.4s,v6.4s,v7.4s},[x0],#64
rbit v16.16b,v16.16b
rbit v17.16b,v17.16b
rbit v18.16b,v18.16b
rbit v19.16b,v19.16b
eor v4.16b, v4.16b, v16.16b
eor v5.16b, v5.16b, v17.16b
eor v6.16b, v6.16b, v18.16b
eor v7.16b, v7.16b, v19.16b
ld1 {v8.4s,v9.4s,v10.4s,v11.4s},[x0],#64
st1 {v16.4s,v17.4s,v18.4s,v19.4s},[x24], #64
mov v16.d[0],x12
mov v16.d[1],x13
#ifdef HITLS_BIG_ENDIAN
rev32 v16.16b,v16.16b
#endif
mov w7,0x87
extr x9,x19,x19,#32
extr x13,x19,x18,#63
and w8,w7,w9,asr#31
eor x12,x8,x18,lsl#1
mov v17.d[0],x14
mov v17.d[1],x15
#ifdef HITLS_BIG_ENDIAN
rev32 v17.16b,v17.16b
#endif
mov w7,0x87
extr x9,x13,x13,#32
extr x15,x13,x12,#63
and w8,w7,w9,asr#31
eor x14,x8,x12,lsl#1
mov v18.d[0],x16
mov v18.d[1],x17
#ifdef HITLS_BIG_ENDIAN
rev32 v18.16b,v18.16b
#endif
mov w7,0x87
extr x9,x15,x15,#32
extr x17,x15,x14,#63
and w8,w7,w9,asr#31
eor x16,x8,x14,lsl#1
mov v19.d[0],x18
mov v19.d[1],x19
#ifdef HITLS_BIG_ENDIAN
rev32 v19.16b,v19.16b
#endif
mov w7,0x87
extr x9,x17,x17,#32
extr x19,x17,x16,#63
and w8,w7,w9,asr#31
eor x18,x8,x16,lsl#1
rbit v16.16b,v16.16b
rbit v17.16b,v17.16b
rbit v18.16b,v18.16b
rbit v19.16b,v19.16b
eor v8.16b, v8.16b, v16.16b
eor v9.16b, v9.16b, v17.16b
eor v10.16b, v10.16b, v18.16b
eor v11.16b, v11.16b, v19.16b
st1 {v16.4s,v17.4s,v18.4s,v19.4s},[x24],#64
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
rev32 v5.16b,v5.16b
rev32 v6.16b,v6.16b
rev32 v7.16b,v7.16b
rev32 v8.16b,v8.16b
rev32 v9.16b,v9.16b
rev32 v10.16b,v10.16b
rev32 v11.16b,v11.16b
#endif
zip1 v0.4s,v4.4s,v5.4s
zip2 v1.4s,v4.4s,v5.4s
zip1 v2.4s,v6.4s,v7.4s
zip2 v3.4s,v6.4s,v7.4s
zip1 v4.2d,v0.2d,v2.2d
zip2 v5.2d,v0.2d,v2.2d
zip1 v6.2d,v1.2d,v3.2d
zip2 v7.2d,v1.2d,v3.2d
zip1 v0.4s,v8.4s,v9.4s
zip2 v1.4s,v8.4s,v9.4s
zip1 v2.4s,v10.4s,v11.4s
zip2 v3.4s,v10.4s,v11.4s
zip1 v8.2d,v0.2d,v2.2d
zip2 v9.2d,v0.2d,v2.2d
zip1 v10.2d,v1.2d,v3.2d
zip2 v11.2d,v1.2d,v3.2d
bl Sm4Enc8blks
zip1 v8.4s,v0.4s,v1.4s
zip2 v9.4s,v0.4s,v1.4s
zip1 v10.4s,v2.4s,v3.4s
zip2 v11.4s,v2.4s,v3.4s
zip1 v0.2d,v8.2d,v10.2d
zip2 v1.2d,v8.2d,v10.2d
zip1 v2.2d,v9.2d,v11.2d
zip2 v3.2d,v9.2d,v11.2d
zip1 v8.4s,v4.4s,v5.4s
zip2 v9.4s,v4.4s,v5.4s
zip1 v10.4s,v6.4s,v7.4s
zip2 v11.4s,v6.4s,v7.4s
zip1 v4.2d,v8.2d,v10.2d
zip2 v5.2d,v8.2d,v10.2d
zip1 v6.2d,v9.2d,v11.2d
zip2 v7.2d,v9.2d,v11.2d
mov x24, sp
ld1 {v16.4s,v17.4s,v18.4s,v19.4s},[x24],#64
eor v0.16b, v0.16b, v16.16b
eor v1.16b, v1.16b, v17.16b
eor v2.16b, v2.16b, v18.16b
eor v3.16b, v3.16b, v19.16b
ld1 {v16.4s,v17.4s,v18.4s,v19.4s},[x24],#64
eor v4.16b, v4.16b, v16.16b
eor v5.16b, v5.16b, v17.16b
eor v6.16b, v6.16b, v18.16b
eor v7.16b, v7.16b, v19.16b
// save the last tweak
mov v24.16b,v19.16b
st1 {v0.4s,v1.4s,v2.4s,v3.4s},[x1],#64
st1 {v4.4s,v5.4s,v6.4s,v7.4s},[x1],#64
subs x2,x2,#8
b.gt .Lxts_8_blocks_process
b 100f
.Lxts_4_blocks_process:
cmp x2,#4
b.lt 1f
ld1 {v4.4s,v5.4s,v6.4s,v7.4s},[x0],#64
rbit v16.16b,v16.16b
rbit v17.16b,v17.16b
rbit v18.16b,v18.16b
rbit v19.16b,v19.16b
eor v4.16b, v4.16b, v16.16b
eor v5.16b, v5.16b, v17.16b
eor v6.16b, v6.16b, v18.16b
eor v7.16b, v7.16b, v19.16b
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
rev32 v5.16b,v5.16b
rev32 v6.16b,v6.16b
rev32 v7.16b,v7.16b
#endif
zip1 v0.4s,v4.4s,v5.4s
zip2 v1.4s,v4.4s,v5.4s
zip1 v2.4s,v6.4s,v7.4s
zip2 v3.4s,v6.4s,v7.4s
zip1 v4.2d,v0.2d,v2.2d
zip2 v5.2d,v0.2d,v2.2d
zip1 v6.2d,v1.2d,v3.2d
zip2 v7.2d,v1.2d,v3.2d
bl Sm4Enc4blks
zip1 v4.4s,v0.4s,v1.4s
zip2 v5.4s,v0.4s,v1.4s
zip1 v6.4s,v2.4s,v3.4s
zip2 v7.4s,v2.4s,v3.4s
zip1 v0.2d,v4.2d,v6.2d
zip2 v1.2d,v4.2d,v6.2d
zip1 v2.2d,v5.2d,v7.2d
zip2 v3.2d,v5.2d,v7.2d
eor v0.16b, v0.16b, v16.16b
eor v1.16b, v1.16b, v17.16b
eor v2.16b, v2.16b, v18.16b
eor v3.16b, v3.16b, v19.16b
st1 {v0.4s,v1.4s,v2.4s,v3.4s},[x1],#64
sub x2,x2,#4
// save the last tweak
mov v24.16b,v19.16b
mov v16.d[0],x12
mov v16.d[1],x13
#ifdef HITLS_BIG_ENDIAN
rev32 v16.16b,v16.16b
#endif
mov w7,0x87
extr x9,x19,x19,#32
extr x13,x19,x18,#63
and w8,w7,w9,asr#31
eor x12,x8,x18,lsl#1
mov v17.d[0],x14
mov v17.d[1],x15
#ifdef HITLS_BIG_ENDIAN
rev32 v17.16b,v17.16b
#endif
mov w7,0x87
extr x9,x13,x13,#32
extr x15,x13,x12,#63
and w8,w7,w9,asr#31
eor x14,x8,x12,lsl#1
mov v18.d[0],x16
mov v18.d[1],x17
#ifdef HITLS_BIG_ENDIAN
rev32 v18.16b,v18.16b
#endif
mov w7,0x87
extr x9,x15,x15,#32
extr x17,x15,x14,#63
and w8,w7,w9,asr#31
eor x16,x8,x14,lsl#1
mov v19.d[0],x18
mov v19.d[1],x19
#ifdef HITLS_BIG_ENDIAN
rev32 v19.16b,v19.16b
#endif
mov w7,0x87
extr x9,x17,x17,#32
extr x19,x17,x16,#63
and w8,w7,w9,asr#31
eor x18,x8,x16,lsl#1
1:
// process last block
cmp x2,#1
b.lt 100f
b.gt 1f
ld1 {v4.4s},[x0],#16
rbit v16.16b,v16.16b
eor v4.16b, v4.16b, v16.16b
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
#endif
mov x10,x3
mov w11,#8
mov w12,v4.s[0]
mov w13,v4.s[1]
mov w14,v4.s[2]
mov w15,v4.s[3]
10:
ldp w7,w8,[x10],8
// B0 ^= SBOX(B1 ^ B2 ^ B3 ^ RK0)
eor w6,w14,w15
eor w9,w7,w13
eor w6,w6,w9
movi v31.16b, #0x0f
mov v3.s[0],w6
// optimize sbox using AESE instruction
tbl v0.16b, {v3.16b}, v26.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v28.16b}, v0.16b
tbl v2.16b, {v27.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
eor v1.16b, v1.16b, v1.16b
aese v0.16b,v1.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v30.16b}, v0.16b
tbl v2.16b, {v29.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
mov w7,v0.s[0]
eor w6,w7,w7,ror #32-2
eor w6,w6,w7,ror #32-10
eor w6,w6,w7,ror #32-18
eor w6,w6,w7,ror #32-24
eor w12,w12,w6
// B1 ^= SBOX(B0 ^ B2 ^ B3 ^ RK1)
eor w6,w14,w15
eor w9,w12,w8
eor w6,w6,w9
movi v31.16b, #0x0f
mov v3.s[0],w6
// optimize sbox using AESE instruction
tbl v0.16b, {v3.16b}, v26.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v28.16b}, v0.16b
tbl v2.16b, {v27.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
eor v1.16b, v1.16b, v1.16b
aese v0.16b,v1.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v30.16b}, v0.16b
tbl v2.16b, {v29.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
mov w7,v0.s[0]
eor w6,w7,w7,ror #32-2
eor w6,w6,w7,ror #32-10
eor w6,w6,w7,ror #32-18
eor w6,w6,w7,ror #32-24
ldp w7,w8,[x10],8
eor w13,w13,w6
// B2 ^= SBOX(B0 ^ B1 ^ B3 ^ RK2)
eor w6,w12,w13
eor w9,w7,w15
eor w6,w6,w9
movi v31.16b, #0x0f
mov v3.s[0],w6
// optimize sbox using AESE instruction
tbl v0.16b, {v3.16b}, v26.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v28.16b}, v0.16b
tbl v2.16b, {v27.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
eor v1.16b, v1.16b, v1.16b
aese v0.16b,v1.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v30.16b}, v0.16b
tbl v2.16b, {v29.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
mov w7,v0.s[0]
eor w6,w7,w7,ror #32-2
eor w6,w6,w7,ror #32-10
eor w6,w6,w7,ror #32-18
eor w6,w6,w7,ror #32-24
eor w14,w14,w6
// B3 ^= SBOX(B0 ^ B1 ^ B2 ^ RK3)
eor w6,w12,w13
eor w9,w14,w8
eor w6,w6,w9
movi v31.16b, #0x0f
mov v3.s[0],w6
// optimize sbox using AESE instruction
tbl v0.16b, {v3.16b}, v26.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v28.16b}, v0.16b
tbl v2.16b, {v27.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
eor v1.16b, v1.16b, v1.16b
aese v0.16b,v1.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v30.16b}, v0.16b
tbl v2.16b, {v29.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
mov w7,v0.s[0]
eor w6,w7,w7,ror #32-2
eor w6,w6,w7,ror #32-10
eor w6,w6,w7,ror #32-18
eor w6,w6,w7,ror #32-24
eor w15,w15,w6
subs w11,w11,#1
b.ne 10b
mov v4.s[0],w15
mov v4.s[1],w14
mov v4.s[2],w13
mov v4.s[3],w12
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
#endif
eor v4.16b, v4.16b, v16.16b
st1 {v4.4s},[x1],#16
// save the last tweak
mov v24.16b,v16.16b
b 100f
1: // process last 2 blocks
cmp x2,#2
b.gt 1f
ld1 {v4.4s,v5.4s},[x0],#32
rbit v16.16b,v16.16b
rbit v17.16b,v17.16b
eor v4.16b, v4.16b, v16.16b
eor v5.16b, v5.16b, v17.16b
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
rev32 v5.16b,v5.16b
#endif
zip1 v0.4s,v4.4s,v5.4s
zip2 v1.4s,v4.4s,v5.4s
zip1 v2.4s,v6.4s,v7.4s
zip2 v3.4s,v6.4s,v7.4s
zip1 v4.2d,v0.2d,v2.2d
zip2 v5.2d,v0.2d,v2.2d
zip1 v6.2d,v1.2d,v3.2d
zip2 v7.2d,v1.2d,v3.2d
bl Sm4Enc4blks
zip1 v4.4s,v0.4s,v1.4s
zip2 v5.4s,v0.4s,v1.4s
zip1 v6.4s,v2.4s,v3.4s
zip2 v7.4s,v2.4s,v3.4s
zip1 v0.2d,v4.2d,v6.2d
zip2 v1.2d,v4.2d,v6.2d
zip1 v2.2d,v5.2d,v7.2d
zip2 v3.2d,v5.2d,v7.2d
eor v0.16b, v0.16b, v16.16b
eor v1.16b, v1.16b, v17.16b
st1 {v0.4s,v1.4s},[x1],#32
// save the last tweak
mov v24.16b,v17.16b
b 100f
1: // process last 3 blocks
ld1 {v4.4s,v5.4s,v6.4s},[x0],#48
rbit v16.16b,v16.16b
rbit v17.16b,v17.16b
rbit v18.16b,v18.16b
eor v4.16b, v4.16b, v16.16b
eor v5.16b, v5.16b, v17.16b
eor v6.16b, v6.16b, v18.16b
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
rev32 v5.16b,v5.16b
rev32 v6.16b,v6.16b
#endif
zip1 v0.4s,v4.4s,v5.4s
zip2 v1.4s,v4.4s,v5.4s
zip1 v2.4s,v6.4s,v7.4s
zip2 v3.4s,v6.4s,v7.4s
zip1 v4.2d,v0.2d,v2.2d
zip2 v5.2d,v0.2d,v2.2d
zip1 v6.2d,v1.2d,v3.2d
zip2 v7.2d,v1.2d,v3.2d
bl Sm4Enc4blks
zip1 v4.4s,v0.4s,v1.4s
zip2 v5.4s,v0.4s,v1.4s
zip1 v6.4s,v2.4s,v3.4s
zip2 v7.4s,v2.4s,v3.4s
zip1 v0.2d,v4.2d,v6.2d
zip2 v1.2d,v4.2d,v6.2d
zip1 v2.2d,v5.2d,v7.2d
zip2 v3.2d,v5.2d,v7.2d
eor v0.16b, v0.16b, v16.16b
eor v1.16b, v1.16b, v17.16b
eor v2.16b, v2.16b, v18.16b
st1 {v0.4s,v1.4s,v2.4s},[x1],#48
// save the last tweak
mov v24.16b,v18.16b
100:
cmp x29,0
b.eq .Lxts_cipher_return
// This branch calculates the last two tweaks,
// while the encryption/decryption length is larger than 32
.last_2blks_tweak:
#ifdef HITLS_BIG_ENDIAN
rev32 v24.16b,v24.16b
#endif
rbit v2.16b,v24.16b
adrp x26, .Lxts_magic
add x26, x26, :lo12:.Lxts_magic
ldr q0, [x26]
shl v17.16b, v2.16b, #1
ext v1.16b, v2.16b, v2.16b,#15
ushr v1.16b, v1.16b, #7
mul v1.16b, v1.16b, v0.16b
eor v17.16b, v17.16b, v1.16b
rbit v17.16b,v17.16b
rbit v2.16b,v17.16b
adrp x26, .Lxts_magic
add x26, x26, :lo12:.Lxts_magic
ldr q0, [x26]
shl v18.16b, v2.16b, #1
ext v1.16b, v2.16b, v2.16b,#15
ushr v1.16b, v1.16b, #7
mul v1.16b, v1.16b, v0.16b
eor v18.16b, v18.16b, v1.16b
rbit v18.16b,v18.16b
b .Lxts_check_dec
// This branch calculates the last two tweaks,
// while the encryption/decryption length is equal to 32, who only need two tweaks
.only_2blks_tweak:
mov v17.16b,v16.16b
#ifdef HITLS_BIG_ENDIAN
rev32 v17.16b,v17.16b
#endif
rbit v2.16b,v17.16b
adrp x26, .Lxts_magic
add x26, x26, :lo12:.Lxts_magic
ldr q0, [x26]
shl v18.16b, v2.16b, #1
ext v1.16b, v2.16b, v2.16b,#15
ushr v1.16b, v1.16b, #7
mul v1.16b, v1.16b, v0.16b
eor v18.16b, v18.16b, v1.16b
rbit v18.16b,v18.16b
b .Lxts_check_dec
// Determine whether encryption or decryption is required.
// The last two tweaks need to be swapped for decryption.
.Lxts_check_dec:
// encryption:1 decryption:0
cmp w28,1
b.eq .Lxts_prcess_last_2blks
mov v0.16B,v17.16b
mov v17.16B,v18.16b
mov v18.16B,v0.16b
.Lxts_prcess_last_2blks:
#ifdef HITLS_BIG_ENDIAN
rev32 v17.16b,v17.16b
rev32 v18.16b,v18.16b
#endif
ld1 {v4.4s},[x0],#16
eor v4.16b, v4.16b, v17.16b
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
#endif
mov x10,x3
mov w11,#8
mov w12,v4.s[0]
mov w13,v4.s[1]
mov w14,v4.s[2]
mov w15,v4.s[3]
10:
ldp w7,w8,[x10],8
// B0 ^= SBOX(B1 ^ B2 ^ B3 ^ RK0)
eor w6,w14,w15
eor w9,w7,w13
eor w6,w6,w9
movi v31.16b, #0x0f
mov v3.s[0],w6
// optimize sbox using AESE instruction
tbl v0.16b, {v3.16b}, v26.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v28.16b}, v0.16b
tbl v2.16b, {v27.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
eor v1.16b, v1.16b, v1.16b
aese v0.16b,v1.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v30.16b}, v0.16b
tbl v2.16b, {v29.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
mov w7,v0.s[0]
eor w6,w7,w7,ror #32-2
eor w6,w6,w7,ror #32-10
eor w6,w6,w7,ror #32-18
eor w6,w6,w7,ror #32-24
eor w12,w12,w6
// B1 ^= SBOX(B0 ^ B2 ^ B3 ^ RK1)
eor w6,w14,w15
eor w9,w12,w8
eor w6,w6,w9
movi v31.16b, #0x0f
mov v3.s[0],w6
// optimize sbox using AESE instruction
tbl v0.16b, {v3.16b}, v26.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v28.16b}, v0.16b
tbl v2.16b, {v27.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
eor v1.16b, v1.16b, v1.16b
aese v0.16b,v1.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v30.16b}, v0.16b
tbl v2.16b, {v29.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
mov w7,v0.s[0]
eor w6,w7,w7,ror #32-2
eor w6,w6,w7,ror #32-10
eor w6,w6,w7,ror #32-18
eor w6,w6,w7,ror #32-24
ldp w7,w8,[x10],8
eor w13,w13,w6
// B2 ^= SBOX(B0 ^ B1 ^ B3 ^ RK2)
eor w6,w12,w13
eor w9,w7,w15
eor w6,w6,w9
movi v31.16b, #0x0f
mov v3.s[0],w6
// optimize sbox using AESE instruction
tbl v0.16b, {v3.16b}, v26.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v28.16b}, v0.16b
tbl v2.16b, {v27.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
eor v1.16b, v1.16b, v1.16b
aese v0.16b,v1.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v30.16b}, v0.16b
tbl v2.16b, {v29.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
mov w7,v0.s[0]
eor w6,w7,w7,ror #32-2
eor w6,w6,w7,ror #32-10
eor w6,w6,w7,ror #32-18
eor w6,w6,w7,ror #32-24
eor w14,w14,w6
// B3 ^= SBOX(B0 ^ B1 ^ B2 ^ RK3)
eor w6,w12,w13
eor w9,w14,w8
eor w6,w6,w9
movi v31.16b, #0x0f
mov v3.s[0],w6
// optimize sbox using AESE instruction
tbl v0.16b, {v3.16b}, v26.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v28.16b}, v0.16b
tbl v2.16b, {v27.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
eor v1.16b, v1.16b, v1.16b
aese v0.16b,v1.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v30.16b}, v0.16b
tbl v2.16b, {v29.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
mov w7,v0.s[0]
eor w6,w7,w7,ror #32-2
eor w6,w6,w7,ror #32-10
eor w6,w6,w7,ror #32-18
eor w6,w6,w7,ror #32-24
eor w15,w15,w6
subs w11,w11,#1
b.ne 10b
mov v4.s[0],w15
mov v4.s[1],w14
mov v4.s[2],w13
mov v4.s[3],w12
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
#endif
eor v4.16b, v4.16b, v17.16b
st1 {v4.4s},[x1],#16
sub x26,x1,16
.Lxts_loop:
subs x29,x29,1
ldrb w7,[x26,x29]
ldrb w8,[x0,x29]
strb w8,[x26,x29]
strb w7,[x1,x29]
b.gt .Lxts_loop
ld1 {v4.4s}, [x26]
eor v4.16b, v4.16b, v18.16b
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
#endif
mov x10,x3
mov w11,#8
mov w12,v4.s[0]
mov w13,v4.s[1]
mov w14,v4.s[2]
mov w15,v4.s[3]
10:
ldp w7,w8,[x10],8
// B0 ^= SBOX(B1 ^ B2 ^ B3 ^ RK0)
eor w6,w14,w15
eor w9,w7,w13
eor w6,w6,w9
movi v31.16b, #0x0f
mov v3.s[0],w6
// optimize sbox using AESE instruction
tbl v0.16b, {v3.16b}, v26.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v28.16b}, v0.16b
tbl v2.16b, {v27.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
eor v1.16b, v1.16b, v1.16b
aese v0.16b,v1.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v30.16b}, v0.16b
tbl v2.16b, {v29.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
mov w7,v0.s[0]
eor w6,w7,w7,ror #32-2
eor w6,w6,w7,ror #32-10
eor w6,w6,w7,ror #32-18
eor w6,w6,w7,ror #32-24
eor w12,w12,w6
// B1 ^= SBOX(B0 ^ B2 ^ B3 ^ RK1)
eor w6,w14,w15
eor w9,w12,w8
eor w6,w6,w9
movi v31.16b, #0x0f
mov v3.s[0],w6
// optimize sbox using AESE instruction
tbl v0.16b, {v3.16b}, v26.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v28.16b}, v0.16b
tbl v2.16b, {v27.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
eor v1.16b, v1.16b, v1.16b
aese v0.16b,v1.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v30.16b}, v0.16b
tbl v2.16b, {v29.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
mov w7,v0.s[0]
eor w6,w7,w7,ror #32-2
eor w6,w6,w7,ror #32-10
eor w6,w6,w7,ror #32-18
eor w6,w6,w7,ror #32-24
ldp w7,w8,[x10],8
eor w13,w13,w6
// B2 ^= SBOX(B0 ^ B1 ^ B3 ^ RK2)
eor w6,w12,w13
eor w9,w7,w15
eor w6,w6,w9
movi v31.16b, #0x0f
mov v3.s[0],w6
// optimize sbox using AESE instruction
tbl v0.16b, {v3.16b}, v26.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v28.16b}, v0.16b
tbl v2.16b, {v27.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
eor v1.16b, v1.16b, v1.16b
aese v0.16b,v1.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v30.16b}, v0.16b
tbl v2.16b, {v29.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
mov w7,v0.s[0]
eor w6,w7,w7,ror #32-2
eor w6,w6,w7,ror #32-10
eor w6,w6,w7,ror #32-18
eor w6,w6,w7,ror #32-24
eor w14,w14,w6
// B3 ^= SBOX(B0 ^ B1 ^ B2 ^ RK3)
eor w6,w12,w13
eor w9,w14,w8
eor w6,w6,w9
movi v31.16b, #0x0f
mov v3.s[0],w6
// optimize sbox using AESE instruction
tbl v0.16b, {v3.16b}, v26.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v28.16b}, v0.16b
tbl v2.16b, {v27.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
eor v1.16b, v1.16b, v1.16b
aese v0.16b,v1.16b
ushr v2.16b, v0.16b, 4
and v0.16b, v0.16b, v31.16b
tbl v0.16b, {v30.16b}, v0.16b
tbl v2.16b, {v29.16b}, v2.16b
eor v0.16b, v0.16b, v2.16b
mov w7,v0.s[0]
eor w6,w7,w7,ror #32-2
eor w6,w6,w7,ror #32-10
eor w6,w6,w7,ror #32-18
eor w6,w6,w7,ror #32-24
eor w15,w15,w6
subs w11,w11,#1
b.ne 10b
mov v4.s[0],w15
mov v4.s[1],w14
mov v4.s[2],w13
mov v4.s[3],w12
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
#endif
eor v4.16b, v4.16b, v18.16b
st1 {v4.4s}, [x26]
.Lxts_cipher_return:
add sp, sp, #192
ldp d14, d15, [sp], #0x10
ldp d12, d13, [sp], #0x10
ldp d10, d11, [sp], #0x10
ldp d8, d9, [sp], #0x10
ldp x29, x30, [sp], #0x10
ldp x27, x28, [sp], #0x10
ldp x25, x26, [sp], #0x10
ldp x23, x24, [sp], #0x10
ldp x21, x22, [sp], #0x10
ldp x19, x20, [sp], #0x10
AARCH64_AUTIASP
ret
.size Vpsm4XtsCipher,.-Vpsm4XtsCipher
.globl Vpsm4Cfb128Encrypt
.type Vpsm4Cfb128Encrypt,%function
.align 5
Vpsm4Cfb128Encrypt:
AARCH64_PACIASP
stp x29,x30,[sp,#-80]!
add x29,sp,#0
stp x19,x20,[sp,#16]
stp x21,x22,[sp,#32]
stp x23,x8,[sp,#48]
stp x16,x17,[sp,#64]
// load tbox
adrp x19, .Ltbox1
add x19,x19,:lo12:.Ltbox1
adrp x20, .Ltbox2
add x20,x20,:lo12:.Ltbox2
adrp x21, .Ltbox3
add x21,x21,:lo12:.Ltbox3
adrp x22, .Ltbox4
add x22,x22,:lo12:.Ltbox4
// load num
ldr w23,[x5]
cbz w23,.Lcfb128_enc_update
.Lcfb128_enc_init:
ldrb w7,[ivp,x23]
ldrb w8,[inp]
eor w7,w7,w8
strb w7,[outp]
strb w7,[ivp,x23]
add inp,inp,#1
add outp,outp,#1
add w23,w23,#1
sub len,len,#1
cmp w23,#16
b.eq .Lcfb128_enc_init_final
cbz len,.Lcfb128_enc_ret
b .Lcfb128_enc_init
.Lcfb128_enc_init_final:
mov w23,#0
.Lcfb128_enc_update:
cbz len,.Lcfb128_enc_ret
// load iv
ldp w8,w9,[ivp]
ldp w10,w11,[ivp,#8]
#ifndef HITLS_BIG_ENDIAN
rev w8,w8
rev w9,w9
rev w10,w10
rev w11,w11
#endif
EncRound
#ifndef HITLS_BIG_ENDIAN
rev w8,w8
rev w9,w9
rev w10,w10
rev w11,w11
#endif
// save back IV
stp w11,w10,[ivp]
stp w9,w8,[ivp,#8]
cmp len,#16
b.lt .Lcfb128_enc_final
// xor with plain
ldp w6,w7,[inp],#8
ldp w16,w17,[inp],#8
eor w11,w11,w6
eor w10,w10,w7
eor w9,w9,w16
eor w8,w8,w17
stp w11,w10,[outp],#8
stp w9,w8,[outp],#8
// save back IV
stp w11,w10,[ivp]
stp w9,w8,[ivp,#8]
sub len,len,#16
b .Lcfb128_enc_update
.Lcfb128_enc_final:
ldrb w7,[ivp,x23]
ldrb w8,[inp]
eor w7,w7,w8
strb w7,[outp]
strb w7,[ivp,x23]
add inp,inp,#1
add outp,outp,#1
add w23,w23,#1
subs len,len,#1
b.ne .Lcfb128_enc_final
.Lcfb128_enc_ret:
// store num
str w23,[x5]
// restore register
ldp x19,x20,[sp,#16]
ldp x21,x22,[sp,#32]
ldp x23,x8,[sp,#48]
ldp x16,x17,[sp,#64]
ldp x29,x30,[sp],#80
AARCH64_AUTIASP
ret
.size Vpsm4Cfb128Encrypt,.-Vpsm4Cfb128Encrypt
# void Vpsm4Cfb128Decrypt(const uint8_t *in, uint8_t *out, uint64_t len, const uint32_t *key, uint8_t *iv, int *num);
.globl Vpsm4Cfb128Decrypt
.type Vpsm4Cfb128Decrypt,%function
.align 5
Vpsm4Cfb128Decrypt:
AARCH64_PACIASP
stp x29,x30,[sp,#-128]!
stp x19,x20,[sp,#16]
stp x21,x22,[sp,#32]
stp x23,x24,[sp,#48]
stp d8,d9,[sp,#64]
stp d10,d11,[sp,#80]
stp d12,d13,[sp,#96]
stp d14,d15,[sp,#112]
// load tbox
adrp x19, .Ltbox1
add x19,x19,:lo12:.Ltbox1
adrp x20, .Ltbox2
add x20,x20,:lo12:.Ltbox2
adrp x21, .Ltbox3
add x21,x21,:lo12:.Ltbox3
adrp x22, .Ltbox4
add x22,x22,:lo12:.Ltbox4
LoadSbox
// load num
ldr w23,[x5]
cbz w23,.Lcfb128_12_blocks_dec
.Lcfb128_dec_init:
ldrb w7,[ivp,x23]
ldrb w8,[inp]
eor w7,w7,w8
strb w7,[outp]
// store in to iv
strb w8,[ivp,x23]
add inp,inp,#1
add outp,outp,#1
subs len,len,#1
add w23,w23,#1
and w23,w23,#15
b.eq 100f
cbz w23,.Lcfb128_12_blocks_dec
b .Lcfb128_dec_init
.Lcfb128_12_blocks_dec:
cmp len,#192
b.lt .Lcfb128_8_blocks_dec
ld4 {v4.4s,v5.4s,v6.4s,v7.4s},[inp]
// append iv as last element
ld4 {v4.s,v5.s,v6.s,v7.s}[3],[ivp]
add ptr,inp,#48
ld4 {v8.4s,v9.4s,v10.4s,v11.4s},[ptr]
add ptr,ptr,#64
ld4 {v16.4s,v17.4s,v18.4s,v19.4s},[ptr]
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
rev32 v5.16b,v5.16b
rev32 v6.16b,v6.16b
rev32 v7.16b,v7.16b
rev32 v8.16b,v8.16b
rev32 v9.16b,v9.16b
rev32 v10.16b,v10.16b
rev32 v11.16b,v11.16b
rev32 v16.16b,v16.16b
rev32 v17.16b,v17.16b
rev32 v18.16b,v18.16b
rev32 v19.16b,v19.16b
#endif
bl Sm4Enc12blks
transpose v0.4s,v1.4s,v2.4s,v3.4s,v0.2d,v1.2d,v2.2d,v3.2d,v16.4s,v17.4s,v18.4s,v19.4s,v16.2d,v17.2d,v18.2d,v19.2d
transpose v4.4s,v5.4s,v6.4s,v7.4s,v4.2d,v5.2d,v6.2d,v7.2d,v16.4s,v17.4s,v18.4s,v19.4s,v16.2d,v17.2d,v18.2d,v19.2d
transpose v8.4s,v9.4s,v10.4s,v11.4s,v8.2d,v9.2d,v10.2d,v11.2d,v16.4s,v17.4s,v18.4s,v19.4s,v16.2d,v17.2d,v18.2d,v19.2d
ld1 {v16.4s,v17.4s,v18.4s,v19.4s},[inp],#64
ld1 {v12.4s,v13.4s,v14.4s,v15.4s},[inp],#64
eor v0.16b,v0.16b,v17.16b
eor v1.16b,v1.16b,v18.16b
eor v2.16b,v2.16b,v19.16b
eor v3.16b,v3.16b,v16.16b
// save plainText decrypted from iv as first one
st1 {v3.4s},[outp],#16
st1 {v0.4s,v1.4s,v2.4s},[outp],#48
eor v4.16b,v4.16b,v12.16b
eor v5.16b,v5.16b,v13.16b
eor v6.16b,v6.16b,v14.16b
eor v7.16b,v7.16b,v15.16b
st1 {v4.4s,v5.4s,v6.4s,v7.4s},[outp],#64
ld1 {v16.4s,v17.4s,v18.4s,v19.4s},[inp],#64
eor v8.16b,v8.16b,v16.16b
eor v9.16b,v9.16b,v17.16b
eor v10.16b,v10.16b,v18.16b
eor v11.16b,v11.16b,v19.16b
st1 {v8.4s,v9.4s,v10.4s,v11.4s},[outp],#64
// save back IV
st1 {v19.4s}, [ivp]
subs len,len,#192
b.gt .Lcfb128_12_blocks_dec
b.eq 100f
.Lcfb128_8_blocks_dec:
cmp len,#128
b.lt .Lcfb128_4_blocks_dec
ld4 {v4.4s,v5.4s,v6.4s,v7.4s},[inp]
// append iv as last element
ld4 {v4.s,v5.s,v6.s,v7.s}[3],[ivp]
add ptr,inp,#48
ld4 {v8.4s,v9.4s,v10.4s,v11.4s},[ptr]
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
rev32 v5.16b,v5.16b
rev32 v6.16b,v6.16b
rev32 v7.16b,v7.16b
rev32 v8.16b,v8.16b
rev32 v9.16b,v9.16b
rev32 v10.16b,v10.16b
rev32 v11.16b,v11.16b
#endif
bl Sm4Enc8blks
transpose v0.4s,v1.4s,v2.4s,v3.4s,v0.2d,v1.2d,v2.2d,v3.2d,v8.4s,v9.4s,v10.4s,v11.4s,v8.2d,v9.2d,v10.2d,v11.2d
transpose v4.4s,v5.4s,v6.4s,v7.4s,v4.2d,v5.2d,v6.2d,v7.2d,v8.4s,v9.4s,v10.4s,v11.4s,v8.2d,v9.2d,v10.2d,v11.2d
ld1 {v8.4s,v9.4s,v10.4s,v11.4s},[inp],#64
ld1 {v12.4s,v13.4s,v14.4s,v15.4s},[inp],#64
eor v0.16b,v0.16b,v9.16b
eor v1.16b,v1.16b,v10.16b
eor v2.16b,v2.16b,v11.16b
eor v3.16b,v3.16b,v8.16b
// save back IV
st1 {v15.4s}, [ivp]
eor v4.16b,v4.16b,v12.16b
eor v5.16b,v5.16b,v13.16b
eor v6.16b,v6.16b,v14.16b
eor v7.16b,v7.16b,v15.16b
st1 {v3.4s},[outp],#16
st1 {v0.4s,v1.4s,v2.4s},[outp],#48
st1 {v4.4s,v5.4s,v6.4s,v7.4s},[outp],#64
subs len,len,#128
b.gt .Lcfb128_8_blocks_dec
b.eq 100f
.Lcfb128_4_blocks_dec:
cmp len,#64
b.lt .Llast_block
ld4 {v4.4s,v5.4s,v6.4s,v7.4s},[inp]
// append iv as last element
ld4 {v4.s,v5.s,v6.s,v7.s}[3],[ivp]
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
rev32 v5.16b,v5.16b
rev32 v6.16b,v6.16b
rev32 v7.16b,v7.16b
#endif
bl Sm4Enc4blks
ld1 {v4.4s,v5.4s,v6.4s,v7.4s},[inp],#64
transpose v0.4s,v1.4s,v2.4s,v3.4s,v0.2d,v1.2d,v2.2d,v3.2d,v8.4s,v9.4s,v10.4s,v11.4s,v8.2d,v9.2d,v10.2d,v11.2d
eor v0.16b,v0.16b,v5.16b
eor v1.16b,v1.16b,v6.16b
eor v2.16b,v2.16b,v7.16b
eor v3.16b,v3.16b,v4.16b
st1 {v3.4s},[outp],#16
st1 {v0.4s,v1.4s,v2.4s},[outp],#48
// save back IV
st1 {v7.4s}, [ivp]
subs len,len,#64
b.gt .Lcfb128_4_blocks_dec
b.eq 100f
.Llast_block: // last block
cmp len,#16
b.gt .Llast_2_blocks
1:
// load in
ldp w6,w7,[inp]
ldp w16,w17,[inp,#8]
// load iv
ldp w8,w9,[ivp]
ldp w10,w11,[ivp,#8]
#ifndef HITLS_BIG_ENDIAN
rev w8,w8
rev w9,w9
rev w10,w10
rev w11,w11
#endif
EncRound
#ifndef HITLS_BIG_ENDIAN
rev w8,w8
rev w9,w9
rev w10,w10
rev w11,w11
#endif
// save encrypted iv
stp w11,w10,[ivp]
stp w9,w8,[ivp,#8]
cmp len,#16
b.lt .Lcfb128_dec_final
stp w6,w7,[ivp]
stp w16,w17,[ivp,#8]
eor w11,w11,w6
eor w10,w10,w7
eor w9,w9,w16
eor w8,w8,w17
stp w11,w10,[outp],#8
stp w9,w8,[outp],#8
add inp,inp,#16
subs len,len,#16
b.gt 1b
b.eq 100f
b .Lcfb128_dec_final
.Llast_2_blocks: // last two blocks
ld4 {v4.s,v5.s,v6.s,v7.s}[0],[ivp]
mov ptr,inp
ld4 {v4.s,v5.s,v6.s,v7.s}[1],[ptr],#16
cmp x2,#32
b.gt .Llast_3_blocks
b.lt 1b
1:
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
rev32 v5.16b,v5.16b
rev32 v6.16b,v6.16b
rev32 v7.16b,v7.16b
#endif
bl Sm4Enc4blks
ld1 {v4.4s,v5.4s},[inp],#32
transpose v0.4s,v1.4s,v2.4s,v3.4s,v0.2d,v1.2d,v2.2d,v3.2d,v8.4s,v9.4s,v10.4s,v11.4s,v8.2d,v9.2d,v10.2d,v11.2d
eor v0.16b,v0.16b,v4.16b
eor v1.16b,v1.16b,v5.16b
st1 {v0.4s,v1.4s},[outp],#32
// save back IV
st1 {v5.4s}, [ivp]
subs len,len,#32
b.eq 100f
b .Llast_block
.Llast_3_blocks: // last 3 blocks
cmp len,#48
b.lt 1b
ld4 {v4.s,v5.s,v6.s,v7.s}[2],[ptr]
#ifndef HITLS_BIG_ENDIAN
rev32 v4.16b,v4.16b
rev32 v5.16b,v5.16b
rev32 v6.16b,v6.16b
rev32 v7.16b,v7.16b
#endif
bl Sm4Enc4blks
ld1 {v4.4s,v5.4s,v6.4s},[inp],#48
transpose v0.4s,v1.4s,v2.4s,v3.4s,v0.2d,v1.2d,v2.2d,v3.2d,v8.4s,v9.4s,v10.4s,v11.4s,v8.2d,v9.2d,v10.2d,v11.2d
eor v0.16b,v0.16b,v4.16b
eor v1.16b,v1.16b,v5.16b
eor v2.16b,v2.16b,v6.16b
st1 {v0.4s,v1.4s,v2.4s},[outp],#48
// save back IV
st1 {v6.4s}, [ivp]
subs len,len,#48
b.eq 100f
b .Llast_block
.Lcfb128_dec_final:
ldrb w7,[ivp,x23]
ldrb w8,[inp]
eor w7,w7,w8
strb w7,[outp]
// store in to iv
strb w8,[ivp,x23]
add inp,inp,#1
add outp,outp,#1
add w23,w23,#1
subs len,len,#1
b.ne .Lcfb128_dec_final
100:
// store num
str w23,[x5]
ldp x19,x20,[sp,#16]
ldp x21,x22,[sp,#32]
ldp x23,x24,[sp,#48]
ldp d8,d9,[sp,#64]
ldp d10,d11,[sp,#80]
ldp d12,d13,[sp,#96]
ldp d14,d15,[sp,#112]
ldp x29,x30,[sp],#128
AARCH64_AUTIASP
ret
.size Vpsm4Cfb128Decrypt,.-Vpsm4Cfb128Decrypt
#endif
| 2302_82127028/openHiTLS-examples_1508 | crypto/sm4/src/asm/crypt_sm4_armv8.S | Unix Assembly | unknown | 76,228 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SM4
#include "crypt_arm.h"
#define VTMP0 V8
#define VTMP1 V9
#define VTMP2 V10
#define DATA0 V16
#define MaskV v26
#define TAHMatV v27
#define TALMatV v28
#define ATAHMatV v29
#define ATALMatV v30
#define ANDMaskV v31
#define MaskQ q26
#define TAHMatQ q27
#define TALMatQ q28
#define ATAHMatQ q29
#define ATALMatQ q30
#define ANDMaskQ q31
.section .rodata
.align 4
#ifdef HITLS_BIG_ENDIAN
.qtmp0:
.quad 0x0101010101010101,0x0101010101010187
.Lsbox_magic:
.quad 0x0306090c0f020508,0x0b0e0104070a0d00
.quad 0x22581a6002783a40,0x62185a2042387a00
.quad 0xc10bb67c4a803df7,0x15df62a89e54e923
.quad 0x1407c6d56c7fbead,0xb9aa6b78c1d21300
.quad 0xe383c1a1fe9edcbc,0x6404462679195b3b
.quad 0x0f0f0f0f0f0f0f0f,0x0f0f0f0f0f0f0f0f
#else
.qtmp0:
.quad 0x0101010101010187,0x0101010101010101
.Lsbox_magic:
.quad 0x0b0e0104070a0d00,0x0306090c0f020508
.quad 0x62185a2042387a00,0x22581a6002783a40
.quad 0x15df62a89e54e923,0xc10bb67c4a803df7
.quad 0xb9aa6b78c1d21300,0x1407c6d56c7fbead
.quad 0x6404462679195b3b,0xe383c1a1fe9edcbc
.quad 0x0f0f0f0f0f0f0f0f,0x0f0f0f0f0f0f0f0f
#endif
.Lck:
.long 0x00070E15, 0x1C232A31, 0x383F464D, 0x545B6269
.long 0x70777E85, 0x8C939AA1, 0xA8AFB6BD, 0xC4CBD2D9
.long 0xE0E7EEF5, 0xFC030A11, 0x181F262D, 0x343B4249
.long 0x50575E65, 0x6C737A81, 0x888F969D, 0xA4ABB2B9
.long 0xC0C7CED5, 0xDCE3EAF1, 0xF8FF060D, 0x141B2229
.long 0x30373E45, 0x4C535A61, 0x686F767D, 0x848B9299
.long 0xA0A7AEB5, 0xBCC3CAD1, 0xD8DFE6ED, 0xF4FB0209
.long 0x10171E25, 0x2C333A41, 0x484F565D, 0x646B7279
.Lfk:
.long 0xa3b1bac6, 0x56aa3350, 0x677d9197, 0xb27022dc
.Lshuffles:
.long 0x07060504, 0x0B0A0908, 0x0F0E0D0C, 0x03020100
#ifndef HITLS_BIG_ENDIAN
#define REV32_EQ(DST, SRC) \
rev32 DST.16b,DST.16b ;
#else
#define REV32_EQ(DST, SRC) \
/*rev32 eq is null in armeb */ ;
#endif
.macro LOAD_SBOX_MATRIX
adrp x15,.Lsbox_magic
add x15,x15,:lo12:.Lsbox_magic
ldr MaskQ, [x15]
ldr TAHMatQ, [x15, #16]
ldr TALMatQ, [x15, #32]
ldr ATAHMatQ, [x15, #48]
ldr ATALMatQ, [x15, #64]
ldr ANDMaskQ, [x15, #80]
.endm
/* matrix multiplication Mat*x = (lowerMat*x) ^ (higherMat*x) */
#define MUL_MATRIX(X, HIGHERMAT, LOWERMAT, TMP) \
ushr TMP.16b, X.16b, 4 ; \
and X.16b, X.16b, ANDMaskV.16b ; \
tbl X.16b, {LOWERMAT.16b}, X.16b ; \
tbl TMP.16b, {HIGHERMAT.16b}, TMP.16b ; \
eor X.16b, X.16b, TMP.16b ;
.arch armv8-a+crypto
.text
#define USER_KEY x0
#define ROUND_KEY1 x1
#define ENC1 w2
#define POINTER1 x5
#define SCHEDULES x6
#define WTMP w7
#define ROUND_KEY2 w8
#define V_KEY v5
#define V_FK v6
#define V_MAP v7
/*
* void vpsm4_ex_set_key(const unsigned char *userKey, SM4_KEY *key, int enc);
* generate sm4 rounk key context
* USER_KEY => userKey;
* ROUND_KEY1 => key ;
* if encryption:ENC=>enc
*/
.type vpsm4_ex_set_key,%function
.align 4
vpsm4_ex_set_key:
AARCH64_PACIASP
stp x29, x30, [sp, #-0x30]!
stp d8, d9, [sp, #0x10]
stp d10, d11, [sp, #0x20]
ld1 {V_KEY.4s},[USER_KEY]
LOAD_SBOX_MATRIX
REV32_EQ(V_KEY,V_KEY)
adrp POINTER1,.Lshuffles
add POINTER1,POINTER1,:lo12:.Lshuffles
ld1 {V_MAP.4s},[POINTER1]
adrp POINTER1,.Lfk
add POINTER1,POINTER1,:lo12:.Lfk
ld1 {V_FK.4s},[POINTER1]
eor V_KEY.16b,V_KEY.16b,V_FK.16b
mov SCHEDULES,#32
adrp POINTER1,.Lck
add POINTER1,POINTER1,:lo12:.Lck
movi VTMP0.16b,#64
cbnz ENC1,1f
add ROUND_KEY1,ROUND_KEY1,124
1: // loop
mov WTMP,V_KEY.s[1]
ldr ROUND_KEY2,[POINTER1],#4
eor ROUND_KEY2,ROUND_KEY2,WTMP
mov WTMP,V_KEY.s[2]
eor ROUND_KEY2,ROUND_KEY2,WTMP
mov WTMP,V_KEY.s[3]
eor ROUND_KEY2,ROUND_KEY2,WTMP
/* optimize sbox using AESE instruction */
mov DATA0.s[0],ROUND_KEY2
tbl VTMP0.16b, {DATA0.16b}, MaskV.16b
MUL_MATRIX(VTMP0, TAHMatV, TALMatV, VTMP2)
eor VTMP1.16b, VTMP1.16b, VTMP1.16b
aese VTMP0.16b,VTMP1.16b
MUL_MATRIX(VTMP0, ATAHMatV, ATALMatV, VTMP2)
mov WTMP,VTMP0.s[0]
/* linear transformation */
eor ROUND_KEY2,WTMP,WTMP,ror #19
eor ROUND_KEY2,ROUND_KEY2,WTMP,ror #9
mov WTMP,V_KEY.s[0]
eor ROUND_KEY2,ROUND_KEY2,WTMP
mov V_KEY.s[0],ROUND_KEY2
cbz ENC1,2f
str ROUND_KEY2,[ROUND_KEY1],#4
b 3f
2: // set encrypt key
str ROUND_KEY2,[ROUND_KEY1],#-4
3: // final
tbl V_KEY.16b,{V_KEY.16b},V_MAP.16b
subs SCHEDULES,SCHEDULES,#1
b.ne 1b
/*clear register for temp key */
eor V_KEY.16b, V_KEY.16b, V_KEY.16b
eor ROUND_KEY2, ROUND_KEY2, ROUND_KEY2
ldp d10, d11, [sp, #0x20]
ldp d8, d9, [sp, #0x10]
ldp x29, x30, [sp], #0x30
AARCH64_AUTIASP
ret
.size vpsm4_ex_set_key,.-vpsm4_ex_set_key
/*
* void Vpsm4SetEncryptKey(const unsigned char *userKey, SM4_KEY *key);
* generate SM4 encrypt round KEY context
* x0 => userKey; x1 => key
*/
.globl Vpsm4SetEncryptKey
.type Vpsm4SetEncryptKey,%function
.align 5
Vpsm4SetEncryptKey:
AARCH64_PACIASP
stp x29,x30,[sp,#-16]!
mov w2,1
bl vpsm4_ex_set_key
ldp x29,x30,[sp],#16
AARCH64_AUTIASP
ret
.size Vpsm4SetEncryptKey,.-Vpsm4SetEncryptKey
/*
* void Vpsm4SetDecryptKey(const unsigned char *userKey, SM4_KEY *key);
* generate SM4 decryption round KEY context
* x0 => userKey; x1 => key
*/
.globl Vpsm4SetDecryptKey
.type Vpsm4SetDecryptKey,%function
.align 5
Vpsm4SetDecryptKey:
AARCH64_PACIASP
stp x29,x30,[sp,#-16]!
mov w2,0
bl vpsm4_ex_set_key
ldp x29,x30,[sp],#16
AARCH64_AUTIASP
ret
.size Vpsm4SetDecryptKey,.-Vpsm4SetDecryptKey
#endif
| 2302_82127028/openHiTLS-examples_1508 | crypto/sm4/src/asm/crypt_sm4_ex_armv8.S | Unix Assembly | unknown | 6,469 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SM4
.file "crypt_sm4_macro_x86_64.s"
.macro MUL_MATRIX A0 HI_MASK LO_MASK
vpsrlw $4,\A0,%ymm5
vpand %ymm14,\A0,%ymm6
vpand %ymm14,%ymm5,%ymm5
vpshufb %ymm6,\LO_MASK,%ymm6
vpshufb %ymm5,\HI_MASK,%ymm5
vpxor %ymm6,%ymm5,\A0
.endm
.macro SM4_MM256_AESENCLAST A0
vextractf128 $0,\A0,%xmm5
vextractf128 $1,\A0,%xmm6
vpxor %xmm12,%xmm12,%xmm12
vaesenclast %xmm12,%xmm5,%xmm5
vaesenclast %xmm12,%xmm6,%xmm6
subq $16, %rsp
vmovdqu %xmm5, (%rsp)
vbroadcasti128 (%rsp), %ymm5
vinsertf128 $1,%xmm6,%ymm5,\A0
addq $16, %rsp
.endm
.macro SM4_MM256_ROL A0 A1 Imm1 Imm2
vpslld \Imm1,\A1,%ymm5
vpsrld \Imm2,\A1,%ymm6
vpxor %ymm5,%ymm6,%ymm12
vpxor %ymm12,\A0,\A0
.endm
##### SBOX Extend Tables (1 Table, 256*4 bytes): SBOX_0, SBOX_1, SBOX_2, SBOX_3 #####
##### MASK: XOR SHUFFLE LOAD STORE #####
.section .rodata
.align 64
SBOX4X_MASK:
#SBOX_0:
.long 0xd55b5b8e, 0x924242d0, 0xeaa7a74d, 0xfdfbfb06, 0xcf3333fc, 0xe2878765, 0x3df4f4c9, 0xb5dede6b, 0x1658584e, 0xb4dada6e, 0x14505044, 0xc10b0bca, 0x28a0a088, 0xf8efef17, 0x2cb0b09c, 0x5141411
.long 0x2bacac87, 0x669d9dfb, 0x986a6af2, 0x77d9d9ae, 0x2aa8a882, 0xbcfafa46, 0x4101014, 0xc00f0fcf, 0xa8aaaa02, 0x45111154, 0x134c4c5f, 0x269898be, 0x4825256d, 0x841a1a9e, 0x618181e, 0x9b6666fd
.long 0x9e7272ec, 0x4309094a, 0x51414110, 0xf7d3d324, 0x934646d5, 0xecbfbf53, 0x9a6262f8, 0x7be9e992, 0x33ccccff, 0x55515104, 0xb2c2c27, 0x420d0d4f, 0xeeb7b759, 0xcc3f3ff3, 0xaeb2b21c, 0x638989ea
.long 0xe7939374, 0xb1cece7f, 0x1c70706c, 0xaba6a60d, 0xca2727ed, 0x8202028, 0xeba3a348, 0x975656c1, 0x82020280, 0xdc7f7fa3, 0x965252c4, 0xf9ebeb12, 0x74d5d5a1, 0x8d3e3eb3, 0x3ffcfcc3, 0xa49a9a3e
.long 0x461d1d5b, 0x71c1c1b, 0xa59e9e3b, 0xfff3f30c, 0xf0cfcf3f, 0x72cdcdbf, 0x175c5c4b, 0xb8eaea52, 0x810e0e8f, 0x5865653d, 0x3cf0f0cc, 0x1964647d, 0xe59b9b7e, 0x87161691, 0x4e3d3d73, 0xaaa2a208
.long 0x69a1a1c8, 0x6aadadc7, 0x83060685, 0xb0caca7a, 0x70c5c5b5, 0x659191f4, 0xd96b6bb2, 0x892e2ea7, 0xfbe3e318, 0xe8afaf47, 0xf3c3c33, 0x4a2d2d67, 0x71c1c1b0, 0x5759590e, 0x9f7676e9, 0x35d4d4e1
.long 0x1e787866, 0x249090b4, 0xe383836, 0x5f797926, 0x628d8def, 0x59616138, 0xd2474795, 0xa08a8a2a, 0x259494b1, 0x228888aa, 0x7df1f18c, 0x3bececd7, 0x1040405, 0x218484a5, 0x79e1e198, 0x851e1e9b
.long 0xd7535384, 0x0, 0x4719195e, 0x565d5d0b, 0x9d7e7ee3, 0xd04f4f9f, 0x279c9cbb, 0x5349491a, 0x4d31317c, 0x36d8d8ee, 0x208080a, 0xe49f9f7b, 0xa2828220, 0xc71313d4, 0xcb2323e8, 0x9c7a7ae6
.long 0xe9abab42, 0xbdfefe43, 0x882a2aa2, 0xd14b4b9a, 0x41010140, 0xc41f1fdb, 0x38e0e0d8, 0xb7d6d661, 0xa18e8e2f, 0xf4dfdf2b, 0xf1cbcb3a, 0xcd3b3bf6, 0xfae7e71d, 0x608585e5, 0x15545441, 0xa3868625
.long 0xe3838360, 0xacbaba16, 0x5c757529, 0xa6929234, 0x996e6ef7, 0x34d0d0e4, 0x1a686872, 0x54555501, 0xafb6b619, 0x914e4edf, 0x32c8c8fa, 0x30c0c0f0, 0xf6d7d721, 0x8e3232bc, 0xb3c6c675, 0xe08f8f6f
.long 0x1d747469, 0xf5dbdb2e, 0xe18b8b6a, 0x2eb8b896, 0x800a0a8a, 0x679999fe, 0xc92b2be2, 0x618181e0, 0xc30303c0, 0x29a4a48d, 0x238c8caf, 0xa9aeae07, 0xd343439, 0x524d4d1f, 0x4f393976, 0x6ebdbdd3
.long 0xd6575781, 0xd86f6fb7, 0x37dcdceb, 0x44151551, 0xdd7b7ba6, 0xfef7f709, 0x8c3a3ab6, 0x2fbcbc93, 0x30c0c0f, 0xfcffff03, 0x6ba9a9c2, 0x73c9c9ba, 0x6cb5b5d9, 0x6db1b1dc, 0x5a6d6d37, 0x50454515
.long 0x8f3636b9, 0x1b6c6c77, 0xadbebe13, 0x904a4ada, 0xb9eeee57, 0xde7777a9, 0xbef2f24c, 0x7efdfd83, 0x11444455, 0xda6767bd, 0x5d71712c, 0x40050545, 0x1f7c7c63, 0x10404050, 0x5b696932, 0xdb6363b8
.long 0xa282822, 0xc20707c5, 0x31c4c4f5, 0x8a2222a8, 0xa7969631, 0xce3737f9, 0x7aeded97, 0xbff6f649, 0x2db4b499, 0x75d1d1a4, 0xd3434390, 0x1248485a, 0xbae2e258, 0xe6979771, 0xb6d2d264, 0xb2c2c270
.long 0x8b2626ad, 0x68a5a5cd, 0x955e5ecb, 0x4b292962, 0xc30303c, 0x945a5ace, 0x76ddddab, 0x7ff9f986, 0x649595f1, 0xbbe6e65d, 0xf2c7c735, 0x924242d, 0xc61717d1, 0x6fb9b9d6, 0xc51b1bde, 0x86121294
.long 0x18606078, 0xf3c3c330, 0x7cf5f589, 0xefb3b35c, 0x3ae8e8d2, 0xdf7373ac, 0x4c353579, 0x208080a0, 0x78e5e59d, 0xedbbbb56, 0x5e7d7d23, 0x3ef8f8c6, 0xd45f5f8b, 0xc82f2fe7, 0x39e4e4dd, 0x49212168
#SBOX_1:
.long 0x5b5b8ed5, 0x4242d092, 0xa7a74dea, 0xfbfb06fd, 0x3333fccf, 0x878765e2, 0xf4f4c93d, 0xdede6bb5, 0x58584e16, 0xdada6eb4, 0x50504414, 0xb0bcac1, 0xa0a08828, 0xefef17f8, 0xb0b09c2c, 0x14141105
.long 0xacac872b, 0x9d9dfb66, 0x6a6af298, 0xd9d9ae77, 0xa8a8822a, 0xfafa46bc, 0x10101404, 0xf0fcfc0, 0xaaaa02a8, 0x11115445, 0x4c4c5f13, 0x9898be26, 0x25256d48, 0x1a1a9e84, 0x18181e06, 0x6666fd9b
.long 0x7272ec9e, 0x9094a43, 0x41411051, 0xd3d324f7, 0x4646d593, 0xbfbf53ec, 0x6262f89a, 0xe9e9927b, 0xccccff33, 0x51510455, 0x2c2c270b, 0xd0d4f42, 0xb7b759ee, 0x3f3ff3cc, 0xb2b21cae, 0x8989ea63
.long 0x939374e7, 0xcece7fb1, 0x70706c1c, 0xa6a60dab, 0x2727edca, 0x20202808, 0xa3a348eb, 0x5656c197, 0x2028082, 0x7f7fa3dc, 0x5252c496, 0xebeb12f9, 0xd5d5a174, 0x3e3eb38d, 0xfcfcc33f, 0x9a9a3ea4
.long 0x1d1d5b46, 0x1c1c1b07, 0x9e9e3ba5, 0xf3f30cff, 0xcfcf3ff0, 0xcdcdbf72, 0x5c5c4b17, 0xeaea52b8, 0xe0e8f81, 0x65653d58, 0xf0f0cc3c, 0x64647d19, 0x9b9b7ee5, 0x16169187, 0x3d3d734e, 0xa2a208aa
.long 0xa1a1c869, 0xadadc76a, 0x6068583, 0xcaca7ab0, 0xc5c5b570, 0x9191f465, 0x6b6bb2d9, 0x2e2ea789, 0xe3e318fb, 0xafaf47e8, 0x3c3c330f, 0x2d2d674a, 0xc1c1b071, 0x59590e57, 0x7676e99f, 0xd4d4e135
.long 0x7878661e, 0x9090b424, 0x3838360e, 0x7979265f, 0x8d8def62, 0x61613859, 0x474795d2, 0x8a8a2aa0, 0x9494b125, 0x8888aa22, 0xf1f18c7d, 0xececd73b, 0x4040501, 0x8484a521, 0xe1e19879, 0x1e1e9b85
.long 0x535384d7, 0x0, 0x19195e47, 0x5d5d0b56, 0x7e7ee39d, 0x4f4f9fd0, 0x9c9cbb27, 0x49491a53, 0x31317c4d, 0xd8d8ee36, 0x8080a02, 0x9f9f7be4, 0x828220a2, 0x1313d4c7, 0x2323e8cb, 0x7a7ae69c
.long 0xabab42e9, 0xfefe43bd, 0x2a2aa288, 0x4b4b9ad1, 0x1014041, 0x1f1fdbc4, 0xe0e0d838, 0xd6d661b7, 0x8e8e2fa1, 0xdfdf2bf4, 0xcbcb3af1, 0x3b3bf6cd, 0xe7e71dfa, 0x8585e560, 0x54544115, 0x868625a3
.long 0x838360e3, 0xbaba16ac, 0x7575295c, 0x929234a6, 0x6e6ef799, 0xd0d0e434, 0x6868721a, 0x55550154, 0xb6b619af, 0x4e4edf91, 0xc8c8fa32, 0xc0c0f030, 0xd7d721f6, 0x3232bc8e, 0xc6c675b3, 0x8f8f6fe0
.long 0x7474691d, 0xdbdb2ef5, 0x8b8b6ae1, 0xb8b8962e, 0xa0a8a80, 0x9999fe67, 0x2b2be2c9, 0x8181e061, 0x303c0c3, 0xa4a48d29, 0x8c8caf23, 0xaeae07a9, 0x3434390d, 0x4d4d1f52, 0x3939764f, 0xbdbdd36e
.long 0x575781d6, 0x6f6fb7d8, 0xdcdceb37, 0x15155144, 0x7b7ba6dd, 0xf7f709fe, 0x3a3ab68c, 0xbcbc932f, 0xc0c0f03, 0xffff03fc, 0xa9a9c26b, 0xc9c9ba73, 0xb5b5d96c, 0xb1b1dc6d, 0x6d6d375a, 0x45451550
.long 0x3636b98f, 0x6c6c771b, 0xbebe13ad, 0x4a4ada90, 0xeeee57b9, 0x7777a9de, 0xf2f24cbe, 0xfdfd837e, 0x44445511, 0x6767bdda, 0x71712c5d, 0x5054540, 0x7c7c631f, 0x40405010, 0x6969325b, 0x6363b8db
.long 0x2828220a, 0x707c5c2, 0xc4c4f531, 0x2222a88a, 0x969631a7, 0x3737f9ce, 0xeded977a, 0xf6f649bf, 0xb4b4992d, 0xd1d1a475, 0x434390d3, 0x48485a12, 0xe2e258ba, 0x979771e6, 0xd2d264b6, 0xc2c270b2
.long 0x2626ad8b, 0xa5a5cd68, 0x5e5ecb95, 0x2929624b, 0x30303c0c, 0x5a5ace94, 0xddddab76, 0xf9f9867f, 0x9595f164, 0xe6e65dbb, 0xc7c735f2, 0x24242d09, 0x1717d1c6, 0xb9b9d66f, 0x1b1bdec5, 0x12129486
.long 0x60607818, 0xc3c330f3, 0xf5f5897c, 0xb3b35cef, 0xe8e8d23a, 0x7373acdf, 0x3535794c, 0x8080a020, 0xe5e59d78, 0xbbbb56ed, 0x7d7d235e, 0xf8f8c63e, 0x5f5f8bd4, 0x2f2fe7c8, 0xe4e4dd39, 0x21216849
#SBOX_2:
.long 0x5b8ed55b, 0x42d09242, 0xa74deaa7, 0xfb06fdfb, 0x33fccf33, 0x8765e287, 0xf4c93df4, 0xde6bb5de, 0x584e1658, 0xda6eb4da, 0x50441450, 0xbcac10b, 0xa08828a0, 0xef17f8ef, 0xb09c2cb0, 0x14110514
.long 0xac872bac, 0x9dfb669d, 0x6af2986a, 0xd9ae77d9, 0xa8822aa8, 0xfa46bcfa, 0x10140410, 0xfcfc00f, 0xaa02a8aa, 0x11544511, 0x4c5f134c, 0x98be2698, 0x256d4825, 0x1a9e841a, 0x181e0618, 0x66fd9b66
.long 0x72ec9e72, 0x94a4309, 0x41105141, 0xd324f7d3, 0x46d59346, 0xbf53ecbf, 0x62f89a62, 0xe9927be9, 0xccff33cc, 0x51045551, 0x2c270b2c, 0xd4f420d, 0xb759eeb7, 0x3ff3cc3f, 0xb21caeb2, 0x89ea6389
.long 0x9374e793, 0xce7fb1ce, 0x706c1c70, 0xa60daba6, 0x27edca27, 0x20280820, 0xa348eba3, 0x56c19756, 0x2808202, 0x7fa3dc7f, 0x52c49652, 0xeb12f9eb, 0xd5a174d5, 0x3eb38d3e, 0xfcc33ffc, 0x9a3ea49a
.long 0x1d5b461d, 0x1c1b071c, 0x9e3ba59e, 0xf30cfff3, 0xcf3ff0cf, 0xcdbf72cd, 0x5c4b175c, 0xea52b8ea, 0xe8f810e, 0x653d5865, 0xf0cc3cf0, 0x647d1964, 0x9b7ee59b, 0x16918716, 0x3d734e3d, 0xa208aaa2
.long 0xa1c869a1, 0xadc76aad, 0x6858306, 0xca7ab0ca, 0xc5b570c5, 0x91f46591, 0x6bb2d96b, 0x2ea7892e, 0xe318fbe3, 0xaf47e8af, 0x3c330f3c, 0x2d674a2d, 0xc1b071c1, 0x590e5759, 0x76e99f76, 0xd4e135d4
.long 0x78661e78, 0x90b42490, 0x38360e38, 0x79265f79, 0x8def628d, 0x61385961, 0x4795d247, 0x8a2aa08a, 0x94b12594, 0x88aa2288, 0xf18c7df1, 0xecd73bec, 0x4050104, 0x84a52184, 0xe19879e1, 0x1e9b851e
.long 0x5384d753, 0x0, 0x195e4719, 0x5d0b565d, 0x7ee39d7e, 0x4f9fd04f, 0x9cbb279c, 0x491a5349, 0x317c4d31, 0xd8ee36d8, 0x80a0208, 0x9f7be49f, 0x8220a282, 0x13d4c713, 0x23e8cb23, 0x7ae69c7a
.long 0xab42e9ab, 0xfe43bdfe, 0x2aa2882a, 0x4b9ad14b, 0x1404101, 0x1fdbc41f, 0xe0d838e0, 0xd661b7d6, 0x8e2fa18e, 0xdf2bf4df, 0xcb3af1cb, 0x3bf6cd3b, 0xe71dfae7, 0x85e56085, 0x54411554, 0x8625a386
.long 0x8360e383, 0xba16acba, 0x75295c75, 0x9234a692, 0x6ef7996e, 0xd0e434d0, 0x68721a68, 0x55015455, 0xb619afb6, 0x4edf914e, 0xc8fa32c8, 0xc0f030c0, 0xd721f6d7, 0x32bc8e32, 0xc675b3c6, 0x8f6fe08f
.long 0x74691d74, 0xdb2ef5db, 0x8b6ae18b, 0xb8962eb8, 0xa8a800a, 0x99fe6799, 0x2be2c92b, 0x81e06181, 0x3c0c303, 0xa48d29a4, 0x8caf238c, 0xae07a9ae, 0x34390d34, 0x4d1f524d, 0x39764f39, 0xbdd36ebd
.long 0x5781d657, 0x6fb7d86f, 0xdceb37dc, 0x15514415, 0x7ba6dd7b, 0xf709fef7, 0x3ab68c3a, 0xbc932fbc, 0xc0f030c, 0xff03fcff, 0xa9c26ba9, 0xc9ba73c9, 0xb5d96cb5, 0xb1dc6db1, 0x6d375a6d, 0x45155045
.long 0x36b98f36, 0x6c771b6c, 0xbe13adbe, 0x4ada904a, 0xee57b9ee, 0x77a9de77, 0xf24cbef2, 0xfd837efd, 0x44551144, 0x67bdda67, 0x712c5d71, 0x5454005, 0x7c631f7c, 0x40501040, 0x69325b69, 0x63b8db63
.long 0x28220a28, 0x7c5c207, 0xc4f531c4, 0x22a88a22, 0x9631a796, 0x37f9ce37, 0xed977aed, 0xf649bff6, 0xb4992db4, 0xd1a475d1, 0x4390d343, 0x485a1248, 0xe258bae2, 0x9771e697, 0xd264b6d2, 0xc270b2c2
.long 0x26ad8b26, 0xa5cd68a5, 0x5ecb955e, 0x29624b29, 0x303c0c30, 0x5ace945a, 0xddab76dd, 0xf9867ff9, 0x95f16495, 0xe65dbbe6, 0xc735f2c7, 0x242d0924, 0x17d1c617, 0xb9d66fb9, 0x1bdec51b, 0x12948612
.long 0x60781860, 0xc330f3c3, 0xf5897cf5, 0xb35cefb3, 0xe8d23ae8, 0x73acdf73, 0x35794c35, 0x80a02080, 0xe59d78e5, 0xbb56edbb, 0x7d235e7d, 0xf8c63ef8, 0x5f8bd45f, 0x2fe7c82f, 0xe4dd39e4, 0x21684921
#SBOX_3:
.long 0x8ed55b5b, 0xd0924242, 0x4deaa7a7, 0x6fdfbfb, 0xfccf3333, 0x65e28787, 0xc93df4f4, 0x6bb5dede, 0x4e165858, 0x6eb4dada, 0x44145050, 0xcac10b0b, 0x8828a0a0, 0x17f8efef, 0x9c2cb0b0, 0x11051414
.long 0x872bacac, 0xfb669d9d, 0xf2986a6a, 0xae77d9d9, 0x822aa8a8, 0x46bcfafa, 0x14041010, 0xcfc00f0f, 0x2a8aaaa, 0x54451111, 0x5f134c4c, 0xbe269898, 0x6d482525, 0x9e841a1a, 0x1e061818, 0xfd9b6666
.long 0xec9e7272, 0x4a430909, 0x10514141, 0x24f7d3d3, 0xd5934646, 0x53ecbfbf, 0xf89a6262, 0x927be9e9, 0xff33cccc, 0x4555151, 0x270b2c2c, 0x4f420d0d, 0x59eeb7b7, 0xf3cc3f3f, 0x1caeb2b2, 0xea638989
.long 0x74e79393, 0x7fb1cece, 0x6c1c7070, 0xdaba6a6, 0xedca2727, 0x28082020, 0x48eba3a3, 0xc1975656, 0x80820202, 0xa3dc7f7f, 0xc4965252, 0x12f9ebeb, 0xa174d5d5, 0xb38d3e3e, 0xc33ffcfc, 0x3ea49a9a
.long 0x5b461d1d, 0x1b071c1c, 0x3ba59e9e, 0xcfff3f3, 0x3ff0cfcf, 0xbf72cdcd, 0x4b175c5c, 0x52b8eaea, 0x8f810e0e, 0x3d586565, 0xcc3cf0f0, 0x7d196464, 0x7ee59b9b, 0x91871616, 0x734e3d3d, 0x8aaa2a2
.long 0xc869a1a1, 0xc76aadad, 0x85830606, 0x7ab0caca, 0xb570c5c5, 0xf4659191, 0xb2d96b6b, 0xa7892e2e, 0x18fbe3e3, 0x47e8afaf, 0x330f3c3c, 0x674a2d2d, 0xb071c1c1, 0xe575959, 0xe99f7676, 0xe135d4d4
.long 0x661e7878, 0xb4249090, 0x360e3838, 0x265f7979, 0xef628d8d, 0x38596161, 0x95d24747, 0x2aa08a8a, 0xb1259494, 0xaa228888, 0x8c7df1f1, 0xd73becec, 0x5010404, 0xa5218484, 0x9879e1e1, 0x9b851e1e
.long 0x84d75353, 0x0, 0x5e471919, 0xb565d5d, 0xe39d7e7e, 0x9fd04f4f, 0xbb279c9c, 0x1a534949, 0x7c4d3131, 0xee36d8d8, 0xa020808, 0x7be49f9f, 0x20a28282, 0xd4c71313, 0xe8cb2323, 0xe69c7a7a
.long 0x42e9abab, 0x43bdfefe, 0xa2882a2a, 0x9ad14b4b, 0x40410101, 0xdbc41f1f, 0xd838e0e0, 0x61b7d6d6, 0x2fa18e8e, 0x2bf4dfdf, 0x3af1cbcb, 0xf6cd3b3b, 0x1dfae7e7, 0xe5608585, 0x41155454, 0x25a38686
.long 0x60e38383, 0x16acbaba, 0x295c7575, 0x34a69292, 0xf7996e6e, 0xe434d0d0, 0x721a6868, 0x1545555, 0x19afb6b6, 0xdf914e4e, 0xfa32c8c8, 0xf030c0c0, 0x21f6d7d7, 0xbc8e3232, 0x75b3c6c6, 0x6fe08f8f
.long 0x691d7474, 0x2ef5dbdb, 0x6ae18b8b, 0x962eb8b8, 0x8a800a0a, 0xfe679999, 0xe2c92b2b, 0xe0618181, 0xc0c30303, 0x8d29a4a4, 0xaf238c8c, 0x7a9aeae, 0x390d3434, 0x1f524d4d, 0x764f3939, 0xd36ebdbd
.long 0x81d65757, 0xb7d86f6f, 0xeb37dcdc, 0x51441515, 0xa6dd7b7b, 0x9fef7f7, 0xb68c3a3a, 0x932fbcbc, 0xf030c0c, 0x3fcffff, 0xc26ba9a9, 0xba73c9c9, 0xd96cb5b5, 0xdc6db1b1, 0x375a6d6d, 0x15504545
.long 0xb98f3636, 0x771b6c6c, 0x13adbebe, 0xda904a4a, 0x57b9eeee, 0xa9de7777, 0x4cbef2f2, 0x837efdfd, 0x55114444, 0xbdda6767, 0x2c5d7171, 0x45400505, 0x631f7c7c, 0x50104040, 0x325b6969, 0xb8db6363
.long 0x220a2828, 0xc5c20707, 0xf531c4c4, 0xa88a2222, 0x31a79696, 0xf9ce3737, 0x977aeded, 0x49bff6f6, 0x992db4b4, 0xa475d1d1, 0x90d34343, 0x5a124848, 0x58bae2e2, 0x71e69797, 0x64b6d2d2, 0x70b2c2c2
.long 0xad8b2626, 0xcd68a5a5, 0xcb955e5e, 0x624b2929, 0x3c0c3030, 0xce945a5a, 0xab76dddd, 0x867ff9f9, 0xf1649595, 0x5dbbe6e6, 0x35f2c7c7, 0x2d092424, 0xd1c61717, 0xd66fb9b9, 0xdec51b1b, 0x94861212
.long 0x78186060, 0x30f3c3c3, 0x897cf5f5, 0x5cefb3b3, 0xd23ae8e8, 0xacdf7373, 0x794c3535, 0xa0208080, 0x9d78e5e5, 0x56edbbbb, 0x235e7d7d, 0xc63ef8f8, 0x8bd45f5f, 0xe7c82f2f, 0xdd39e4e4, 0x68492121
#.xor_mask:
.long 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF
#.shuffle_mask:
.byte 3,2,1,0,7,6,5,4,11,10,9,8,15,14,13,12,3,2,1,0,7,6,5,4,11,10,9,8,15,14,13,12
#.load_mask:
.long 0,4,8,12,16,20,24,28
#.store_mask:
.long 0,8,16,24,1,9,17,25
#below are for AESNI
#.aes_mask: 128+4096(%rax)
.byte 0x00, 0x0d, 0x0a, 0x07, 0x04, 0x01, 0x0e, 0x0b, 0x08, 0x05, 0x02, 0x0f, 0x0c, 0x09, 0x06, 0x03
.byte 0x00, 0x0d, 0x0a, 0x07, 0x04, 0x01, 0x0e, 0x0b, 0x08, 0x05, 0x02, 0x0f, 0x0c, 0x09, 0x06, 0x03
#.aes_hi_mask_0: 160+4096(%rax)
.byte 0x00, 0x7a, 0x38, 0x42, 0x20, 0x5a, 0x18, 0x62, 0x40, 0x3a, 0x78, 0x02, 0x60, 0x1a, 0x58, 0x22
.byte 0x00, 0x7a, 0x38, 0x42, 0x20, 0x5a, 0x18, 0x62, 0x40, 0x3a, 0x78, 0x02, 0x60, 0x1a, 0x58, 0x22
#.aes_hi_mask_1: 192+4096(%rax)
.byte 0x00, 0x13, 0xd2, 0xc1, 0x78, 0x6b, 0xaa, 0xb9, 0xad, 0xbe, 0x7f, 0x6c, 0xd5, 0xc6, 0x07, 0x14
.byte 0x00, 0x13, 0xd2, 0xc1, 0x78, 0x6b, 0xaa, 0xb9, 0xad, 0xbe, 0x7f, 0x6c, 0xd5, 0xc6, 0x07, 0x14
#.aes_lo_mask_0: 224+4096(%rax)
.byte 0x00, 0xca, 0x77, 0xbd, 0x8b, 0x41, 0xfc, 0x36, 0xd4, 0x1e, 0xa3, 0x69, 0x5f, 0x95, 0x28, 0xe2
.byte 0x00, 0xca, 0x77, 0xbd, 0x8b, 0x41, 0xfc, 0x36, 0xd4, 0x1e, 0xa3, 0x69, 0x5f, 0x95, 0x28, 0xe2
#.aes_lo_mask_1: 256+4096(%rax)
.byte 0x00, 0x60, 0x22, 0x42, 0x1d, 0x7d, 0x3f, 0x5f, 0x87, 0xe7, 0xa5, 0xc5, 0x9a, 0xfa, 0xb8, 0xd8
.byte 0x00, 0x60, 0x22, 0x42, 0x1d, 0x7d, 0x3f, 0x5f, 0x87, 0xe7, 0xa5, 0xc5, 0x9a, 0xfa, 0xb8, 0xd8
#.aes_and_mask: 288+4096(%rax)
.byte 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f
.byte 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f
#.aes_mask_ta: 320
.byte 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35
.byte 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35
#.aes_mask_ata: 352
.byte 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59
.byte 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59
#endif
| 2302_82127028/openHiTLS-examples_1508 | crypto/sm4/src/asm/crypt_sm4_macro_x86_64.s | Unix Assembly | unknown | 16,207 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SM4
.file "crypt_sm4_modes_macro_x86_64.s"
.set TMP0,%ymm8
.set TMP1,%ymm9
.set TMP2,%ymm10
.set TMP3,%ymm11
.set TMP4,%ymm12
.set TMP5,%ymm13
.set TMP6,%ymm14
.set TMP7,%ymm15
.set AES_AND_MASK,%ymm14
.set AES_MASK,%ymm15
.set TMP0x,%xmm8
.set TMP1x,%xmm9
.set TMP2x,%xmm10
.set TMP3x,%xmm11
.set TMP4x,%xmm12
.set TMP5x,%xmm13
.set PreConst, 0x3e
.set PostConst, 0xd3
.set PreAffineTReg, %xmm10
.set PostAffineTReg, %xmm11
.set PreAffineTRegBLOCK16,%ymm14
.set PostAffineTRegBLOCK16,%ymm15
.macro SM4_SBOX A B PreReg PostReg TMP
vgf2p8affineqb $PreConst,\PreReg,\A,\TMP
vgf2p8affineinvqb $PostConst,\PostReg,\TMP,\B
.endm
.macro KeyExpandLTrans A B
movl \A,\B
movl \A,%r14d
roll $13,%r14d
xorl %r14d,\B
movl \A,%r14d
roll $23,%r14d
xorl %r14d,\B
.endm
.macro LTrans A B
movl \A,\B
movl \A,%r14d
roll $2,%r14d
xorl %r14d,\B
movl \A,%r14d
roll $10,%r14d
xorl %r14d,\B
movl \A,%r14d
roll $18,%r14d
xorl %r14d,\B
movl \A,%r14d
roll $24,%r14d
xorl %r14d,\B
.endm
/*
* x4 = x1 ^ x2 ^ x3 ^ *(rk + i);
* x4 = SBOX(x4);
* x0 = x0 ^ L32(x4);
*/
.macro SM4_ROUND A0 A1 A2 A3 RKey No
# x4 = x1 ^ x2 ^ x3 ^ *(rk + i);
movl \No(\RKey), T0
xorl \A1, T0
xorl \A2, T0
xorl \A3, T0
# x0 = x0 ^ (SBOX_0[x4 & 0xff]) ^ (SBOX_1[(x4 >> 8) & 0xff]) ^ (SBOX_2[(x4 >> 16) & 0xff]) ^ (SBOX_3[(x4 >> 24) & 0xff]);
movzbl T0BL, T1
xorl (ADDR,T1_64,4), \A0
shrl $8, T0
movzbl T0BL, T1
xorl 1024(ADDR,T1_64,4), \A0
shrl $8, T0
movzbl T0BL, T1
xorl 2048(ADDR,T1_64,4), \A0
shrl $8, T0
xorl 3072(ADDR,T0_64,4), \A0
.endm
.macro MATRIX_MUL X HI_MASK LO_MASK
vpsrlw $4,\X,TMP4
vpand AES_AND_MASK,\X,TMP5
vpand AES_AND_MASK,TMP4,TMP4
vpshufb TMP5,\LO_MASK,TMP5
vpshufb TMP4,\HI_MASK,TMP4
vpxor TMP5,TMP4,\X
.endm
.macro MATRIX_TRANSPOSE A0 A1 A2 A3
vpunpckhdq \A1,\A0,TMP0
vpunpckhdq \A3,\A2,TMP1
vpunpckldq \A1,\A0,\A0
vpunpckldq \A3,\A2,\A2
vpunpckhqdq \A2,\A0,\A1
vpunpcklqdq \A2,\A0,\A0
vpunpckhqdq TMP1,TMP0,\A3
vpunpcklqdq TMP1,TMP0,\A2
.endm
.macro SM4_LT X Y
# load LR masks (8 16 24)
vmovdqa 288+4096(%rax),TMP3
vmovdqa 320+4096(%rax),TMP4
vmovdqa 352+4096(%rax),TMP5
vpshufb TMP5,\Y,TMP2
vpxor TMP2,\X,\X
vpxor \Y,\X,\X
vpshufb TMP3,\Y,TMP2
vpshufb TMP4,\Y,TMP5
vpxor TMP5,TMP2,TMP2
vpxor \Y,TMP2,TMP2
vpslld $2,TMP2,TMP3
vpsrld $30,TMP2,TMP4
vpxor TMP4,TMP3,TMP3
vpxor TMP3,\X,\X
.endm
# load aes_mask and aes_and_mask prewards
.macro SM4_AVX2_AES_2_ROUND A0 A1 A2 A3 B0 B1 B2 B3 RKey No
# load round key
vpbroadcastd \No(\RKey),TMP0
# S-BOX inputs
vpxor \B1,TMP0,TMP1
vpxor \B2,TMP1,TMP1
vpxor \B3,TMP1,TMP1
vpxor \A1,TMP0,TMP0
vpxor \A2,TMP0,TMP0
vpxor \A3,TMP0,TMP0
# inverse shift rows
vpshufb AES_MASK,TMP0,TMP0
vpshufb AES_MASK,TMP1,TMP1
# SM4 with AESENCLAST : SM4-S(x) = A2(AES-S(A1(x)))
# load aes_hi_mask_0 & aes_lo_mask_0
vmovdqa 128+4096(%rax),TMP2
vmovdqa 160+4096(%rax),TMP3
# inner affine transform : A1(x) = M1*x + C1
MATRIX_MUL TMP0 TMP2 TMP3
MATRIX_MUL TMP1 TMP2 TMP3
# aesni instruction : AES-S(x)
# perform AES-S transformation
vmovdqa 192+4096(%rax),TMP4
vextracti128 $1,TMP0,TMP2x
vextracti128 $1,TMP1,TMP3x
vaesenclast TMP4x,TMP0x,TMP0x
vaesenclast TMP4x,TMP1x,TMP1x
vaesenclast TMP4x,TMP2x,TMP2x
vaesenclast TMP4x,TMP3x,TMP3x
vinserti128 $1,TMP2x,TMP0,TMP0
vinserti128 $1,TMP3x,TMP1,TMP1
# load aes_hi_mask_1 & aes_lo_mask_1
vmovdqa 224+4096(%rax),TMP2
vmovdqa 256+4096(%rax),TMP3
# outer affine transform : A2(x) = M2*x + C2
MATRIX_MUL TMP0 TMP2 TMP3
MATRIX_MUL TMP1 TMP2 TMP3
# linear transform : 4 parallel left rotations
SM4_LT \A0 TMP0
SM4_LT \B0 TMP1
.endm
# gfni implementation
.macro SM4_AVX2_GFNI_2_ROUND A0 A1 A2 A3 B0 B1 B2 B3 RKey No
# load round key
vpbroadcastd \No(\RKey),TMP0
# S-BOX inputs
vpxor \B1,TMP0,TMP1
vpxor \B2,TMP1,TMP1
vpxor \B3,TMP1,TMP1
vpxor \A1,TMP0,TMP0
vpxor \A2,TMP0,TMP0
vpxor \A3,TMP0,TMP0
# sbox
SM4_SBOX TMP1 TMP1 PreAffineTRegBLOCK16 PostAffineTRegBLOCK16 %ymm10
SM4_SBOX TMP0 TMP0 PreAffineTRegBLOCK16 PostAffineTRegBLOCK16 %ymm10
# linear transform : 4 parallel left rotations
SM4_LT \A0 TMP0
SM4_LT \B0 TMP1
.endm
.macro SM4_SERIAL_ROUNDS
xorq T0_64, T0_64
xorq T1_64, T1_64
SM4_ROUND W0 W1 W2 W3 RK 0
SM4_ROUND W1 W2 W3 W0 RK 4
SM4_ROUND W2 W3 W0 W1 RK 8
SM4_ROUND W3 W0 W1 W2 RK 12
SM4_ROUND W0 W1 W2 W3 RK 16
SM4_ROUND W1 W2 W3 W0 RK 20
SM4_ROUND W2 W3 W0 W1 RK 24
SM4_ROUND W3 W0 W1 W2 RK 28
SM4_ROUND W0 W1 W2 W3 RK 32
SM4_ROUND W1 W2 W3 W0 RK 36
SM4_ROUND W2 W3 W0 W1 RK 40
SM4_ROUND W3 W0 W1 W2 RK 44
SM4_ROUND W0 W1 W2 W3 RK 48
SM4_ROUND W1 W2 W3 W0 RK 52
SM4_ROUND W2 W3 W0 W1 RK 56
SM4_ROUND W3 W0 W1 W2 RK 60
SM4_ROUND W0 W1 W2 W3 RK 64
SM4_ROUND W1 W2 W3 W0 RK 68
SM4_ROUND W2 W3 W0 W1 RK 72
SM4_ROUND W3 W0 W1 W2 RK 76
SM4_ROUND W0 W1 W2 W3 RK 80
SM4_ROUND W1 W2 W3 W0 RK 84
SM4_ROUND W2 W3 W0 W1 RK 88
SM4_ROUND W3 W0 W1 W2 RK 92
SM4_ROUND W0 W1 W2 W3 RK 96
SM4_ROUND W1 W2 W3 W0 RK 100
SM4_ROUND W2 W3 W0 W1 RK 104
SM4_ROUND W3 W0 W1 W2 RK 108
SM4_ROUND W0 W1 W2 W3 RK 112
SM4_ROUND W1 W2 W3 W0 RK 116
SM4_ROUND W2 W3 W0 W1 RK 120
SM4_ROUND W3 W0 W1 W2 RK 124
.endm
.macro SM4_AVX2_AES_2_ROUNDS
SM4_AVX2_AES_2_ROUND X0 X1 X2 X3 Y0 Y1 Y2 Y3 RK 0
SM4_AVX2_AES_2_ROUND X1 X2 X3 X0 Y1 Y2 Y3 Y0 RK 4
SM4_AVX2_AES_2_ROUND X2 X3 X0 X1 Y2 Y3 Y0 Y1 RK 8
SM4_AVX2_AES_2_ROUND X3 X0 X1 X2 Y3 Y0 Y1 Y2 RK 12
SM4_AVX2_AES_2_ROUND X0 X1 X2 X3 Y0 Y1 Y2 Y3 RK 16
SM4_AVX2_AES_2_ROUND X1 X2 X3 X0 Y1 Y2 Y3 Y0 RK 20
SM4_AVX2_AES_2_ROUND X2 X3 X0 X1 Y2 Y3 Y0 Y1 RK 24
SM4_AVX2_AES_2_ROUND X3 X0 X1 X2 Y3 Y0 Y1 Y2 RK 28
SM4_AVX2_AES_2_ROUND X0 X1 X2 X3 Y0 Y1 Y2 Y3 RK 32
SM4_AVX2_AES_2_ROUND X1 X2 X3 X0 Y1 Y2 Y3 Y0 RK 36
SM4_AVX2_AES_2_ROUND X2 X3 X0 X1 Y2 Y3 Y0 Y1 RK 40
SM4_AVX2_AES_2_ROUND X3 X0 X1 X2 Y3 Y0 Y1 Y2 RK 44
SM4_AVX2_AES_2_ROUND X0 X1 X2 X3 Y0 Y1 Y2 Y3 RK 48
SM4_AVX2_AES_2_ROUND X1 X2 X3 X0 Y1 Y2 Y3 Y0 RK 52
SM4_AVX2_AES_2_ROUND X2 X3 X0 X1 Y2 Y3 Y0 Y1 RK 56
SM4_AVX2_AES_2_ROUND X3 X0 X1 X2 Y3 Y0 Y1 Y2 RK 60
SM4_AVX2_AES_2_ROUND X0 X1 X2 X3 Y0 Y1 Y2 Y3 RK 64
SM4_AVX2_AES_2_ROUND X1 X2 X3 X0 Y1 Y2 Y3 Y0 RK 68
SM4_AVX2_AES_2_ROUND X2 X3 X0 X1 Y2 Y3 Y0 Y1 RK 72
SM4_AVX2_AES_2_ROUND X3 X0 X1 X2 Y3 Y0 Y1 Y2 RK 76
SM4_AVX2_AES_2_ROUND X0 X1 X2 X3 Y0 Y1 Y2 Y3 RK 80
SM4_AVX2_AES_2_ROUND X1 X2 X3 X0 Y1 Y2 Y3 Y0 RK 84
SM4_AVX2_AES_2_ROUND X2 X3 X0 X1 Y2 Y3 Y0 Y1 RK 88
SM4_AVX2_AES_2_ROUND X3 X0 X1 X2 Y3 Y0 Y1 Y2 RK 92
SM4_AVX2_AES_2_ROUND X0 X1 X2 X3 Y0 Y1 Y2 Y3 RK 96
SM4_AVX2_AES_2_ROUND X1 X2 X3 X0 Y1 Y2 Y3 Y0 RK 100
SM4_AVX2_AES_2_ROUND X2 X3 X0 X1 Y2 Y3 Y0 Y1 RK 104
SM4_AVX2_AES_2_ROUND X3 X0 X1 X2 Y3 Y0 Y1 Y2 RK 108
SM4_AVX2_AES_2_ROUND X0 X1 X2 X3 Y0 Y1 Y2 Y3 RK 112
SM4_AVX2_AES_2_ROUND X1 X2 X3 X0 Y1 Y2 Y3 Y0 RK 116
SM4_AVX2_AES_2_ROUND X2 X3 X0 X1 Y2 Y3 Y0 Y1 RK 120
SM4_AVX2_AES_2_ROUND X3 X0 X1 X2 Y3 Y0 Y1 Y2 RK 124
.endm
.macro SM4_AVX2_GFNI_2_ROUNDS
SM4_AVX2_GFNI_2_ROUND X0 X1 X2 X3 Y0 Y1 Y2 Y3 RK 0
SM4_AVX2_GFNI_2_ROUND X1 X2 X3 X0 Y1 Y2 Y3 Y0 RK 4
SM4_AVX2_GFNI_2_ROUND X2 X3 X0 X1 Y2 Y3 Y0 Y1 RK 8
SM4_AVX2_GFNI_2_ROUND X3 X0 X1 X2 Y3 Y0 Y1 Y2 RK 12
SM4_AVX2_GFNI_2_ROUND X0 X1 X2 X3 Y0 Y1 Y2 Y3 RK 16
SM4_AVX2_GFNI_2_ROUND X1 X2 X3 X0 Y1 Y2 Y3 Y0 RK 20
SM4_AVX2_GFNI_2_ROUND X2 X3 X0 X1 Y2 Y3 Y0 Y1 RK 24
SM4_AVX2_GFNI_2_ROUND X3 X0 X1 X2 Y3 Y0 Y1 Y2 RK 28
SM4_AVX2_GFNI_2_ROUND X0 X1 X2 X3 Y0 Y1 Y2 Y3 RK 32
SM4_AVX2_GFNI_2_ROUND X1 X2 X3 X0 Y1 Y2 Y3 Y0 RK 36
SM4_AVX2_GFNI_2_ROUND X2 X3 X0 X1 Y2 Y3 Y0 Y1 RK 40
SM4_AVX2_GFNI_2_ROUND X3 X0 X1 X2 Y3 Y0 Y1 Y2 RK 44
SM4_AVX2_GFNI_2_ROUND X0 X1 X2 X3 Y0 Y1 Y2 Y3 RK 48
SM4_AVX2_GFNI_2_ROUND X1 X2 X3 X0 Y1 Y2 Y3 Y0 RK 52
SM4_AVX2_GFNI_2_ROUND X2 X3 X0 X1 Y2 Y3 Y0 Y1 RK 56
SM4_AVX2_GFNI_2_ROUND X3 X0 X1 X2 Y3 Y0 Y1 Y2 RK 60
SM4_AVX2_GFNI_2_ROUND X0 X1 X2 X3 Y0 Y1 Y2 Y3 RK 64
SM4_AVX2_GFNI_2_ROUND X1 X2 X3 X0 Y1 Y2 Y3 Y0 RK 68
SM4_AVX2_GFNI_2_ROUND X2 X3 X0 X1 Y2 Y3 Y0 Y1 RK 72
SM4_AVX2_GFNI_2_ROUND X3 X0 X1 X2 Y3 Y0 Y1 Y2 RK 76
SM4_AVX2_GFNI_2_ROUND X0 X1 X2 X3 Y0 Y1 Y2 Y3 RK 80
SM4_AVX2_GFNI_2_ROUND X1 X2 X3 X0 Y1 Y2 Y3 Y0 RK 84
SM4_AVX2_GFNI_2_ROUND X2 X3 X0 X1 Y2 Y3 Y0 Y1 RK 88
SM4_AVX2_GFNI_2_ROUND X3 X0 X1 X2 Y3 Y0 Y1 Y2 RK 92
SM4_AVX2_GFNI_2_ROUND X0 X1 X2 X3 Y0 Y1 Y2 Y3 RK 96
SM4_AVX2_GFNI_2_ROUND X1 X2 X3 X0 Y1 Y2 Y3 Y0 RK 100
SM4_AVX2_GFNI_2_ROUND X2 X3 X0 X1 Y2 Y3 Y0 Y1 RK 104
SM4_AVX2_GFNI_2_ROUND X3 X0 X1 X2 Y3 Y0 Y1 Y2 RK 108
SM4_AVX2_GFNI_2_ROUND X0 X1 X2 X3 Y0 Y1 Y2 Y3 RK 112
SM4_AVX2_GFNI_2_ROUND X1 X2 X3 X0 Y1 Y2 Y3 Y0 RK 116
SM4_AVX2_GFNI_2_ROUND X2 X3 X0 X1 Y2 Y3 Y0 Y1 RK 120
SM4_AVX2_GFNI_2_ROUND X3 X0 X1 X2 Y3 Y0 Y1 Y2 RK 124
.endm
##### SBOX Extend Tables (1 Table, 256*4 bytes): SBOX_0, SBOX_1, SBOX_2, SBOX_3 #####
.section .rodata
.balign 64
.PreAffinT:
.quad 0x4c287db91a22505d
.PostAffinT:
.quad 0xf3ab34a974a6b589
.align 64
SBOX4X_MASK:
#SBOX_0:
.long 0xd55b5b8e, 0x924242d0, 0xeaa7a74d, 0xfdfbfb06, 0xcf3333fc, 0xe2878765, 0x3df4f4c9, 0xb5dede6b, 0x1658584e, 0xb4dada6e, 0x14505044, 0xc10b0bca, 0x28a0a088, 0xf8efef17, 0x2cb0b09c, 0x05141411
.long 0x2bacac87, 0x669d9dfb, 0x986a6af2, 0x77d9d9ae, 0x2aa8a882, 0xbcfafa46, 0x04101014, 0xc00f0fcf, 0xa8aaaa02, 0x45111154, 0x134c4c5f, 0x269898be, 0x4825256d, 0x841a1a9e, 0x0618181e, 0x9b6666fd
.long 0x9e7272ec, 0x4309094a, 0x51414110, 0xf7d3d324, 0x934646d5, 0xecbfbf53, 0x9a6262f8, 0x7be9e992, 0x33ccccff, 0x55515104, 0x0b2c2c27, 0x420d0d4f, 0xeeb7b759, 0xcc3f3ff3, 0xaeb2b21c, 0x638989ea
.long 0xe7939374, 0xb1cece7f, 0x1c70706c, 0xaba6a60d, 0xca2727ed, 0x08202028, 0xeba3a348, 0x975656c1, 0x82020280, 0xdc7f7fa3, 0x965252c4, 0xf9ebeb12, 0x74d5d5a1, 0x8d3e3eb3, 0x3ffcfcc3, 0xa49a9a3e
.long 0x461d1d5b, 0x071c1c1b, 0xa59e9e3b, 0xfff3f30c, 0xf0cfcf3f, 0x72cdcdbf, 0x175c5c4b, 0xb8eaea52, 0x810e0e8f, 0x5865653d, 0x3cf0f0cc, 0x1964647d, 0xe59b9b7e, 0x87161691, 0x4e3d3d73, 0xaaa2a208
.long 0x69a1a1c8, 0x6aadadc7, 0x83060685, 0xb0caca7a, 0x70c5c5b5, 0x659191f4, 0xd96b6bb2, 0x892e2ea7, 0xfbe3e318, 0xe8afaf47, 0x0f3c3c33, 0x4a2d2d67, 0x71c1c1b0, 0x5759590e, 0x9f7676e9, 0x35d4d4e1
.long 0x1e787866, 0x249090b4, 0x0e383836, 0x5f797926, 0x628d8def, 0x59616138, 0xd2474795, 0xa08a8a2a, 0x259494b1, 0x228888aa, 0x7df1f18c, 0x3bececd7, 0x01040405, 0x218484a5, 0x79e1e198, 0x851e1e9b
.long 0xd7535384, 0x0, 0x4719195e, 0x565d5d0b, 0x9d7e7ee3, 0xd04f4f9f, 0x279c9cbb, 0x5349491a, 0x4d31317c, 0x36d8d8ee, 0x0208080a, 0xe49f9f7b, 0xa2828220, 0xc71313d4, 0xcb2323e8, 0x9c7a7ae6
.long 0xe9abab42, 0xbdfefe43, 0x882a2aa2, 0xd14b4b9a, 0x41010140, 0xc41f1fdb, 0x38e0e0d8, 0xb7d6d661, 0xa18e8e2f, 0xf4dfdf2b, 0xf1cbcb3a, 0xcd3b3bf6, 0xfae7e71d, 0x608585e5, 0x15545441, 0xa3868625
.long 0xe3838360, 0xacbaba16, 0x5c757529, 0xa6929234, 0x996e6ef7, 0x34d0d0e4, 0x1a686872, 0x54555501, 0xafb6b619, 0x914e4edf, 0x32c8c8fa, 0x30c0c0f0, 0xf6d7d721, 0x8e3232bc, 0xb3c6c675, 0xe08f8f6f
.long 0x1d747469, 0xf5dbdb2e, 0xe18b8b6a, 0x2eb8b896, 0x800a0a8a, 0x679999fe, 0xc92b2be2, 0x618181e0, 0xc30303c0, 0x29a4a48d, 0x238c8caf, 0xa9aeae07, 0x0d343439, 0x524d4d1f, 0x4f393976, 0x6ebdbdd3
.long 0xd6575781, 0xd86f6fb7, 0x37dcdceb, 0x44151551, 0xdd7b7ba6, 0xfef7f709, 0x8c3a3ab6, 0x2fbcbc93, 0x030c0c0f, 0xfcffff03, 0x6ba9a9c2, 0x73c9c9ba, 0x6cb5b5d9, 0x6db1b1dc, 0x5a6d6d37, 0x50454515
.long 0x8f3636b9, 0x1b6c6c77, 0xadbebe13, 0x904a4ada, 0xb9eeee57, 0xde7777a9, 0xbef2f24c, 0x7efdfd83, 0x11444455, 0xda6767bd, 0x5d71712c, 0x40050545, 0x1f7c7c63, 0x10404050, 0x5b696932, 0xdb6363b8
.long 0x0a282822, 0xc20707c5, 0x31c4c4f5, 0x8a2222a8, 0xa7969631, 0xce3737f9, 0x7aeded97, 0xbff6f649, 0x2db4b499, 0x75d1d1a4, 0xd3434390, 0x1248485a, 0xbae2e258, 0xe6979771, 0xb6d2d264, 0xb2c2c270
.long 0x8b2626ad, 0x68a5a5cd, 0x955e5ecb, 0x4b292962, 0x0c30303c, 0x945a5ace, 0x76ddddab, 0x7ff9f986, 0x649595f1, 0xbbe6e65d, 0xf2c7c735, 0x0924242d, 0xc61717d1, 0x6fb9b9d6, 0xc51b1bde, 0x86121294
.long 0x18606078, 0xf3c3c330, 0x7cf5f589, 0xefb3b35c, 0x3ae8e8d2, 0xdf7373ac, 0x4c353579, 0x208080a0, 0x78e5e59d, 0xedbbbb56, 0x5e7d7d23, 0x3ef8f8c6, 0xd45f5f8b, 0xc82f2fe7, 0x39e4e4dd, 0x49212168
#SBOX_1:
.long 0x5b5b8ed5, 0x4242d092, 0xa7a74dea, 0xfbfb06fd, 0x3333fccf, 0x878765e2, 0xf4f4c93d, 0xdede6bb5, 0x58584e16, 0xdada6eb4, 0x50504414, 0x0b0bcac1, 0xa0a08828, 0xefef17f8, 0xb0b09c2c, 0x14141105
.long 0xacac872b, 0x9d9dfb66, 0x6a6af298, 0xd9d9ae77, 0xa8a8822a, 0xfafa46bc, 0x10101404, 0x0f0fcfc0, 0xaaaa02a8, 0x11115445, 0x4c4c5f13, 0x9898be26, 0x25256d48, 0x1a1a9e84, 0x18181e06, 0x6666fd9b
.long 0x7272ec9e, 0x09094a43, 0x41411051, 0xd3d324f7, 0x4646d593, 0xbfbf53ec, 0x6262f89a, 0xe9e9927b, 0xccccff33, 0x51510455, 0x2c2c270b, 0x0d0d4f42, 0xb7b759ee, 0x3f3ff3cc, 0xb2b21cae, 0x8989ea63
.long 0x939374e7, 0xcece7fb1, 0x70706c1c, 0xa6a60dab, 0x2727edca, 0x20202808, 0xa3a348eb, 0x5656c197, 0x02028082, 0x7f7fa3dc, 0x5252c496, 0xebeb12f9, 0xd5d5a174, 0x3e3eb38d, 0xfcfcc33f, 0x9a9a3ea4
.long 0x1d1d5b46, 0x1c1c1b07, 0x9e9e3ba5, 0xf3f30cff, 0xcfcf3ff0, 0xcdcdbf72, 0x5c5c4b17, 0xeaea52b8, 0x0e0e8f81, 0x65653d58, 0xf0f0cc3c, 0x64647d19, 0x9b9b7ee5, 0x16169187, 0x3d3d734e, 0xa2a208aa
.long 0xa1a1c869, 0xadadc76a, 0x06068583, 0xcaca7ab0, 0xc5c5b570, 0x9191f465, 0x6b6bb2d9, 0x2e2ea789, 0xe3e318fb, 0xafaf47e8, 0x3c3c330f, 0x2d2d674a, 0xc1c1b071, 0x59590e57, 0x7676e99f, 0xd4d4e135
.long 0x7878661e, 0x9090b424, 0x3838360e, 0x7979265f, 0x8d8def62, 0x61613859, 0x474795d2, 0x8a8a2aa0, 0x9494b125, 0x8888aa22, 0xf1f18c7d, 0xececd73b, 0x04040501, 0x8484a521, 0xe1e19879, 0x1e1e9b85
.long 0x535384d7, 0x0, 0x19195e47, 0x5d5d0b56, 0x7e7ee39d, 0x4f4f9fd0, 0x9c9cbb27, 0x49491a53, 0x31317c4d, 0xd8d8ee36, 0x08080a02, 0x9f9f7be4, 0x828220a2, 0x1313d4c7, 0x2323e8cb, 0x7a7ae69c
.long 0xabab42e9, 0xfefe43bd, 0x2a2aa288, 0x4b4b9ad1, 0x01014041, 0x1f1fdbc4, 0xe0e0d838, 0xd6d661b7, 0x8e8e2fa1, 0xdfdf2bf4, 0xcbcb3af1, 0x3b3bf6cd, 0xe7e71dfa, 0x8585e560, 0x54544115, 0x868625a3
.long 0x838360e3, 0xbaba16ac, 0x7575295c, 0x929234a6, 0x6e6ef799, 0xd0d0e434, 0x6868721a, 0x55550154, 0xb6b619af, 0x4e4edf91, 0xc8c8fa32, 0xc0c0f030, 0xd7d721f6, 0x3232bc8e, 0xc6c675b3, 0x8f8f6fe0
.long 0x7474691d, 0xdbdb2ef5, 0x8b8b6ae1, 0xb8b8962e, 0x0a0a8a80, 0x9999fe67, 0x2b2be2c9, 0x8181e061, 0x0303c0c3, 0xa4a48d29, 0x8c8caf23, 0xaeae07a9, 0x3434390d, 0x4d4d1f52, 0x3939764f, 0xbdbdd36e
.long 0x575781d6, 0x6f6fb7d8, 0xdcdceb37, 0x15155144, 0x7b7ba6dd, 0xf7f709fe, 0x3a3ab68c, 0xbcbc932f, 0x0c0c0f03, 0xffff03fc, 0xa9a9c26b, 0xc9c9ba73, 0xb5b5d96c, 0xb1b1dc6d, 0x6d6d375a, 0x45451550
.long 0x3636b98f, 0x6c6c771b, 0xbebe13ad, 0x4a4ada90, 0xeeee57b9, 0x7777a9de, 0xf2f24cbe, 0xfdfd837e, 0x44445511, 0x6767bdda, 0x71712c5d, 0x05054540, 0x7c7c631f, 0x40405010, 0x6969325b, 0x6363b8db
.long 0x2828220a, 0x0707c5c2, 0xc4c4f531, 0x2222a88a, 0x969631a7, 0x3737f9ce, 0xeded977a, 0xf6f649bf, 0xb4b4992d, 0xd1d1a475, 0x434390d3, 0x48485a12, 0xe2e258ba, 0x979771e6, 0xd2d264b6, 0xc2c270b2
.long 0x2626ad8b, 0xa5a5cd68, 0x5e5ecb95, 0x2929624b, 0x30303c0c, 0x5a5ace94, 0xddddab76, 0xf9f9867f, 0x9595f164, 0xe6e65dbb, 0xc7c735f2, 0x24242d09, 0x1717d1c6, 0xb9b9d66f, 0x1b1bdec5, 0x12129486
.long 0x60607818, 0xc3c330f3, 0xf5f5897c, 0xb3b35cef, 0xe8e8d23a, 0x7373acdf, 0x3535794c, 0x8080a020, 0xe5e59d78, 0xbbbb56ed, 0x7d7d235e, 0xf8f8c63e, 0x5f5f8bd4, 0x2f2fe7c8, 0xe4e4dd39, 0x21216849
#SBOX_2:
.long 0x5b8ed55b, 0x42d09242, 0xa74deaa7, 0xfb06fdfb, 0x33fccf33, 0x8765e287, 0xf4c93df4, 0xde6bb5de, 0x584e1658, 0xda6eb4da, 0x50441450, 0x0bcac10b, 0xa08828a0, 0xef17f8ef, 0xb09c2cb0, 0x14110514
.long 0xac872bac, 0x9dfb669d, 0x6af2986a, 0xd9ae77d9, 0xa8822aa8, 0xfa46bcfa, 0x10140410, 0x0fcfc00f, 0xaa02a8aa, 0x11544511, 0x4c5f134c, 0x98be2698, 0x256d4825, 0x1a9e841a, 0x181e0618, 0x66fd9b66
.long 0x72ec9e72, 0x094a4309, 0x41105141, 0xd324f7d3, 0x46d59346, 0xbf53ecbf, 0x62f89a62, 0xe9927be9, 0xccff33cc, 0x51045551, 0x2c270b2c, 0x0d4f420d, 0xb759eeb7, 0x3ff3cc3f, 0xb21caeb2, 0x89ea6389
.long 0x9374e793, 0xce7fb1ce, 0x706c1c70, 0xa60daba6, 0x27edca27, 0x20280820, 0xa348eba3, 0x56c19756, 0x02808202, 0x7fa3dc7f, 0x52c49652, 0xeb12f9eb, 0xd5a174d5, 0x3eb38d3e, 0xfcc33ffc, 0x9a3ea49a
.long 0x1d5b461d, 0x1c1b071c, 0x9e3ba59e, 0xf30cfff3, 0xcf3ff0cf, 0xcdbf72cd, 0x5c4b175c, 0xea52b8ea, 0x0e8f810e, 0x653d5865, 0xf0cc3cf0, 0x647d1964, 0x9b7ee59b, 0x16918716, 0x3d734e3d, 0xa208aaa2
.long 0xa1c869a1, 0xadc76aad, 0x06858306, 0xca7ab0ca, 0xc5b570c5, 0x91f46591, 0x6bb2d96b, 0x2ea7892e, 0xe318fbe3, 0xaf47e8af, 0x3c330f3c, 0x2d674a2d, 0xc1b071c1, 0x590e5759, 0x76e99f76, 0xd4e135d4
.long 0x78661e78, 0x90b42490, 0x38360e38, 0x79265f79, 0x8def628d, 0x61385961, 0x4795d247, 0x8a2aa08a, 0x94b12594, 0x88aa2288, 0xf18c7df1, 0xecd73bec, 0x04050104, 0x84a52184, 0xe19879e1, 0x1e9b851e
.long 0x5384d753, 0x0, 0x195e4719, 0x5d0b565d, 0x7ee39d7e, 0x4f9fd04f, 0x9cbb279c, 0x491a5349, 0x317c4d31, 0xd8ee36d8, 0x080a0208, 0x9f7be49f, 0x8220a282, 0x13d4c713, 0x23e8cb23, 0x7ae69c7a
.long 0xab42e9ab, 0xfe43bdfe, 0x2aa2882a, 0x4b9ad14b, 0x01404101, 0x1fdbc41f, 0xe0d838e0, 0xd661b7d6, 0x8e2fa18e, 0xdf2bf4df, 0xcb3af1cb, 0x3bf6cd3b, 0xe71dfae7, 0x85e56085, 0x54411554, 0x8625a386
.long 0x8360e383, 0xba16acba, 0x75295c75, 0x9234a692, 0x6ef7996e, 0xd0e434d0, 0x68721a68, 0x55015455, 0xb619afb6, 0x4edf914e, 0xc8fa32c8, 0xc0f030c0, 0xd721f6d7, 0x32bc8e32, 0xc675b3c6, 0x8f6fe08f
.long 0x74691d74, 0xdb2ef5db, 0x8b6ae18b, 0xb8962eb8, 0x0a8a800a, 0x99fe6799, 0x2be2c92b, 0x81e06181, 0x03c0c303, 0xa48d29a4, 0x8caf238c, 0xae07a9ae, 0x34390d34, 0x4d1f524d, 0x39764f39, 0xbdd36ebd
.long 0x5781d657, 0x6fb7d86f, 0xdceb37dc, 0x15514415, 0x7ba6dd7b, 0xf709fef7, 0x3ab68c3a, 0xbc932fbc, 0x0c0f030c, 0xff03fcff, 0xa9c26ba9, 0xc9ba73c9, 0xb5d96cb5, 0xb1dc6db1, 0x6d375a6d, 0x45155045
.long 0x36b98f36, 0x6c771b6c, 0xbe13adbe, 0x4ada904a, 0xee57b9ee, 0x77a9de77, 0xf24cbef2, 0xfd837efd, 0x44551144, 0x67bdda67, 0x712c5d71, 0x05454005, 0x7c631f7c, 0x40501040, 0x69325b69, 0x63b8db63
.long 0x28220a28, 0x07c5c207, 0xc4f531c4, 0x22a88a22, 0x9631a796, 0x37f9ce37, 0xed977aed, 0xf649bff6, 0xb4992db4, 0xd1a475d1, 0x4390d343, 0x485a1248, 0xe258bae2, 0x9771e697, 0xd264b6d2, 0xc270b2c2
.long 0x26ad8b26, 0xa5cd68a5, 0x5ecb955e, 0x29624b29, 0x303c0c30, 0x5ace945a, 0xddab76dd, 0xf9867ff9, 0x95f16495, 0xe65dbbe6, 0xc735f2c7, 0x242d0924, 0x17d1c617, 0xb9d66fb9, 0x1bdec51b, 0x12948612
.long 0x60781860, 0xc330f3c3, 0xf5897cf5, 0xb35cefb3, 0xe8d23ae8, 0x73acdf73, 0x35794c35, 0x80a02080, 0xe59d78e5, 0xbb56edbb, 0x7d235e7d, 0xf8c63ef8, 0x5f8bd45f, 0x2fe7c82f, 0xe4dd39e4, 0x21684921
#SBOX_3:
.long 0x8ed55b5b, 0xd0924242, 0x4deaa7a7, 0x06fdfbfb, 0xfccf3333, 0x65e28787, 0xc93df4f4, 0x6bb5dede, 0x4e165858, 0x6eb4dada, 0x44145050, 0xcac10b0b, 0x8828a0a0, 0x17f8efef, 0x9c2cb0b0, 0x11051414
.long 0x872bacac, 0xfb669d9d, 0xf2986a6a, 0xae77d9d9, 0x822aa8a8, 0x46bcfafa, 0x14041010, 0xcfc00f0f, 0x02a8aaaa, 0x54451111, 0x5f134c4c, 0xbe269898, 0x6d482525, 0x9e841a1a, 0x1e061818, 0xfd9b6666
.long 0xec9e7272, 0x4a430909, 0x10514141, 0x24f7d3d3, 0xd5934646, 0x53ecbfbf, 0xf89a6262, 0x927be9e9, 0xff33cccc, 0x04555151, 0x270b2c2c, 0x4f420d0d, 0x59eeb7b7, 0xf3cc3f3f, 0x1caeb2b2, 0xea638989
.long 0x74e79393, 0x7fb1cece, 0x6c1c7070, 0x0daba6a6, 0xedca2727, 0x28082020, 0x48eba3a3, 0xc1975656, 0x80820202, 0xa3dc7f7f, 0xc4965252, 0x12f9ebeb, 0xa174d5d5, 0xb38d3e3e, 0xc33ffcfc, 0x3ea49a9a
.long 0x5b461d1d, 0x1b071c1c, 0x3ba59e9e, 0x0cfff3f3, 0x3ff0cfcf, 0xbf72cdcd, 0x4b175c5c, 0x52b8eaea, 0x8f810e0e, 0x3d586565, 0xcc3cf0f0, 0x7d196464, 0x7ee59b9b, 0x91871616, 0x734e3d3d, 0x08aaa2a2
.long 0xc869a1a1, 0xc76aadad, 0x85830606, 0x7ab0caca, 0xb570c5c5, 0xf4659191, 0xb2d96b6b, 0xa7892e2e, 0x18fbe3e3, 0x47e8afaf, 0x330f3c3c, 0x674a2d2d, 0xb071c1c1, 0x0e575959, 0xe99f7676, 0xe135d4d4
.long 0x661e7878, 0xb4249090, 0x360e3838, 0x265f7979, 0xef628d8d, 0x38596161, 0x95d24747, 0x2aa08a8a, 0xb1259494, 0xaa228888, 0x8c7df1f1, 0xd73becec, 0x05010404, 0xa5218484, 0x9879e1e1, 0x9b851e1e
.long 0x84d75353, 0x0, 0x5e471919, 0x0b565d5d, 0xe39d7e7e, 0x9fd04f4f, 0xbb279c9c, 0x1a534949, 0x7c4d3131, 0xee36d8d8, 0x0a020808, 0x7be49f9f, 0x20a28282, 0xd4c71313, 0xe8cb2323, 0xe69c7a7a
.long 0x42e9abab, 0x43bdfefe, 0xa2882a2a, 0x9ad14b4b, 0x40410101, 0xdbc41f1f, 0xd838e0e0, 0x61b7d6d6, 0x2fa18e8e, 0x2bf4dfdf, 0x3af1cbcb, 0xf6cd3b3b, 0x1dfae7e7, 0xe5608585, 0x41155454, 0x25a38686
.long 0x60e38383, 0x16acbaba, 0x295c7575, 0x34a69292, 0xf7996e6e, 0xe434d0d0, 0x721a6868, 0x01545555, 0x19afb6b6, 0xdf914e4e, 0xfa32c8c8, 0xf030c0c0, 0x21f6d7d7, 0xbc8e3232, 0x75b3c6c6, 0x6fe08f8f
.long 0x691d7474, 0x2ef5dbdb, 0x6ae18b8b, 0x962eb8b8, 0x8a800a0a, 0xfe679999, 0xe2c92b2b, 0xe0618181, 0xc0c30303, 0x8d29a4a4, 0xaf238c8c, 0x07a9aeae, 0x390d3434, 0x1f524d4d, 0x764f3939, 0xd36ebdbd
.long 0x81d65757, 0xb7d86f6f, 0xeb37dcdc, 0x51441515, 0xa6dd7b7b, 0x09fef7f7, 0xb68c3a3a, 0x932fbcbc, 0x0f030c0c, 0x03fcffff, 0xc26ba9a9, 0xba73c9c9, 0xd96cb5b5, 0xdc6db1b1, 0x375a6d6d, 0x15504545
.long 0xb98f3636, 0x771b6c6c, 0x13adbebe, 0xda904a4a, 0x57b9eeee, 0xa9de7777, 0x4cbef2f2, 0x837efdfd, 0x55114444, 0xbdda6767, 0x2c5d7171, 0x45400505, 0x631f7c7c, 0x50104040, 0x325b6969, 0xb8db6363
.long 0x220a2828, 0xc5c20707, 0xf531c4c4, 0xa88a2222, 0x31a79696, 0xf9ce3737, 0x977aeded, 0x49bff6f6, 0x992db4b4, 0xa475d1d1, 0x90d34343, 0x5a124848, 0x58bae2e2, 0x71e69797, 0x64b6d2d2, 0x70b2c2c2
.long 0xad8b2626, 0xcd68a5a5, 0xcb955e5e, 0x624b2929, 0x3c0c3030, 0xce945a5a, 0xab76dddd, 0x867ff9f9, 0xf1649595, 0x5dbbe6e6, 0x35f2c7c7, 0x2d092424, 0xd1c61717, 0xd66fb9b9, 0xdec51b1b, 0x94861212
.long 0x78186060, 0x30f3c3c3, 0x897cf5f5, 0x5cefb3b3, 0xd23ae8e8, 0xacdf7373, 0x794c3535, 0xa0208080, 0x9d78e5e5, 0x56edbbbb, 0x235e7d7d, 0xc63ef8f8, 0x8bd45f5f, 0xe7c82f2f, 0xdd39e4e4, 0x68492121
##### MASKS #####
#.shuffle_mask_128: 4096(%rax)
.byte 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0
#.shuffle_mask_32: 32+4096(%rax)
.byte 3,2,1,0,7,6,5,4,11,10,9,8,15,14,13,12,3,2,1,0,7,6,5,4,11,10,9,8,15,14,13,12
# below are for AESNI
#.aes_mask: 64+4096(%rax)
.byte 0x00, 0x0d, 0x0a, 0x07, 0x04, 0x01, 0x0e, 0x0b, 0x08, 0x05, 0x02, 0x0f, 0x0c, 0x09, 0x06, 0x03
.byte 0x00, 0x0d, 0x0a, 0x07, 0x04, 0x01, 0x0e, 0x0b, 0x08, 0x05, 0x02, 0x0f, 0x0c, 0x09, 0x06, 0x03
#.aes_and_mask: 96+4096(%rax)
.byte 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f
.byte 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f
#.aes_hi_mask_0: 128+4096(%rax)
.byte 0x00, 0xa2, 0x49, 0xeb, 0x09, 0xab, 0x40, 0xe2, 0x12, 0xb0, 0x5b, 0xf9, 0x1b, 0xb9, 0x52, 0xf0
.byte 0x00, 0xa2, 0x49, 0xeb, 0x09, 0xab, 0x40, 0xe2, 0x12, 0xb0, 0x5b, 0xf9, 0x1b, 0xb9, 0x52, 0xf0
#.aes_lo_mask_0: 160+4096(%rax)
.byte 0x01, 0x07, 0x72, 0x74, 0xe4, 0xe2, 0x97, 0x91, 0x57, 0x51, 0x24, 0x22, 0xb2, 0xb4, 0xc1, 0xc7
.byte 0x01, 0x07, 0x72, 0x74, 0xe4, 0xe2, 0x97, 0x91, 0x57, 0x51, 0x24, 0x22, 0xb2, 0xb4, 0xc1, 0xc7
#.all_zero_mask: 192+4096(%rax)
.long 0,0,0,0,0,0,0,0
#.aes_hi_mask_1: 224+4096(%rax)
.byte 0x00, 0xdc, 0xaf, 0x73, 0xdd, 0x01, 0x72, 0xae, 0xbf, 0x63, 0x10, 0xcc, 0x62, 0xbe, 0xcd, 0x11
.byte 0x00, 0xdc, 0xaf, 0x73, 0xdd, 0x01, 0x72, 0xae, 0xbf, 0x63, 0x10, 0xcc, 0x62, 0xbe, 0xcd, 0x11
#.aes_lo_mask_1: 256+4096(%rax)
.byte 0x34, 0x08, 0x9d, 0xa1, 0xce, 0xf2, 0x67, 0x5b, 0x82, 0xbe, 0x2b, 0x17, 0x78, 0x44, 0xd1, 0xed
.byte 0x34, 0x08, 0x9d, 0xa1, 0xce, 0xf2, 0x67, 0x5b, 0x82, 0xbe, 0x2b, 0x17, 0x78, 0x44, 0xd1, 0xed
# left rotations
#.r08: 288+4096(%rax)
.byte 3,0,1,2,7,4,5,6,11,8,9,10,15,12,13,14,3,0,1,2,7,4,5,6,11,8,9,10,15,12,13,14
#.r16: 320+4096(%rax)
.byte 2,3,0,1,6,7,4,5,10,11,8,9,14,15,12,13,2,3,0,1,6,7,4,5,10,11,8,9,14,15,12,13
#.r24: 352+4096(%rax)
.byte 1,2,3,0,5,6,7,4,9,10,11,8,13,14,15,12,1,2,3,0,5,6,7,4,9,10,11,8,13,14,15,12
#endif
| 2302_82127028/openHiTLS-examples_1508 | crypto/sm4/src/asm/crypt_sm4_modes_macro_x86_64.s | Unix Assembly | unknown | 24,215 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SM4
#include "crypt_sm4_modes_macro_x86_64.s"
.file "crypt_sm4_modes_x86_64.S"
.text
.extern g_cpuState
.hidden g_cpuState
.set X0,%ymm0
.set X1,%ymm1
.set X2,%ymm2
.set X3,%ymm3
.set Y0,%ymm4
.set Y1,%ymm5
.set Y2,%ymm6
.set Y3,%ymm7
.set ADDR,%rax
.set IN,%rdi
.set OUT,%rsi
.set LEN,%rdx
.set BLOCKS,%rdx
.set RK,%rcx
.set IV,%r8
.set TWEAK,%r8
.set TWEAK_MASK,%r9
.set ENC,%r9d
.set HI,%r12
.set LO,%r13
.set HI_TMP,%r14
.set LO_TMP,%r15
.set T0,%r10d
.set T0BL,%r10b
.set T1,%r11d
.set T0_64,%r10
.set T1_64,%r11
.set W0,%r12d
.set W1,%r13d
.set W2,%r14d
.set W3,%r15d
.macro LOAD_DATA
vmovdqu (IN),X0
vmovdqu 32(IN),X1
vmovdqu 64(IN),X2
vmovdqu 96(IN),X3
vmovdqu 128(IN),Y0
vmovdqu 128+32(IN),Y1
vmovdqu 128+64(IN),Y2
vmovdqu 128+96(IN),Y3
.endm
.macro XOR_DATA
vpxor (IN),X0,X0
vpxor 32(IN),X1,X1
vpxor 64(IN),X2,X2
vpxor 96(IN),X3,X3
vpxor 128(IN),Y0,Y0
vpxor 128+32(IN),Y1,Y1
vpxor 128+64(IN),Y2,Y2
vpxor 128+96(IN),Y3,Y3
.endm
.macro CHECK_GFNI re tmp
xorl \re, \re
movl $0x100, \tmp
andl g_cpuState+24(%rip), \tmp # get gfni flag
orl \tmp, \re
movl $0x20, \tmp
andl g_cpuState+20(%rip), \tmp # check avx2 flag
orl \tmp, \re
cmpl $0x120, \re # code7Out[EAX] & (1<<5)) | code7Out[ECX_OUT_IDX] & (1<<8))
.endm
.macro SM4_CRYPT_GFNI_BLOCK16
# load affine matric
vpbroadcastq .PreAffinT(%rip),PreAffineTRegBLOCK16
vpbroadcastq .PostAffinT(%rip),PostAffineTRegBLOCK16
vmovdqa 32+4096(ADDR),TMP0
# vmovdqa 64+4096(ADDR),AES_MASK
# vmovdqa 96+4096(ADDR),AES_AND_MASK
vpshufb TMP0,X0,X0
vpshufb TMP0,X1,X1
vpshufb TMP0,X2,X2
vpshufb TMP0,X3,X3
vpshufb TMP0,Y0,Y0
vpshufb TMP0,Y1,Y1
vpshufb TMP0,Y2,Y2
vpshufb TMP0,Y3,Y3
# Pack SIMD Vectors
MATRIX_TRANSPOSE X0 X1 X2 X3
MATRIX_TRANSPOSE Y0 Y1 Y2 Y3
# AVX2 Rounds
SM4_AVX2_GFNI_2_ROUNDS
# Restore SIMD Vectors
MATRIX_TRANSPOSE X0 X1 X2 X3
MATRIX_TRANSPOSE Y0 Y1 Y2 Y3
# Reverse Transformation
vmovdqa 4096(ADDR),TMP0
vpshufb TMP0,X0,X0
vpshufb TMP0,X1,X1
vpshufb TMP0,X2,X2
vpshufb TMP0,X3,X3
vpshufb TMP0,Y0,Y0
vpshufb TMP0,Y1,Y1
vpshufb TMP0,Y2,Y2
vpshufb TMP0,Y3,Y3
.endm
.macro SM4_CRYPT_AESNI_BLOCK16
vmovdqa 32+4096(ADDR),TMP0
vmovdqa 64+4096(ADDR),AES_MASK
vmovdqa 96+4096(ADDR),AES_AND_MASK
vpshufb TMP0,X0,X0
vpshufb TMP0,X1,X1
vpshufb TMP0,X2,X2
vpshufb TMP0,X3,X3
vpshufb TMP0,Y0,Y0
vpshufb TMP0,Y1,Y1
vpshufb TMP0,Y2,Y2
vpshufb TMP0,Y3,Y3
# Pack SIMD Vectors
MATRIX_TRANSPOSE X0 X1 X2 X3
MATRIX_TRANSPOSE Y0 Y1 Y2 Y3
# AVX2 Rounds
SM4_AVX2_AES_2_ROUNDS
# Restore SIMD Vectors
MATRIX_TRANSPOSE X0 X1 X2 X3
MATRIX_TRANSPOSE Y0 Y1 Y2 Y3
# Reverse Transformation
vmovdqa 4096(ADDR),TMP0
vpshufb TMP0,X0,X0
vpshufb TMP0,X1,X1
vpshufb TMP0,X2,X2
vpshufb TMP0,X3,X3
vpshufb TMP0,Y0,Y0
vpshufb TMP0,Y1,Y1
vpshufb TMP0,Y2,Y2
vpshufb TMP0,Y3,Y3
.endm
.macro STORE_RESULTS
vmovdqu X0,0(OUT)
vmovdqu X1,32(OUT)
vmovdqu X2,64(OUT)
vmovdqu X3,96(OUT)
vmovdqu Y0,128(OUT)
vmovdqu Y1,128+32(OUT)
vmovdqu Y2,128+64(OUT)
vmovdqu Y3,128+96(OUT)
.endm
.macro CLEAR_CONTEXT
xorl T0,T0
xorl T1,T1
xorl W0,W0
xorl W1,W1
xorl W2,W2
xorl W3,W3
.endm
##### SM4-CBC #####
# void SM4_CBC_Encrypt(const unsigned char *in, unsigned char *out, size_t len, const SM4_KEY *key, unsigned char *iv, const int enc)
# in %rdi
# out %rsi
# len %rdx
# rk %rcx
# iv %r8
# enc %r9d
.globl SM4_CBC_Encrypt
.type SM4_CBC_Encrypt, @function
.align 64
SM4_CBC_Encrypt:
# Store Registers
subq $72,%rsp
movq %rbx,(%rsp)
movq %rbp,8(%rsp)
movq %r9,16(%rsp)
movq %r10,24(%rsp)
movq %r11,32(%rsp)
movq %r12,40(%rsp)
movq %r13,48(%rsp)
movq %r14,56(%rsp)
movq %r15,64(%rsp)
# Get Address
leaq SBOX4X_MASK(%rip),ADDR
testl ENC,ENC
jz .Lcbc_decrypt
.Lcbc_encrypt:
cmpq $16,LEN
jl .Lcbc_ret
# Load Data
movl (IN),W0
movl 4(IN),W1
movl 8(IN),W2
movl 12(IN),W3
# XOR IV
xorl (IV),W0
xorl 4(IV),W1
xorl 8(IV),W2
xorl 12(IV),W3
bswap W0
bswap W1
bswap W2
bswap W3
# Serial Rounds
SM4_SERIAL_ROUNDS
# Store Results
bswap W0
bswap W1
bswap W2
bswap W3
movl W3,(OUT)
movl W2,4(OUT)
movl W1,8(OUT)
movl W0,12(OUT)
movl W3,(IV)
movl W2,4(IV)
movl W1,8(IV)
movl W0,12(IV)
leaq 16(IN),IN
leaq 16(OUT),OUT
subq $16,LEN
jmp .Lcbc_encrypt
.Lcbc_decrypt:
cmpq $256,LEN
jl .Lcbc_dec
.Lcbc_dec16:
LOAD_DATA
CHECK_GFNI %r9d %r10d
jl .Lcbc_dec_aesni
.Lcbc_dec_gfni:
SM4_CRYPT_GFNI_BLOCK16
jmp .Lafter_cbc_dec
.Lcbc_dec_aesni:
SM4_CRYPT_AESNI_BLOCK16
.Lafter_cbc_dec:
vmovdqu (IV),TMP0x
vmovdqu (IN),TMP1x
vinserti128 $1,TMP1x,TMP0,TMP0
vmovdqu 240(IN),TMP2x
vmovdqu TMP2x,(IV)
vpxor TMP0,X0,X0
vpxor 16(IN),X1,X1
vpxor 32+16(IN),X2,X2
vpxor 64+16(IN),X3,X3
vpxor 96+16(IN),Y0,Y0
vpxor 128+16(IN),Y1,Y1
vpxor 160+16(IN),Y2,Y2
vpxor 192+16(IN),Y3,Y3
STORE_RESULTS
leaq 256(IN),IN
leaq 256(OUT),OUT
subq $256,LEN
cmpq $256,LEN
jl .Lcbc_dec16_ret
jmp .Lcbc_dec16
.Lcbc_dec16_ret:
vzeroall
.Lcbc_dec:
cmpq $16,LEN
jl .Lcbc_ret
# Load Data
movl (IN),W0
movl 4(IN),W1
movl 8(IN),W2
movl 12(IN),W3
bswap W0
bswap W1
bswap W2
bswap W3
# Serial Rounds
SM4_SERIAL_ROUNDS
# Store Result
bswap W0
bswap W1
bswap W2
bswap W3
xorl (IV),W3
xorl 4(IV),W2
xorl 8(IV),W1
xorl 12(IV),W0
movq (IN),%r10
movq %r10,(IV)
movq 8(IN),%r10
movq %r10,8(IV)
movl W3,(OUT)
movl W2,4(OUT)
movl W1,8(OUT)
movl W0,12(OUT)
leaq 16(IN),IN
leaq 16(OUT),OUT
subq $16,LEN
jmp .Lcbc_dec
.Lcbc_ret:
CLEAR_CONTEXT
# Restore Registers
movq (%rsp),%rbx
movq 8(%rsp),%rbp
movq 16(%rsp),%rax
movq 24(%rsp),%r10
movq 32(%rsp),%r11
movq 40(%rsp),%r12
movq 48(%rsp),%r13
movq 56(%rsp),%r14
movq 64(%rsp),%r15
addq $72,%rsp
ret
.size SM4_CBC_Encrypt, .-SM4_CBC_Encrypt
##### SM4-ECB #####
# void SM4_ECB_Encrypt(const unsigned char *in, unsigned char *out, size_t len, const SM4_KEY *key)
# in %rdi
# out %rsi
# len %rdx
# key %rcx
.globl SM4_ECB_Encrypt
.type SM4_ECB_Encrypt, @function
.align 64
SM4_ECB_Encrypt:
# Store Registers
subq $32,%rsp
movq %r12,(%rsp)
movq %r13,8(%rsp)
movq %r14,16(%rsp)
movq %r15,24(%rsp)
# Get Address
leaq SBOX4X_MASK(%rip),ADDR
.Lecb_encrypt:
cmpq $256,LEN
jl .Lecb_enc
.Lecb_enc16:
LOAD_DATA
CHECK_GFNI %r12d %r13d
jl .Lecb_enc_aesni
.Lecb_enc_gfni:
SM4_CRYPT_GFNI_BLOCK16
jmp .Lafter_ecb_enc
.Lecb_enc_aesni:
SM4_CRYPT_AESNI_BLOCK16
.Lafter_ecb_enc:
STORE_RESULTS
leaq 256(IN),IN
leaq 256(OUT),OUT
subq $256,LEN
cmpq $256,LEN
jl .Lecb_enc16_ret
jmp .Lecb_enc16
.Lecb_enc16_ret:
vzeroall
.Lecb_enc:
cmpq $16,LEN
jl .Lecb_ret
# Load Data
movl (IN),W0
movl 4(IN),W1
movl 8(IN),W2
movl 12(IN),W3
bswap W0
bswap W1
bswap W2
bswap W3
# Serial Rounds
SM4_SERIAL_ROUNDS
# Store Result
bswap W0
bswap W1
bswap W2
bswap W3
movl W3,(OUT)
movl W2,4(OUT)
movl W1,8(OUT)
movl W0,12(OUT)
leaq 16(IN),IN
leaq 16(OUT),OUT
subq $16,LEN
jmp .Lecb_enc
.Lecb_ret:
CLEAR_CONTEXT
# Restore Registers
movq (%rsp),%r12
movq 8(%rsp),%r13
movq 16(%rsp),%r14
movq 24(%rsp),%r15
addq $32,%rsp
ret
.size SM4_ECB_Encrypt, .-SM4_ECB_Encrypt
##### SM4-CFB ENC #####
# void SM4_CFB128_Encrypt(const unsigned char *in, unsigned char *out, size_t len, const SM4_KEY *key, unsigned char *iv, int *num)
# in %rdi
# out %rsi
# len %rdx
# rk %rcx
# iv %r8
# num %r9d
.globl SM4_CFB128_Encrypt
.type SM4_CFB128_Encrypt, @function
.align 64
SM4_CFB128_Encrypt:
# Store Registers
subq $72,%rsp
movq %rbx,(%rsp)
movq %rbp,8(%rsp)
movq %r9,16(%rsp)
movq %r10,24(%rsp)
movq %r11,32(%rsp)
movq %r12,40(%rsp)
movq %r13,48(%rsp)
movq %r14,56(%rsp)
movq %r15,64(%rsp)
# Load Num
movl (%r9),%r9d
cmpl $0,%r9d
je .Lcfb128_enc_update
.Lcfb128_enc_init:
movb 0(IV,%r9,1),%al
xorb (IN),%al
movb %al,(OUT)
movb %al,0(IV,%r9,1)
leaq 1(IN),IN
leaq 1(OUT),OUT
incl %r9d
decq LEN
cmpl $16,%r9d
je .Lcfb128_enc_update
cmpq $0,LEN
je .Lcfb128_enc_ret
jmp .Lcfb128_enc_init
.Lcfb128_enc_update:
movl $0,%r9d
# Get Address
leaq SBOX4X_MASK(%rip),ADDR
.Lcfb128_enc_loop:
cmpq $0,LEN
je .Lcfb128_enc_ret
movl $0,%r9d
# Load IV
movl (IV),W0
movl 4(IV),W1
movl 8(IV),W2
movl 12(IV),W3
bswap W0
bswap W1
bswap W2
bswap W3
# Serial Rounds
SM4_SERIAL_ROUNDS
# Store Results
bswap W0
bswap W1
bswap W2
bswap W3
movl W3,(IV)
movl W2,4(IV)
movl W1,8(IV)
movl W0,12(IV)
cmpq $16,LEN
jl .Lcfb128_enc_final
xorl (IN),W3
xorl 4(IN),W2
xorl 8(IN),W1
xorl 12(IN),W0
movl W3,(OUT)
movl W2,4(OUT)
movl W1,8(OUT)
movl W0,12(OUT)
movl W3,(IV)
movl W2,4(IV)
movl W1,8(IV)
movl W0,12(IV)
leaq 16(IN),IN
leaq 16(OUT),OUT
subq $16,LEN
jmp .Lcfb128_enc_loop
.Lcfb128_enc_final:
movb 0(IV,%r9,1),%al
xorb (IN),%al
movb %al,(OUT)
movb %al,0(IV,%r9,1)
leaq 1(IN),IN
leaq 1(OUT),OUT
incl %r9d
decq LEN
jnz .Lcfb128_enc_final
.Lcfb128_enc_ret:
CLEAR_CONTEXT
# Restore Registers
movq (%rsp),%rbx
movq 8(%rsp),%rbp
movq 16(%rsp),%rax
movq 24(%rsp),%r10
movq 32(%rsp),%r11
movq 40(%rsp),%r12
movq 48(%rsp),%r13
movq 56(%rsp),%r14
movq 64(%rsp),%r15
addq $72,%rsp
# Store Num
movl %r9d,(%rax)
ret
.size SM4_CFB128_Encrypt, .-SM4_CFB128_Encrypt
##### SM4-CFB DEC #####
# void SM4_CFB128_Decrypt(const unsigned char *in, unsigned char *out, size_t len, const SM4_KEY *key, unsigned char *iv, int *num)
# in %rdi
# out %rsi
# len %rdx
# rk %rcx
# iv %r8
# num %r9d
.globl SM4_CFB128_Decrypt
.type SM4_CFB128_Decrypt, @function
.align 64
SM4_CFB128_Decrypt:
# Store Registers
subq $72,%rsp
movq %rbx,(%rsp)
movq %rbp,8(%rsp)
movq %r9,16(%rsp)
movq %r10,24(%rsp)
movq %r11,32(%rsp)
movq %r12,40(%rsp)
movq %r13,48(%rsp)
movq %r14,56(%rsp)
movq %r15,64(%rsp)
# Load Num
movl (%r9),%r9d
cmpl $0,%r9d
je .Lcfb128_dec_update
.Lcfb128_dec_init:
movb 0(IV,%r9,1),%al
movb (IN),%bl
xorb %bl,%al
movb %al,(OUT)
movb %bl,0(IV,%r9,1)
leaq 1(IN),IN
leaq 1(OUT),OUT
incl %r9d
decq LEN
cmpl $16,%r9d
je .Lcfb128_dec_update
cmpq $0,LEN
je .Lcfb128_dec_ret
jmp .Lcfb128_dec_init
.Lcfb128_dec_update:
# Get Address
leaq SBOX4X_MASK(%rip),ADDR
movl $0,%r9d
cmpq $256,LEN
jl .Lcfb128_dec
.Lcfb128_dec16:
vmovdqu (IV),TMP0x
vmovdqu (IN),TMP1x
vinserti128 $1,TMP1x,TMP0,TMP0
vmovdqu 240(IN),TMP2x
vmovdqu TMP2x,(IV)
vmovdqu TMP0,X0
vmovdqu 16(IN),X1
vmovdqu 32+16(IN),X2
vmovdqu 64+16(IN),X3
vmovdqu 96+16(IN),Y0
vmovdqu 128+16(IN),Y1
vmovdqu 160+16(IN),Y2
vmovdqu 192+16(IN),Y3
CHECK_GFNI %r10d %r11d
jl .Lcfb128_dec_aesni
.Lcfb128_dec_gfni:
SM4_CRYPT_GFNI_BLOCK16
jmp .Lafter_cfb128_dec
.Lcfb128_dec_aesni:
SM4_CRYPT_AESNI_BLOCK16
.Lafter_cfb128_dec:
XOR_DATA
STORE_RESULTS
leaq 256(IN),IN
leaq 256(OUT),OUT
subq $256,LEN
cmpq $256,LEN
jl .Lcfb128_dec16_ret
jmp .Lcfb128_dec16
.Lcfb128_dec16_ret:
vzeroall
.Lcfb128_dec:
cmpq $0,LEN
je .Lcfb128_dec_ret
.Lcfb128_dec1:
# Load IV
movl (IV),W0
movl 4(IV),W1
movl 8(IV),W2
movl 12(IV),W3
bswap W0
bswap W1
bswap W2
bswap W3
# Serial Rounds
SM4_SERIAL_ROUNDS
# Store Results
bswap W0
bswap W1
bswap W2
bswap W3
movl W3,(IV)
movl W2,4(IV)
movl W1,8(IV)
movl W0,12(IV)
cmpq $16,LEN
jl .Lcfb128_dec_final
movq (IN),%rbx
movq %rbx,(IV)
movq 8(IN),%rbx
movq %rbx,8(IV)
xorq %rbx,%rbx
xorl (IN),W3
xorl 4(IN),W2
xorl 8(IN),W1
xorl 12(IN),W0
movl W3,(OUT)
movl W2,4(OUT)
movl W1,8(OUT)
movl W0,12(OUT)
leaq 16(IN),IN
leaq 16(OUT),OUT
subq $16,LEN
cmpq $0,LEN
je .Lcfb128_dec_ret
jmp .Lcfb128_dec1
.Lcfb128_dec_final:
movb 0(IV,%r9,1),%al
movb (IN),%bl
xorb %bl,%al
movb %al,(OUT)
movb %bl,0(IV,%r9,1)
leaq 1(IN),IN
leaq 1(OUT),OUT
incl %r9d
decq LEN
jnz .Lcfb128_dec_final
.Lcfb128_dec_ret:
CLEAR_CONTEXT
# Restore Registers
movq (%rsp),%rbx
movq 8(%rsp),%rbp
movq 16(%rsp),%rax
movq 24(%rsp),%r10
movq 32(%rsp),%r11
movq 40(%rsp),%r12
movq 48(%rsp),%r13
movq 56(%rsp),%r14
movq 64(%rsp),%r15
addq $72,%rsp
# Store Num
movl %r9d,(%rax)
ret
.size SM4_CFB128_Decrypt, .-SM4_CFB128_Decrypt
##### SM4-OFB #####
# void SM4_OFB_Encrypt(const unsigned char *in, unsigned char *out, size_t len, const SM4_KEY *key, unsigned char *iv, int *num)
# in %rdi
# out %rsi
# len %rdx
# rk %rcx
# iv %r8
# num %r9d
.globl SM4_OFB_Encrypt
.type SM4_OFB_Encrypt, @function
.align 64
SM4_OFB_Encrypt:
# Store Registers
subq $72,%rsp
movq %rbx,(%rsp)
movq %rbp,8(%rsp)
movq %r9,16(%rsp)
movq %r10,24(%rsp)
movq %r11,32(%rsp)
movq %r12,40(%rsp)
movq %r13,48(%rsp)
movq %r14,56(%rsp)
movq %r15,64(%rsp)
# Load Num
movl (%r9),%r9d
cmpl $0,%r9d
jz .Lofb128_enc_update
.Lofb128_enc_init:
movb 0(IV,%r9,1),%al
xorb (IN),%al
movb %al,(OUT)
leaq 1(IN),IN
leaq 1(OUT),OUT
incl %r9d
decq LEN
cmpl $16,%r9d
je .Lofb128_enc_update
cmpq $0,LEN
je .Lofb128_enc_ret
jmp .Lofb128_enc_init
.Lofb128_enc_update:
movl $0,%r9d
# Get Address
leaq SBOX4X_MASK(%rip),ADDR
.Lofb128_enc_loop:
cmpq $0,LEN
je .Lofb128_enc_ret
# Load IV
movl (IV),W0
movl 4(IV),W1
movl 8(IV),W2
movl 12(IV),W3
bswap W0
bswap W1
bswap W2
bswap W3
# Serial Rounds
SM4_SERIAL_ROUNDS
# Store Results
bswap W0
bswap W1
bswap W2
bswap W3
movl W3,(IV)
movl W2,4(IV)
movl W1,8(IV)
movl W0,12(IV)
cmpq $16,LEN
jl .Lofb128_enc_final
xorl (IN),W3
xorl 4(IN),W2
xorl 8(IN),W1
xorl 12(IN),W0
movl W3,(OUT)
movl W2,4(OUT)
movl W1,8(OUT)
movl W0,12(OUT)
leaq 16(IN),IN
leaq 16(OUT),OUT
subq $16,LEN
jmp .Lofb128_enc_loop
.Lofb128_enc_final:
movb 0(IV,%r9,1),%al
xorb (IN),%al
movb %al,(OUT)
leaq 1(IN),IN
leaq 1(OUT),OUT
incl %r9d
decq LEN
jnz .Lofb128_enc_final
.Lofb128_enc_ret:
CLEAR_CONTEXT
# Restore Registers
movq (%rsp),%rbx
movq 8(%rsp),%rbp
movq 16(%rsp),%rax
movq 24(%rsp),%r10
movq 32(%rsp),%r11
movq 40(%rsp),%r12
movq 48(%rsp),%r13
movq 56(%rsp),%r14
movq 64(%rsp),%r15
addq $72,%rsp
# Store Num
movl %r9d,(%rax)
ret
.size SM4_OFB_Encrypt, .-SM4_OFB_Encrypt
##### SM4-CTR32 #####
# NOTE: the IV/counter CTR mode is big-endian.
.align 64
.Lmovbe12:
.byte 0,1,2,3,4,5,6,7,8,9,10,11,15,14,13,12,0,1,2,3,4,5,6,7,8,9,10,11,15,14,13,12
.Lone:
.long 0,0,0,1
.macro INCREMENT_COUNTER
movbe 12(IV),%ebx
incl %ebx
movbe %ebx,12(IV)
.endm
.macro LOAD_ECOUNT_BUF SINK
vpaddd TMP1x,TMP2x,TMP3x
vpaddd TMP1x,TMP3x,TMP4x
vinserti128 $1,TMP3x,TMP2,TMP2
vpshufb TMP0,TMP2,TMP2
vmovdqa TMP2,\SINK
vmovdqa TMP4x,TMP2x
.endm
.macro LOAD_ECOUNT_BUF_ALL
vmovdqa .Lmovbe12(%rip),TMP0
vmovdqa .Lone(%rip),TMP1x
vmovdqu (IV),TMP2x
vpshufb TMP0x,TMP2x,TMP2x
LOAD_ECOUNT_BUF X0
LOAD_ECOUNT_BUF X1
LOAD_ECOUNT_BUF X2
LOAD_ECOUNT_BUF X3
LOAD_ECOUNT_BUF Y0
LOAD_ECOUNT_BUF Y1
LOAD_ECOUNT_BUF Y2
LOAD_ECOUNT_BUF Y3
vpshufb TMP0x,TMP2x,TMP2x
vmovdqu TMP2x,(IV)
.endm
# void SM4_CTR_EncryptBlocks(const unsigned char *in, unsigned char *out, size_t blocks, const SM4_KEY *key, const unsigned char *iv)
# in %rdi
# out %rsi
# blocks %rdx
# rk %rcx
# iv %r8
.globl SM4_CTR_EncryptBlocks
.type SM4_CTR_EncryptBlocks, @function
.align 64
SM4_CTR_EncryptBlocks:
# Get Address
leaq SBOX4X_MASK(%rip),ADDR
# Store Registers
subq $88,%rsp
movq %rbx,(%rsp)
movq %rbp,8(%rsp)
movq %r8,16(%rsp)
movq %r9,24(%rsp)
movq %r10,32(%rsp)
movq %r11,40(%rsp)
movq %r12,48(%rsp)
movq %r13,56(%rsp)
movq %r14,64(%rsp)
movq %r15,72(%rsp)
movq %rdx,80(%rsp)
cmpq $16,BLOCKS
jl .Lctr32_enc
.Lctr32_enc16:
LOAD_ECOUNT_BUF_ALL
CHECK_GFNI %r9d %r10d
jl .Lctr32_enc_aesni
.Lctr32_enc_gfni:
SM4_CRYPT_GFNI_BLOCK16
jmp .Lafter_ctr32_enc
.Lctr32_enc_aesni:
SM4_CRYPT_AESNI_BLOCK16
.Lafter_ctr32_enc:
XOR_DATA
STORE_RESULTS
leaq 256(IN),IN
leaq 256(OUT),OUT
subq $16,BLOCKS
cmpq $16,BLOCKS
jl .Lctr32_enc16_ret
jmp .Lctr32_enc16
.Lctr32_enc16_ret:
vzeroall
.Lctr32_enc:
cmpq $0,BLOCKS
je .Lctr32_ret
# Load IV
movl (IV),W0
movl 4(IV),W1
movl 8(IV),W2
movl 12(IV),W3
bswap W0
bswap W1
bswap W2
bswap W3
# Serial Rounds
SM4_SERIAL_ROUNDS
# Store Results
bswap W0
bswap W1
bswap W2
bswap W3
xorl (IN),W3
xorl 4(IN),W2
xorl 8(IN),W1
xorl 12(IN),W0
movl W3,(OUT)
movl W2,4(OUT)
movl W1,8(OUT)
movl W0,12(OUT)
leaq 16(IN),IN
leaq 16(OUT),OUT
decq BLOCKS
INCREMENT_COUNTER
jmp .Lctr32_enc
.Lctr32_ret:
CLEAR_CONTEXT
# Restore Registers
movq (%rsp),%rbx
movq 8(%rsp),%rbp
movq 16(%rsp),%r8
movq 24(%rsp),%r9
movq 32(%rsp),%r10
movq 40(%rsp),%r11
movq 48(%rsp),%r12
movq 56(%rsp),%r13
movq 64(%rsp),%r14
movq 72(%rsp),%r15
movq 80(%rsp),%rdx
addq $88,%rsp
ret
.size SM4_CTR_EncryptBlocks, .-SM4_CTR_EncryptBlocks
##### SM4-XTS #####
.align 16
.Lxts_tweak_mask:
.long 0,0xe1000000
.macro GALOIS_FIELD_MUL Idx
xorq LO_TMP,LO_TMP
testq $1,LO
cmovnzq TWEAK_MASK,LO_TMP
shrd $1,HI,LO
shrq $1,HI
xorq LO_TMP,HI
movbe HI,\Idx(TWEAK)
movbe LO,\Idx+8(TWEAK)
.endm
.macro GALOIS_FIELD_MUL_16_INNER
GALOIS_FIELD_MUL 16
# T2:T1->T2
GALOIS_FIELD_MUL 32
# T3:T2->T3
GALOIS_FIELD_MUL 48
# T4:T3->T4
GALOIS_FIELD_MUL 64
# T5:T4->T5
GALOIS_FIELD_MUL 80
# T6:T5->T6
GALOIS_FIELD_MUL 96
# T7:T6->T7
GALOIS_FIELD_MUL 112
# T8:T7->T8
GALOIS_FIELD_MUL 128
# T9:T8->T9
GALOIS_FIELD_MUL 144
# T10:T9->T10
GALOIS_FIELD_MUL 160
# T11:T10->T11
GALOIS_FIELD_MUL 176
# T12:T11->T12
GALOIS_FIELD_MUL 192
# T13:T12->T13
GALOIS_FIELD_MUL 208
# T14:T13->T14
GALOIS_FIELD_MUL 224
# T15:T14->T15
GALOIS_FIELD_MUL 240
.endm
.macro XOR_TWEAK
vpxor (TWEAK),X0,X0
vpxor 32(TWEAK),X1,X1
vpxor 64(TWEAK),X2,X2
vpxor 96(TWEAK),X3,X3
vpxor 128(TWEAK),Y0,Y0
vpxor 128+32(TWEAK),Y1,Y1
vpxor 128+64(TWEAK),Y2,Y2
vpxor 128+96(TWEAK),Y3,Y3
.endm
.macro SM4_XTS_16_EN_INNER
LOAD_DATA
XOR_TWEAK
CHECK_GFNI %r15d %r14d
jl .Lxts_enc_aesni
.Lxts_enc_gfni:
SM4_CRYPT_GFNI_BLOCK16
jmp .Lafter_xts_enc
.Lxts_enc_aesni:
SM4_CRYPT_AESNI_BLOCK16
.Lafter_xts_enc:
XOR_TWEAK
STORE_RESULTS
.endm
# void SM4_XTS_Encrypt_Blocks(const unsigned char *in, unsigned char *out, size_t len, const SM4_KEY *key, unsigned char *t)
# in %rdi
# out %rsi
# len %rdx
# key %rcx
# t %r8
.globl SM4_XTS_Encrypt_Blocks
.type SM4_XTS_Encrypt_Blocks, @function
.align 64
SM4_XTS_Encrypt_Blocks:
cmpq $256,LEN
jl .Lxts_ret
# Store Registers
subq $56,%rsp
movq %r9,(%rsp)
movq %r10,8(%rsp)
movq %r11,16(%rsp)
movq %r12,24(%rsp)
movq %r13,32(%rsp)
movq %r14,40(%rsp)
movq %r15,48(%rsp)
# Get Address
leaq SBOX4X_MASK(%rip),ADDR
# Load tweak mask
movq .Lxts_tweak_mask(%rip),TWEAK_MASK
# T0: Initial
movbe (TWEAK),HI
movbe 8(TWEAK),LO
.Lxts_update:
GALOIS_FIELD_MUL_16_INNER
SM4_XTS_16_EN_INNER
leaq 256(IN),IN
leaq 256(OUT),OUT
subq $256,LEN
cmpq $256,LEN
jl .Lxts_final
# T15: Initial
movbe 240(TWEAK),HI
movbe 248(TWEAK),LO
# T0:T15->T0
GALOIS_FIELD_MUL 0
jmp .Lxts_update
.Lxts_final:
# Clear Context
vzeroall
# Restore Registers
movq (%rsp),%r9
movq 8(%rsp),%r10
movq 16(%rsp),%r11
movq 24(%rsp),%r12
movq 32(%rsp),%r13
movq 40(%rsp),%r14
movq 48(%rsp),%r15
addq $56,%rsp
.Lxts_ret:
ret
.size SM4_XTS_Encrypt_Blocks, .-SM4_XTS_Encrypt_Blocks
#endif
| 2302_82127028/openHiTLS-examples_1508 | crypto/sm4/src/asm/crypt_sm4_modes_x86_64.S | Unix Assembly | unknown | 19,839 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SM4
#include "crypt_sm4_modes_macro_x86_64.s"
.file "crypt_sm4_x86_64.S"
.text
.set W0, %r8d
.set W1, %r9d
.set W2, %r10d
.set W3, %r11d
.set T0, %eax
.set T0BL, %al
.set T1, %ecx
.set T0_64, %rax
.set T1_64, %rcx
.set RK, %rdx
.set ADDR, %rdi
.set RoundKey, %rsi
.set CK, %rdx
.macro SETKEY_ROUND RKey A0 A1 A2 A3 CK_ADDR No_CK No_RK
# x4 = x1 ^ x2 ^ x3 ^ *(CK + i);
# x4 = S32(x4);
# x4 = x0 ^ L_Key32(x4);
# *(rk + i) = x4;
# x4 = x1 ^ x2 ^ x3 ^ *(CK + i);
movl \No_CK(\CK_ADDR), T0
xorl \A1, T0
xorl \A2, T0
xorl \A3, T0
# x0 = x0 ^ (SBOX_KEY_0[x4 & 0xff]) ^ (SBOX_KEY_1[(x4 >> 8) & 0xff]) ^ (SBOX_KEY_2[(x4 >> 16) & 0xff]) ^ (SBOX_KEY_3[(x4 >> 24) & 0xff]);
movzbl T0BL, T1
xorl (ADDR,T1_64,4), \A0
shrl $8, T0
movzbl T0BL, T1
xorl 1024(ADDR,T1_64,4), \A0
shrl $8, T0
movzbl T0BL, T1
xorl 2048(ADDR,T1_64,4), \A0
shrl $8, T0
xorl 3072(ADDR,T0_64,4), \A0
# enc round *(rk + i) = x4;
# dec round *(rk + 31 - i) = x4;
movl \A0, \No_RK(\RKey)
.endm
##### SM4 Encryption #####
# void SM4_Encrypt(const unsigned char *in, unsigned char *out, const SM4_KEY *key)
# %rdi in plain ptr 16 bytes
# %rsi out cipher ptr 16 bytes
# %rdx key round key ptr 128 bytes
.globl SM4_Encrypt
.type SM4_Encrypt, @function
.align 64
SM4_Encrypt:
##### Load Data #####
movl (%rdi), W0
movl 4(%rdi), W1
movl 8(%rdi), W2
movl 12(%rdi), W3
bswap W0
bswap W1
bswap W2
bswap W3
##### Load SBOX ADDRESS #####
leaq SBOX4X_MASK(%rip), ADDR
##### Serial Rounds #####
SM4_SERIAL_ROUNDS
##### Store Results #####
bswap W0
bswap W1
bswap W2
bswap W3
movl W3, (%rsi)
movl W2, 4(%rsi)
movl W1, 8(%rsi)
movl W0, 12(%rsi)
##### Clear Context #####
xorl W0, W0
xorl W1, W1
xorl W2, W2
xorl W3, W3
xorl T0, T0
xorl T1, T1
ret
.size SM4_Encrypt, .-SM4_Encrypt
##### SM4 SET ROUND KEY #####
# void SM4_SetEncKey(const unsigned char *userKey, SM4_KEY *key)
# %rdi userKey: user key ptr 16 bytes
# %rsi key: round key ptr 128 bytes
.globl SM4_SetEncKey
.type SM4_SetEncKey, @function
.align 64
SM4_SetEncKey:
##### Load MK #####
movl (%rdi), W0
movl 4(%rdi), W1
movl 8(%rdi), W2
movl 12(%rdi), W3
bswap W0
bswap W1
bswap W2
bswap W3
##### Load SBOX ADDRESS #####
leaq SBOX_KEY_X4(%rip), ADDR
leaq CK_NUM(%rip), CK
xorq T0_64, T0_64
xorq T1_64, T1_64
##### XOR FK #####
xorl $0xa3b1bac6, W0
xorl $0x56aa3350, W1
xorl $0x677d9197, W2
xorl $0xb27022dc, W3
##### ROUNDS #####
SETKEY_ROUND RoundKey W0 W1 W2 W3 CK 0 0
SETKEY_ROUND RoundKey W1 W2 W3 W0 CK 4 4
SETKEY_ROUND RoundKey W2 W3 W0 W1 CK 8 8
SETKEY_ROUND RoundKey W3 W0 W1 W2 CK 12 12
SETKEY_ROUND RoundKey W0 W1 W2 W3 CK 16 16
SETKEY_ROUND RoundKey W1 W2 W3 W0 CK 20 20
SETKEY_ROUND RoundKey W2 W3 W0 W1 CK 24 24
SETKEY_ROUND RoundKey W3 W0 W1 W2 CK 28 28
SETKEY_ROUND RoundKey W0 W1 W2 W3 CK 32 32
SETKEY_ROUND RoundKey W1 W2 W3 W0 CK 36 36
SETKEY_ROUND RoundKey W2 W3 W0 W1 CK 40 40
SETKEY_ROUND RoundKey W3 W0 W1 W2 CK 44 44
SETKEY_ROUND RoundKey W0 W1 W2 W3 CK 48 48
SETKEY_ROUND RoundKey W1 W2 W3 W0 CK 52 52
SETKEY_ROUND RoundKey W2 W3 W0 W1 CK 56 56
SETKEY_ROUND RoundKey W3 W0 W1 W2 CK 60 60
SETKEY_ROUND RoundKey W0 W1 W2 W3 CK 64 64
SETKEY_ROUND RoundKey W1 W2 W3 W0 CK 68 68
SETKEY_ROUND RoundKey W2 W3 W0 W1 CK 72 72
SETKEY_ROUND RoundKey W3 W0 W1 W2 CK 76 76
SETKEY_ROUND RoundKey W0 W1 W2 W3 CK 80 80
SETKEY_ROUND RoundKey W1 W2 W3 W0 CK 84 84
SETKEY_ROUND RoundKey W2 W3 W0 W1 CK 88 88
SETKEY_ROUND RoundKey W3 W0 W1 W2 CK 92 92
SETKEY_ROUND RoundKey W0 W1 W2 W3 CK 96 96
SETKEY_ROUND RoundKey W1 W2 W3 W0 CK 100 100
SETKEY_ROUND RoundKey W2 W3 W0 W1 CK 104 104
SETKEY_ROUND RoundKey W3 W0 W1 W2 CK 108 108
SETKEY_ROUND RoundKey W0 W1 W2 W3 CK 112 112
SETKEY_ROUND RoundKey W1 W2 W3 W0 CK 116 116
SETKEY_ROUND RoundKey W2 W3 W0 W1 CK 120 120
SETKEY_ROUND RoundKey W3 W0 W1 W2 CK 124 124
##### Clear Context #####
xorl W0, W0
xorl W1, W1
xorl W2, W2
xorl W3, W3
xorl T0, T0
xorl T1, T1
ret
.size SM4_SetEncKey, .-SM4_SetEncKey
# void SM4_SetDecKey(const unsigned char *userKey, SM4_KEY *key)
# %rdi userKey: user key ptr 16 bytes
# %rsi key: round key ptr 128 bytes
.globl SM4_SetDecKey
.type SM4_SetDecKey, @function
.align 64
SM4_SetDecKey:
##### Load MK #####
movl (%rdi), W0
movl 4(%rdi), W1
movl 8(%rdi), W2
movl 12(%rdi), W3
bswap W0
bswap W1
bswap W2
bswap W3
##### Load SBOX ADDRESS #####
leaq SBOX_KEY_X4(%rip), ADDR
leaq CK_NUM(%rip), CK
xorq T0_64, T0_64
xorq T1_64, T1_64
##### XOR FK #####
xorl $0xa3b1bac6, W0
xorl $0x56aa3350, W1
xorl $0x677d9197, W2
xorl $0xb27022dc, W3
##### ROUNDS #####
SETKEY_ROUND RoundKey W0 W1 W2 W3 CK 0 124
SETKEY_ROUND RoundKey W1 W2 W3 W0 CK 4 120
SETKEY_ROUND RoundKey W2 W3 W0 W1 CK 8 116
SETKEY_ROUND RoundKey W3 W0 W1 W2 CK 12 112
SETKEY_ROUND RoundKey W0 W1 W2 W3 CK 16 108
SETKEY_ROUND RoundKey W1 W2 W3 W0 CK 20 104
SETKEY_ROUND RoundKey W2 W3 W0 W1 CK 24 100
SETKEY_ROUND RoundKey W3 W0 W1 W2 CK 28 96
SETKEY_ROUND RoundKey W0 W1 W2 W3 CK 32 92
SETKEY_ROUND RoundKey W1 W2 W3 W0 CK 36 88
SETKEY_ROUND RoundKey W2 W3 W0 W1 CK 40 84
SETKEY_ROUND RoundKey W3 W0 W1 W2 CK 44 80
SETKEY_ROUND RoundKey W0 W1 W2 W3 CK 48 76
SETKEY_ROUND RoundKey W1 W2 W3 W0 CK 52 72
SETKEY_ROUND RoundKey W2 W3 W0 W1 CK 56 68
SETKEY_ROUND RoundKey W3 W0 W1 W2 CK 60 64
SETKEY_ROUND RoundKey W0 W1 W2 W3 CK 64 60
SETKEY_ROUND RoundKey W1 W2 W3 W0 CK 68 56
SETKEY_ROUND RoundKey W2 W3 W0 W1 CK 72 52
SETKEY_ROUND RoundKey W3 W0 W1 W2 CK 76 48
SETKEY_ROUND RoundKey W0 W1 W2 W3 CK 80 44
SETKEY_ROUND RoundKey W1 W2 W3 W0 CK 84 40
SETKEY_ROUND RoundKey W2 W3 W0 W1 CK 88 36
SETKEY_ROUND RoundKey W3 W0 W1 W2 CK 92 32
SETKEY_ROUND RoundKey W0 W1 W2 W3 CK 96 28
SETKEY_ROUND RoundKey W1 W2 W3 W0 CK 100 24
SETKEY_ROUND RoundKey W2 W3 W0 W1 CK 104 20
SETKEY_ROUND RoundKey W3 W0 W1 W2 CK 108 16
SETKEY_ROUND RoundKey W0 W1 W2 W3 CK 112 12
SETKEY_ROUND RoundKey W1 W2 W3 W0 CK 116 8
SETKEY_ROUND RoundKey W2 W3 W0 W1 CK 120 4
SETKEY_ROUND RoundKey W3 W0 W1 W2 CK 124 0
##### Clear Context #####
xorl W0, W0
xorl W1, W1
xorl W2, W2
xorl W3, W3
xorl T0, T0
xorl T1, T1
ret
.size SM4_SetDecKey, .-SM4_SetDecKey
##### SBOX Extend Tables (1 Table, 256*4 bytes) for round key: SBOX_KEY_0, SBOX_KEY_1, SBOX_KEY_2, SBOX_KEY_3 #####
.section .rodata
.align 64
CK_NUM:
.long 0x00070e15, 0x1c232a31, 0x383f464d, 0x545b6269, 0x70777e85, 0x8c939aa1, 0xa8afb6bd, 0xc4cbd2d9, 0xe0e7eef5, 0xfc030a11, 0x181f262d, 0x343b4249, 0x50575e65, 0x6c737a81, 0x888f969d, 0xa4abb2b9
.long 0xc0c7ced5, 0xdce3eaf1, 0xf8ff060d, 0x141b2229, 0x30373e45, 0x4c535a61, 0x686f767d, 0x848b9299, 0xa0a7aeb5, 0xbcc3cad1, 0xd8dfe6ed, 0xf4fb0209, 0x10171e25, 0x2c333a41, 0x484f565d, 0x646b7279
SBOX_KEY_X4:
#SBOX_KEY_0:
.long 0x6b1ac0d6, 0x48120090, 0x749d20e9, 0x7f1fc0fe, 0x661980cc, 0x709c20e1, 0x1e87a03d, 0x5b96e0b7, 0x0b02c016, 0x5b16c0b6, 0x0a028014, 0x611840c2, 0x14050028, 0x7d9f60fb, 0x1605802c, 0x0280a005
.long 0x1585602b, 0x338ce067, 0x4d13409a, 0x3b0ec076, 0x1505402a, 0x5f17c0be, 0x02008004, 0x619860c3, 0x551540aa, 0x22088044, 0x09826013, 0x1304c026, 0x24892049, 0x4310c086, 0x0300c006, 0x4c932099
.long 0x4e13809c, 0x21084042, 0x280a0050, 0x7a1e80f4, 0x48922091, 0x779de0ef, 0x4c130098, 0x3d0f407a, 0x19866033, 0x2a0a8054, 0x0581600b, 0x21886043, 0x769da0ed, 0x6799e0cf, 0x561580ac, 0x310c4062
.long 0x721c80e4, 0x599660b3, 0x0e03801c, 0x549520a9, 0x649920c9, 0x04010008, 0x741d00e8, 0x4a92a095, 0x40100080, 0x6f9be0df, 0x4a128094, 0x7d1f40fa, 0x3a8ea075, 0x4791e08f, 0x1f87e03f, 0x5314c0a6
.long 0x2388e047, 0x0380e007, 0x5394e0a7, 0x7e1f80fc, 0x799e60f3, 0x398e6073, 0x0b82e017, 0x5d1740ba, 0x41906083, 0x2c8b2059, 0x1e07803c, 0x0c832019, 0x731cc0e6, 0x4290a085, 0x2789e04f, 0x541500a8
.long 0x340d0068, 0x358d606b, 0x40902081, 0x591640b2, 0x388e2071, 0x320c8064, 0x6d1b40da, 0x4591608b, 0x7c1f00f8, 0x759d60eb, 0x0781e00f, 0x2589604b, 0x380e0070, 0x2b0ac056, 0x4e93a09d, 0x1a86a035
.long 0x0f03c01e, 0x12048024, 0x0701c00e, 0x2f0bc05e, 0x318c6063, 0x2c0b0058, 0x689a20d1, 0x511440a2, 0x1284a025, 0x11044022, 0x3e0f807c, 0x1d87603b, 0x00802001, 0x10842021, 0x3c0f0078, 0x4390e087
.long 0x6a1a80d4, 0x0, 0x2308c046, 0x2b8ae057, 0x4f93e09f, 0x699a60d3, 0x1384e027, 0x290a4052, 0x2609804c, 0x1b06c036, 0x01004002, 0x739ce0e7, 0x501400a0, 0x621880c4, 0x641900c8, 0x4f13c09e
.long 0x751d40ea, 0x5f97e0bf, 0x4511408a, 0x691a40d2, 0x20080040, 0x6398e0c7, 0x1c070038, 0x5a96a0b5, 0x519460a3, 0x7b9ee0f7, 0x791e40f2, 0x6719c0ce, 0x7c9f20f9, 0x308c2061, 0x0a82a015, 0x509420a1
.long 0x701c00e0, 0x5715c0ae, 0x2e8ba05d, 0x521480a4, 0x4d93609b, 0x1a068034, 0x0d03401a, 0x2a8aa055, 0x5695a0ad, 0x49926093, 0x19064032, 0x18060030, 0x7a9ea0f5, 0x4611808c, 0x589620b1, 0x719c60e3
.long 0x0e83a01d, 0x7b1ec0f6, 0x711c40e2, 0x1705c02e, 0x41104082, 0x330cc066, 0x651940ca, 0x300c0060, 0x601800c0, 0x14852029, 0x11846023, 0x559560ab, 0x0681a00d, 0x298a6053, 0x2709c04e, 0x378de06f
.long 0x6a9aa0d5, 0x6d9b60db, 0x1b86e037, 0x2288a045, 0x6f1bc0de, 0x7e9fa0fd, 0x4711c08e, 0x1785e02f, 0x01806003, 0x7f9fe0ff, 0x350d406a, 0x390e4072, 0x368da06d, 0x360d806c, 0x2d8b605b, 0x288a2051
.long 0x4691a08d, 0x0d83601b, 0x5795e0af, 0x49124092, 0x5d9760bb, 0x6e9ba0dd, 0x5e1780bc, 0x3f8fe07f, 0x08822011, 0x6c9b20d9, 0x2e0b805c, 0x20882041, 0x0f83e01f, 0x08020010, 0x2d0b405a, 0x6c1b00d8
.long 0x0501400a, 0x609820c1, 0x18862031, 0x44110088, 0x5294a0a5, 0x6699a0cd, 0x3d8f607b, 0x5e97a0bd, 0x1685a02d, 0x3a0e8074, 0x681a00d0, 0x09024012, 0x5c1700b8, 0x729ca0e5, 0x5a1680b4, 0x581600b0
.long 0x44912089, 0x348d2069, 0x4b92e097, 0x2509404a, 0x0601800c, 0x4b12c096, 0x3b8ee077, 0x3f0fc07e, 0x328ca065, 0x5c9720b9, 0x789e20f1, 0x04812009, 0x6298a0c5, 0x370dc06e, 0x6318c0c6, 0x42108084
.long 0x0c030018, 0x781e00f0, 0x3e8fa07d, 0x761d80ec, 0x1d07403a, 0x6e1b80dc, 0x2689a04d, 0x10040020, 0x3c8f2079, 0x771dc0ee, 0x2f8be05f, 0x1f07c03e, 0x6b9ae0d7, 0x659960cb, 0x1c872039, 0x24090048
#SBOX_KEY_1:
.long 0x1ac0d66b, 0x12009048, 0x9d20e974, 0x1fc0fe7f, 0x1980cc66, 0x9c20e170, 0x87a03d1e, 0x96e0b75b, 0x02c0160b, 0x16c0b65b, 0x0280140a, 0x1840c261, 0x05002814, 0x9f60fb7d, 0x05802c16, 0x80a00502
.long 0x85602b15, 0x8ce06733, 0x13409a4d, 0x0ec0763b, 0x05402a15, 0x17c0be5f, 0x00800402, 0x9860c361, 0x1540aa55, 0x08804422, 0x82601309, 0x04c02613, 0x89204924, 0x10c08643, 0x00c00603, 0x9320994c
.long 0x13809c4e, 0x08404221, 0x0a005028, 0x1e80f47a, 0x92209148, 0x9de0ef77, 0x1300984c, 0x0f407a3d, 0x86603319, 0x0a80542a, 0x81600b05, 0x88604321, 0x9da0ed76, 0x99e0cf67, 0x1580ac56, 0x0c406231
.long 0x1c80e472, 0x9660b359, 0x03801c0e, 0x9520a954, 0x9920c964, 0x01000804, 0x1d00e874, 0x92a0954a, 0x10008040, 0x9be0df6f, 0x1280944a, 0x1f40fa7d, 0x8ea0753a, 0x91e08f47, 0x87e03f1f, 0x14c0a653
.long 0x88e04723, 0x80e00703, 0x94e0a753, 0x1f80fc7e, 0x9e60f379, 0x8e607339, 0x82e0170b, 0x1740ba5d, 0x90608341, 0x8b20592c, 0x07803c1e, 0x8320190c, 0x1cc0e673, 0x90a08542, 0x89e04f27, 0x1500a854
.long 0x0d006834, 0x8d606b35, 0x90208140, 0x1640b259, 0x8e207138, 0x0c806432, 0x1b40da6d, 0x91608b45, 0x1f00f87c, 0x9d60eb75, 0x81e00f07, 0x89604b25, 0x0e007038, 0x0ac0562b, 0x93a09d4e, 0x86a0351a
.long 0x03c01e0f, 0x04802412, 0x01c00e07, 0x0bc05e2f, 0x8c606331, 0x0b00582c, 0x9a20d168, 0x1440a251, 0x84a02512, 0x04402211, 0x0f807c3e, 0x87603b1d, 0x80200100, 0x84202110, 0x0f00783c, 0x90e08743
.long 0x1a80d46a, 0x0, 0x08c04623, 0x8ae0572b, 0x93e09f4f, 0x9a60d369, 0x84e02713, 0x0a405229, 0x09804c26, 0x06c0361b, 0x00400201, 0x9ce0e773, 0x1400a050, 0x1880c462, 0x1900c864, 0x13c09e4f
.long 0x1d40ea75, 0x97e0bf5f, 0x11408a45, 0x1a40d269, 0x08004020, 0x98e0c763, 0x0700381c, 0x96a0b55a, 0x9460a351, 0x9ee0f77b, 0x1e40f279, 0x19c0ce67, 0x9f20f97c, 0x8c206130, 0x82a0150a, 0x9420a150
.long 0x1c00e070, 0x15c0ae57, 0x8ba05d2e, 0x1480a452, 0x93609b4d, 0x0680341a, 0x03401a0d, 0x8aa0552a, 0x95a0ad56, 0x92609349, 0x06403219, 0x06003018, 0x9ea0f57a, 0x11808c46, 0x9620b158, 0x9c60e371
.long 0x83a01d0e, 0x1ec0f67b, 0x1c40e271, 0x05c02e17, 0x10408241, 0x0cc06633, 0x1940ca65, 0x0c006030, 0x1800c060, 0x85202914, 0x84602311, 0x9560ab55, 0x81a00d06, 0x8a605329, 0x09c04e27, 0x8de06f37
.long 0x9aa0d56a, 0x9b60db6d, 0x86e0371b, 0x88a04522, 0x1bc0de6f, 0x9fa0fd7e, 0x11c08e47, 0x85e02f17, 0x80600301, 0x9fe0ff7f, 0x0d406a35, 0x0e407239, 0x8da06d36, 0x0d806c36, 0x8b605b2d, 0x8a205128
.long 0x91a08d46, 0x83601b0d, 0x95e0af57, 0x12409249, 0x9760bb5d, 0x9ba0dd6e, 0x1780bc5e, 0x8fe07f3f, 0x82201108, 0x9b20d96c, 0x0b805c2e, 0x88204120, 0x83e01f0f, 0x02001008, 0x0b405a2d, 0x1b00d86c
.long 0x01400a05, 0x9820c160, 0x86203118, 0x11008844, 0x94a0a552, 0x99a0cd66, 0x8f607b3d, 0x97a0bd5e, 0x85a02d16, 0x0e80743a, 0x1a00d068, 0x02401209, 0x1700b85c, 0x9ca0e572, 0x1680b45a, 0x1600b058
.long 0x91208944, 0x8d206934, 0x92e0974b, 0x09404a25, 0x01800c06, 0x12c0964b, 0x8ee0773b, 0x0fc07e3f, 0x8ca06532, 0x9720b95c, 0x9e20f178, 0x81200904, 0x98a0c562, 0x0dc06e37, 0x18c0c663, 0x10808442
.long 0x0300180c, 0x1e00f078, 0x8fa07d3e, 0x1d80ec76, 0x07403a1d, 0x1b80dc6e, 0x89a04d26, 0x04002010, 0x8f20793c, 0x1dc0ee77, 0x8be05f2f, 0x07c03e1f, 0x9ae0d76b, 0x9960cb65, 0x8720391c, 0x09004824
#SBOX_KEY_2:
.long 0xc0d66b1a, 0x00904812, 0x20e9749d, 0xc0fe7f1f, 0x80cc6619, 0x20e1709c, 0xa03d1e87, 0xe0b75b96, 0xc0160b02, 0xc0b65b16, 0x80140a02, 0x40c26118, 0x00281405, 0x60fb7d9f, 0x802c1605, 0xa0050280
.long 0x602b1585, 0xe067338c, 0x409a4d13, 0xc0763b0e, 0x402a1505, 0xc0be5f17, 0x80040200, 0x60c36198, 0x40aa5515, 0x80442208, 0x60130982, 0xc0261304, 0x20492489, 0xc0864310, 0xc0060300, 0x20994c93
.long 0x809c4e13, 0x40422108, 0x0050280a, 0x80f47a1e, 0x20914892, 0xe0ef779d, 0x00984c13, 0x407a3d0f, 0x60331986, 0x80542a0a, 0x600b0581, 0x60432188, 0xa0ed769d, 0xe0cf6799, 0x80ac5615, 0x4062310c
.long 0x80e4721c, 0x60b35996, 0x801c0e03, 0x20a95495, 0x20c96499, 0x00080401, 0x00e8741d, 0xa0954a92, 0x00804010, 0xe0df6f9b, 0x80944a12, 0x40fa7d1f, 0xa0753a8e, 0xe08f4791, 0xe03f1f87, 0xc0a65314
.long 0xe0472388, 0xe0070380, 0xe0a75394, 0x80fc7e1f, 0x60f3799e, 0x6073398e, 0xe0170b82, 0x40ba5d17, 0x60834190, 0x20592c8b, 0x803c1e07, 0x20190c83, 0xc0e6731c, 0xa0854290, 0xe04f2789, 0x00a85415
.long 0x0068340d, 0x606b358d, 0x20814090, 0x40b25916, 0x2071388e, 0x8064320c, 0x40da6d1b, 0x608b4591, 0x00f87c1f, 0x60eb759d, 0xe00f0781, 0x604b2589, 0x0070380e, 0xc0562b0a, 0xa09d4e93, 0xa0351a86
.long 0xc01e0f03, 0x80241204, 0xc00e0701, 0xc05e2f0b, 0x6063318c, 0x00582c0b, 0x20d1689a, 0x40a25114, 0xa0251284, 0x40221104, 0x807c3e0f, 0x603b1d87, 0x20010080, 0x20211084, 0x00783c0f, 0xe0874390
.long 0x80d46a1a, 0x0, 0xc0462308, 0xe0572b8a, 0xe09f4f93, 0x60d3699a, 0xe0271384, 0x4052290a, 0x804c2609, 0xc0361b06, 0x40020100, 0xe0e7739c, 0x00a05014, 0x80c46218, 0x00c86419, 0xc09e4f13
.long 0x40ea751d, 0xe0bf5f97, 0x408a4511, 0x40d2691a, 0x00402008, 0xe0c76398, 0x00381c07, 0xa0b55a96, 0x60a35194, 0xe0f77b9e, 0x40f2791e, 0xc0ce6719, 0x20f97c9f, 0x2061308c, 0xa0150a82, 0x20a15094
.long 0x00e0701c, 0xc0ae5715, 0xa05d2e8b, 0x80a45214, 0x609b4d93, 0x80341a06, 0x401a0d03, 0xa0552a8a, 0xa0ad5695, 0x60934992, 0x40321906, 0x00301806, 0xa0f57a9e, 0x808c4611, 0x20b15896, 0x60e3719c
.long 0xa01d0e83, 0xc0f67b1e, 0x40e2711c, 0xc02e1705, 0x40824110, 0xc066330c, 0x40ca6519, 0x0060300c, 0x00c06018, 0x20291485, 0x60231184, 0x60ab5595, 0xa00d0681, 0x6053298a, 0xc04e2709, 0xe06f378d
.long 0xa0d56a9a, 0x60db6d9b, 0xe0371b86, 0xa0452288, 0xc0de6f1b, 0xa0fd7e9f, 0xc08e4711, 0xe02f1785, 0x60030180, 0xe0ff7f9f, 0x406a350d, 0x4072390e, 0xa06d368d, 0x806c360d, 0x605b2d8b, 0x2051288a
.long 0xa08d4691, 0x601b0d83, 0xe0af5795, 0x40924912, 0x60bb5d97, 0xa0dd6e9b, 0x80bc5e17, 0xe07f3f8f, 0x20110882, 0x20d96c9b, 0x805c2e0b, 0x20412088, 0xe01f0f83, 0x00100802, 0x405a2d0b, 0x00d86c1b
.long 0x400a0501, 0x20c16098, 0x20311886, 0x00884411, 0xa0a55294, 0xa0cd6699, 0x607b3d8f, 0xa0bd5e97, 0xa02d1685, 0x80743a0e, 0x00d0681a, 0x40120902, 0x00b85c17, 0xa0e5729c, 0x80b45a16, 0x00b05816
.long 0x20894491, 0x2069348d, 0xe0974b92, 0x404a2509, 0x800c0601, 0xc0964b12, 0xe0773b8e, 0xc07e3f0f, 0xa065328c, 0x20b95c97, 0x20f1789e, 0x20090481, 0xa0c56298, 0xc06e370d, 0xc0c66318, 0x80844210
.long 0x00180c03, 0x00f0781e, 0xa07d3e8f, 0x80ec761d, 0x403a1d07, 0x80dc6e1b, 0xa04d2689, 0x00201004, 0x20793c8f, 0xc0ee771d, 0xe05f2f8b, 0xc03e1f07, 0xe0d76b9a, 0x60cb6599, 0x20391c87, 0x00482409
#SBOX_KEY_3:
.long 0xd66b1ac0, 0x90481200, 0xe9749d20, 0xfe7f1fc0, 0xcc661980, 0xe1709c20, 0x3d1e87a0, 0xb75b96e0, 0x160b02c0, 0xb65b16c0, 0x140a0280, 0xc2611840, 0x28140500, 0xfb7d9f60, 0x2c160580, 0x050280a0
.long 0x2b158560, 0x67338ce0, 0x9a4d1340, 0x763b0ec0, 0x2a150540, 0xbe5f17c0, 0x04020080, 0xc3619860, 0xaa551540, 0x44220880, 0x13098260, 0x261304c0, 0x49248920, 0x864310c0, 0x060300c0, 0x994c9320
.long 0x9c4e1380, 0x42210840, 0x50280a00, 0xf47a1e80, 0x91489220, 0xef779de0, 0x984c1300, 0x7a3d0f40, 0x33198660, 0x542a0a80, 0x0b058160, 0x43218860, 0xed769da0, 0xcf6799e0, 0xac561580, 0x62310c40
.long 0xe4721c80, 0xb3599660, 0x1c0e0380, 0xa9549520, 0xc9649920, 0x08040100, 0xe8741d00, 0x954a92a0, 0x80401000, 0xdf6f9be0, 0x944a1280, 0xfa7d1f40, 0x753a8ea0, 0x8f4791e0, 0x3f1f87e0, 0xa65314c0
.long 0x472388e0, 0x070380e0, 0xa75394e0, 0xfc7e1f80, 0xf3799e60, 0x73398e60, 0x170b82e0, 0xba5d1740, 0x83419060, 0x592c8b20, 0x3c1e0780, 0x190c8320, 0xe6731cc0, 0x854290a0, 0x4f2789e0, 0xa8541500
.long 0x68340d00, 0x6b358d60, 0x81409020, 0xb2591640, 0x71388e20, 0x64320c80, 0xda6d1b40, 0x8b459160, 0xf87c1f00, 0xeb759d60, 0x0f0781e0, 0x4b258960, 0x70380e00, 0x562b0ac0, 0x9d4e93a0, 0x351a86a0
.long 0x1e0f03c0, 0x24120480, 0x0e0701c0, 0x5e2f0bc0, 0x63318c60, 0x582c0b00, 0xd1689a20, 0xa2511440, 0x251284a0, 0x22110440, 0x7c3e0f80, 0x3b1d8760, 0x01008020, 0x21108420, 0x783c0f00, 0x874390e0
.long 0xd46a1a80, 0x0, 0x462308c0, 0x572b8ae0, 0x9f4f93e0, 0xd3699a60, 0x271384e0, 0x52290a40, 0x4c260980, 0x361b06c0, 0x02010040, 0xe7739ce0, 0xa0501400, 0xc4621880, 0xc8641900, 0x9e4f13c0
.long 0xea751d40, 0xbf5f97e0, 0x8a451140, 0xd2691a40, 0x40200800, 0xc76398e0, 0x381c0700, 0xb55a96a0, 0xa3519460, 0xf77b9ee0, 0xf2791e40, 0xce6719c0, 0xf97c9f20, 0x61308c20, 0x150a82a0, 0xa1509420
.long 0xe0701c00, 0xae5715c0, 0x5d2e8ba0, 0xa4521480, 0x9b4d9360, 0x341a0680, 0x1a0d0340, 0x552a8aa0, 0xad5695a0, 0x93499260, 0x32190640, 0x30180600, 0xf57a9ea0, 0x8c461180, 0xb1589620, 0xe3719c60
.long 0x1d0e83a0, 0xf67b1ec0, 0xe2711c40, 0x2e1705c0, 0x82411040, 0x66330cc0, 0xca651940, 0x60300c00, 0xc0601800, 0x29148520, 0x23118460, 0xab559560, 0x0d0681a0, 0x53298a60, 0x4e2709c0, 0x6f378de0
.long 0xd56a9aa0, 0xdb6d9b60, 0x371b86e0, 0x452288a0, 0xde6f1bc0, 0xfd7e9fa0, 0x8e4711c0, 0x2f1785e0, 0x03018060, 0xff7f9fe0, 0x6a350d40, 0x72390e40, 0x6d368da0, 0x6c360d80, 0x5b2d8b60, 0x51288a20
.long 0x8d4691a0, 0x1b0d8360, 0xaf5795e0, 0x92491240, 0xbb5d9760, 0xdd6e9ba0, 0xbc5e1780, 0x7f3f8fe0, 0x11088220, 0xd96c9b20, 0x5c2e0b80, 0x41208820, 0x1f0f83e0, 0x10080200, 0x5a2d0b40, 0xd86c1b00
.long 0x0a050140, 0xc1609820, 0x31188620, 0x88441100, 0xa55294a0, 0xcd6699a0, 0x7b3d8f60, 0xbd5e97a0, 0x2d1685a0, 0x743a0e80, 0xd0681a00, 0x12090240, 0xb85c1700, 0xe5729ca0, 0xb45a1680, 0xb0581600
.long 0x89449120, 0x69348d20, 0x974b92e0, 0x4a250940, 0x0c060180, 0x964b12c0, 0x773b8ee0, 0x7e3f0fc0, 0x65328ca0, 0xb95c9720, 0xf1789e20, 0x09048120, 0xc56298a0, 0x6e370dc0, 0xc66318c0, 0x84421080
.long 0x180c0300, 0xf0781e00, 0x7d3e8fa0, 0xec761d80, 0x3a1d0740, 0xdc6e1b80, 0x4d2689a0, 0x20100400, 0x793c8f20, 0xee771dc0, 0x5f2f8be0, 0x3e1f07c0, 0xd76b9ae0, 0xcb659960, 0x391c8720, 0x48240900
#endif
| 2302_82127028/openHiTLS-examples_1508 | crypto/sm4/src/asm/crypt_sm4_x86_64.S | Unix Assembly | unknown | 20,515 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_SM4
#include <stdlib.h>
#include <stdbool.h>
#include "securec.h"
#include "bsl_sal.h"
#include "bsl_err_internal.h"
#include "crypt_errno.h"
#include "crypt_utils.h"
#include "crypt_sm4.h"
/**
* <<<: Cyclic shift to the left
* ⊕: XOR
* S-box: (see GB/T 32907-2016 6.2 a or GM/T 0002-2012 6.2 1)
* L(B) = B⊕(B <<< 2)⊕(B <<< 10)⊕(B <<< 18)⊕(B <<< 24)
* XBOX_0[i] = L(SBOX[i])
*/
static const uint32_t XBOX_0[] = {
0xd55b5b8e, 0x924242d0, 0xeaa7a74d, 0xfdfbfb06, 0xcf3333fc, 0xe2878765, 0x3df4f4c9, 0xb5dede6b,
0x1658584e, 0xb4dada6e, 0x14505044, 0xc10b0bca, 0x28a0a088, 0xf8efef17, 0x2cb0b09c, 0x05141411,
0x2bacac87, 0x669d9dfb, 0x986a6af2, 0x77d9d9ae, 0x2aa8a882, 0xbcfafa46, 0x04101014, 0xc00f0fcf,
0xa8aaaa02, 0x45111154, 0x134c4c5f, 0x269898be, 0x4825256d, 0x841a1a9e, 0x0618181e, 0x9b6666fd,
0x9e7272ec, 0x4309094a, 0x51414110, 0xf7d3d324, 0x934646d5, 0xecbfbf53, 0x9a6262f8, 0x7be9e992,
0x33ccccff, 0x55515104, 0x0b2c2c27, 0x420d0d4f, 0xeeb7b759, 0xcc3f3ff3, 0xaeb2b21c, 0x638989ea,
0xe7939374, 0xb1cece7f, 0x1c70706c, 0xaba6a60d, 0xca2727ed, 0x08202028, 0xeba3a348, 0x975656c1,
0x82020280, 0xdc7f7fa3, 0x965252c4, 0xf9ebeb12, 0x74d5d5a1, 0x8d3e3eb3, 0x3ffcfcc3, 0xa49a9a3e,
0x461d1d5b, 0x071c1c1b, 0xa59e9e3b, 0xfff3f30c, 0xf0cfcf3f, 0x72cdcdbf, 0x175c5c4b, 0xb8eaea52,
0x810e0e8f, 0x5865653d, 0x3cf0f0cc, 0x1964647d, 0xe59b9b7e, 0x87161691, 0x4e3d3d73, 0xaaa2a208,
0x69a1a1c8, 0x6aadadc7, 0x83060685, 0xb0caca7a, 0x70c5c5b5, 0x659191f4, 0xd96b6bb2, 0x892e2ea7,
0xfbe3e318, 0xe8afaf47, 0x0f3c3c33, 0x4a2d2d67, 0x71c1c1b0, 0x5759590e, 0x9f7676e9, 0x35d4d4e1,
0x1e787866, 0x249090b4, 0x0e383836, 0x5f797926, 0x628d8def, 0x59616138, 0xd2474795, 0xa08a8a2a,
0x259494b1, 0x228888aa, 0x7df1f18c, 0x3bececd7, 0x01040405, 0x218484a5, 0x79e1e198, 0x851e1e9b,
0xd7535384, 0x00000000, 0x4719195e, 0x565d5d0b, 0x9d7e7ee3, 0xd04f4f9f, 0x279c9cbb, 0x5349491a,
0x4d31317c, 0x36d8d8ee, 0x0208080a, 0xe49f9f7b, 0xa2828220, 0xc71313d4, 0xcb2323e8, 0x9c7a7ae6,
0xe9abab42, 0xbdfefe43, 0x882a2aa2, 0xd14b4b9a, 0x41010140, 0xc41f1fdb, 0x38e0e0d8, 0xb7d6d661,
0xa18e8e2f, 0xf4dfdf2b, 0xf1cbcb3a, 0xcd3b3bf6, 0xfae7e71d, 0x608585e5, 0x15545441, 0xa3868625,
0xe3838360, 0xacbaba16, 0x5c757529, 0xa6929234, 0x996e6ef7, 0x34d0d0e4, 0x1a686872, 0x54555501,
0xafb6b619, 0x914e4edf, 0x32c8c8fa, 0x30c0c0f0, 0xf6d7d721, 0x8e3232bc, 0xb3c6c675, 0xe08f8f6f,
0x1d747469, 0xf5dbdb2e, 0xe18b8b6a, 0x2eb8b896, 0x800a0a8a, 0x679999fe, 0xc92b2be2, 0x618181e0,
0xc30303c0, 0x29a4a48d, 0x238c8caf, 0xa9aeae07, 0x0d343439, 0x524d4d1f, 0x4f393976, 0x6ebdbdd3,
0xd6575781, 0xd86f6fb7, 0x37dcdceb, 0x44151551, 0xdd7b7ba6, 0xfef7f709, 0x8c3a3ab6, 0x2fbcbc93,
0x030c0c0f, 0xfcffff03, 0x6ba9a9c2, 0x73c9c9ba, 0x6cb5b5d9, 0x6db1b1dc, 0x5a6d6d37, 0x50454515,
0x8f3636b9, 0x1b6c6c77, 0xadbebe13, 0x904a4ada, 0xb9eeee57, 0xde7777a9, 0xbef2f24c, 0x7efdfd83,
0x11444455, 0xda6767bd, 0x5d71712c, 0x40050545, 0x1f7c7c63, 0x10404050, 0x5b696932, 0xdb6363b8,
0x0a282822, 0xc20707c5, 0x31c4c4f5, 0x8a2222a8, 0xa7969631, 0xce3737f9, 0x7aeded97, 0xbff6f649,
0x2db4b499, 0x75d1d1a4, 0xd3434390, 0x1248485a, 0xbae2e258, 0xe6979771, 0xb6d2d264, 0xb2c2c270,
0x8b2626ad, 0x68a5a5cd, 0x955e5ecb, 0x4b292962, 0x0c30303c, 0x945a5ace, 0x76ddddab, 0x7ff9f986,
0x649595f1, 0xbbe6e65d, 0xf2c7c735, 0x0924242d, 0xc61717d1, 0x6fb9b9d6, 0xc51b1bde, 0x86121294,
0x18606078, 0xf3c3c330, 0x7cf5f589, 0xefb3b35c, 0x3ae8e8d2, 0xdf7373ac, 0x4c353579, 0x208080a0,
0x78e5e59d, 0xedbbbb56, 0x5e7d7d23, 0x3ef8f8c6, 0xd45f5f8b, 0xc82f2fe7, 0x39e4e4dd, 0x49212168,
};
/* XBOX_1[i] = XBOX_0[i] <<< 8 */
static const uint32_t XBOX_1[] = {
0x5b5b8ed5, 0x4242d092, 0xa7a74dea, 0xfbfb06fd, 0x3333fccf, 0x878765e2, 0xf4f4c93d, 0xdede6bb5,
0x58584e16, 0xdada6eb4, 0x50504414, 0x0b0bcac1, 0xa0a08828, 0xefef17f8, 0xb0b09c2c, 0x14141105,
0xacac872b, 0x9d9dfb66, 0x6a6af298, 0xd9d9ae77, 0xa8a8822a, 0xfafa46bc, 0x10101404, 0x0f0fcfc0,
0xaaaa02a8, 0x11115445, 0x4c4c5f13, 0x9898be26, 0x25256d48, 0x1a1a9e84, 0x18181e06, 0x6666fd9b,
0x7272ec9e, 0x09094a43, 0x41411051, 0xd3d324f7, 0x4646d593, 0xbfbf53ec, 0x6262f89a, 0xe9e9927b,
0xccccff33, 0x51510455, 0x2c2c270b, 0xd0d4f42, 0xb7b759ee, 0x3f3ff3cc, 0xb2b21cae, 0x8989ea63,
0x939374e7, 0xcece7fb1, 0x70706c1c, 0xa6a60dab, 0x2727edca, 0x20202808, 0xa3a348eb, 0x5656c197,
0x02028082, 0x7f7fa3dc, 0x5252c496, 0xebeb12f9, 0xd5d5a174, 0x3e3eb38d, 0xfcfcc33f, 0x9a9a3ea4,
0x1d1d5b46, 0x1c1c1b07, 0x9e9e3ba5, 0xf3f30cff, 0xcfcf3ff0, 0xcdcdbf72, 0x5c5c4b17, 0xeaea52b8,
0x0e0e8f81, 0x65653d58, 0xf0f0cc3c, 0x64647d19, 0x9b9b7ee5, 0x16169187, 0x3d3d734e, 0xa2a208aa,
0xa1a1c869, 0xadadc76a, 0x06068583, 0xcaca7ab0, 0xc5c5b570, 0x9191f465, 0x6b6bb2d9, 0x2e2ea789,
0xe3e318fb, 0xafaf47e8, 0x3c3c330f, 0x2d2d674a, 0xc1c1b071, 0x59590e57, 0x7676e99f, 0xd4d4e135,
0x7878661e, 0x9090b424, 0x3838360e, 0x7979265f, 0x8d8def62, 0x61613859, 0x474795d2, 0x8a8a2aa0,
0x9494b125, 0x8888aa22, 0xf1f18c7d, 0xececd73b, 0x04040501, 0x8484a521, 0xe1e19879, 0x1e1e9b85,
0x535384d7, 0x00000000, 0x19195e47, 0x5d5d0b56, 0x7e7ee39d, 0x4f4f9fd0, 0x9c9cbb27, 0x49491a53,
0x31317c4d, 0xd8d8ee36, 0x08080a02, 0x9f9f7be4, 0x828220a2, 0x1313d4c7, 0x2323e8cb, 0x7a7ae69c,
0xabab42e9, 0xfefe43bd, 0x2a2aa288, 0x4b4b9ad1, 0x01014041, 0x1f1fdbc4, 0xe0e0d838, 0xd6d661b7,
0x8e8e2fa1, 0xdfdf2bf4, 0xcbcb3af1, 0x3b3bf6cd, 0xe7e71dfa, 0x8585e560, 0x54544115, 0x868625a3,
0x838360e3, 0xbaba16ac, 0x7575295c, 0x929234a6, 0x6e6ef799, 0xd0d0e434, 0x6868721a, 0x55550154,
0xb6b619af, 0x4e4edf91, 0xc8c8fa32, 0xc0c0f030, 0xd7d721f6, 0x3232bc8e, 0xc6c675b3, 0x8f8f6fe0,
0x7474691d, 0xdbdb2ef5, 0x8b8b6ae1, 0xb8b8962e, 0x0a0a8a80, 0x9999fe67, 0x2b2be2c9, 0x8181e061,
0x0303c0c3, 0xa4a48d29, 0x8c8caf23, 0xaeae07a9, 0x3434390d, 0x4d4d1f52, 0x3939764f, 0xbdbdd36e,
0x575781d6, 0x6f6fb7d8, 0xdcdceb37, 0x15155144, 0x7b7ba6dd, 0xf7f709fe, 0x3a3ab68c, 0xbcbc932f,
0x0c0c0f03, 0xffff03fc, 0xa9a9c26b, 0xc9c9ba73, 0xb5b5d96c, 0xb1b1dc6d, 0x6d6d375a, 0x45451550,
0x3636b98f, 0x6c6c771b, 0xbebe13ad, 0x4a4ada90, 0xeeee57b9, 0x7777a9de, 0xf2f24cbe, 0xfdfd837e,
0x44445511, 0x6767bdda, 0x71712c5d, 0x05054540, 0x7c7c631f, 0x40405010, 0x6969325b, 0x6363b8db,
0x2828220a, 0x0707c5c2, 0xc4c4f531, 0x2222a88a, 0x969631a7, 0x3737f9ce, 0xeded977a, 0xf6f649bf,
0xb4b4992d, 0xd1d1a475, 0x434390d3, 0x48485a12, 0xe2e258ba, 0x979771e6, 0xd2d264b6, 0xc2c270b2,
0x2626ad8b, 0xa5a5cd68, 0x5e5ecb95, 0x2929624b, 0x30303c0c, 0x5a5ace94, 0xddddab76, 0xf9f9867f,
0x9595f164, 0xe6e65dbb, 0xc7c735f2, 0x24242d09, 0x1717d1c6, 0xb9b9d66f, 0x1b1bdec5, 0x12129486,
0x60607818, 0xc3c330f3, 0xf5f5897c, 0xb3b35cef, 0xe8e8d23a, 0x7373acdf, 0x3535794c, 0x8080a020,
0xe5e59d78, 0xbbbb56ed, 0x7d7d235e, 0xf8f8c63e, 0x5f5f8bd4, 0x2f2fe7c8, 0xe4e4dd39, 0x21216849,
};
/* XBOX_2[i] = XBOX_0[i] <<< 16 */
static const uint32_t XBOX_2[] = {
0x5b8ed55b, 0x42d09242, 0xa74deaa7, 0xfb06fdfb, 0x33fccf33, 0x8765e287, 0xf4c93df4, 0xde6bb5de,
0x584e1658, 0xda6eb4da, 0x50441450, 0x0bcac10b, 0xa08828a0, 0xef17f8ef, 0xb09c2cb0, 0x14110514,
0xac872bac, 0x9dfb669d, 0x6af2986a, 0xd9ae77d9, 0xa8822aa8, 0xfa46bcfa, 0x10140410, 0x0fcfc00f,
0xaa02a8aa, 0x11544511, 0x4c5f134c, 0x98be2698, 0x256d4825, 0x1a9e841a, 0x181e0618, 0x66fd9b66,
0x72ec9e72, 0x094a4309, 0x41105141, 0xd324f7d3, 0x46d59346, 0xbf53ecbf, 0x62f89a62, 0xe9927be9,
0xccff33cc, 0x51045551, 0x2c270b2c, 0x0d4f420d, 0xb759eeb7, 0x3ff3cc3f, 0xb21caeb2, 0x89ea6389,
0x9374e793, 0xce7fb1ce, 0x706c1c70, 0xa60daba6, 0x27edca27, 0x20280820, 0xa348eba3, 0x56c19756,
0x02808202, 0x7fa3dc7f, 0x52c49652, 0xeb12f9eb, 0xd5a174d5, 0x3eb38d3e, 0xfcc33ffc, 0x9a3ea49a,
0x1d5b461d, 0x1c1b071c, 0x9e3ba59e, 0xf30cfff3, 0xcf3ff0cf, 0xcdbf72cd, 0x5c4b175c, 0xea52b8ea,
0x0e8f810e, 0x653d5865, 0xf0cc3cf0, 0x647d1964, 0x9b7ee59b, 0x16918716, 0x3d734e3d, 0xa208aaa2,
0xa1c869a1, 0xadc76aad, 0x06858306, 0xca7ab0ca, 0xc5b570c5, 0x91f46591, 0x6bb2d96b, 0x2ea7892e,
0xe318fbe3, 0xaf47e8af, 0x3c330f3c, 0x2d674a2d, 0xc1b071c1, 0x590e5759, 0x76e99f76, 0xd4e135d4,
0x78661e78, 0x90b42490, 0x38360e38, 0x79265f79, 0x8def628d, 0x61385961, 0x4795d247, 0x8a2aa08a,
0x94b12594, 0x88aa2288, 0xf18c7df1, 0xecd73bec, 0x04050104, 0x84a52184, 0xe19879e1, 0x1e9b851e,
0x5384d753, 0x00000000, 0x195e4719, 0x5d0b565d, 0x7ee39d7e, 0x4f9fd04f, 0x9cbb279c, 0x491a5349,
0x317c4d31, 0xd8ee36d8, 0x080a0208, 0x9f7be49f, 0x8220a282, 0x13d4c713, 0x23e8cb23, 0x7ae69c7a,
0xab42e9ab, 0xfe43bdfe, 0x2aa2882a, 0x4b9ad14b, 0x01404101, 0x1fdbc41f, 0xe0d838e0, 0xd661b7d6,
0x8e2fa18e, 0xdf2bf4df, 0xcb3af1cb, 0x3bf6cd3b, 0xe71dfae7, 0x85e56085, 0x54411554, 0x8625a386,
0x8360e383, 0xba16acba, 0x75295c75, 0x9234a692, 0x6ef7996e, 0xd0e434d0, 0x68721a68, 0x55015455,
0xb619afb6, 0x4edf914e, 0xc8fa32c8, 0xc0f030c0, 0xd721f6d7, 0x32bc8e32, 0xc675b3c6, 0x8f6fe08f,
0x74691d74, 0xdb2ef5db, 0x8b6ae18b, 0xb8962eb8, 0x0a8a800a, 0x99fe6799, 0x2be2c92b, 0x81e06181,
0x03c0c303, 0xa48d29a4, 0x8caf238c, 0xae07a9ae, 0x34390d34, 0x4d1f524d, 0x39764f39, 0xbdd36ebd,
0x5781d657, 0x6fb7d86f, 0xdceb37dc, 0x15514415, 0x7ba6dd7b, 0xf709fef7, 0x3ab68c3a, 0xbc932fbc,
0x0c0f030c, 0xff03fcff, 0xa9c26ba9, 0xc9ba73c9, 0xb5d96cb5, 0xb1dc6db1, 0x6d375a6d, 0x45155045,
0x36b98f36, 0x6c771b6c, 0xbe13adbe, 0x4ada904a, 0xee57b9ee, 0x77a9de77, 0xf24cbef2, 0xfd837efd,
0x44551144, 0x67bdda67, 0x712c5d71, 0x05454005, 0x7c631f7c, 0x40501040, 0x69325b69, 0x63b8db63,
0x28220a28, 0x07c5c207, 0xc4f531c4, 0x22a88a22, 0x9631a796, 0x37f9ce37, 0xed977aed, 0xf649bff6,
0xb4992db4, 0xd1a475d1, 0x4390d343, 0x485a1248, 0xe258bae2, 0x9771e697, 0xd264b6d2, 0xc270b2c2,
0x26ad8b26, 0xa5cd68a5, 0x5ecb955e, 0x29624b29, 0x303c0c30, 0x5ace945a, 0xddab76dd, 0xf9867ff9,
0x95f16495, 0xe65dbbe6, 0xc735f2c7, 0x242d0924, 0x17d1c617, 0xb9d66fb9, 0x1bdec51b, 0x12948612,
0x60781860, 0xc330f3c3, 0xf5897cf5, 0xb35cefb3, 0xe8d23ae8, 0x73acdf73, 0x35794c35, 0x80a02080,
0xe59d78e5, 0xbb56edbb, 0x7d235e7d, 0xf8c63ef8, 0x5f8bd45f, 0x2fe7c82f, 0xe4dd39e4, 0x21684921,
};
/* XBOX_3[i] = XBOX_0[i] <<< 24 */
static const uint32_t XBOX_3[] = {
0x8ed55b5b, 0xd0924242, 0x4deaa7a7, 0x06fdfbfb, 0xfccf3333, 0x65e28787, 0xc93df4f4, 0x6bb5dede,
0x4e165858, 0x6eb4dada, 0x44145050, 0xcac10b0b, 0x8828a0a0, 0x17f8efef, 0x9c2cb0b0, 0x11051414,
0x872bacac, 0xfb669d9d, 0xf2986a6a, 0xae77d9d9, 0x822aa8a8, 0x46bcfafa, 0x14041010, 0xcfc00f0f,
0x02a8aaaa, 0x54451111, 0x5f134c4c, 0xbe269898, 0x6d482525, 0x9e841a1a, 0x1e061818, 0xfd9b6666,
0xec9e7272, 0x4a430909, 0x10514141, 0x24f7d3d3, 0xd5934646, 0x53ecbfbf, 0xf89a6262, 0x927be9e9,
0xff33cccc, 0x04555151, 0x270b2c2c, 0x4f420d0d, 0x59eeb7b7, 0xf3cc3f3f, 0x1caeb2b2, 0xea638989,
0x74e79393, 0x7fb1cece, 0x6c1c7070, 0x0daba6a6, 0xedca2727, 0x28082020, 0x48eba3a3, 0xc1975656,
0x80820202, 0xa3dc7f7f, 0xc4965252, 0x12f9ebeb, 0xa174d5d5, 0xb38d3e3e, 0xc33ffcfc, 0x3ea49a9a,
0x5b461d1d, 0x1b071c1c, 0x3ba59e9e, 0x0cfff3f3, 0x3ff0cfcf, 0xbf72cdcd, 0x4b175c5c, 0x52b8eaea,
0x8f810e0e, 0x3d586565, 0xcc3cf0f0, 0x7d196464, 0x7ee59b9b, 0x91871616, 0x734e3d3d, 0x08aaa2a2,
0xc869a1a1, 0xc76aadad, 0x85830606, 0x7ab0caca, 0xb570c5c5, 0xf4659191, 0xb2d96b6b, 0xa7892e2e,
0x18fbe3e3, 0x47e8afaf, 0x330f3c3c, 0x674a2d2d, 0xb071c1c1, 0x0e575959, 0xe99f7676, 0xe135d4d4,
0x661e7878, 0xb4249090, 0x360e3838, 0x265f7979, 0xef628d8d, 0x38596161, 0x95d24747, 0x2aa08a8a,
0xb1259494, 0xaa228888, 0x8c7df1f1, 0xd73becec, 0x05010404, 0xa5218484, 0x9879e1e1, 0x9b851e1e,
0x84d75353, 0x00000000, 0x5e471919, 0x0b565d5d, 0xe39d7e7e, 0x9fd04f4f, 0xbb279c9c, 0x1a534949,
0x7c4d3131, 0xee36d8d8, 0x0a020808, 0x7be49f9f, 0x20a28282, 0xd4c71313, 0xe8cb2323, 0xe69c7a7a,
0x42e9abab, 0x43bdfefe, 0xa2882a2a, 0x9ad14b4b, 0x40410101, 0xdbc41f1f, 0xd838e0e0, 0x61b7d6d6,
0x2fa18e8e, 0x2bf4dfdf, 0x3af1cbcb, 0xf6cd3b3b, 0x1dfae7e7, 0xe5608585, 0x41155454, 0x25a38686,
0x60e38383, 0x16acbaba, 0x295c7575, 0x34a69292, 0xf7996e6e, 0xe434d0d0, 0x721a6868, 0x01545555,
0x19afb6b6, 0xdf914e4e, 0xfa32c8c8, 0xf030c0c0, 0x21f6d7d7, 0xbc8e3232, 0x75b3c6c6, 0x6fe08f8f,
0x691d7474, 0x2ef5dbdb, 0x6ae18b8b, 0x962eb8b8, 0x8a800a0a, 0xfe679999, 0xe2c92b2b, 0xe0618181,
0xc0c30303, 0x8d29a4a4, 0xaf238c8c, 0x07a9aeae, 0x390d3434, 0x1f524d4d, 0x764f3939, 0xd36ebdbd,
0x81d65757, 0xb7d86f6f, 0xeb37dcdc, 0x51441515, 0xa6dd7b7b, 0x09fef7f7, 0xb68c3a3a, 0x932fbcbc,
0x0f030c0c, 0x03fcffff, 0xc26ba9a9, 0xba73c9c9, 0xd96cb5b5, 0xdc6db1b1, 0x375a6d6d, 0x15504545,
0xb98f3636, 0x771b6c6c, 0x13adbebe, 0xda904a4a, 0x57b9eeee, 0xa9de7777, 0x4cbef2f2, 0x837efdfd,
0x55114444, 0xbdda6767, 0x2c5d7171, 0x45400505, 0x631f7c7c, 0x50104040, 0x325b6969, 0xb8db6363,
0x220a2828, 0xc5c20707, 0xf531c4c4, 0xa88a2222, 0x31a79696, 0xf9ce3737, 0x977aeded, 0x49bff6f6,
0x992db4b4, 0xa475d1d1, 0x90d34343, 0x5a124848, 0x58bae2e2, 0x71e69797, 0x64b6d2d2, 0x70b2c2c2,
0xad8b2626, 0xcd68a5a5, 0xcb955e5e, 0x624b2929, 0x3c0c3030, 0xce945a5a, 0xab76dddd, 0x867ff9f9,
0xf1649595, 0x5dbbe6e6, 0x35f2c7c7, 0x2d092424, 0xd1c61717, 0xd66fb9b9, 0xdec51b1b, 0x94861212,
0x78186060, 0x30f3c3c3, 0x897cf5f5, 0x5cefb3b3, 0xd23ae8e8, 0xacdf7373, 0x794c3535, 0xa0208080,
0x9d78e5e5, 0x56edbbbb, 0x235e7d7d, 0xc63ef8f8, 0x8bd45f5f, 0xe7c82f2f, 0xdd39e4e4, 0x68492121,
};
/**
* TE(a,b,c,d) = LE(SBOX[a],SBOX[b],SBOX[c],SBOX[d])
* = LE(SBOX[a],0,0,0)⊕LE(0,SBOX[b],0,0)⊕LE(0,0,SBOX[c],0)⊕LE(0,0,0,SBOX[d])
* = LE(SBOX[a] << 24)⊕LE(SBOX[b] << 16)⊕LE(SBOX[c] << 8)⊕LE(SBOX[d])
* = LE(SBOX[a] <<< 24)⊕LE(SBOX[b] <<< 16)⊕LE(SBOX[c] <<< 8)⊕LE(SBOX[d])
* = (LE(SBOX[a]) <<< 24)⊕(LE(SBOX[b]) <<< 16)⊕(LE(SBOX[c]) <<< 8)⊕LE(SBOX[d])
* = (XBOX_0[a] <<< 24)⊕(XBOX_0[b] <<< 16)⊕(XBOX_0[c] <<< 8)⊕XBOX_0[d]
* = XBOX_3[a]⊕XBOX_2[b]⊕XBOX_1[c]⊕XBOX_0[d]
* F(Xi,Xi+1,Xi+2,Xi+3,rki) = Xi⊕TE(Xi+1⊕Xi+2⊕Xi+3⊕rki)
*/
#define CRYPT_SM4_ROUND(t, x0, x1, x2, x3, rk, sbox) \
do { \
(t) = (x1) ^ (x2) ^ (x3) ^ (rk); \
(x0) ^= (sbox##_3)[((t) >> 24) & 0xff]; \
(x0) ^= (sbox##_2)[((t) >> 16) & 0xff]; \
(x0) ^= (sbox##_1)[((t) >> 8) & 0xff]; \
(x0) ^= (sbox##_0)[(t) & 0xff]; \
} while (0)
/* X(i+4) = F(Xi Xi+1 Xi+2 Xi+3 rk[i]),i = 0,1,...,31; */
#define ENC_ROUND_FUNCTION(t, x0, x1, x2, x3, roundKey, sbox) \
for (int i = 0; i < 32; i += 4) { \
CRYPT_SM4_ROUND((t), (x0), (x1), (x2), (x3), (roundKey)[(i) + 0], sbox); \
CRYPT_SM4_ROUND((t), (x1), (x2), (x3), (x0), (roundKey)[(i) + 1], sbox); \
CRYPT_SM4_ROUND((t), (x2), (x3), (x0), (x1), (roundKey)[(i) + 2], sbox); \
CRYPT_SM4_ROUND((t), (x3), (x0), (x1), (x2), (roundKey)[(i) + 3], sbox); \
}
/* X(i+4) = F(Xi Xi+1 Xi+2 Xi+3 rk[31 - i]),i = 0,1,...,31; */
#define DEC_ROUND_FUNCTION(t, x0, x1, x2, x3, roundKey, sbox) \
for (int i = 28; i >= 0; i -= 4) { \
CRYPT_SM4_ROUND((t), (x0), (x1), (x2), (x3), (roundKey)[(i) + 3], sbox); \
CRYPT_SM4_ROUND((t), (x1), (x2), (x3), (x0), (roundKey)[(i) + 2], sbox); \
CRYPT_SM4_ROUND((t), (x2), (x3), (x0), (x1), (roundKey)[(i) + 1], sbox); \
CRYPT_SM4_ROUND((t), (x3), (x0), (x1), (x2), (roundKey)[(i) + 0], sbox); \
}
/* enc is true: encrypt, enc is false: decrypt */
static void SM4_Crypt(uint8_t *out, const uint8_t *in, const uint32_t *rk, uint32_t x[5], bool enc)
{
x[0] = GET_UINT32_BE(in, 0); // x[0]: 4 bytes starting from index 0 of the in
x[1] = GET_UINT32_BE(in, 4); // x[1]: 4 bytes starting from index 4 of the in
x[2] = GET_UINT32_BE(in, 8); // x[2]: 4 bytes starting from index 8 of the in
x[3] = GET_UINT32_BE(in, 12); // x[3]: 4 bytes starting from index 12 of the in
/* Round function */
if (enc) {
ENC_ROUND_FUNCTION(x[4], x[0], x[1], x[2], x[3], rk, XBOX); // Encryption
} else {
DEC_ROUND_FUNCTION(x[4], x[0], x[1], x[2], x[3], rk, XBOX); // Decryption
}
/* Reverse R(X32 X33 X34 X35) = (X35 X34 X33 X32) */
PUT_UINT32_BE(x[3], out, 0); // x[3] put into the 4 bytes starting from index 0 of the out
PUT_UINT32_BE(x[2], out, 4); // x[2] put into the 4 bytes starting from index 4 of the out
PUT_UINT32_BE(x[1], out, 8); // x[1] put into the 4 bytes starting from index 8 of the out
PUT_UINT32_BE(x[0], out, 12); // x[0] put into the 4 bytes starting from index 12 of the out
}
static int32_t CRYPT_SM4_Crypt(CRYPT_SM4_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t length, bool enc)
{
if (ctx == NULL || in == NULL || out == NULL || length == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (length % CRYPT_SM4_BLOCKSIZE != 0) {
BSL_ERR_PUSH_ERROR(CRYPT_SM4_ERR_MSG_LEN);
return CRYPT_SM4_ERR_MSG_LEN;
}
uint32_t x[5]; // Used as a temporary variable.
uint32_t blocks = length / CRYPT_SM4_BLOCKSIZE;
for (uint32_t i = 0; i < blocks; i++) {
SM4_Crypt(out + i * CRYPT_SM4_BLOCKSIZE, in + i * CRYPT_SM4_BLOCKSIZE, ctx->rk, x, enc);
}
if (!enc) {
(void)memset_s(x, sizeof(x), 0, sizeof(x));
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_SM4_Encrypt(CRYPT_SM4_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t length)
{
return CRYPT_SM4_Crypt(ctx, in, out, length, true);
}
int32_t CRYPT_SM4_Decrypt(CRYPT_SM4_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t length)
{
return CRYPT_SM4_Crypt(ctx, in, out, length, false);
}
void CRYPT_SM4_Clean(CRYPT_SM4_Ctx *ctx)
{
BSL_SAL_CleanseData((void *)(ctx), sizeof(CRYPT_SM4_Ctx));
}
#endif // HITLS_CRYPTO_SM4
| 2302_82127028/openHiTLS-examples_1508 | crypto/sm4/src/crypt_sm4.c | C | unknown | 18,542 |