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_ECDH #include <stdbool.h> #include "crypt_errno.h" #include "crypt_types.h" #include "securec.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "crypt_utils.h" #include "crypt_bn.h" #include "crypt_ecc.h" #include "crypt_ecc_pkey.h" #include "crypt_ecdh.h" #include "sal_atomic.h" #include "crypt_local_types.h" #include "crypt_params_key.h" CRYPT_ECDH_Ctx *CRYPT_ECDH_NewCtx(void) { ECC_Pkey *ctx = BSL_SAL_Calloc(1u, sizeof(ECC_Pkey)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } ctx->useCofactorMode = true; ctx->pointFormat = CRYPT_POINT_UNCOMPRESSED; // the point format is uncompressed by default BSL_SAL_ReferencesInit(&(ctx->references)); return ctx; } CRYPT_ECDH_Ctx *CRYPT_ECDH_NewCtxEx(void *libCtx) { CRYPT_ECDH_Ctx *ctx = CRYPT_ECDH_NewCtx(); if (ctx == NULL) { return NULL; } ctx->libCtx = libCtx; return ctx; } CRYPT_ECDH_Ctx *CRYPT_ECDH_DupCtx(CRYPT_ECDH_Ctx *ctx) { return ECC_DupCtx(ctx); } void CRYPT_ECDH_FreeCtx(CRYPT_ECDH_Ctx *ctx) { if (ctx == NULL) { return; } ECC_FreeCtx(ctx); return; } CRYPT_EcdhPara *CRYPT_ECDH_NewParaById(CRYPT_PKEY_ParaId id) { return ECC_NewPara(id); } CRYPT_EcdhPara *CRYPT_ECDH_NewPara(const CRYPT_EccPara *eccPara) { CRYPT_PKEY_ParaId id = GetCurveId(eccPara); if (id == CRYPT_PKEY_PARAID_MAX) { BSL_ERR_PUSH_ERROR(CRYPT_ECC_ERR_PARA); return NULL; } return CRYPT_ECDH_NewParaById(id); } CRYPT_PKEY_ParaId CRYPT_ECDH_GetParaId(const CRYPT_ECDH_Ctx *ctx) { if (ctx == NULL) { return CRYPT_PKEY_PARAID_MAX; } return ECC_GetParaId(ctx->para); } void CRYPT_ECDH_FreePara(CRYPT_EcdhPara *para) { ECC_FreePara(para); } int32_t CRYPT_ECDH_GetPara(const CRYPT_ECDH_Ctx *ctx, CRYPT_EccPara *para) { return ECC_GetPara(ctx, para); } static int32_t EcdhSetPara(CRYPT_ECDH_Ctx *ctx, CRYPT_EcdhPara *para) { return ECC_SetPara(ctx, para); } int32_t CRYPT_ECDH_SetPara(CRYPT_ECDH_Ctx *ctx, const CRYPT_EccPara *para) { if (ctx == NULL || para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } return EcdhSetPara(ctx, CRYPT_ECDH_NewPara(para)); } uint32_t CRYPT_ECDH_GetBits(const CRYPT_ECDH_Ctx *ctx) { return ECC_PkeyGetBits(ctx); } int32_t CRYPT_ECDH_SetPrvKey(CRYPT_ECDH_Ctx *ctx, const CRYPT_EcdhPrv *prv) { return ECC_PkeySetPrvKey(ctx, prv); } int32_t CRYPT_ECDH_SetPubKey(CRYPT_ECDH_Ctx *ctx, const CRYPT_EcdhPub *pub) { return ECC_PkeySetPubKey(ctx, pub); } int32_t CRYPT_ECDH_GetPrvKey(const CRYPT_ECDH_Ctx *ctx, CRYPT_EcdhPrv *prv) { return ECC_PkeyGetPrvKey(ctx, prv); } int32_t CRYPT_ECDH_GetPubKey(const CRYPT_ECDH_Ctx *ctx, CRYPT_EcdhPub *pub) { return ECC_PkeyGetPubKey(ctx, pub); } #ifdef HITLS_BSL_PARAMS int32_t CRYPT_ECDH_GetParaEx(const CRYPT_ECDH_Ctx *ctx, BSL_Param *para) { return ECC_GetParaEx(ctx, para); } int32_t CRYPT_ECDH_SetParaEx(CRYPT_ECDH_Ctx *ctx, const BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_EccPara eccPara = {0}; (void)GetConstParamValue(para, CRYPT_PARAM_EC_P, &(eccPara.p), &(eccPara.pLen)); (void)GetConstParamValue(para, CRYPT_PARAM_EC_A, &(eccPara.a), &(eccPara.aLen)); (void)GetConstParamValue(para, CRYPT_PARAM_EC_B, &(eccPara.b), &(eccPara.bLen)); (void)GetConstParamValue(para, CRYPT_PARAM_EC_N, &(eccPara.n), &(eccPara.nLen)); (void)GetConstParamValue(para, CRYPT_PARAM_EC_H, &(eccPara.h), &(eccPara.hLen)); (void)GetConstParamValue(para, CRYPT_PARAM_EC_X, &(eccPara.x), &(eccPara.xLen)); (void)GetConstParamValue(para, CRYPT_PARAM_EC_Y, &(eccPara.y), &(eccPara.yLen)); return CRYPT_ECDH_SetPara(ctx, &eccPara); } int32_t CRYPT_ECDH_SetPrvKeyEx(CRYPT_ECDH_Ctx *ctx, const BSL_Param *para) { return ECC_PkeySetPrvKeyEx(ctx, para); } int32_t CRYPT_ECDH_SetPubKeyEx(CRYPT_ECDH_Ctx *ctx, const BSL_Param *para) { return ECC_PkeySetPubKeyEx(ctx, para); } int32_t CRYPT_ECDH_GetPrvKeyEx(const CRYPT_ECDH_Ctx *ctx, BSL_Param *para) { return ECC_PkeyGetPrvKeyEx(ctx, para); } int32_t CRYPT_ECDH_GetPubKeyEx(const CRYPT_ECDH_Ctx *ctx, BSL_Param *para) { return ECC_PkeyGetPubKeyEx(ctx, para); } #endif int32_t CRYPT_ECDH_Gen(CRYPT_ECDH_Ctx *ctx) { return ECC_PkeyGen(ctx); } static int32_t ComputeShareKeyInputCheck(const CRYPT_ECDH_Ctx *ctx, const CRYPT_ECDH_Ctx *pubKey, const uint8_t *shareKey, const uint32_t *shareKeyLen) { if ((ctx == NULL) || (pubKey == NULL) || (shareKey == NULL) || (shareKeyLen == NULL)) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if ((ctx->prvkey == NULL) || (pubKey->pubkey == NULL)) { BSL_ERR_PUSH_ERROR(CRYPT_ECDH_ERR_EMPTY_KEY); return CRYPT_ECDH_ERR_EMPTY_KEY; } // only the cofactor which value is 1 is supported currently BN_BigNum *paraH = ECC_GetParaH(ctx->para); if (paraH == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } if (BN_IsOne(paraH) != true) { BN_Destroy(paraH); BSL_ERR_PUSH_ERROR(CRYPT_ECDH_ERR_INVALID_COFACTOR); return CRYPT_ECDH_ERR_INVALID_COFACTOR; } BN_Destroy(paraH); return CRYPT_SUCCESS; } int32_t CRYPT_ECDH_ComputeShareKey(const CRYPT_ECDH_Ctx *ctx, const CRYPT_ECDH_Ctx *pubKey, uint8_t *shareKey, uint32_t *shareKeyLen) { int32_t ret = ComputeShareKeyInputCheck(ctx, pubKey, shareKey, shareKeyLen); if (ret != CRYPT_SUCCESS) { return ret; } ECC_Point *sharePoint = NULL; CRYPT_Data shareKeyX = {shareKey, *shareKeyLen}; BN_BigNum *tmpPrvkey = BN_Dup(ctx->prvkey); sharePoint = ECC_NewPoint(ctx->para); if ((tmpPrvkey == NULL) || (sharePoint == NULL)) { ret = CRYPT_MEM_ALLOC_FAIL; BSL_ERR_PUSH_ERROR(ret); goto EXIT; } /** When the cofactor mode is enabled, pubkey = prvkey * h * G. When h is 1, no calculation is required. * Currently, the cofactor of the prime curve is only 1, and no related calculation is required. */ ret = ECC_PointMul(ctx->para, sharePoint, ctx->prvkey, pubKey->pubkey); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = ECC_PointCheck(sharePoint); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = ECC_GetPoint(ctx->para, sharePoint, &shareKeyX, NULL); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } *shareKeyLen = shareKeyX.len; EXIT: ECC_FreePoint(sharePoint); BN_Destroy(tmpPrvkey); return ret; } static int32_t CRYPT_ECDH_GetLen(const CRYPT_ECDH_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_ECDH_Ctrl(CRYPT_ECDH_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) { case CRYPT_CTRL_GET_PARAID: return CRYPT_ECDH_GetLen(ctx, (GetLenFunc)CRYPT_ECDH_GetParaId, val, len); case CRYPT_CTRL_GET_BITS: return CRYPT_ECDH_GetLen(ctx, (GetLenFunc)CRYPT_ECDH_GetBits, val, len); case CRYPT_CTRL_GET_SECBITS: return CRYPT_ECDH_GetLen(ctx, (GetLenFunc)CRYPT_ECDH_GetSecBits, val, len); case CRYPT_CTRL_SET_PARA_BY_ID: return EcdhSetPara(ctx, CRYPT_ECDH_NewParaById(*(CRYPT_PKEY_ParaId *)val)); default: break; } return ECC_PkeyCtrl(ctx, opt, val, len); } int32_t CRYPT_ECDH_Cmp(const CRYPT_ECDH_Ctx *a, const CRYPT_ECDH_Ctx *b) { return ECC_PkeyCmp(a, b); } int32_t CRYPT_ECDH_GetSecBits(const CRYPT_ECDH_Ctx *ctx) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return 0; } return ECC_GetSecBits(ctx->para); } #ifdef HITLS_CRYPTO_ECDH_CHECK int32_t CRYPT_ECDH_Check(uint32_t checkType, const CRYPT_ECDH_Ctx *pkey1, const CRYPT_ECDH_Ctx *pkey2) { int32_t ret = ECC_PkeyCheck(pkey1, pkey2, checkType); if (ret == CRYPT_ECC_PAIRWISE_CHECK_FAIL) { BSL_ERR_PUSH_ERROR(CRYPT_ECDH_PAIRWISE_CHECK_FAIL); return CRYPT_ECDH_PAIRWISE_CHECK_FAIL; } if (ret == CRYPT_ECC_INVALID_PRVKEY) { BSL_ERR_PUSH_ERROR(CRYPT_ECDH_INVALID_PRVKEY); return CRYPT_ECDH_INVALID_PRVKEY; } return ret; // may be other error occurred. } #endif // HITLS_CRYPTO_ECDH_CHECK #endif /* HITLS_CRYPTO_ECDH */
2302_82127028/openHiTLS-examples_1508
crypto/ecdh/src/ecdh.c
C
unknown
9,384
/* * 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_ECDSA_H #define CRYPT_ECDSA_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_ECDSA #include <stdint.h> #include "crypt_types.h" #include "crypt_local_types.h" #include "crypt_ecc_pkey.h" #include "crypt_ecc.h" #ifdef __cplusplus extern "C" { #endif /* __cpluscplus */ /* ECDSA key context */ typedef struct ECC_PkeyCtx CRYPT_ECDSA_Ctx; /* ECDSA parameter structure */ typedef struct EccPara CRYPT_EcdsaPara; /** * @ingroup ecdsa * @brief ecdsa Allocate context memory space. * * @retval (CRYPT_ECDSA_Ctx *) Pointer to the memory space of the allocated context * @retval NULL Invalid null pointer */ CRYPT_ECDSA_Ctx *CRYPT_ECDSA_NewCtx(void); /** * @ingroup ecdsa * @brief ecdsa Allocate context memory space. * * @param libCtx [IN] Library context * * @retval (CRYPT_ECDSA_Ctx *) Pointer to the memory space of the allocated context * @retval NULL Invalid null pointer */ CRYPT_ECDSA_Ctx *CRYPT_ECDSA_NewCtxEx(void *libCtx); /** * @ingroup ecdsa * @brief Copy the ECDSA context. After the duplication is complete, call the CRYPT_ECDSA_FreeCtx to release the memory. * * @param ctx [IN] Source ECDSA context * * @return CRYPT_ECDSA_Ctx ECDSA context pointer * If it fails, null is returned. */ CRYPT_ECDSA_Ctx *CRYPT_ECDSA_DupCtx(CRYPT_ECDSA_Ctx *ctx); /** * @ingroup ecdsa * @brief ecdsa Releasing the key context structure * * @param ctx [IN] Pointer to the context structure to be released. The ctx is set NULL by the invoker. */ void CRYPT_ECDSA_FreeCtx(CRYPT_ECDSA_Ctx *ctx); /** * @ingroup ecdsa * @brief ecdsa Generate the key parameter structure * * @param id [IN] Curve ID Parameter ID, which can be selected CRYPT_ECC_NISTP224 to CRYPT_ECC_NISTP521 only * from CRYPT_PKEY_ParaId. * * @retval (CRYPT_EcdsaPara *) Pointer to the memory space of the allocated context * @retval NULL Invalid null pointer */ CRYPT_EcdsaPara *CRYPT_ECDSA_NewParaById(int32_t id); /** * @ingroup ecdsa * @brief ecdsa Generate the key parameter structure * * @param eccPara [IN] Curve parameter information, which can be selected CRYPT_ECC_NISTP224 to CRYPT_ECC_NISTP521 only * from CRYPT_PKEY_ParaId. * * @retval (CRYPT_EcdsaPara *) Pointer to the memory space of the allocated context * @retval NULL Invalid null pointer */ CRYPT_EcdsaPara *CRYPT_ECDSA_NewPara(const CRYPT_EccPara *eccPara); /** * @ingroup ecdsa * @brief Obtain the parameter ID. * * @param ctx [IN] ECDSA context * * @retval ID. If the context is invalid, CRYPT_PKEY_PARAID_MAX is returned. */ CRYPT_PKEY_ParaId CRYPT_ECDSA_GetParaId(const CRYPT_ECDSA_Ctx *ctx); /** * @ingroup ecdsa * @brief ecdsa Release the key parameter structure * * @param para [IN] Pointer to the key parameter structure to be released. The parameter is set NULL by the invoker. */ void CRYPT_ECDSA_FreePara(CRYPT_EcdsaPara *para); /** * @ingroup ecdsa * @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 parameters * * @retval CRYPT_NULL_INPUT Invalid null pointer input * @retval CRYPT_MEM_ALLOC_FAIL Internal memory allocation error * @retval CRYPT_SUCCESS Set successfully. */ int32_t CRYPT_ECDSA_SetPara(CRYPT_ECDSA_Ctx *ctx, const CRYPT_EccPara *para); /** * @ingroup ecdsa * @brief Obtain the key parameter structure. * * @param ctx [IN] Key structure for which related parameters need to be get * @param para [OUT] Key parameters * * @retval CRYPT_NULL_INPUT Invalid null pointer input * @retval CRYPT_MEM_ALLOC_FAIL Internal memory allocation error * @retval CRYPT_SUCCESS Get parameters successfully. */ int32_t CRYPT_ECDSA_GetPara(const CRYPT_ECDSA_Ctx *ctx, CRYPT_EccPara *para); /** * @ingroup ecdsa * @brief ecdsa Obtain the key length. * * @param ctx [IN] ecdsa 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_ECDSA_GetBits(const CRYPT_ECDSA_Ctx *ctx); /** * @ingroup ecdsa * @brief ecdsa Obtains the length required for signing. * * @param ctx [IN] ecdsa 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_ECDSA_GetSignLen(const CRYPT_ECDSA_Ctx *ctx); /** * @ingroup ecdsa * @brief Generate the ECDSA key pair. * * @param ctx [IN/OUT] ecdsa context structure * * @retval CRYPT_NULL_INPUT Error 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_ECDSA_Gen(CRYPT_ECDSA_Ctx *ctx); /** * @ingroup ecdsa * @brief ECDSA Signature * * @param ctx [IN] ecdsa 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_ECDSA_GetSignLen. * * @retval CRYPT_NULL_INPUT Error null pointer input * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_ECDSA_ERR_EMPTY_KEY The key cannot be empty. * @retval CRYPT_ECDSA_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_ECDSA_Sign(const CRYPT_ECDSA_Ctx *ctx, int32_t algId, const uint8_t *data, uint32_t dataLen, uint8_t *sign, uint32_t *signLen); /** * @ingroup ecdsa * @brief ECDSA Signature * * @param ctx [IN] ecdsa context structure * @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_ECDSA_GetSignLen. * * @retval CRYPT_NULL_INPUT Error null pointer input * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_ECDSA_ERR_EMPTY_KEY The key cannot be empty. * @retval CRYPT_ECDSA_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_ECDSA_SignData(const CRYPT_ECDSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint8_t *sign, uint32_t *signLen); /** * @ingroup ecdsa * @brief ECDSA Verification * * @param ctx [IN] ecdsa 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 Error null pointer input * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_ECDSA_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 is verified successfully. */ int32_t CRYPT_ECDSA_Verify(const CRYPT_ECDSA_Ctx *ctx, int32_t algId, const uint8_t *data, uint32_t dataLen, const uint8_t *sign, uint32_t signLen); /** * @ingroup ecdsa * @brief ECDSA Verification * * @param ctx [IN] ecdsa context structure * @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 Error null pointer input * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_ECDSA_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 is verified successfully. */ int32_t CRYPT_ECDSA_VerifyData(const CRYPT_ECDSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen, const uint8_t *sign, uint32_t signLen); /** * @ingroup ecdsa * @brief ECDSA Set the private key data. * * @param ctx [OUT] ecdsa 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_ECDSA_SetPrvKey(CRYPT_ECDSA_Ctx *ctx, const CRYPT_DsaPrv *prv); /** * @ingroup ecdsa * @brief ECDSA Set the public key data. * * @param ctx [OUT] ecdsa context structure * @param pub [IN] External public 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_ECDSA_SetPubKey(CRYPT_ECDSA_Ctx *ctx, const CRYPT_DsaPub *pub); /** * @ingroup ecdsa * @brief ECDSA Obtain the private key data. * * @param ctx [IN] ecdsa context structure * @param prv [OUT] External private 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_ECDSA_GetPrvKey(const CRYPT_ECDSA_Ctx *ctx, CRYPT_DsaPrv *prv); /** * @ingroup ecdsa * @brief ECDSA Obtain the public key data. * * @param ctx [IN] ecdsa 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_ECDSA_GetPubKey(const CRYPT_ECDSA_Ctx *ctx, CRYPT_DsaPub *pub); #ifdef HITLS_BSL_PARAMS /** * @ingroup ecdsa * @brief ECDSA Set the private key data. * * @param ctx [OUT] ecdsa 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_ECDSA_SetPrvKeyEx(CRYPT_ECDSA_Ctx *ctx, const BSL_Param *para); /** * @ingroup ecdsa * @brief ECDSA Set the public key data. * * @param ctx [OUT] ecdsa context structure * @param para [IN] External public 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_ECDSA_SetPubKeyEx(CRYPT_ECDSA_Ctx *ctx, const BSL_Param *para); /** * @ingroup ecdsa * @brief ECDSA Obtain the private key data. * * @param ctx [IN] ecdsa context structure * @param para [OUT] External private 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_ECDSA_GetPrvKeyEx(const CRYPT_ECDSA_Ctx *ctx, BSL_Param *para); /** * @ingroup ecdsa * @brief ECDSA Obtain the public key data. * * @param ctx [IN] ecdsa 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_ECDSA_GetPubKeyEx(const CRYPT_ECDSA_Ctx *ctx, BSL_Param *para); /** * @ingroup ecdsa * @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 parameters * * @retval CRYPT_NULL_INPUT Invalid null pointer input * @retval CRYPT_MEM_ALLOC_FAIL Internal memory allocation error * @retval CRYPT_SUCCESS Set successfully. */ int32_t CRYPT_ECDSA_SetParaEx(CRYPT_ECDSA_Ctx *ctx, const BSL_Param *para); /** * @ingroup ecdsa * @brief Obtain the key parameter structure. * * @param ctx [IN] Key structure for which related parameters need to be get * @param para [OUT] Key parameters * * @retval CRYPT_NULL_INPUT Invalid null pointer input * @retval CRYPT_MEM_ALLOC_FAIL Internal memory allocation error * @retval CRYPT_SUCCESS Get parameters successfully. */ int32_t CRYPT_ECDSA_GetParaEx(const CRYPT_ECDSA_Ctx *ctx, BSL_Param *para); #endif /** * @ingroup ecdsa * @brief ecdsa control interface * * @param ctx [IN/OUT] ecdsa 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 CRYPT_ECC_PKEY_ERR_INVALID_POINT_FORMAT Invalid point format * @retval CRYPT_ECC_PKEY_ERR_CTRL_LEN The length of len is incorrect. * @retval CRYPT_ECDSA_ERR_UNSUPPORTED_CTRL_OPTION The opt mode is not supported. */ int32_t CRYPT_ECDSA_Ctrl(CRYPT_ECDSA_Ctx *ctx, int32_t opt, void *val, uint32_t len); /** * @ingroup ecdsa * @brief ecdsa Compare public keys and parameters * * @param a [IN] ecdsa Context structure * @param b [IN] ecdsa context structure * * @retval CRYPT_SUCCESS is the same * Others. For details, see error code in errno. */ int32_t CRYPT_ECDSA_Cmp(const CRYPT_ECDSA_Ctx *a, const CRYPT_ECDSA_Ctx *b); /** * @ingroup ecdsa * @brief ecdsa get security bits * * @param ctx [IN] ecdsa Context structure * * @retval security bits */ int32_t CRYPT_ECDSA_GetSecBits(const CRYPT_ECDSA_Ctx *ctx); #ifdef HITLS_CRYPTO_PROVIDER /** * @ingroup ecdsa * @brief ecdsa import key * * @param ctx [IN/OUT] ecdsa context structure * @param params [IN] parameters */ int32_t CRYPT_ECDSA_Import(CRYPT_ECDSA_Ctx *ctx, const BSL_Param *params); /** * @ingroup ecdsa * @brief ecdsa export key * * @param ctx [IN] ecdsa context structure * @param params [IN/OUT] key parameters */ int32_t CRYPT_ECDSA_Export(const CRYPT_ECDSA_Ctx *ctx, BSL_Param *params); #endif // HITLS_CRYPTO_PROVIDER #ifdef HITLS_CRYPTO_ECDSA_CHECK /** * @ingroup ecdsa * @brief ecdsa check public key * * @param checkType [IN] check type * @param pkey1 [IN] ecdsa context structure * @param pkey2 [IN] ecdsa context structure * * @retval CRYPT_SUCCESS is the same * Others. For details, see error code in errno. */ int32_t CRYPT_ECDSA_Check(uint32_t checkType, const CRYPT_ECDSA_Ctx *pkey1, const CRYPT_ECDSA_Ctx *pkey2); #endif // HITLS_CRYPTO_ECDSA_CHECK #ifdef __cplusplus } #endif #endif // HITLS_CRYPTO_ECDSA #endif // CRYPT_ECDSA_H
2302_82127028/openHiTLS-examples_1508
crypto/ecdsa/include/crypt_ecdsa.h
C
unknown
17,143
/* * 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_ECDSA #include <stdbool.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_encode_internal.h" #include "crypt_ecc.h" #include "crypt_ecc_pkey.h" #include "eal_pkey_local.h" #include "eal_md_local.h" #include "crypt_ecdsa.h" CRYPT_ECDSA_Ctx *CRYPT_ECDSA_NewCtx(void) { CRYPT_ECDSA_Ctx *ctx = BSL_SAL_Calloc(1u, sizeof(CRYPT_ECDSA_Ctx)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } ctx->pointFormat = CRYPT_POINT_UNCOMPRESSED; // point format is uncompressed by default. BSL_SAL_ReferencesInit(&(ctx->references)); return ctx; } CRYPT_ECDSA_Ctx *CRYPT_ECDSA_NewCtxEx(void *libCtx) { CRYPT_ECDSA_Ctx *ctx = CRYPT_ECDSA_NewCtx(); if (ctx == NULL) { return NULL; } ctx->libCtx = libCtx; return ctx; } CRYPT_ECDSA_Ctx *CRYPT_ECDSA_DupCtx(CRYPT_ECDSA_Ctx *ctx) { return ECC_DupCtx(ctx); } void CRYPT_ECDSA_FreeCtx(CRYPT_ECDSA_Ctx *ctx) { if (ctx == NULL) { return; } ECC_FreeCtx(ctx); } CRYPT_EcdsaPara *CRYPT_ECDSA_NewParaById(int32_t id) { return ECC_NewPara(id); } CRYPT_EcdsaPara *CRYPT_ECDSA_NewPara(const CRYPT_EccPara *eccPara) { CRYPT_PKEY_ParaId id = GetCurveId(eccPara); if (id == CRYPT_PKEY_PARAID_MAX) { BSL_ERR_PUSH_ERROR(CRYPT_ECC_ERR_PARA); return NULL; } return CRYPT_ECDSA_NewParaById(id); } CRYPT_PKEY_ParaId CRYPT_ECDSA_GetParaId(const CRYPT_ECDSA_Ctx *ctx) { if (ctx == NULL) { return CRYPT_PKEY_PARAID_MAX; } return ECC_GetParaId(ctx->para); } void CRYPT_ECDSA_FreePara(CRYPT_EcdsaPara *para) { ECC_FreePara(para); } int32_t CRYPT_ECDSA_GetPara(const CRYPT_ECDSA_Ctx *ctx, CRYPT_EccPara *para) { return ECC_GetPara(ctx, para); } static int32_t EcdsaSetPara(CRYPT_ECDSA_Ctx *ctx, CRYPT_EcdsaPara *para) { return ECC_SetPara(ctx, para); } int32_t CRYPT_ECDSA_SetPara(CRYPT_ECDSA_Ctx *ctx, const CRYPT_EccPara *para) { if (ctx == NULL || para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } return EcdsaSetPara(ctx, CRYPT_ECDSA_NewPara(para)); } uint32_t CRYPT_ECDSA_GetBits(const CRYPT_ECDSA_Ctx *ctx) { return ECC_PkeyGetBits(ctx); } int32_t CRYPT_ECDSA_SetPrvKey(CRYPT_ECDSA_Ctx *ctx, const CRYPT_EcdsaPrv *prv) { return ECC_PkeySetPrvKey(ctx, prv); } int32_t CRYPT_ECDSA_SetPubKey(CRYPT_ECDSA_Ctx *ctx, const CRYPT_EcdsaPub *pub) { return ECC_PkeySetPubKey(ctx, pub); } int32_t CRYPT_ECDSA_GetPrvKey(const CRYPT_ECDSA_Ctx *ctx, CRYPT_EcdsaPrv *prv) { return ECC_PkeyGetPrvKey(ctx, prv); } int32_t CRYPT_ECDSA_GetPubKey(const CRYPT_ECDSA_Ctx *ctx, CRYPT_EcdsaPub *pub) { return ECC_PkeyGetPubKey(ctx, pub); } #ifdef HITLS_BSL_PARAMS int32_t CRYPT_ECDSA_SetParaEx(CRYPT_ECDSA_Ctx *ctx, const BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } #ifdef HITLS_CRYPTO_PROVIDER int32_t ret; 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_EC_P) == NULL) { return CRYPT_SUCCESS; } CRYPT_EccPara eccPara = {0}; (void)GetConstParamValue(para, CRYPT_PARAM_EC_P, &(eccPara.p), &(eccPara.pLen)); (void)GetConstParamValue(para, CRYPT_PARAM_EC_A, &(eccPara.a), &(eccPara.aLen)); (void)GetConstParamValue(para, CRYPT_PARAM_EC_B, &(eccPara.b), &(eccPara.bLen)); (void)GetConstParamValue(para, CRYPT_PARAM_EC_N, &(eccPara.n), &(eccPara.nLen)); (void)GetConstParamValue(para, CRYPT_PARAM_EC_H, &(eccPara.h), &(eccPara.hLen)); (void)GetConstParamValue(para, CRYPT_PARAM_EC_X, &(eccPara.x), &(eccPara.xLen)); (void)GetConstParamValue(para, CRYPT_PARAM_EC_Y, &(eccPara.y), &(eccPara.yLen)); return CRYPT_ECDSA_SetPara(ctx, &eccPara); } int32_t CRYPT_ECDSA_GetParaEx(const CRYPT_ECDSA_Ctx *ctx, BSL_Param *para) { return ECC_GetParaEx(ctx, para); } int32_t CRYPT_ECDSA_SetPrvKeyEx(CRYPT_ECDSA_Ctx *ctx, const BSL_Param *para) { return ECC_PkeySetPrvKeyEx(ctx, para); } int32_t CRYPT_ECDSA_SetPubKeyEx(CRYPT_ECDSA_Ctx *ctx, const BSL_Param *para) { return ECC_PkeySetPubKeyEx(ctx, para); } int32_t CRYPT_ECDSA_GetPrvKeyEx(const CRYPT_ECDSA_Ctx *ctx, BSL_Param *para) { return ECC_PkeyGetPrvKeyEx(ctx, para); } int32_t CRYPT_ECDSA_GetPubKeyEx(const CRYPT_ECDSA_Ctx *ctx, BSL_Param *para) { return ECC_PkeyGetPubKeyEx(ctx, para); } #endif int32_t CRYPT_ECDSA_Gen(CRYPT_ECDSA_Ctx *ctx) { return ECC_PkeyGen(ctx); } uint32_t CRYPT_ECDSA_GetSignLen(const CRYPT_ECDSA_Ctx *ctx) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return 0; } /** * https://docs.microsoft.com/en-us/windows/win32/seccertenroll/about-integer * If the integer is positive but the high order bit is set to 1, * a leading 0x00 is added to the content to indicate that the number is not negative */ // When the number of bits is a multiple of 8 and the most significant bit is 1, 0x00 needs to be added. // If the number of bits is not a multiple of 8, // an extra byte needs to be added to store the data with less than 8 bits. uint32_t qLen = (ECC_ParaBits(ctx->para) / 8) + 1; // divided by 8 to converted to bytes 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; } // Obtain the input hash data. For details, see RFC6979-2.4.1 and RFC6979-2.3.2 static BN_BigNum *GetBnByData(const BN_BigNum *n, const uint8_t *data, uint32_t dataLen) { uint32_t nBits = BN_Bits(n); BN_BigNum *d = BN_Create(nBits); // each byte has 8bits if (d == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } if (data == NULL) { return d; } uint32_t dLen = dataLen; if (8 * dLen > nBits) { // bytes * 8 = bits dLen = (nBits + 7) >> 3; // Add 7 and shift rightward by 3 (equal to /8) to achieve the effect of bits2bytes. } // The input parameters of the function have been verified, and no failure case exists. (void)BN_Bin2Bn(d, data, dLen); if (8 * dLen > nBits) { // bytes * 8 = bits // Subtracted by 8 and &7 to be accurate to bits. int32_t ret = BN_Rshift(d, d, (8 - (nBits & 7))); if (ret != CRYPT_SUCCESS) { BN_Destroy(d); BSL_ERR_PUSH_ERROR(ret); return NULL; } } return d; } static int32_t EcdsaSignCore(const CRYPT_ECDSA_Ctx *ctx, const BN_BigNum *paraN, BN_BigNum *d, BN_BigNum *r, BN_BigNum *s) { uint32_t keyBits = CRYPT_ECDSA_GetBits(ctx); // input parameter has been checked externally. BN_BigNum *k = BN_Create(keyBits); BN_BigNum *k2 = BN_Create(keyBits); ECC_Point *pt = ECC_NewPoint(ctx->para); BN_BigNum *ptX = BN_Create(keyBits); BN_Optimizer *opt = BN_OptimizerCreate(); int32_t ret; int32_t i; if ((k == NULL) || (k2 == NULL) || (pt == NULL) || (opt == NULL) || (ptX == 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->libCtx, k, paraN), ret); if (BN_IsZero(k)) { continue; } // pt = k * G GOTO_ERR_IF(ECC_PointMul(ctx->para, pt, k, NULL), ret); // r = pt->x mod n GOTO_ERR_IF_EX(ECC_GetPointDataX(ctx->para, pt, ptX), ret); GOTO_ERR_IF(BN_Mod(r, ptX, paraN, opt), ret); // if r == 0, then restart if (BN_IsZero(r)) { continue; } // prvkey * r mod n GOTO_ERR_IF(BN_ModMul(s, ctx->prvkey, r, paraN, opt), ret); // hash + prvkey * r mod n GOTO_ERR_IF(BN_ModAddQuick(s, d, s, paraN, opt), ret); // 1/k mod n GOTO_ERR_IF(ECC_ModOrderInv(ctx->para, k2, k), ret); // s = (1/k) * (hash + prvkey * r) mod n GOTO_ERR_IF(BN_ModMul(s, k2, s, paraN, opt), ret); // if s == 0, then restart if (BN_IsZero(s) != true) { break; } } if (i >= CRYPT_ECC_TRY_MAX_CNT) { BSL_ERR_PUSH_ERROR(CRYPT_ECDSA_ERR_TRY_CNT); ret = CRYPT_ECDSA_ERR_TRY_CNT; } ERR: BN_Destroy(k); BN_Destroy(k2); BN_Destroy(ptX); ECC_FreePoint(pt); BN_OptimizerDestroy(opt); return ret; } static int32_t CryptEcdsaSign(const CRYPT_ECDSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen, BN_BigNum **r, BN_BigNum **s) { int32_t rc = CRYPT_SUCCESS; BN_BigNum *signR = NULL; BN_BigNum *signS = NULL; BN_BigNum *d = NULL; BN_BigNum *paraN = ECC_GetParaN(ctx->para); if (paraN == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } uint32_t keyBits = ECC_PkeyGetBits(ctx); signR = BN_Create(keyBits); signS = BN_Create(keyBits); if ((signR == NULL) || (signS == NULL)) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); rc = CRYPT_MEM_ALLOC_FAIL; goto ERR; } d = GetBnByData(paraN, data, dataLen); if (d == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); rc = CRYPT_MEM_ALLOC_FAIL; goto ERR; } GOTO_ERR_IF_EX(EcdsaSignCore(ctx, paraN, d, signR, signS), rc); *r = signR; *s = signS; goto OK; ERR: BN_Destroy(signR); BN_Destroy(signS); OK: BN_Destroy(paraN); BN_Destroy(d); return rc; } // Data with a value of 0 can also be signed. int32_t CRYPT_ECDSA_SignData(const CRYPT_ECDSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint8_t *sign, uint32_t *signLen) { if ((ctx == NULL) || (ctx->para == NULL) || (sign == NULL) || (signLen == NULL) || ((data == NULL) && (dataLen != 0))) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->prvkey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_ECDSA_ERR_EMPTY_KEY); return CRYPT_ECDSA_ERR_EMPTY_KEY; } if (*signLen < CRYPT_ECDSA_GetSignLen(ctx)) { BSL_ERR_PUSH_ERROR(CRYPT_ECDSA_BUFF_LEN_NOT_ENOUGH); return CRYPT_ECDSA_BUFF_LEN_NOT_ENOUGH; } int32_t ret; BN_BigNum *r = NULL; BN_BigNum *s = NULL; ret = CryptEcdsaSign(ctx, data, dataLen, &r, &s); if (ret != CRYPT_SUCCESS) { return ret; } ret = CRYPT_EAL_EncodeSign(r, s, sign, signLen); BN_Destroy(r); BN_Destroy(s); return ret; } int32_t CRYPT_ECDSA_Sign(const CRYPT_ECDSA_Ctx *ctx, int32_t algId, const uint8_t *data, uint32_t dataLen, uint8_t *sign, uint32_t *signLen) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } uint8_t hash[64]; // 64 is max hash len uint32_t hashLen = sizeof(hash) / sizeof(hash[0]); int32_t ret = EAL_Md(algId, ctx->libCtx, ctx->mdAttr, data, dataLen, hash, &hashLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } return CRYPT_ECDSA_SignData(ctx, hash, hashLen, sign, signLen); } static int32_t VerifyCheckSign(const BN_BigNum *paraN, BN_BigNum *r, BN_BigNum *s) { if ((BN_Cmp(r, paraN) >= 0) || (BN_Cmp(s, paraN) >= 0)) { BSL_ERR_PUSH_ERROR(CRYPT_ECDSA_VERIFY_FAIL); return CRYPT_ECDSA_VERIFY_FAIL; } if (BN_IsZero(r) || BN_IsZero(s)) { BSL_ERR_PUSH_ERROR(CRYPT_ECDSA_VERIFY_FAIL); return CRYPT_ECDSA_VERIFY_FAIL; } return CRYPT_SUCCESS; } static int32_t EcdsaVerifyCore(const CRYPT_ECDSA_Ctx *ctx, const BN_BigNum *paraN, BN_BigNum *d, const BN_BigNum *r, const BN_BigNum *s) { BN_Optimizer *opt = BN_OptimizerCreate(); if (opt == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } (void)OptimizerStart(opt); ECC_Point *tpt = ECC_NewPoint(ctx->para); uint32_t keyBits = CRYPT_ECDSA_GetBits(ctx); uint32_t room = BITS_TO_BN_UNIT(keyBits); BN_BigNum *w = OptimizerGetBn(opt, room); BN_BigNum *u1 = OptimizerGetBn(opt, room); BN_BigNum *u2 = OptimizerGetBn(opt, room); BN_BigNum *v = OptimizerGetBn(opt, room); BN_BigNum *tptX = OptimizerGetBn(opt, room); int32_t ret; if (tpt == NULL) { ret = CRYPT_MEM_ALLOC_FAIL; BSL_ERR_PUSH_ERROR(ret); goto ERR; } if ((w == NULL) || (u1 == NULL) || (u2 == NULL) || (v == NULL) || (tptX == NULL)) { ret = CRYPT_BN_OPTIMIZER_GET_FAIL; BSL_ERR_PUSH_ERROR(ret); goto ERR; } // w = 1/s mod n GOTO_ERR_IF(ECC_ModOrderInv(ctx->para, w, s), ret); // u1 = msg*(1/s) mod n GOTO_ERR_IF(BN_ModMul(u1, d, w, paraN, opt), ret); // u2 = r*(1/s) mod n GOTO_ERR_IF(BN_ModMul(u2, r, w, paraN, opt), ret); // tpt : u1*G + u2*pubkey GOTO_ERR_IF(ECC_PointMulAdd(ctx->para, tpt, u1, u2, ctx->pubkey), ret); GOTO_ERR_IF(ECC_GetPointDataX(ctx->para, tpt, tptX), ret); GOTO_ERR_IF(BN_Mod(v, tptX, paraN, opt), ret); if (BN_Cmp(v, r) != 0) { BSL_ERR_PUSH_ERROR(ret); ret = CRYPT_ECDSA_VERIFY_FAIL; } ERR: ECC_FreePoint(tpt); OptimizerEnd(opt); BN_OptimizerDestroy(opt); return ret; } int32_t CRYPT_ECDSA_VerifyData(const CRYPT_ECDSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen, const uint8_t *sign, uint32_t signLen) { if ((ctx == NULL) || (ctx->para == NULL) || ((data == NULL) && (dataLen != 0)) || (sign == NULL) || (signLen == 0)) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->pubkey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_ECDSA_ERR_EMPTY_KEY); return CRYPT_ECDSA_ERR_EMPTY_KEY; } int32_t ret; BN_BigNum *paraN = ECC_GetParaN(ctx->para); if (paraN == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } uint32_t keyBits = ECC_PkeyGetBits(ctx); BN_BigNum *r = BN_Create(keyBits); BN_BigNum *s = BN_Create(keyBits); BN_BigNum *d = GetBnByData(paraN, data, dataLen); if (r == NULL || s == NULL || d == NULL) { ret = CRYPT_MEM_ALLOC_FAIL; goto ERR; } GOTO_ERR_IF(CRYPT_EAL_DecodeSign(sign, signLen, r, s), ret); GOTO_ERR_IF(VerifyCheckSign(paraN, r, s), ret); GOTO_ERR_IF(EcdsaVerifyCore(ctx, paraN, d, r, s), ret); ERR: BN_Destroy(paraN); BN_Destroy(r); BN_Destroy(s); BN_Destroy(d); return ret; } int32_t CRYPT_ECDSA_Verify(const CRYPT_ECDSA_Ctx *ctx, int32_t algId, const uint8_t *data, uint32_t dataLen, const uint8_t *sign, uint32_t signLen) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } uint8_t hash[64]; // 64 is max hash len uint32_t hashLen = sizeof(hash) / sizeof(hash[0]); int32_t ret = EAL_Md(algId, ctx->libCtx, ctx->mdAttr, data, dataLen, hash, &hashLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } return CRYPT_ECDSA_VerifyData(ctx, hash, hashLen, sign, signLen); } static int32_t CRYPT_ECDSA_GetLen(const CRYPT_ECDSA_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_ECDSA_Ctrl(CRYPT_ECDSA_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) { case CRYPT_CTRL_SET_ECC_USE_COFACTOR_MODE: BSL_ERR_PUSH_ERROR(CRYPT_ECDSA_ERR_UNSUPPORTED_CTRL_OPTION); return CRYPT_ECDSA_ERR_UNSUPPORTED_CTRL_OPTION; case CRYPT_CTRL_GET_PARAID: return CRYPT_ECDSA_GetLen(ctx, (GetLenFunc)CRYPT_ECDSA_GetParaId, val, len); case CRYPT_CTRL_GET_BITS: return CRYPT_ECDSA_GetLen(ctx, (GetLenFunc)CRYPT_ECDSA_GetBits, val, len); case CRYPT_CTRL_GET_SIGNLEN: return CRYPT_ECDSA_GetLen(ctx, (GetLenFunc)CRYPT_ECDSA_GetSignLen, val, len); case CRYPT_CTRL_GET_SECBITS: return CRYPT_ECDSA_GetLen(ctx, (GetLenFunc)CRYPT_ECDSA_GetSecBits, val, len); case CRYPT_CTRL_SET_PARA_BY_ID: if (val == NULL || len != sizeof(CRYPT_PKEY_ParaId)) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } return EcdsaSetPara(ctx, CRYPT_ECDSA_NewParaById(*(CRYPT_PKEY_ParaId *)val)); default: break; } return ECC_PkeyCtrl(ctx, opt, val, len); } int32_t CRYPT_ECDSA_Cmp(const CRYPT_ECDSA_Ctx *a, const CRYPT_ECDSA_Ctx *b) { return ECC_PkeyCmp(a, b); } int32_t CRYPT_ECDSA_GetSecBits(const CRYPT_ECDSA_Ctx *ctx) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return 0; } return ECC_GetSecBits(ctx->para); } #ifdef HITLS_CRYPTO_PROVIDER static int32_t SetCurveInfo(CRYPT_ECDSA_Ctx *ctx, const BSL_Param *curve) { if (curve->value == NULL || curve->valueType != BSL_PARAM_TYPE_INT32 || curve->valueLen != sizeof(int32_t)) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_PKEY_ParaId paraId = *(CRYPT_PKEY_ParaId *)curve->value; int32_t ret = ECC_SetPara(ctx, CRYPT_ECDSA_NewParaById((int32_t)paraId)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } int32_t CRYPT_ECDSA_Import(CRYPT_ECDSA_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 = CRYPT_SUCCESS; const BSL_Param *prv = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_EC_PRVKEY); const BSL_Param *pub = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_EC_PUBKEY); const BSL_Param *curve = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_EC_CURVE_ID); if (curve != NULL) { ret = SetCurveInfo(ctx, curve); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } if (prv != NULL) { ret = CRYPT_ECDSA_SetPrvKeyEx(ctx, params); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } if (pub != NULL) { ret = CRYPT_ECDSA_SetPubKeyEx(ctx, params); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } return ret; } int32_t CRYPT_ECDSA_Export(const CRYPT_ECDSA_Ctx *ctx, BSL_Param *params) { if (ctx == NULL || params == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_PKEY_ParaId curveId = CRYPT_ECDSA_GetParaId(ctx); if (curveId == CRYPT_PKEY_PARAID_MAX) { BSL_ERR_PUSH_ERROR(CRYPT_ECC_ERR_PARA); return CRYPT_ECC_ERR_PARA; } uint32_t keyBytes = (CRYPT_ECDSA_GetBits(ctx) + 7) / 8; if (keyBytes == 0) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } int32_t ret; int index = 1; void *args = NULL; CRYPT_EAL_ProcessFuncCb processCb = NULL; BSL_Param ecdsaParams[4] = { {CRYPT_PARAM_EC_CURVE_ID, BSL_PARAM_TYPE_INT32, (int32_t *)&curveId, sizeof(int32_t), 0}, {0}, {0}, BSL_PARAM_END }; 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); // 2 denote private + public key if (buffer == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } if (ctx->pubkey != NULL) { (void)BSL_PARAM_InitValue(&ecdsaParams[index], CRYPT_PARAM_EC_PUBKEY, BSL_PARAM_TYPE_OCTETS, buffer, keyBytes); ret = CRYPT_ECDSA_GetPubKeyEx(ctx, ecdsaParams); if (ret != CRYPT_SUCCESS) { BSL_SAL_Free(buffer); BSL_ERR_PUSH_ERROR(ret); return ret; } ecdsaParams[index].valueLen = ecdsaParams[index].useLen; index++; } if (ctx->prvkey != NULL) { (void)BSL_PARAM_InitValue(&ecdsaParams[index], CRYPT_PARAM_EC_PRVKEY, BSL_PARAM_TYPE_OCTETS, buffer + keyBytes, keyBytes); ret = CRYPT_ECDSA_GetPrvKeyEx(ctx, ecdsaParams); if (ret != CRYPT_SUCCESS) { BSL_SAL_Free(buffer); BSL_ERR_PUSH_ERROR(ret); return ret; } ecdsaParams[index].valueLen = ecdsaParams[index].useLen; index++; } ret = processCb(ecdsaParams, args); BSL_SAL_Free(buffer); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif // HITLS_CRYPTO_PROVIDER #ifdef HITLS_CRYPTO_ECDSA_CHECK int32_t CRYPT_ECDSA_Check(uint32_t checkType, const CRYPT_ECDSA_Ctx *pkey1, const CRYPT_ECDSA_Ctx *pkey2) { int32_t ret = ECC_PkeyCheck(pkey1, pkey2, checkType); if (ret == CRYPT_ECC_PAIRWISE_CHECK_FAIL) { BSL_ERR_PUSH_ERROR(CRYPT_ECDSA_PAIRWISE_CHECK_FAIL); return CRYPT_ECDSA_PAIRWISE_CHECK_FAIL; } if (ret == CRYPT_ECC_INVALID_PRVKEY) { BSL_ERR_PUSH_ERROR(CRYPT_ECDSA_INVALID_PRVKEY); return CRYPT_ECDSA_INVALID_PRVKEY; } return ret; // may be other error occurred. } #endif // HITLS_CRYPTO_ECDSA_CHECK #endif /* HITLS_CRYPTO_ECDSA */
2302_82127028/openHiTLS-examples_1508
crypto/ecdsa/src/ecdsa.c
C
unknown
22,652
/* * 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_ELGAMAL_H #define CRYPT_ELGAMAL_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_ELGAMAL #include <stdlib.h> #include <stdint.h> #include "crypt_bn.h" #include "crypt_local_types.h" #include "bsl_params.h" #ifdef __cplusplus extern "C" { #endif /* __cpluscplus */ #define ELGAMAL_MAX_MODULUS_BITS 16384 /* ElGamal*/ typedef struct ELGAMAL_Ctx CRYPT_ELGAMAL_Ctx; typedef struct ELGAMAL_Para CRYPT_ELGAMAL_Para; /* ElGamal method*/ /** * @ingroup elgamal * @brief Allocate elgamal context memory space. * * @retval (CRYPT_ELGAMAL_Ctx *) Pointer to the memory space of the allocated context * @retval NULL Invalid null pointer. */ CRYPT_ELGAMAL_Ctx *CRYPT_ELGAMAL_NewCtx(void); CRYPT_ELGAMAL_Ctx *CRYPT_ELGAMAL_NewCtxEx(void *libCtx); /** * @ingroup elgamal * @brief Copy the ElGamal context. After the duplication is complete, call the CRYPT_ELGAMAL_FreeCtx to release the memory. * * @param ctx [IN] ELGAMAL context * * @return CRYPT_ELGAMAL_Ctx ELGAMAL context pointer * If the operation fails, a null value is returned. */ CRYPT_ELGAMAL_Ctx *CRYPT_ELGAMAL_DupCtx(CRYPT_ELGAMAL_Ctx *keyCtx); /** * @ingroup elgamal * @brief Create elgamal key parameter structure * * @param para [IN] ELGAMAL External parameter * * @retval (CRYPT_ELGAMAL_Para *) Pointer to the allocated memory space of the structure * @retval NULL Invalid null pointer. */ CRYPT_ELGAMAL_Para *CRYPT_ELGAMAL_NewPara(const CRYPT_ElGamalPara *para); /** * @ingroup elgamal * @brief release ElGamal key context structure * * @param ctx [IN] Pointer to the context structure to be released. The ctx is set NULL by the invoker. */ void CRYPT_ELGAMAL_FreeCtx(CRYPT_ELGAMAL_Ctx *ctx); /** * @ingroup elgamal * @brief Release ElGamal 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_ELGAMAL_FreePara(CRYPT_ELGAMAL_Para *para); /** * @ingroup elgamal * @brief Set the data of the key parameter structure to the key structure. * * @param ctx [OUT] ElGamal context 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_ELGAMAL_ERR_KEY_BITS The expected key length does not meet the requirements. * @retval CRYPT_ELGAMAL_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_ELGAMAL_SetPara(CRYPT_ELGAMAL_Ctx *ctx, const CRYPT_ElGamalPara *para); #ifdef HITLS_BSL_PARAMS /** * @ingroup elgamal * @brief Set the data of the key parameter structure to the key structure. * * @param ctx [OUT] ElGamal context 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_ELGAMAL_ERR_KEY_BITS The expected key length does not meet the requirements. * @retval CRYPT_ELGAMAL_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_ELGAMAL_SetParaEx(CRYPT_ELGAMAL_Ctx *ctx, const BSL_Param *para); #endif /** * @ingroup elgamal * @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_ELGAMAL_GetBits(const CRYPT_ELGAMAL_Ctx *ctx); /** * @ingroup elgamal * @brief Obtain the valid length of the k. * * @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_ELGAMAL_GetKBits(const CRYPT_ELGAMAL_Ctx *ctx); /** * @ingroup elgamal * @brief Generate the ElGamal key pair. * * @param ctx [IN/OUT] elgamal context structure * * @retval CRYPT_NULL_INPUT Error null pointer input * @retval CRYPT_ELGAMAL_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_ELGAMAL_Gen(CRYPT_ELGAMAL_Ctx *ctx); /** * @ingroup elgamal * @brief ElGamal public key encryption * * @param ctx [IN] ElGamal context structure * @param input [IN] Information to be encrypted * @param inputLen [IN] Length of the information to be encrypted * @param out1 [OUT] Pointer to the encrypted information output.(c1) * @param out1Len [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. * @param out2 [OUT] Pointer to the encrypted information output.(c2) * @param out2Len [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_ELGAMAL_NO_KEY_INFO does not contain the key information. * @retval CRYPT_ELGAMAL_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_ELGAMAL_PubEnc(const CRYPT_ELGAMAL_Ctx *ctx, const uint8_t *input, uint32_t inputLen, uint8_t *out1, uint32_t *out1Len, uint8_t *out2, uint32_t *out2Len); /** * @ingroup elgamal * @brief ElGamal private key decryption * * @param ctx [IN] ElGamal context structure * @param c1 [IN] Information to be decrypted * @param c2 [IN] Information to be decrypted * @param bits [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_ELGAMAL_ERR_DEC_BITS Incorrect length of the encrypted private key. * @retval CRYPT_ELGAMAL_NO_KEY_INFO does not contain the key information. * @retval CRYPT_ELGAMAL_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_ELGAMAL_PrvDec(const CRYPT_ELGAMAL_Ctx *ctx, const BN_BigNum *c1, const BN_BigNum *c2, uint32_t bits, uint8_t *out, uint32_t *outLen); /** * @ingroup elgamal * @brief ElGamal Set the private key information. * * @param ctx [OUT] ElGamal context structure * @param prv [IN] Private key data * * @retval CRYPT_NULL_INPUT Error null pointer input * @retval CRYPT_ELGAMAL_ERR_KEY_BITS The key length does not meet the requirements. * @retval CRYPT_ELGAMAL_NO_KEY_INFO does not contain the key information. * @retval CRYPT_ELGAMAL_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_ELGAMAL_SetPrvKey(CRYPT_ELGAMAL_Ctx *ctx, const CRYPT_ElGamalPrv *prv); /** * @ingroup elgamal * @brief ElGamal Set the public key information. * * @param ctx [OUT] ElGamal context structure * @param pub [IN] Public key data * * @retval CRYPT_NULL_INPUT Error null pointer input * @retval CRYPT_ELGAMAL_ERR_KEY_BITS The key length does not meet the requirements. * @retval CRYPT_ELGAMAL_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_ELGAMAL_SetPubKey(CRYPT_ELGAMAL_Ctx *ctx, const CRYPT_ElGamalPub *pub); /** * @ingroup elgamal * @brief ElGamal Obtain the private key information. * * @param ctx [IN] ElGamal 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_ELGAMAL_GetPrvKey(const CRYPT_ELGAMAL_Ctx *ctx, CRYPT_ElGamalPrv *prv); /** * @ingroup elgamal * @brief ElGamal Obtain the public key information. * * @param ctx [IN] ElGamal 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_ELGAMAL_GetPubKey(const CRYPT_ELGAMAL_Ctx *ctx, CRYPT_ElGamalPub *pub); #ifdef HITLS_BSL_PARAMS /** * @ingroup elgamal * @brief ElGamal Set the private key information. * * @param ctx [OUT] ElGamal context structure * @param para [IN] Private key data * * @retval CRYPT_NULL_INPUT Error null pointer input * @retval CRYPT_ELGAMAL_ERR_KEY_BITS The key length does not meet the requirements. * @retval CRYPT_ELGAMAL_NO_KEY_INFO does not contain the key information. * @retval CRYPT_ELGAMAL_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_ELGAMAL_SetPrvKeyEx(CRYPT_ELGAMAL_Ctx *ctx, const BSL_Param *para); /** * @ingroup elgamal * @brief ElGamal Set the public key information. * * @param ctx [OUT] ElGamal context structure * @param para [IN] Public key data * * @retval CRYPT_NULL_INPUT Error null pointer input * @retval CRYPT_ELGAMAL_ERR_KEY_BITS The key length does not meet the requirements. * @retval CRYPT_ELGAMAL_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_ELGAMAL_SetPubKeyEx(CRYPT_ELGAMAL_Ctx *ctx, const BSL_Param *para); /** * @ingroup elgamal * @brief ElGamal Obtain the private key information. * * @param ctx [IN] ElGamal 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_ELGAMAL_GetPrvKeyEx(const CRYPT_ELGAMAL_Ctx *ctx, BSL_Param *para); /** * @ingroup elgamal * @brief ElGamal Obtain the public key information. * * @param ctx [IN] ElGamal 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_ELGAMAL_GetPubKeyEx(const CRYPT_ELGAMAL_Ctx *ctx, BSL_Param *para); #endif /** * @ingroup elgamal * @brief ElGamal public key encryption * * @param ctx [IN] ELGAMAL 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_ELGAMAL_NO_KEY_INFO does not contain the key information. * @retval CRYPT_ELGAMAL_ERR_INPUT_VALUE The entered value does not meet the calculation conditions. * @retval CRYPT_ELGAMAL_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_ELGAMAL_Encrypt(CRYPT_ELGAMAL_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint8_t *out, uint32_t *outLen); /** * @ingroup elgamal * @brief ElGamal private key decryption * * @param ctx [IN] ELGAMAL 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_ELGAMAL_NO_KEY_INFO does not contain the key information. * @retval CRYPT_ELGAMAL_ERR_INPUT_VALUE The entered value does not meet the calculation conditions. * @retval CRYPT_ELGAMAL_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_ELGAMAL_Decrypt(CRYPT_ELGAMAL_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint8_t *out, uint32_t *outLen); /** * @ingroup elgamal * @brief ELGAMAL get security bits * * @param ctx [IN] ELGAMAL Context structure * * @retval security bits */ int32_t CRYPT_ELGAMAL_GetSecBits(const CRYPT_ELGAMAL_Ctx *ctx); /** * @ingroup elgamal * @brief ELGAMAL control function for various operations * * @param ctx [IN/OUT] ELGAMAL context structure * @param opt [IN] Control operation type * @param val [IN/OUT] Parameter value for the operation * @param len [IN] Length of the parameter value * * @retval CRYPT_NULL_INPUT Invalid null pointer input * @retval CRYPT_ELGAMAL_ERR_INPUT_VALUE The entered value does not meet the calculation conditions * @retval CRYPT_ELGAMAL_NO_KEY_INFO Does not contain the key information * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_EAL_ALG_NOT_SUPPORT Operation not supported * @retval CRYPT_SUCCESS Operation succeeded */ int32_t CRYPT_ELGAMAL_Ctrl(CRYPT_ELGAMAL_Ctx *ctx, int32_t opt, void *val, uint32_t len); #ifdef HITLS_CRYPTO_ELGAMAL /** * @ingroup elgamal * @brief BigNum Calculate the original root * * @param g [OUT] Safety prime * @param p [IN] Big prime * @param q [IN] Big prime * @param opt [IN] Optimizer * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure */ int32_t OriginalRoot(void *libCtx, BN_BigNum *g, const BN_BigNum *p, const BN_BigNum *q, uint32_t bits); #endif #ifdef _cplusplus } #endif #endif // HITLS_CRYPTO_ELGAMAL #endif // CRYPT_ELGAMAL_H
2302_82127028/openHiTLS-examples_1508
crypto/elgamal/include/crypt_elgamal.h
C
unknown
17,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_ELGAMAL #include "crypt_utils.h" #include "crypt_elgamal.h" #include "elgamal_local.h" #include "crypt_errno.h" #include "bsl_sal.h" #include "securec.h" #include "bsl_err_internal.h" static int32_t AddZero(uint32_t bits, uint8_t *out, uint32_t *outLen) { int32_t ret; uint32_t i; uint32_t zeros = 0; /* Divide bits by 8 to obtain the byte length. If it is smaller than the key length, pad it with 0. */ if ((*outLen) < 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. */ zeros = BN_BITS_TO_BYTES(bits) - (*outLen); ret = memmove_s(out + zeros, BN_BITS_TO_BYTES(bits) - zeros, out, (*outLen)); if (ret != EOK) { BSL_ERR_PUSH_ERROR(CRYPT_SECUREC_FAIL); return CRYPT_SECUREC_FAIL; } for (i = 0; i < zeros; i++) { out[i] = 0x0; } } *outLen = BN_BITS_TO_BYTES(bits); 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); } int32_t CRYPT_ELGAMAL_PubEnc(const CRYPT_ELGAMAL_Ctx *ctx, const uint8_t *input, uint32_t inputLen, uint8_t *out1, uint32_t *out1Len, uint8_t *out2, uint32_t *out2Len) { int32_t ret; CRYPT_ELGAMAL_PubKey *pubKey = ctx->pubKey; if (pubKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } BN_Mont *mont = BN_MontCreate(pubKey->p); uint32_t bits = CRYPT_ELGAMAL_GetBits(ctx); uint32_t k_bits = CRYPT_ELGAMAL_GetKBits(ctx); BN_Optimizer *optimizer = BN_OptimizerCreate(); if (optimizer == NULL || mont == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); BN_MontDestroy(mont); BN_OptimizerDestroy(optimizer); return CRYPT_MEM_ALLOC_FAIL; } BN_BigNum *m = BN_Create(bits); BN_BigNum *r = BN_Create(k_bits); BN_BigNum *yr = BN_Create(bits); BN_BigNum *c1 = BN_Create(bits); BN_BigNum *c2 = BN_Create(bits); BN_BigNum *gcd_result = BN_Create(bits); BN_BigNum *top = BN_Create(k_bits); bool createFailed = (m == NULL || r == NULL || yr == NULL || c1 == NULL || c2 == NULL || gcd_result == NULL || top == NULL); if (createFailed) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); ret = CRYPT_MEM_ALLOC_FAIL; goto EXIT; } ret = BN_Bin2Bn(m, input, inputLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } if (BN_IsNegative(m)) { BSL_ERR_PUSH_ERROR(CRYPT_ELGAMAL_ERR_INPUT_VALUE); ret = CRYPT_ELGAMAL_ERR_INPUT_VALUE; goto EXIT; } ret = BN_SubLimb(top, pubKey->q, 1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } while (true) { ret = BN_RandRangeEx(ctx->libCtx, r, top); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } // Check whether r is relatively prime to p-1, if not, regenerate r ret = BN_Gcd(gcd_result, r, top, optimizer); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } if (BN_IsOne(gcd_result)) { break; } } ret = BN_MontExp(c1, pubKey->g, r, mont, optimizer); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BN_MontExp(yr, pubKey->y, r, mont, optimizer); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BN_ModMul(c2, m, yr, pubKey->p, optimizer); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BN_Bn2Bin(c1, out1, out1Len); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BN_Bn2Bin(c2, out2, out2Len); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } EXIT: BN_Destroy(m); BN_Destroy(r); BN_Destroy(yr); BN_Destroy(c1); BN_Destroy(c2); BN_Destroy(gcd_result); BN_Destroy(top); BN_OptimizerDestroy(optimizer); BN_MontDestroy(mont); return ret; } int32_t CRYPT_ELGAMAL_PrvDec(const CRYPT_ELGAMAL_Ctx *ctx, const BN_BigNum *c1, const BN_BigNum *c2, uint32_t bits, uint8_t *out, uint32_t *outLen) { int32_t ret; CRYPT_ELGAMAL_PrvKey *prvKey = ctx->prvKey; if (prvKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } BN_Optimizer *optimizer = BN_OptimizerCreate(); if (optimizer == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } bits = CRYPT_ELGAMAL_GetBits(ctx); BN_BigNum *m = BN_Create(bits); BN_BigNum *c1_x = BN_Create(bits); BN_BigNum *c1_x_inv = BN_Create(bits); BN_BigNum *result = BN_Create(bits); bool createFailed = (m == NULL || c1_x == NULL || c1_x_inv == NULL || result == NULL); if (createFailed) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); ret = CRYPT_MEM_ALLOC_FAIL; goto EXIT; } ret = BN_ModExp(c1_x, c1, prvKey->x, prvKey->p, optimizer); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BN_ModInv(c1_x_inv, c1_x, prvKey->p, optimizer); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BN_ModMul(m, c2, c1_x_inv, prvKey->p, optimizer); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = ResultToOut(bits, result, out, outLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } EXIT: BN_Destroy(m); BN_Destroy(c1_x); BN_Destroy(c1_x_inv); BN_Destroy(result); BN_OptimizerDestroy(optimizer); return ret; } static int32_t EncryptInputCheck(const CRYPT_ELGAMAL_Ctx *ctx, const uint8_t *input, uint32_t inputLen, uint8_t *out, uint32_t *outLen) { if (ctx == NULL || (input == NULL && inputLen != 0) || out == NULL || outLen == 0) { 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_ELGAMAL_NO_KEY_INFO); return CRYPT_ELGAMAL_NO_KEY_INFO; } // Check whether the length of the out is sufficient to place the encryption information. uint32_t bits = CRYPT_ELGAMAL_GetBits(ctx); if ((*outLen) < BN_BITS_TO_BYTES(bits)) { BSL_ERR_PUSH_ERROR(CRYPT_ELGAMAL_BUFF_LEN_NOT_ENOUGH); return CRYPT_ELGAMAL_BUFF_LEN_NOT_ENOUGH; } if (inputLen > BN_BITS_TO_BYTES(bits)) { BSL_ERR_PUSH_ERROR(CRYPT_ELGAMAL_ERR_ENC_BITS); return CRYPT_ELGAMAL_ERR_ENC_BITS; } return CRYPT_SUCCESS; } int32_t CRYPT_ELGAMAL_Encrypt(CRYPT_ELGAMAL_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; } uint32_t bits = CRYPT_ELGAMAL_GetBits(ctx); uint32_t out1Len = bits; uint32_t out2Len = (*outLen) - bits; uint32_t out3Len = 2 * bits ; uint8_t *out1 = BSL_SAL_Calloc(1u, out1Len); uint8_t *out2 = BSL_SAL_Calloc(1u, out2Len); uint8_t *out3 = BSL_SAL_Calloc(1u, out3Len); BN_BigNum *result = BN_Create(*outLen); BN_BigNum *c = BN_Create(*outLen); if (out1 == NULL || out2 == NULL || out3 == NULL || result == NULL || c == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); ret = CRYPT_MEM_ALLOC_FAIL; goto EXIT; } ret = CRYPT_ELGAMAL_PubEnc(ctx, data, dataLen, out1, &out1Len, out2, &out2Len); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } (void)memcpy_s(out3, out3Len, out1, out1Len); // c1 (void)memcpy_s(out3 + out1Len, out3Len - out1Len, out2, out2Len); // c2 ret = BN_Bin2Bn(c,out3,out3Len); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = ResultToOut(2 * bits, result, out, outLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } EXIT: BSL_SAL_FREE(out1); BSL_SAL_FREE(out2); BSL_SAL_FREE(out3); BN_Destroy(result); BN_Destroy(c); return ret; } static int32_t DecryptInputCheck(const CRYPT_ELGAMAL_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_ELGAMAL_NO_KEY_INFO); return CRYPT_ELGAMAL_NO_KEY_INFO; } // Check whether the length of the out is sufficient to place the decryption information. uint32_t bits = CRYPT_ELGAMAL_GetBits(ctx); if ((*outLen) < BN_BITS_TO_BYTES(bits)) { BSL_ERR_PUSH_ERROR(CRYPT_ELGAMAL_BUFF_LEN_NOT_ENOUGH); return CRYPT_ELGAMAL_BUFF_LEN_NOT_ENOUGH; } if (dataLen != 2 * BN_BITS_TO_BYTES(bits)) { BSL_ERR_PUSH_ERROR(CRYPT_ELGAMAL_ERR_DEC_BITS); return CRYPT_ELGAMAL_ERR_DEC_BITS; } return CRYPT_SUCCESS; } static int32_t CheckCiphertext(const BN_BigNum *c1, const BN_BigNum *c2, const CRYPT_ELGAMAL_PrvKey *prvKey) { if (BN_Cmp(c1, prvKey->p) >= 0 || BN_IsNegative(c1)) { BSL_ERR_PUSH_ERROR(CRYPT_ELGAMAL_ERR_INPUT_VALUE); return CRYPT_ELGAMAL_ERR_INPUT_VALUE; } if (BN_Cmp(c2, prvKey->p) >= 0 || BN_IsNegative(c2)) { BSL_ERR_PUSH_ERROR(CRYPT_ELGAMAL_ERR_INPUT_VALUE); return CRYPT_ELGAMAL_ERR_INPUT_VALUE; } int32_t ret = CRYPT_SUCCESS; BN_BigNum *gcd_result = BN_Create(BN_Bits(c1)); BN_Optimizer *optimizer = BN_OptimizerCreate(); if (gcd_result == NULL || optimizer == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); ret = CRYPT_MEM_ALLOC_FAIL; goto EXIT; } ret = BN_Gcd(gcd_result, c1, prvKey->p, optimizer); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } if (BN_IsOne(gcd_result) == false) { BSL_ERR_PUSH_ERROR(CRYPT_ELGAMAL_ERR_INPUT_VALUE); ret = CRYPT_ELGAMAL_ERR_INPUT_VALUE; goto EXIT; } ret = BN_Gcd(gcd_result, c2, prvKey->p, optimizer); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } if (BN_IsOne(gcd_result) == false) { BSL_ERR_PUSH_ERROR(CRYPT_ELGAMAL_ERR_INPUT_VALUE); ret = CRYPT_ELGAMAL_ERR_INPUT_VALUE; } EXIT: BN_Destroy(gcd_result); BN_OptimizerDestroy(optimizer); return ret; } int32_t CRYPT_ELGAMAL_Decrypt(CRYPT_ELGAMAL_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint8_t *out, uint32_t *outLen) { int32_t ret = DecryptInputCheck(ctx, data, dataLen, out, outLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } uint32_t bits = CRYPT_ELGAMAL_GetBits(ctx); uint32_t data1Len = BN_BITS_TO_BYTES(bits); uint32_t data2Len = dataLen - BN_BITS_TO_BYTES(bits); uint8_t *data1 = BSL_SAL_Calloc(1u, data1Len); uint8_t *data2 = BSL_SAL_Calloc(1u, data2Len); BN_BigNum *c1 = BN_Create(bits); BN_BigNum *c2 = BN_Create(bits); if (data1 == NULL || data2 == NULL || c1 == NULL || c2 == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); ret = CRYPT_MEM_ALLOC_FAIL; goto EXIT; } (void)memcpy_s(data1, data1Len, data, data1Len); // c1 (void)memcpy_s(data2, data2Len, data + data1Len, data2Len); // c2 ret = BN_Bin2Bn(c1, data1, data1Len); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BN_Bin2Bn(c2, data2, data2Len); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = CheckCiphertext(c1, c2, ctx->prvKey); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = CRYPT_ELGAMAL_PrvDec(ctx, c1, c2, bits, out, outLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } EXIT: BSL_SAL_FREE(data1); BSL_SAL_FREE(data2); BN_Destroy(c1); BN_Destroy(c2); return ret; } static uint32_t CRYPT_ELGAMAL_GetLen(const CRYPT_ELGAMAL_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_ELGAMAL_Ctrl(CRYPT_ELGAMAL_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) { case CRYPT_CTRL_GET_BITS: return CRYPT_ELGAMAL_GetLen(ctx, (GetLenFunc)CRYPT_ELGAMAL_GetBits, val, len); case CRYPT_CTRL_GET_SECBITS: return CRYPT_ELGAMAL_GetLen(ctx, (GetLenFunc)CRYPT_ELGAMAL_GetSecBits, val, len); default: BSL_ERR_PUSH_ERROR(CRYPT_ELGAMAL_CTRL_NOT_SUPPORT_ERROR); return CRYPT_ELGAMAL_CTRL_NOT_SUPPORT_ERROR; } } #endif // HITLS_CRYPTO_ELGAMAL
2302_82127028/openHiTLS-examples_1508
crypto/elgamal/src/elgamal_encdec.c
C
unknown
14,388
/* * 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_ELGAMAL #include "crypt_elgamal.h" #include "elgamal_local.h" #include "crypt_errno.h" #include "crypt_utils.h" #include "securec.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "crypt_params_key.h" CRYPT_ELGAMAL_Ctx *CRYPT_ELGAMAL_NewCtx(void) { CRYPT_ELGAMAL_Ctx *ctx = NULL; ctx = (CRYPT_ELGAMAL_Ctx *)BSL_SAL_Malloc(sizeof(CRYPT_ELGAMAL_Ctx)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } (void)memset_s(ctx, sizeof(CRYPT_ELGAMAL_Ctx), 0, sizeof(CRYPT_ELGAMAL_Ctx)); BSL_SAL_ReferencesInit(&(ctx->references)); return ctx; } CRYPT_ELGAMAL_Ctx *CRYPT_ELGAMAL_NewCtxEx(void *libCtx) { CRYPT_ELGAMAL_Ctx *ctx = CRYPT_ELGAMAL_NewCtx(); if (ctx == NULL) { return NULL; } ctx->libCtx = libCtx; return ctx; } static CRYPT_ELGAMAL_PubKey *ElGamalPubKeyDupCtx(CRYPT_ELGAMAL_PubKey *pubKey) { CRYPT_ELGAMAL_PubKey *newPubKey = (CRYPT_ELGAMAL_PubKey *)BSL_SAL_Malloc(sizeof(CRYPT_ELGAMAL_PubKey)); if (newPubKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } (void)memset_s(newPubKey, sizeof(CRYPT_ELGAMAL_PubKey), 0, sizeof(CRYPT_ELGAMAL_PubKey)); GOTO_ERR_IF_SRC_NOT_NULL(newPubKey->p, pubKey->p, BN_Dup(pubKey->p), CRYPT_MEM_ALLOC_FAIL); GOTO_ERR_IF_SRC_NOT_NULL(newPubKey->g, pubKey->g, BN_Dup(pubKey->g), CRYPT_MEM_ALLOC_FAIL); GOTO_ERR_IF_SRC_NOT_NULL(newPubKey->y, pubKey->y, BN_Dup(pubKey->y), CRYPT_MEM_ALLOC_FAIL); GOTO_ERR_IF_SRC_NOT_NULL(newPubKey->q, pubKey->q, BN_Dup(pubKey->q), CRYPT_MEM_ALLOC_FAIL); return newPubKey; ERR: ELGAMAL_FREE_PUB_KEY(newPubKey); return NULL; } static CRYPT_ELGAMAL_PrvKey *ElGamalPrvKeyDupCtx(CRYPT_ELGAMAL_PrvKey *prvKey) { CRYPT_ELGAMAL_PrvKey *newPrvKey = (CRYPT_ELGAMAL_PrvKey *)BSL_SAL_Malloc(sizeof(CRYPT_ELGAMAL_PrvKey)); if (newPrvKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } (void)memset_s(newPrvKey, sizeof(CRYPT_ELGAMAL_PrvKey), 0, sizeof(CRYPT_ELGAMAL_PrvKey)); GOTO_ERR_IF_SRC_NOT_NULL(newPrvKey->p, prvKey->p, BN_Dup(prvKey->p), CRYPT_MEM_ALLOC_FAIL); GOTO_ERR_IF_SRC_NOT_NULL(newPrvKey->g, prvKey->g, BN_Dup(prvKey->g), CRYPT_MEM_ALLOC_FAIL); GOTO_ERR_IF_SRC_NOT_NULL(newPrvKey->x, prvKey->x, BN_Dup(prvKey->x), CRYPT_MEM_ALLOC_FAIL); return newPrvKey; ERR: ELGAMAL_FREE_PRV_KEY(newPrvKey); return NULL; } static CRYPT_ELGAMAL_Para *ElGamalParaDupCtx(CRYPT_ELGAMAL_Para *para) { CRYPT_ELGAMAL_Para *newPara = (CRYPT_ELGAMAL_Para *)BSL_SAL_Malloc(sizeof(CRYPT_ELGAMAL_Para)); if (newPara == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } (void)memset_s(newPara, sizeof(CRYPT_ELGAMAL_Para), 0, sizeof(CRYPT_ELGAMAL_Para)); newPara->bits = para->bits; GOTO_ERR_IF_SRC_NOT_NULL(newPara->q, para->q, BN_Dup(para->q), CRYPT_MEM_ALLOC_FAIL); return newPara; ERR: ELGAMAL_FREE_PARA(newPara); return NULL; } CRYPT_ELGAMAL_Ctx *CRYPT_ELGAMAL_DupCtx(CRYPT_ELGAMAL_Ctx *keyCtx) { if (keyCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return NULL; } CRYPT_ELGAMAL_Ctx *newKeyCtx = BSL_SAL_Malloc(sizeof(CRYPT_ELGAMAL_Ctx));; if (newKeyCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } (void)memset_s(newKeyCtx, sizeof(CRYPT_ELGAMAL_Ctx), 0, sizeof(CRYPT_ELGAMAL_Ctx)); GOTO_ERR_IF_SRC_NOT_NULL(newKeyCtx->prvKey, keyCtx->prvKey, ElGamalPrvKeyDupCtx(keyCtx->prvKey), CRYPT_MEM_ALLOC_FAIL); GOTO_ERR_IF_SRC_NOT_NULL(newKeyCtx->pubKey, keyCtx->pubKey, ElGamalPubKeyDupCtx(keyCtx->pubKey), CRYPT_MEM_ALLOC_FAIL); GOTO_ERR_IF_SRC_NOT_NULL(newKeyCtx->para, keyCtx->para, ElGamalParaDupCtx(keyCtx->para), CRYPT_MEM_ALLOC_FAIL); newKeyCtx->libCtx = keyCtx->libCtx; BSL_SAL_ReferencesInit(&(newKeyCtx->references)); return newKeyCtx; ERR: CRYPT_ELGAMAL_FreeCtx(newKeyCtx); return NULL; } static int32_t NewParaCheck(const CRYPT_ElGamalPara *para) { if (para == NULL || para->q == NULL || para->qLen == 0 || para->bits == 0 || para->k_bits == 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (para->bits > ELGAMAL_MAX_MODULUS_BITS || para->k_bits > ELGAMAL_MAX_MODULUS_BITS) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } if (para->qLen != BN_BITS_TO_BYTES(para->k_bits)) { BSL_ERR_PUSH_ERROR(CRYPT_ELGAMAL_ERR_KEY_KBITS); return CRYPT_ELGAMAL_ERR_KEY_KBITS; } return CRYPT_SUCCESS; } CRYPT_ELGAMAL_Para *CRYPT_ELGAMAL_NewPara(const CRYPT_ElGamalPara *para) { if (NewParaCheck(para) != CRYPT_SUCCESS) { return NULL; } CRYPT_ELGAMAL_Para *retPara = BSL_SAL_Malloc(sizeof(CRYPT_ELGAMAL_Para)); if (retPara == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } retPara->bits = para->bits; retPara->k_bits = para->k_bits; retPara->q = BN_Create(para->k_bits); if (retPara->q == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); goto ERR; } return retPara; ERR: CRYPT_ELGAMAL_FreePara(retPara); return NULL; } void CRYPT_ELGAMAL_FreeCtx(CRYPT_ELGAMAL_Ctx *ctx) { if (ctx == NULL) { return; } int i = 0; BSL_SAL_AtomicDownReferences(&(ctx->references), &i); if (i > 0) { return; } BSL_SAL_ReferencesFree(&(ctx->references)); ELGAMAL_FREE_PRV_KEY(ctx->prvKey); ELGAMAL_FREE_PUB_KEY(ctx->pubKey); ELGAMAL_FREE_PARA(ctx->para); BSL_SAL_Free(ctx); } void CRYPT_ELGAMAL_FreePara(CRYPT_ELGAMAL_Para *para) { if (para == NULL) { return; } BN_Destroy(para->q); BSL_SAL_Free(para); } void ELGAMAL_FreePrvKey(CRYPT_ELGAMAL_PrvKey *prvKey) { if (prvKey == NULL) { return; } BN_Destroy(prvKey->p); BN_Destroy(prvKey->g); BN_Destroy(prvKey->x); BSL_SAL_Free(prvKey); } void ELGAMAL_FreePubKey(CRYPT_ELGAMAL_PubKey *pubKey) { if (pubKey == NULL) { return; } BN_Destroy(pubKey->p); BN_Destroy(pubKey->q); BN_Destroy(pubKey->g); BN_Destroy(pubKey->y); BSL_SAL_Free(pubKey); } static int32_t IsELGAMALSetParaVaild(const CRYPT_ELGAMAL_Ctx *ctx, const CRYPT_ELGAMAL_Para *para) { if (ctx == NULL || para == NULL || para->q == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (para->bits > ELGAMAL_MAX_MODULUS_BITS || para->bits <= 0) { BSL_ERR_PUSH_ERROR(CRYPT_ELGAMAL_ERR_KEY_BITS); return CRYPT_ELGAMAL_ERR_KEY_BITS; } if (para->k_bits > ELGAMAL_MAX_MODULUS_BITS || para->k_bits <= 0) { BSL_ERR_PUSH_ERROR(CRYPT_ELGAMAL_ERR_KEY_KBITS); return CRYPT_ELGAMAL_ERR_KEY_KBITS; } if (para->bits <= para->k_bits) { BSL_ERR_PUSH_ERROR(CRYPT_ELGAMAL_ERR_KEY_BITS_KBITS); return CRYPT_ELGAMAL_ERR_KEY_BITS_KBITS; } return CRYPT_SUCCESS; } CRYPT_ELGAMAL_Para *CRYPT_ElGamal_DupPara(const CRYPT_ELGAMAL_Para *para) { CRYPT_ELGAMAL_Para *paraCopy = BSL_SAL_Malloc(sizeof(CRYPT_ELGAMAL_Para)); if (paraCopy == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } paraCopy->bits = para->bits; paraCopy->k_bits = para->k_bits; paraCopy->q = BN_Dup(para->q); if (paraCopy->q == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); ELGAMAL_FREE_PARA(paraCopy); return NULL; } return paraCopy; } int32_t CRYPT_ELGAMAL_SetPara(CRYPT_ELGAMAL_Ctx *ctx, const CRYPT_ElGamalPara *para) { if (ctx == NULL || para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_ELGAMAL_Para *elGamalPara = CRYPT_ELGAMAL_NewPara(para); if (elGamalPara == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = IsELGAMALSetParaVaild(ctx, elGamalPara); if (ret != CRYPT_SUCCESS) { CRYPT_ELGAMAL_FreePara(elGamalPara); return ret; } ELGAMAL_FREE_PARA(ctx->para); ELGAMAL_FREE_PUB_KEY(ctx->pubKey); ELGAMAL_FREE_PRV_KEY(ctx->prvKey); ctx->para = elGamalPara; return CRYPT_SUCCESS; } #ifdef HITLS_BSL_PARAMS int32_t CRYPT_ELGAMAL_SetParaEx(CRYPT_ELGAMAL_Ctx *ctx, const BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_ElGamalPara elGamalPara = {0}; uint32_t len = sizeof(uint32_t); int32_t ret = 0; (void)GetConstParamValue(para, CRYPT_PARAM_ELGAMAL_Q, &(elGamalPara.q), &(elGamalPara.qLen)); const BSL_Param *temp = BSL_PARAM_FindConstParam(para, CRYPT_PARAM_ELGAMAL_BITS); if (temp != NULL) { RETURN_RET_IF_ERR(BSL_PARAM_GetValue(temp, CRYPT_PARAM_ELGAMAL_BITS, BSL_PARAM_TYPE_UINT32, &elGamalPara.bits, &len), ret); } temp = BSL_PARAM_FindConstParam(para, CRYPT_PARAM_ELGAMAL_KBITS); if (temp != NULL) { RETURN_RET_IF_ERR(BSL_PARAM_GetValue(temp, CRYPT_PARAM_ELGAMAL_KBITS, BSL_PARAM_TYPE_UINT32, &elGamalPara.k_bits, &len), ret); } return CRYPT_ELGAMAL_SetPara(ctx, &elGamalPara); } #endif uint32_t CRYPT_ELGAMAL_GetBits(const CRYPT_ELGAMAL_Ctx *ctx) { if (ctx == NULL) { return 0; } if (ctx->para != NULL) { return ctx->para->bits; } if (ctx->prvKey != NULL) { return BN_Bits(ctx->prvKey->p); } if (ctx->pubKey != NULL) { return BN_Bits(ctx->pubKey->p); } return 0; } uint32_t CRYPT_ELGAMAL_GetKBits(const CRYPT_ELGAMAL_Ctx *ctx) { if (ctx == NULL) { return 0; } if (ctx->para != NULL) { return ctx->para->k_bits; } return 0; } CRYPT_ELGAMAL_PrvKey *ElGamal_NewPrvKey(uint32_t bits) { CRYPT_ELGAMAL_PrvKey *prvKey = (CRYPT_ELGAMAL_PrvKey *)BSL_SAL_Malloc(sizeof(CRYPT_ELGAMAL_PrvKey)); if (prvKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } prvKey->p = BN_Create(bits); prvKey->g = BN_Create(bits); prvKey->x = BN_Create(bits); if (prvKey->p == NULL || prvKey->g == NULL || prvKey->x == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); ELGAMAL_FREE_PRV_KEY(prvKey); } return prvKey; } CRYPT_ELGAMAL_PubKey *ElGamal_NewPubKey(uint32_t bits) { CRYPT_ELGAMAL_PubKey *pubKey = (CRYPT_ELGAMAL_PubKey *)BSL_SAL_Malloc(sizeof(CRYPT_ELGAMAL_PubKey)); if (pubKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } pubKey->p = BN_Create(bits); pubKey->g = BN_Create(bits); pubKey->y = BN_Create(bits); pubKey->q = BN_Create(bits); if (pubKey->p == NULL || pubKey->g == NULL || pubKey->y == NULL || pubKey->q == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); ELGAMAL_FREE_PUB_KEY(pubKey); } return pubKey; } static int32_t ElGamal_GenP(void *libCtx, BN_BigNum *p, CRYPT_ELGAMAL_Para *para, BN_Optimizer *optimizer) { uint32_t bits = para->bits; uint32_t k_bits = para->k_bits; BN_BigNum *k = BN_Create(bits - k_bits); BN_BigNum *kq = BN_Create(bits); int32_t ret = CRYPT_MEM_ALLOC_FAIL; if (kq == NULL || k == NULL) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BN_GenPrime(para->q, NULL, k_bits, false, optimizer, NULL); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BN_RandEx(libCtx, k, (bits - k_bits), 1, 0); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BN_Mul(kq, k, para->q, optimizer); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BN_AddLimb(p, kq, 1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } EXIT: BN_Destroy(k); BN_Destroy(kq); return ret; } static int32_t ElGamal_CalcPrvKey(void *libCtx, CRYPT_ELGAMAL_PrvKey *prvKey, CRYPT_ELGAMAL_Para *para, BN_Optimizer *optimizer) { int32_t ret = CRYPT_SUCCESS; BN_BigNum *xTop = BN_Create(para->bits); if (xTop == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ret = ElGamal_GenP(libCtx, prvKey->p, para, optimizer); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = OriginalRoot(libCtx, prvKey->g, prvKey->p, para->q, para->bits); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BN_SubLimb(xTop, para->q, 1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BN_RandRangeEx(libCtx, prvKey->x, xTop); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } EXIT: BN_Destroy(xTop); return ret; } static int32_t ElGamal_CalcPubKey(CRYPT_ELGAMAL_PubKey *pubKey, CRYPT_ELGAMAL_PrvKey *prvKey, BN_Optimizer *optimizer) { int32_t ret = BN_Copy(pubKey->p, prvKey->p); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BN_Copy(pubKey->g, prvKey->g); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BN_ModExp(pubKey->y, pubKey->g, prvKey->x, pubKey->p, optimizer); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } int32_t CRYPT_ELGAMAL_Gen(CRYPT_ELGAMAL_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_ELGAMAL_Ctx *newCtx = CRYPT_ELGAMAL_NewCtx(); if (newCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } newCtx->para = CRYPT_ElGamal_DupPara(ctx->para); if (newCtx->para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); goto ERR; } newCtx->prvKey = ElGamal_NewPrvKey(newCtx->para->bits); newCtx->pubKey = ElGamal_NewPubKey(newCtx->para->bits); optimizer = BN_OptimizerCreate(); if (optimizer == NULL || newCtx->prvKey == NULL || newCtx->pubKey == NULL) { ret = CRYPT_MEM_ALLOC_FAIL; BSL_ERR_PUSH_ERROR(ret); goto ERR; } BN_OptimizerSetLibCtx(ctx->libCtx, optimizer); ret = ElGamal_GenP(ctx->libCtx, newCtx->prvKey->p, newCtx->para, optimizer); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } ret = ElGamal_CalcPrvKey(ctx->libCtx, newCtx->prvKey, newCtx->para, optimizer); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } ret = ElGamal_CalcPubKey(newCtx->pubKey, newCtx->prvKey, optimizer); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } ELGAMAL_FREE_PARA(ctx->para); ELGAMAL_FREE_PRV_KEY(ctx->prvKey); ELGAMAL_FREE_PUB_KEY(ctx->pubKey); BSL_SAL_ReferencesFree(&(newCtx->references)); ctx->prvKey = newCtx->prvKey; ctx->pubKey = newCtx->pubKey; ctx->para = newCtx->para; BSL_SAL_FREE(newCtx); BN_OptimizerDestroy(optimizer); return ret; ERR: CRYPT_ELGAMAL_FreeCtx(newCtx); BN_OptimizerDestroy(optimizer); return ret; } #endif // HITLS_CRYPTO_ELGAMAL
2302_82127028/openHiTLS-examples_1508
crypto/elgamal/src/elgamal_keygen.c
C
unknown
16,119
/* * 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_ELGAMAL #include "crypt_types.h" #include "crypt_elgamal.h" #include "crypt_utils.h" #include "bsl_err_internal.h" #include "elgamal_local.h" #include "crypt_errno.h" #include "securec.h" #include "bsl_sal.h" #include "crypt_params_key.h" #define PARAMISNULL(a) (a == NULL || a->value == NULL) static int32_t SetPrvPara(const CRYPT_ELGAMAL_PrvKey *prvKey, const CRYPT_ElGamalPrv *prv) { int32_t ret = BN_Bin2Bn(prvKey->p, prv->p, prv->pLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } uint32_t bnBits = BN_Bits(prvKey->p); if (bnBits > ELGAMAL_MAX_MODULUS_BITS || bnBits <= 0) { BSL_ERR_PUSH_ERROR(CRYPT_ELGAMAL_ERR_KEY_BITS); return CRYPT_ELGAMAL_ERR_KEY_BITS; } ret = BN_Bin2Bn(prvKey->g, prv->g, prv->gLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BN_Bin2Bn(prvKey->x, prv->x, prv->xLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } return ret; } int32_t CRYPT_ELGAMAL_SetPrvKey(CRYPT_ELGAMAL_Ctx *ctx, const CRYPT_ElGamalPrv *prv) { if (ctx == NULL || prv == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (prv->p == NULL || prv->g == NULL || prv->x == NULL || prv->pLen == 0 || prv->gLen == 0 || prv->xLen == 0) { BSL_ERR_PUSH_ERROR(CRYPT_ELGAMAL_ERR_INPUT_VALUE); return CRYPT_ELGAMAL_ERR_INPUT_VALUE; } int32_t ret = CRYPT_SUCCESS; CRYPT_ELGAMAL_Ctx *newCtx = CRYPT_ELGAMAL_NewCtx(); if (newCtx == NULL) { return CRYPT_MEM_ALLOC_FAIL; } newCtx->prvKey = ElGamal_NewPrvKey(prv->pLen * 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; } ret = SetPrvPara(newCtx->prvKey, prv); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } ELGAMAL_FREE_PRV_KEY(ctx->prvKey); ctx->prvKey = newCtx->prvKey; BSL_SAL_ReferencesFree(&(newCtx->references)); BSL_SAL_FREE(newCtx); return ret; ERR: CRYPT_ELGAMAL_FreeCtx(newCtx); return ret; } int32_t CRYPT_ELGAMAL_SetPubKey(CRYPT_ELGAMAL_Ctx *ctx, const CRYPT_ElGamalPub *pub) { if (ctx == NULL || pub == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (pub->p == NULL || pub->g == NULL || pub->y == NULL || pub->q == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } int32_t ret = CRYPT_SUCCESS; CRYPT_ELGAMAL_PubKey *newPub = NULL; /* Bit length is obtained by multiplying byte length by 8. */ newPub = ElGamal_NewPubKey(pub->pLen * 8); if (newPub == NULL) { return CRYPT_MEM_ALLOC_FAIL; } GOTO_ERR_IF(BN_Bin2Bn(newPub->p, pub->p, pub->pLen), ret); uint32_t bnBits = BN_Bits(newPub->p); if (bnBits > ELGAMAL_MAX_MODULUS_BITS || bnBits <= 0) { ret = CRYPT_ELGAMAL_ERR_KEY_BITS; BSL_ERR_PUSH_ERROR(ret); goto ERR; } GOTO_ERR_IF(BN_Bin2Bn(newPub->g, pub->g, pub->gLen), ret); GOTO_ERR_IF(BN_Bin2Bn(newPub->y, pub->y, pub->yLen), ret); GOTO_ERR_IF(BN_Bin2Bn(newPub->q, pub->q, pub->qLen), ret); ELGAMAL_FREE_PUB_KEY(ctx->pubKey); ctx->pubKey = newPub; return ret; ERR: ELGAMAL_FREE_PUB_KEY(newPub); return ret; } int32_t CRYPT_ELGAMAL_GetPrvKey(const CRYPT_ELGAMAL_Ctx *ctx, CRYPT_ElGamalPrv *prv) { if (ctx == NULL || ctx->prvKey == NULL || prv == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (prv->x == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_ELGAMAL_ERR_INPUT_VALUE); return CRYPT_ELGAMAL_ERR_INPUT_VALUE; } int32_t ret = CRYPT_SUCCESS; if (prv->p != NULL) { GOTO_ERR_IF(BN_Bn2Bin(ctx->prvKey->p, prv->p, &(prv->pLen)), ret); } if (prv->g != NULL) { GOTO_ERR_IF(BN_Bn2Bin(ctx->prvKey->g, prv->g, &(prv->gLen)), ret); } GOTO_ERR_IF(BN_Bn2Bin(ctx->prvKey->x, prv->x, &(prv->xLen)), ret); return CRYPT_SUCCESS; ERR: BSL_SAL_CleanseData(prv->p, prv->pLen); BSL_SAL_CleanseData(prv->g, prv->gLen); BSL_SAL_CleanseData(prv->x, prv->xLen); prv->pLen = 0; prv->gLen = 0; prv->xLen = 0; return ret; } int32_t CRYPT_ELGAMAL_GetPubKey(const CRYPT_ELGAMAL_Ctx *ctx, CRYPT_ElGamalPub *pub) { if (ctx == NULL || ctx->pubKey == NULL || pub == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (pub->p == NULL || pub->g == NULL || pub->y == NULL || pub->q == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } int32_t ret; GOTO_ERR_IF(BN_Bn2Bin(ctx->pubKey->g, pub->g, &(pub->gLen)), ret); GOTO_ERR_IF(BN_Bn2Bin(ctx->pubKey->p, pub->p, &(pub->pLen)), ret); GOTO_ERR_IF(BN_Bn2Bin(ctx->pubKey->q, pub->q, &(pub->qLen)), ret); GOTO_ERR_IF(BN_Bn2Bin(ctx->pubKey->y, pub->y, &(pub->yLen)), ret); return CRYPT_SUCCESS; ERR: BSL_SAL_CleanseData(pub->g, pub->gLen); BSL_SAL_CleanseData(pub->p, pub->pLen); BSL_SAL_CleanseData(pub->q, pub->qLen); BSL_SAL_CleanseData(pub->y, pub->yLen); pub->gLen = 0; pub->pLen = 0; pub->qLen = 0; pub->yLen = 0; return ret; } #ifdef HITLS_BSL_PARAMS int32_t CRYPT_ELGAMAL_SetPrvKeyEx(CRYPT_ELGAMAL_Ctx *ctx, const BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_ElGamalPrv elGamalPara = {0}; (void)GetConstParamValue(para, CRYPT_PARAM_ELGAMAL_P, &(elGamalPara.p), &(elGamalPara.pLen)); (void)GetConstParamValue(para, CRYPT_PARAM_ELGAMAL_G, &(elGamalPara.g), &(elGamalPara.gLen)); (void)GetConstParamValue(para, CRYPT_PARAM_ELGAMAL_X, &(elGamalPara.x), &(elGamalPara.xLen)); return CRYPT_ELGAMAL_SetPrvKey(ctx, &elGamalPara); } int32_t CRYPT_ELGAMAL_SetPubKeyEx(CRYPT_ELGAMAL_Ctx *ctx, const BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_ElGamalPub elGamalPara = {0}; (void)GetConstParamValue(para, CRYPT_PARAM_ELGAMAL_P, &(elGamalPara.p), &(elGamalPara.pLen)); (void)GetConstParamValue(para, CRYPT_PARAM_ELGAMAL_G, &(elGamalPara.g), &(elGamalPara.gLen)); (void)GetConstParamValue(para, CRYPT_PARAM_ELGAMAL_Y, &(elGamalPara.y), &(elGamalPara.yLen)); (void)GetConstParamValue(para, CRYPT_PARAM_ELGAMAL_Q, &(elGamalPara.q), &(elGamalPara.qLen)); return CRYPT_ELGAMAL_SetPubKey(ctx, &elGamalPara); } int32_t CRYPT_ELGAMAL_GetPrvKeyEx(const CRYPT_ELGAMAL_Ctx *ctx, BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_ElGamalPrv prv = {0}; BSL_Param *paramP = GetParamValue(para, CRYPT_PARAM_ELGAMAL_P, &prv.p, &prv.pLen); BSL_Param *paramG = GetParamValue(para, CRYPT_PARAM_ELGAMAL_G, &prv.g, &prv.gLen); BSL_Param *paramX = GetParamValue(para, CRYPT_PARAM_ELGAMAL_X, &prv.x, &prv.xLen); int32_t ret = CRYPT_ELGAMAL_GetPrvKey(ctx, &prv); if (ret != CRYPT_SUCCESS) { return ret; } if (paramP != NULL) { paramP->useLen = prv.pLen; } if (paramG != NULL) { paramG->useLen = prv.gLen; } paramX->useLen = prv.xLen; return CRYPT_SUCCESS; } int32_t CRYPT_ELGAMAL_GetPubKeyEx(const CRYPT_ELGAMAL_Ctx *ctx, BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_ElGamalPub pub = {0}; BSL_Param *paramP = GetParamValue(para, CRYPT_PARAM_ELGAMAL_P, &pub.p, &pub.pLen); BSL_Param *paramG = GetParamValue(para, CRYPT_PARAM_ELGAMAL_G, &pub.g, &pub.gLen); BSL_Param *paramY = GetParamValue(para, CRYPT_PARAM_ELGAMAL_Y, &pub.y, &pub.yLen); BSL_Param *paramQ = GetParamValue(para, CRYPT_PARAM_ELGAMAL_Q, &pub.q, &pub.qLen); int32_t ret = CRYPT_ELGAMAL_GetPubKey(ctx, &pub); if (ret != CRYPT_SUCCESS) { return ret; } paramP->useLen = pub.pLen; paramG->useLen = pub.gLen; paramY->useLen = pub.yLen; paramQ->useLen = pub.qLen; return ret; } #endif int32_t CRYPT_ELGAMAL_GetSecBits(const CRYPT_ELGAMAL_Ctx *ctx) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return 0; } int32_t bits = (int32_t)CRYPT_ELGAMAL_GetBits(ctx); return BN_SecBits(bits, -1); } #endif /* HITLS_CRYPTO_ELGAMAL */
2302_82127028/openHiTLS-examples_1508
crypto/elgamal/src/elgamal_keyop.c
C
unknown
9,209
/* * 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 ELGAMAL_LOCAL_H #define ELGAMAL_LOCAL_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_ELGAMAL #include "crypt_elgamal.h" #include "crypt_bn.h" #include "crypt_local_types.h" #include "crypt_types.h" #include "sal_atomic.h" #ifdef __cplusplus extern "C" { #endif /* __cpluscplus */ typedef struct { BN_BigNum *p; // prime factor p BN_BigNum *g; // primitive root of p BN_BigNum *y; // y = g^x (mod p) BN_BigNum *q; // prime factor q } CRYPT_ELGAMAL_PubKey; typedef struct { BN_BigNum *p; // prime factor p BN_BigNum *g; // primitive root of g BN_BigNum *x; // pub key x needed for decryption } CRYPT_ELGAMAL_PrvKey; struct ELGAMAL_Para { BN_BigNum *q; // prime factor q uint32_t k_bits; // security parameter k uint32_t bits; // length in bits of modulus }; struct ELGAMAL_Ctx { CRYPT_ELGAMAL_PubKey *pubKey; CRYPT_ELGAMAL_PrvKey *prvKey; CRYPT_ELGAMAL_Para *para; BSL_SAL_RefCount references; void *libCtx; }; CRYPT_ELGAMAL_PrvKey *ElGamal_NewPrvKey(uint32_t bits); CRYPT_ELGAMAL_PubKey *ElGamal_NewPubKey(uint32_t bits); void ELGAMAL_FreePrvKey(CRYPT_ELGAMAL_PrvKey *prvKey); void ELGAMAL_FreePubKey(CRYPT_ELGAMAL_PubKey *pubKey); CRYPT_ELGAMAL_Para *CRYPT_ElGamal_DupPara(const CRYPT_ELGAMAL_Para *para); #define ELGAMAL_FREE_PRV_KEY(prvKey_) \ do { \ ELGAMAL_FreePrvKey((prvKey_)); \ (prvKey_) = NULL; \ } while (0) #define ELGAMAL_FREE_PUB_KEY(pubKey_) \ do { \ ELGAMAL_FreePubKey((pubKey_)); \ (pubKey_) = NULL; \ } while (0) #define ELGAMAL_FREE_PARA(para_) \ do { \ CRYPT_ELGAMAL_FreePara((para_)); \ (para_) = NULL; \ } while (0) #ifdef __cplusplus } #endif #endif // HITLS_CRYPTO_ELGAMAL #endif // ELGAMAL_LOCAL_H
2302_82127028/openHiTLS-examples_1508
crypto/elgamal/src/elgamal_local.h
C
unknown
2,461
/* * 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_ELGAMAL #include <stdbool.h> #include "securec.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "crypt_errno.h" #include "crypt_elgamal.h" #include "elgamal_local.h" #include "crypt_utils.h" #include "crypt_params_key.h" int32_t OriginalRoot(void *libCtx, BN_BigNum *g, const BN_BigNum *p, const BN_BigNum *q, uint32_t bits) { if (g == NULL || p == NULL || q == NULL ) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } BN_Optimizer *optimizer = BN_OptimizerCreate(); if (optimizer == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = CRYPT_MEM_ALLOC_FAIL; BN_BigNum *x1 = BN_Create(bits); BN_BigNum *x2 = BN_Create(bits); BN_BigNum *xTop = BN_Create(bits); if (x1 == NULL || x2 == NULL || xTop == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); goto EXIT; } ret = BN_SubLimb(xTop, p, 1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } while (true) { ret = BN_RandRangeEx(libCtx, g, xTop); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BN_ModSqr(x1, g, p, optimizer); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } if (BN_IsOne(x1)) { continue; } ret = BN_ModExp(x2, g, q, p, optimizer); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } if (!BN_IsOne(x2)) { break; } } EXIT: BN_Destroy(xTop); BN_Destroy(x2); BN_Destroy(x1); BN_OptimizerDestroy(optimizer); return ret; } #endif /* HITLS_CRYPTO_ELGAMAL */
2302_82127028/openHiTLS-examples_1508
crypto/elgamal/src/originalroot.c
C
unknown
2,409
/* * 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_ENCODE_INTERNAL_H #define CRYPT_ENCODE_INTERNAL_H #include "hitls_build.h" #include "bsl_types.h" #include "bsl_asn1_internal.h" #include "crypt_bn.h" #include "crypt_eal_pkey.h" #ifdef __cplusplus extern "C" { #endif /* __cpluscplus */ #if defined(HITLS_CRYPTO_SM2_SIGN) || defined(HITLS_CRYPTO_DSA) || defined(HITLS_CRYPTO_ECDSA) /** * Get the maximum length of the signature data. * * @param rLen [in] The length of r. * @param sLen [in] The length of s. * @param maxLen [out] The maximum length of the signature data. * @return: CRYPT_SUCCESS: Success, other: Error. */ int32_t CRYPT_EAL_GetSignEncodeLen(uint32_t rLen, uint32_t sLen, uint32_t *maxLen); /** * Encode the signature data by big number. * * @param r [in] The r value. * @param s [in] The s value. * @param encode [out] The encoded data. * @param encodeLen [out] The length of the encoded data. * @return: CRYPT_SUCCESS: Success, other: Error. */ int32_t CRYPT_EAL_EncodeSign(const BN_BigNum *r, const BN_BigNum *s, uint8_t *encode, uint32_t *encodeLen); /** * Decode the signature data to big number. * * @param encode [in] The encoded data. * @param encodeLen [in] The length of the encoded data. * @param r [out] The r value. * @param s [out] The s value. * @return: CRYPT_SUCCESS: Success, other: Error. */ int32_t CRYPT_EAL_DecodeSign(const uint8_t *encode, uint32_t encodeLen, BN_BigNum *r, BN_BigNum *s); #endif #ifdef HITLS_CRYPTO_SM2_CRYPT typedef struct { uint8_t *x; // XCoordinate uint8_t *y; // YCoordinate uint8_t *hash; // HASH uint8_t *cipher; // CipherText uint32_t xLen; uint32_t yLen; uint32_t hashLen; uint32_t cipherLen; } CRYPT_SM2_EncryptData; /** * Get the length of the SM2 encoded data. * * @param xLen [in] The length of the x coordinate. * @param yLen [in] The length of the y coordinate. * @param hashLen [in] The length of the hash. * @param dataLen [in] The length of the data. * @param maxLen [out] The length of the SM2 encoded data. * @return: CRYPT_SUCCESS: Success, other: Error. */ int32_t CRYPT_EAL_GetSm2EncryptDataEncodeLen(uint32_t xLen, uint32_t yLen, uint32_t hashLen, uint32_t dataLen, uint32_t *maxLen); /** * Encode the SM2 encrypt data. * * @param data [in] The SM2 encrypt data. * @param encode [out] The encoded data. * @param encodeLen [out] The length of the encoded data. * @return: CRYPT_SUCCESS: Success, other: Error. */ int32_t CRYPT_EAL_EncodeSm2EncryptData(const CRYPT_SM2_EncryptData *data, uint8_t *encode, uint32_t *encodeLen); /** * Decode the SM2 encrypt data. * * @param encode [in] The encoded data. * @param encodeLen [in] The length of the encoded data. * @param data [out] The SM2 encrypt data. * @return: CRYPT_SUCCESS: Success, other: Error. */ int32_t CRYPT_EAL_DecodeSm2EncryptData(const uint8_t *encode, uint32_t encodeLen, CRYPT_SM2_EncryptData *data); #endif #ifdef __cplusplus } #endif #endif // CRYPT_ENCODE_INTERNAL_H
2302_82127028/openHiTLS-examples_1508
crypto/encode/include/crypt_encode_internal.h
C
unknown
3,539
/* * 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_SIGN) || defined(HITLS_CRYPTO_DSA) || defined(HITLS_CRYPTO_ECDSA) || \ defined(HITLS_CRYPTO_SM2_CRYPT) #include "securec.h" #include "crypt_errno.h" #include "bsl_err_internal.h" #include "bsl_obj_internal.h" #include "crypt_encode_internal.h" #include "bsl_asn1_internal.h" /** * Common function to encode ASN.1 template and copy result */ static int32_t EncodeAsn1Template(BSL_ASN1_Template *templ, BSL_ASN1_Buffer *asnArr, uint32_t asnArrLen, uint8_t *encode, uint32_t *encodeLen) { uint8_t *outBuf = NULL; uint32_t outLen = 0; int32_t ret = BSL_ASN1_EncodeTemplate(templ, asnArr, asnArrLen, &outBuf, &outLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (outLen > *encodeLen) { BSL_SAL_Free(outBuf); BSL_ERR_PUSH_ERROR(CRYPT_ENCODE_BUFF_NOT_ENOUGH); return CRYPT_ENCODE_BUFF_NOT_ENOUGH; } (void)memcpy_s(encode, *encodeLen, outBuf, outLen); BSL_SAL_Free(outBuf); *encodeLen = outLen; return CRYPT_SUCCESS; } /** * Common function to decode ASN.1 template and check remaining length */ static int32_t DecodeAsn1Template(const uint8_t *encode, uint32_t encodeLen, BSL_ASN1_Template *templ, BSL_ASN1_Buffer *asnArr, uint32_t asnArrLen) { uint8_t *tmpEnc = (uint8_t *)(uintptr_t)encode; uint32_t tmpEncLen = encodeLen; int32_t ret = BSL_ASN1_DecodeTemplate(templ, NULL, &tmpEnc, &tmpEncLen, asnArr, asnArrLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (tmpEncLen != 0) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ASN1_BUFF_FAILED); return CRYPT_DECODE_ASN1_BUFF_FAILED; } for (uint32_t i = 0; i < asnArrLen; i++) { if (asnArr[i].len == 0) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ASN1_BUFF_LEN_ZERO); return CRYPT_DECODE_ASN1_BUFF_LEN_ZERO; } } return CRYPT_SUCCESS; } #if defined(HITLS_CRYPTO_SM2_SIGN) || defined(HITLS_CRYPTO_DSA) || defined(HITLS_CRYPTO_ECDSA) int32_t CRYPT_EAL_GetSignEncodeLen(uint32_t rLen, uint32_t sLen, uint32_t *maxLen) { /** * https://docs.microsoft.com/en-us/windows/win32/seccertenroll/about-integer * If the integer is positive but the high order bit is set to 1, * a leading 0x00 is added to the content to indicate that the number is not negative */ if (rLen == 0 || rLen > UINT32_MAX - 1 || sLen == 0 || sLen > UINT32_MAX - 1 || maxLen == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } uint32_t rEncodeLen = 0; uint32_t sEncodeLen = 0; int32_t ret = BSL_ASN1_GetEncodeLen(rLen + 1, &rEncodeLen); // + 1: if high bit is 1, should add a leading 0x00 if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BSL_ASN1_GetEncodeLen(sLen + 1, &sEncodeLen); // + 1: if high bit is 1, should add a leading 0x00 if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (rEncodeLen > UINT32_MAX - sEncodeLen) { BSL_ERR_PUSH_ERROR(CRYPT_ENCODE_ERR_SIGN_LEN_OVERFLOW); return CRYPT_ENCODE_ERR_SIGN_LEN_OVERFLOW; } ret = BSL_ASN1_GetEncodeLen(rEncodeLen + sEncodeLen, maxLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static BSL_ASN1_TemplateItem g_signTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, {BSL_ASN1_TAG_INTEGER, 0, 1}, {BSL_ASN1_TAG_INTEGER, 0, 1}, }; static int32_t CheckSignBnParams(const BN_BigNum *r, const BN_BigNum *s, uint8_t *encode, uint32_t *encodeLen) { if (r == NULL || s == NULL || encode == NULL || encodeLen == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } // The big number must be non-negative. if (BN_IsNegative(r) || BN_IsNegative(s)) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } // The big number must be non-zero. if (BN_IsZero(r) || BN_IsZero(s)) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } return CRYPT_SUCCESS; } static int32_t ConvertBNToBuffer(const BN_BigNum *bn, uint8_t **outBuf, uint32_t *outLen) { uint32_t len = BN_Bytes(bn); uint8_t *buf = (uint8_t *)BSL_SAL_Malloc(len); if (buf == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = BN_Bn2Bin(bn, buf, &len); if (ret != CRYPT_SUCCESS) { BSL_SAL_Free(buf); BSL_ERR_PUSH_ERROR(ret); return ret; } *outBuf = buf; *outLen = len; return CRYPT_SUCCESS; } int32_t CRYPT_EAL_EncodeSign(const BN_BigNum *r, const BN_BigNum *s, uint8_t *encode, uint32_t *encodeLen) { int32_t ret = CheckSignBnParams(r, s, encode, encodeLen); if (ret != CRYPT_SUCCESS) { return ret; } uint8_t *rBuf = NULL; uint8_t *sBuf = NULL; uint32_t rLen = 0; uint32_t sLen = 0; // Prepare the buffer for r. ret = ConvertBNToBuffer(r, &rBuf, &rLen); if (ret != CRYPT_SUCCESS) { return ret; // no need to push err } // Prepare the buffer for s. ret = ConvertBNToBuffer(s, &sBuf, &sLen); if (ret != CRYPT_SUCCESS) { BSL_SAL_Free(rBuf); return ret; // no need to push err } BSL_ASN1_Buffer asnArr[2] = { {BSL_ASN1_TAG_INTEGER, rLen, rBuf}, {BSL_ASN1_TAG_INTEGER, sLen, sBuf} }; BSL_ASN1_Template templ = {g_signTempl, sizeof(g_signTempl) / sizeof(g_signTempl[0])}; ret = EncodeAsn1Template(&templ, asnArr, 2, encode, encodeLen); BSL_SAL_Free(rBuf); BSL_SAL_Free(sBuf); return ret; } int32_t CRYPT_EAL_DecodeSign(const uint8_t *encode, uint32_t encodeLen, BN_BigNum *r, BN_BigNum *s) { if (encode == NULL || encodeLen == 0 || r == NULL || s == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } // Decode ASN.1 sequence to get r and s components BSL_ASN1_Buffer asnArr[2] = {0}; // 2: r and s BSL_ASN1_Template templ = {g_signTempl, sizeof(g_signTempl) / sizeof(g_signTempl[0])}; int32_t ret = DecodeAsn1Template(encode, encodeLen, &templ, asnArr, 2); // 2: r and s if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // Convert decoded buffers to big numbers ret = BN_Bin2Bn(r, asnArr[0].buff, asnArr[0].len); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BN_Bin2Bn(s, asnArr[1].buff, asnArr[1].len); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif #ifdef HITLS_CRYPTO_SM2_CRYPT int32_t CRYPT_EAL_GetSm2EncryptDataEncodeLen(uint32_t xLen, uint32_t yLen, uint32_t hashLen, uint32_t dataLen, uint32_t *maxLen) { if (maxLen == NULL || xLen > UINT32_MAX - 1 || yLen > UINT32_MAX - 1) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } uint32_t xEncodeLen = 0; uint32_t yEncodeLen = 0; uint32_t hashEncodeLen = 0; uint32_t cipherEncodeLen = 0; int32_t ret = BSL_ASN1_GetEncodeLen(xLen + 1, &xEncodeLen); // + 1: if high bit is 1, should add a leading 0x00 if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BSL_ASN1_GetEncodeLen(yLen + 1, &yEncodeLen); // + 1: if high bit is 1, should add a leading 0x00 if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BSL_ASN1_GetEncodeLen(hashLen, &hashEncodeLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BSL_ASN1_GetEncodeLen(dataLen, &cipherEncodeLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (xEncodeLen > UINT32_MAX - yEncodeLen || (xEncodeLen + yEncodeLen) > UINT32_MAX - hashEncodeLen || (xEncodeLen + yEncodeLen + hashEncodeLen) > UINT32_MAX - cipherEncodeLen) { BSL_ERR_PUSH_ERROR(CRYPT_ENCODE_ERR_SM2_ENCRYPT_DATA_LEN_OVERFLOW); return CRYPT_ENCODE_ERR_SM2_ENCRYPT_DATA_LEN_OVERFLOW; } // Calculate the total length of the encoded data ret = BSL_ASN1_GetEncodeLen(xEncodeLen + yEncodeLen + hashEncodeLen + cipherEncodeLen, maxLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } /** * Reference: GM/T 0009-2012 7.2 * Define template for SM2 encryption data structure: * SM2Cipher ::= SEQUENCE { * XCoordinate INTEGER, * YCoordinate INTEGER, * HASH OCTET STRING SIZE(32), * CipherText OCTET STRING * } */ static BSL_ASN1_TemplateItem g_sm2EncryptTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, {BSL_ASN1_TAG_INTEGER, 0, 1}, // x coordinate {BSL_ASN1_TAG_INTEGER, 0, 1}, // y coordinate {BSL_ASN1_TAG_OCTETSTRING, 0, 1}, // hash (c3) {BSL_ASN1_TAG_OCTETSTRING, 0, 1} // ciphertext (c2) }; #define SM2_ENCRYPT_DATA_ITEM_NUM 4 int32_t CheckSm2EncryptData(const CRYPT_SM2_EncryptData *data) { if (data == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } // Check x and y coordinate if (data->x == NULL || data->xLen == 0 || data->y == NULL || data->yLen == 0) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } // Check hash if (data->hash == NULL || data->hashLen == 0) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } // Check cipher if (data->cipher == NULL || data->cipherLen == 0) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } return CRYPT_SUCCESS; } int32_t CRYPT_EAL_EncodeSm2EncryptData(const CRYPT_SM2_EncryptData *data, uint8_t *encode, uint32_t *encodeLen) { int32_t ret = CheckSm2EncryptData(data); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (encode == NULL || encodeLen == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } BSL_ASN1_Buffer asnArr[SM2_ENCRYPT_DATA_ITEM_NUM] = { {BSL_ASN1_TAG_INTEGER, data->xLen, data->x}, // x coordinate {BSL_ASN1_TAG_INTEGER, data->yLen, data->y}, // y coordinate {BSL_ASN1_TAG_OCTETSTRING, data->hashLen, data->hash}, // hash {BSL_ASN1_TAG_OCTETSTRING, data->cipherLen, data->cipher} // ciphertext }; BSL_ASN1_Template templ = {g_sm2EncryptTempl, sizeof(g_sm2EncryptTempl) / sizeof(g_sm2EncryptTempl[0])}; return EncodeAsn1Template(&templ, asnArr, SM2_ENCRYPT_DATA_ITEM_NUM, encode, encodeLen); } int32_t CRYPT_EAL_DecodeSm2EncryptData(const uint8_t *encode, uint32_t encodeLen, CRYPT_SM2_EncryptData *data) { int32_t ret = CheckSm2EncryptData(data); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (encode == NULL || encodeLen == 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } BSL_ASN1_Buffer asnArr[SM2_ENCRYPT_DATA_ITEM_NUM] = {0}; BSL_ASN1_Template templ = {g_sm2EncryptTempl, sizeof(g_sm2EncryptTempl) / sizeof(g_sm2EncryptTempl[0])}; ret = DecodeAsn1Template(encode, encodeLen, &templ, asnArr, SM2_ENCRYPT_DATA_ITEM_NUM); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // Validate lengths if (asnArr[0].len > data->xLen || asnArr[1].len > data->yLen || asnArr[2].len > data->hashLen || // 2: hash asnArr[3].len > data->cipherLen) { // 3: cipher BSL_ERR_PUSH_ERROR(CRYPT_DECODE_BUFF_NOT_ENOUGH); return CRYPT_DECODE_BUFF_NOT_ENOUGH; } // 1: point xy (void)memcpy_s(data->x + (data->xLen - asnArr[0].len), asnArr[0].len, asnArr[0].buff, asnArr[0].len); (void)memcpy_s(data->y + (data->yLen - asnArr[1].len), asnArr[1].len, asnArr[1].buff, asnArr[1].len); (void)memcpy_s(data->hash, data->hashLen, asnArr[2].buff, asnArr[2].len); // 2: hash (void)memcpy_s(data->cipher, data->cipherLen, asnArr[3].buff, asnArr[3].len); // 3: cipher data->hashLen = asnArr[2].len; // 2: hash data->cipherLen = asnArr[3].len; // 3: cipher return CRYPT_SUCCESS; } #endif // HITLS_CRYPTO_SM2_CRYPT #endif
2302_82127028/openHiTLS-examples_1508
crypto/encode/src/crypt_encode.c
C
unknown
13,107
/* * 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_ENTROPY_H #define CRYPT_ENTROPY_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_ENTROPY #include <stdint.h> #include <stdbool.h> #include "crypt_types.h" #ifdef __cplusplus extern "C" { #endif /** * drbg1 drbg2 drbg3 drbgi * * * * * * * * * * * * * * * * * * * * get-entropy * * * parent-drbg * * * get-entropy * * * seed-pool * * * * * * * * * * * * * * * * * * * * hard-ES sys-ES hitls-ES ES(add-in) * * * entropy-pool * * * CF/LFST * * * * * * * * * * * * * * * * * * * * timestamp-NS jitter-NS interrup-NS NS(add-in) */ #ifdef HITLS_CRYPTO_ENTROPY_SYS typedef struct ES_Entropy ENTROPY_EntropySource; typedef struct { uint32_t algId; void *md; } ENTROPY_CFPara; /* Entropy source model APIs provided by HiTLS. */ /* Creating an entropy source. */ ENTROPY_EntropySource *ENTROPY_EsNew(void); /* release entropy source. */ void ENTROPY_EsFree(ENTROPY_EntropySource *ctx); /* Initialize Entropy Source. */ int32_t ENTROPY_EsInit(ENTROPY_EntropySource *ctx); /* Deinitialize the entropy source. */ void ENTROPY_EsDeinit(ENTROPY_EntropySource *ctx); /* Interface for Setting the Entropy Source. */ int32_t ENTROPY_EsCtrl(ENTROPY_EntropySource *ctx, int32_t cmd, void *data, uint32_t len); /* Obtaining Entropy Data. */ uint32_t ENTROPY_EsEntropyGet(ENTROPY_EntropySource *ctx, uint8_t *data, uint32_t len); /* Collect entropy data. */ int32_t ENTROPY_EsEntropyGather(ENTROPY_EntropySource *es); #endif typedef struct EntropySeedPool ENTROPY_SeedPool; typedef uint32_t (*EntropyGet)(void *ctx, uint8_t *buf, uint32_t bufLen); /* create seed-pool handles */ ENTROPY_SeedPool *ENTROPY_SeedPoolNew(bool isCreateNullPool); /* Adding an entropy source */ int32_t ENTROPY_SeedPoolAddEs(ENTROPY_SeedPool *pool, const CRYPT_EAL_EsPara *para); /* Interface for releasing the seed pool */ void ENTROPY_SeedPoolFree(ENTROPY_SeedPool *pool); /* Interface for collecting entropy data */ uint32_t ENTROPY_SeedPoolCollect(ENTROPY_SeedPool *pool, bool isNpesUsed, uint32_t needEntropy, uint8_t *data, uint32_t *len); /* Check whether the seed pool contains physical or non-physical entropy sources. */ bool ENTROPY_SeedPoolCheckState(ENTROPY_SeedPool *seedPool, bool isNpesUsed); /* Obtains the minimum entropy of the entropy source. */ uint32_t ENTROPY_SeedPoolGetMinEntropy(ENTROPY_SeedPool *seedPool); typedef int32_t (*ExternalConditioningFunction)(uint32_t algId, uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); typedef struct EcfCtx { uint32_t algId; uint32_t outLen; ExternalConditioningFunction conFunc; } ENTROPY_ECFCtx; /** * @brief Obtain full entropy bits * * @param ctx[IN] ecfCtx * @param pool[IN] seed pool * @param isNpesUsed[IN] whether the npes is available * @param needEntropy[IN] the amount of entropy required * @param data[OUT] data * @param len[IN] length * @return Success: CRYPT_SUCCESS */ int32_t ENTROPY_GetFullEntropyInput(void *ctx, ENTROPY_SeedPool *pool, bool isNpesUsed, uint32_t needEntropy, uint8_t *data, uint32_t len); #ifdef __cplusplus } #endif #endif // HITLS_CRYPTO_ENTROPY #endif // CRYPT_ENTROPY_H
2302_82127028/openHiTLS-examples_1508
crypto/entropy/include/crypt_entropy.h
C
unknown
4,464
/* * 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_ENTROPY #include <stdint.h> #include "securec.h" #include "bsl_err_internal.h" #include "bsl_sal.h" #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_utils.h" #include "crypt_entropy.h" #define ECF_MAX_OUTPUT_LEN 64 #define ECF_ADDITION_ENTROPY 64 // reference nist-800 90c-3pd section 3.3.2 #define ECF_BYTE_TO_BIT 8 static int32_t EntropyEcf(ENTROPY_ECFCtx *enCtx, uint8_t *data, uint32_t dataLen, uint8_t *out, uint32_t *outLen) { uint8_t conData[ECF_MAX_OUTPUT_LEN] = {0}; uint32_t conLen = ECF_MAX_OUTPUT_LEN; int32_t ret = enCtx->conFunc(enCtx->algId, data, dataLen, conData, &conLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } uint32_t cpLen = (conLen > *outLen) ? *outLen : conLen; (void)memcpy_s(out, cpLen, conData, cpLen); (void)memset_s(conData, conLen, 0, conLen); *outLen = cpLen; return CRYPT_SUCCESS; } int32_t ENTROPY_GetFullEntropyInput(void *ctx, ENTROPY_SeedPool *pool, bool isNpesUsed, uint32_t needEntropy, uint8_t *data, uint32_t len) { int32_t ret = CRYPT_SUCCESS; uint8_t *ptr = data; if (ENTROPY_SeedPoolGetMinEntropy(pool) == 0) { return CRYPT_INVALID_ARG; } ENTROPY_ECFCtx *enCtx = (ENTROPY_ECFCtx *)ctx; if (enCtx == NULL || enCtx->conFunc == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ECF_IS_ERROR); return CRYPT_ENTROPY_ECF_IS_ERROR; } uint32_t conEnt = enCtx->outLen * ECF_BYTE_TO_BIT; uint32_t tmpEntropy = conEnt + ECF_ADDITION_ENTROPY; uint32_t tmpDataLen = (tmpEntropy + ECF_BYTE_TO_BIT - 1) / ENTROPY_SeedPoolGetMinEntropy(pool); uint8_t *tmpData = BSL_SAL_Malloc(tmpDataLen); if (tmpData == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } uint32_t remEnt = needEntropy; uint32_t remLen = len; while (remEnt > 0) { uint32_t tmpLen = tmpDataLen; uint32_t oneEnt = (remEnt < conEnt) ? remEnt : conEnt; uint32_t entropy = ENTROPY_SeedPoolCollect(pool, isNpesUsed, oneEnt, tmpData, &tmpLen); if (entropy < oneEnt) { GOTO_ERR_IF(CRYPT_SEED_POOL_NOT_MEET_REQUIREMENT, ret); } uint32_t cpLen; /* If the data of the length specified by tmpLen can be provided, the value is the full entropy (tmpLen * 8). */ if (tmpLen * ECF_BYTE_TO_BIT == entropy) { cpLen = tmpLen < remLen ? tmpLen : remLen; (void)memcpy_s(ptr, remLen, tmpData, cpLen); remEnt -= ((entropy > remEnt) ? remEnt : entropy); } else { uint32_t leftLen = tmpDataLen - tmpLen; uint32_t leftEnt = ENTROPY_SeedPoolCollect(pool, isNpesUsed, tmpEntropy - entropy, tmpData + tmpLen, &leftLen); if (leftEnt < tmpEntropy - entropy) { GOTO_ERR_IF(CRYPT_SEED_POOL_NOT_MEET_REQUIREMENT, ret); } cpLen = remLen; GOTO_ERR_IF(EntropyEcf(ctx, tmpData, tmpLen + leftLen, ptr, &cpLen), ret); remEnt -= (remEnt < conEnt ? remEnt : conEnt); } ptr += cpLen; remLen -= cpLen; } if (remLen > 0) { uint32_t leftLen = remLen; uint32_t entropy = ENTROPY_SeedPoolCollect(pool, true, 0, ptr, &leftLen); if (entropy == 0 || leftLen < remLen) { GOTO_ERR_IF(CRYPT_SEED_POOL_NOT_MEET_REQUIREMENT, ret); } } ERR: (void)memset_s(tmpData, tmpDataLen, 0, tmpDataLen); BSL_SAL_FREE(tmpData); return ret; } #endif /* HITLS_CRYPTO_ENTROPY */
2302_82127028/openHiTLS-examples_1508
crypto/entropy/src/entropy.c
C
unknown
4,153
/* * 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_ENTROPY #include <stdint.h> #include "securec.h" #include "crypt_utils.h" #include "entropy_seed_pool.h" #ifdef HITLS_CRYPTO_ENTROPY_HARDWARE #if defined(__x86_64__) || defined(__aarch64__) /* For clarity */ #define DRNG_NO_SUPPORT 0x0 #define DRNG_HAS_RDRAND 0x1 #define DRNG_HAS_RDSEED 0x2 #define RDRAND_MAX_RETRIES 20 static uint32_t HWRandBytes(uint8_t *buf, uint32_t len, int32_t (*rand)(uint64_t *), uint32_t retries) { uint32_t left = len; while (left != 0) { uint32_t cnt = 0; uint64_t randVal = 0; while (cnt < retries) { if (rand(&randVal) == 1) { break; } cnt++; } if (cnt == retries) { // high probability that it wouldn't be here return len - left; } uint32_t cpLen = left < sizeof(randVal) ? left : sizeof(randVal); (void)memcpy_s(buf + len - left, left, (uint8_t *)&randVal, cpLen); left -= cpLen; } return len; } #ifdef __x86_64__ #include <cpuid.h> /** * Using Intel/AMD cpu's instructions to get hardware random value. * * references: * https://crypto.stackexchange.com/questions/42340/usage-difference-between-x86-rdrand-and-rdseed * * https://www.intel.com/content/www/us/en/developer/articles/guide/intel- * digital-random-number-generator-drng-software-implementation-guide.html */ /** * If the return value is 1, the variable passed by reference will be populated with a usable random value. * If the return value is 0, the caller understands that the value assigned to the variable is not usable. */ static int32_t Rdrand64(uint64_t *rand) { uint8_t ok = 0; asm volatile("rdrand %0; setc %1" : "=r"(*rand), "=qm"(ok)); return (int32_t)ok; } /** * return value of "Rdseed64" is same to "Rdrand64". */ static int32_t Rdseed64(uint64_t *seed) { uint8_t ok = 0; asm volatile("rdseed %0; setc %1" : "=r"(*seed), "=qm"(ok)); return (int32_t)ok; } #define RAND_BYTES(buf, len) HWRandBytes(buf, len, Rdrand64, RDRAND_MAX_RETRIES) #define SEED_BYTES(buf, len) HWRandBytes(buf, len, Rdseed64, RDRAND_MAX_RETRIES) static uint32_t GetDrbgSupport() { static uint32_t drngCap = 0xffffffff; if (drngCap == 0xffffffff) { drngCap = DRNG_NO_SUPPORT; uint32_t cpuid[CPU_ID_OUT_U32_CNT]; GetCpuId(0x1, 0, cpuid); if (cpuid[ECX_OUT_IDX] & bit_RDRND) { drngCap |= DRNG_HAS_RDRAND; } (void)memset_s(cpuid, sizeof(cpuid), 0, sizeof(cpuid)); GetCpuId(0x7, 0, cpuid); if (cpuid[EBX_OUT_IDX] & bit_RDSEED) { drngCap |= DRNG_HAS_RDSEED; } } return drngCap; } uint32_t ENTROPY_HWEntropyGet(void *ctx, uint8_t *buf, uint32_t bufLen) { (void)ctx; uint32_t drngCap = GetDrbgSupport(); if (drngCap & DRNG_HAS_RDSEED) { return SEED_BYTES(buf, bufLen); } else if (drngCap & DRNG_HAS_RDRAND) { return RAND_BYTES(buf, bufLen); } else { return 0; } } #endif #ifdef __aarch64__ #include <sys/auxv.h> #include "crypt_arm.h" static uint32_t GetDrbgSupport() { static uint32_t drngCap = 0xffffffff; if (drngCap == 0xffffffff) { drngCap = DRNG_NO_SUPPORT; if (getauxval(CRYPT_CAP2) & CRYPT_ARM_CAP2_RNG) { drngCap |= (DRNG_HAS_RDRAND | DRNG_HAS_RDSEED); } } return drngCap; } // https://developer.arm.com/documentation/ddi0601/2024-12/AArch64-Registers/RNDR--Random-Number static int32_t Rndr64(uint64_t *rand) { uint8_t ok = 0; asm volatile("mrs %0, s3_3_c2_c4_0; cset %w1, ne;" : "=r"(*rand), "=r"(ok)); return (int32_t)ok; } // https://developer.arm.com/documentation/ddi0601/2024-12/AArch64-Registers/RNDRRS--Random-Number-Full-Entropy static int32_t Rndrrs64(uint64_t *seed) { uint8_t ok = 0; asm volatile("mrs %0, s3_3_c2_c4_1; cset %w1, ne;" : "=r"(*seed), "=r"(ok)); return (int32_t)ok; } #define RAND_BYTES(buf, len) HWRandBytes(buf, len, Rndr64, RDRAND_MAX_RETRIES) #define SEED_BYTES(buf, len) HWRandBytes(buf, len, Rndrrs64, RDRAND_MAX_RETRIES) uint32_t ENTROPY_HWEntropyGet(void *ctx, uint8_t *buf, uint32_t bufLen) { (void)ctx; uint32_t drngCap = GetDrbgSupport(); if (drngCap & DRNG_HAS_RDSEED) { uint32_t len = SEED_BYTES(buf, bufLen); if (bufLen - len > 0) { len += RAND_BYTES(buf + len, bufLen - len); } return len; } else { return 0; } } #endif #else uint32_t ENTROPY_HWEntropyGet(void *ctx, uint8_t *buf, uint32_t bufLen) { (void)ctx; (void)buf; (void)bufLen; return 0; } #endif #else uint32_t ENTROPY_HWEntropyGet(void *ctx, uint8_t *buf, uint32_t bufLen) { (void)ctx; (void)buf; (void)bufLen; return 0; } #endif #endif
2302_82127028/openHiTLS-examples_1508
crypto/entropy/src/entropy_hardware.c
C
unknown
5,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_ENTROPY #include <stdint.h> #include "securec.h" #include "bsl_err_internal.h" #include "crypt_errno.h" #include "entropy_seed_pool.h" #define SEEDPOOL_ES_MAX_SIZE 16 #define SEEDPOOL_ES_INIT_MINENTROPY 9 #define SEEDPOOL_ES_FULL_MINENTROPY 8 #define SEEDPOOL_ES_SYS_MINENTROPY 7 ENTROPY_SeedPool *ENTROPY_SeedPoolNew(bool isCreateNullPool) { ENTROPY_SeedPool *poolCtx = BSL_SAL_Malloc(sizeof(ENTROPY_SeedPool)); if (poolCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } (void)memset_s(poolCtx, sizeof(ENTROPY_SeedPool), 0, sizeof(ENTROPY_SeedPool)); poolCtx->esList = BSL_LIST_New(sizeof(ENTROPY_Source)); if (poolCtx->esList == NULL) { BSL_SAL_Free(poolCtx); BSL_ERR_PUSH_ERROR(BSL_LIST_MALLOC_FAIL); return NULL; } poolCtx->minEntropy = SEEDPOOL_ES_INIT_MINENTROPY; if (isCreateNullPool) { return poolCtx; } CRYPT_EAL_EsPara para = {false, SEEDPOOL_ES_SYS_MINENTROPY, NULL, ENTROPY_SysEntropyGet}; int32_t ret = ENTROPY_SeedPoolAddEs(poolCtx, &para); if (ret != CRYPT_SUCCESS) { ENTROPY_SeedPoolFree(poolCtx); BSL_ERR_PUSH_ERROR(ret); return NULL; } CRYPT_EAL_EsPara hwPara = {true, SEEDPOOL_ES_FULL_MINENTROPY, NULL, ENTROPY_HWEntropyGet}; ret = ENTROPY_SeedPoolAddEs(poolCtx, &hwPara); if (ret != CRYPT_SUCCESS) { ENTROPY_SeedPoolFree(poolCtx); BSL_ERR_PUSH_ERROR(ret); return NULL; } return poolCtx; } static ENTROPY_Source *SeedPoolEsNew(const CRYPT_EAL_EsPara *para) { ENTROPY_Source *es = BSL_SAL_Malloc(sizeof(ENTROPY_Source)); if (es == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } es->isPhysical = para->isPhysical; es->minEntropy = para->minEntropy; es->ctx = para->entropyCtx; es->entropyGet = (EntropyGet)(para->entropyGet); return es; } int32_t ENTROPY_SeedPoolAddEs(ENTROPY_SeedPool *pool, const CRYPT_EAL_EsPara *para) { if (pool == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (BSL_LIST_COUNT(pool->esList) >= SEEDPOOL_ES_MAX_SIZE) { BSL_ERR_PUSH_ERROR(CRYPT_SEED_POOL_ES_LIST_FULL); return CRYPT_SEED_POOL_ES_LIST_FULL; } ENTROPY_Source *es = SeedPoolEsNew(para); if (es == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_SEED_POOL_NEW_ERROR); return CRYPT_SEED_POOL_NEW_ERROR; } /* * The header insertion method is used to add an entropy source to ensure that the entropy source added by the * invoker is used first when the entropy data is obtained. */ int32_t ret = BSL_LIST_AddElement(pool->esList, es, BSL_LIST_POS_BEFORE); if (ret != CRYPT_SUCCESS) { BSL_SAL_Free(es); BSL_ERR_PUSH_ERROR(ret); return ret; } pool->minEntropy = (pool->minEntropy < para->minEntropy) ? pool->minEntropy : para->minEntropy; pool->isContainFes = pool->isContainFes || (para->minEntropy == SEEDPOOL_ES_FULL_MINENTROPY); pool->isContainPes = pool->isContainPes || para->isPhysical; return CRYPT_SUCCESS; } void ENTROPY_SeedPoolFree(ENTROPY_SeedPool *pool) { if (pool == NULL) { return; } if (pool->esList != NULL) { BSL_LIST_FREE(pool->esList, BSL_SAL_Free); } BSL_SAL_Free(pool); return; } static uint32_t GetMinLen(uint32_t needEntropy, uint32_t currEntropy, uint32_t minEntropy, uint32_t bufLen) { if (needEntropy == 0) { return bufLen; } uint32_t len = (uint32_t)(((uint64_t)(needEntropy - currEntropy) + (uint64_t)minEntropy - 1) / (uint64_t)minEntropy); return bufLen >= len ? len : bufLen; } uint32_t ENTROPY_SeedPoolCollect(ENTROPY_SeedPool *pool, bool isNpesUsed, uint32_t needEntropy, uint8_t *data, uint32_t *len) { if (data == NULL || len == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return 0; } if (!ENTROPY_SeedPoolCheckState(pool, isNpesUsed)) { BSL_ERR_PUSH_ERROR(CRYPT_SEED_POOL_STATE_ERROR); return 0; } uint32_t bufLen = *len; uint8_t *buf = data; uint32_t curEntropy = 0; for (ENTROPY_Source *es = BSL_LIST_GET_FIRST(pool->esList); es != NULL; es = BSL_LIST_GET_NEXT(pool->esList)) { if (!isNpesUsed && !es->isPhysical) { continue; } uint32_t tmpLen = GetMinLen(needEntropy, curEntropy, es->minEntropy, bufLen); uint32_t readLen = es->entropyGet(es->ctx, buf, tmpLen); if (readLen > 0) { bufLen -= readLen; buf += readLen; curEntropy += es->minEntropy * readLen; } bool flag = (needEntropy == 0) ? (bufLen == 0) : (curEntropy >= needEntropy); if (flag) { break; } } *len = buf - data; return curEntropy; } bool ENTROPY_SeedPoolCheckState(ENTROPY_SeedPool *seedPool, bool isNpesUsed) { if (seedPool == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return false; } if (BSL_LIST_COUNT(seedPool->esList) == 0) { BSL_ERR_PUSH_ERROR(CRYPT_SEED_POOL_NO_ENTROPY_SOURCE); return false; } if (!isNpesUsed && !seedPool->isContainPes) { BSL_ERR_PUSH_ERROR(CRYPT_SEED_POOL_NO_ENTROPY_SOURCE); return false; } return true; } uint32_t ENTROPY_SeedPoolGetMinEntropy(ENTROPY_SeedPool *seedPool) { if (seedPool == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return 0; } return seedPool->minEntropy; } #endif
2302_82127028/openHiTLS-examples_1508
crypto/entropy/src/entropy_seed_pool.c
C
unknown
6,326
/* * 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 ENTROPY_SEED_POOL_H #define ENTROPY_SEED_POOL_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_ENTROPY #include <stdint.h> #include "crypt_entropy.h" #include "bsl_list.h" #ifdef __cplusplus extern "C" { #endif typedef struct { bool isPhysical; uint32_t minEntropy; void *ctx; EntropyGet entropyGet; } ENTROPY_Source; struct EntropySeedPool { bool isContainFes; bool isContainPes; uint32_t minEntropy; BslList *esList; }; uint32_t ENTROPY_HWEntropyGet(void *ctx, uint8_t *buf, uint32_t bufLen); uint32_t ENTROPY_SysEntropyGet(void *ctx, uint8_t *buf, uint32_t bufLen); #ifdef __cplusplus } #endif #endif #endif
2302_82127028/openHiTLS-examples_1508
crypto/entropy/src/entropy_seed_pool.h
C
unknown
1,253
/* * 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_ENTROPY #include <stdint.h> #include <unistd.h> #ifdef HITLS_CRYPTO_ENTROPY_GETENTROPY #include <sys/random.h> #endif #ifdef HITLS_CRYPTO_ENTROPY_DEVRANDOM #include <fcntl.h> #include <errno.h> #endif #include "securec.h" #include "bsl_err_internal.h" #include "crypt_errno.h" #include "entropy_seed_pool.h" uint32_t ENTROPY_SysEntropyGet(void *ctx, uint8_t *buf, uint32_t bufLen) { (void)ctx; #if defined(HITLS_CRYPTO_ENTROPY_GETENTROPY) || defined(HITLS_CRYPTO_ENTROPY_DEVRANDOM) uint32_t res = 0; #if defined(HITLS_CRYPTO_ENTROPY_GETENTROPY) if (getentropy(buf, bufLen) == 0) { return bufLen; } #endif #if defined(HITLS_CRYPTO_ENTROPY_DEVRANDOM) int32_t fd = open("/dev/random", O_RDONLY); if (fd == -1) { BSL_ERR_PUSH_ERROR(CRYPT_DRBG_FAIL_GET_ENTROPY); return 0; } uint32_t left = bufLen; uint8_t *tmp = buf; do { int32_t count = (int32_t)read(fd, tmp, left); if (count == -1 && errno == EINTR) { continue; } else if (count == -1) { break; } left -= (uint32_t)count; tmp += (uint32_t)count; } while (left > 0); close(fd); if (left > 0) { BSL_ERR_PUSH_ERROR(CRYPT_DRBG_FAIL_GET_ENTROPY); } res = bufLen - left; #endif return res; #else (void)buf; (void)bufLen; BSL_ERR_PUSH_ERROR(CRYPT_DRBG_FAIL_GET_ENTROPY); return 0; #endif } #endif
2302_82127028/openHiTLS-examples_1508
crypto/entropy/src/entropy_system.c
C
unknown
2,098
/* * 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_ENTROPY) && defined(HITLS_CRYPTO_ENTROPY_SYS) #include <stdint.h> #include "crypt_errno.h" #include "bsl_err_internal.h" #include "es_cf.h" ES_CfMethod *ES_CFGetMethod(uint32_t algId, void *md) { switch (algId) { case CRYPT_MD_SM3: case CRYPT_MD_SHA256: case CRYPT_MD_SHA224: case CRYPT_MD_SHA384: case CRYPT_MD_SHA512: return ES_CFGetDfMethod((EAL_MdMethod *)md); default: BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ECF_ALG_ERROR); return NULL; } } #endif
2302_82127028/openHiTLS-examples_1508
crypto/entropy/src/es_cf.c
C
unknown
1,171
/* * 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 ES_CF_H #define ES_CF_H #include "hitls_build.h" #if defined(HITLS_CRYPTO_ENTROPY) && defined(HITLS_CRYPTO_ENTROPY_SYS) #include <stdint.h> #include "crypt_local_types.h" #ifdef __cplusplus extern "C" { #endif typedef struct { uint32_t algId; union { EAL_MdMethod mdMeth; EAL_SymMethod ciMeth; EAL_MacMethod macMeth; } meth; uint8_t *ctx; /* Conditioning function initialization. */ void *(*init)(void *mdMeth); /* Conditioning Function Conditioning Raw Entropy Output. */ int32_t (*update)(void *ctx, uint8_t *data, uint32_t dataLen); /* Deinitialize the conditioning function. */ void (*deinit)(void *ctx); /* Output length of each conditioning function. */ uint32_t (*getCfOutLen)(void *ctx); /* Obtaining the Entropy Data After Conditioning. */ uint8_t *(*getEntropyData)(void *ctx, uint32_t *len); /* Obtains the entropy required for full entropy output. */ uint32_t (*getNeedEntropy)(void *ctx); } ES_CfMethod; ES_CfMethod *ES_CFGetMethod(uint32_t algId, void *md); ES_CfMethod *ES_CFGetDfMethod(EAL_MdMethod *mdMeth); #ifdef __cplusplus } #endif #endif #endif
2302_82127028/openHiTLS-examples_1508
crypto/entropy/src/es_cf.h
C
unknown
1,773
/* * 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_ENTROPY) && defined(HITLS_CRYPTO_ENTROPY_SYS) #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 "es_cf.h" /* * see FIPS 140-3 section Full Entropy * To receive full entropy from the output of a conditioning component, the following criteria must be met: * The conditioning component shall be vetted, * ℎin shall be greater than or equal to 𝑛𝑛out + 64 bits, * 𝑛𝑛out shall be less than or equal to the security strength of the cryptographic function used as the * conditioning component. */ #define CF_FE_EXLEN 64 #define CF_BYTE_TO_BIT 8 typedef struct { void *ctx; // Hash algorithm handle EAL_MdMethod meth; // Hash algorithm operation function } ES_CfDfCtx; static void ES_CfDfDeinit(void *ctx) { ES_CfDfCtx *cfCtx = (ES_CfDfCtx *)ctx; if (cfCtx == NULL) { return; } if (cfCtx->ctx != NULL) { cfCtx->meth.freeCtx(cfCtx->ctx); } BSL_SAL_Free(cfCtx); return; } static void *ES_CfDfInit(void *mdMeth) { ES_CfDfCtx *ctx = BSL_SAL_Malloc(sizeof(ES_CfDfCtx)); EAL_MdMethod *meth = (EAL_MdMethod *)mdMeth; if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } (void)memcpy_s(&ctx->meth, sizeof(EAL_MdMethod), meth, sizeof(EAL_MdMethod)); ctx->ctx = meth->newCtx(NULL, meth->id); if (ctx->ctx == NULL) { BSL_SAL_Free(ctx); BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } int32_t ret = meth->init(ctx->ctx, NULL); if (ret != CRYPT_SUCCESS) { ES_CfDfDeinit(ctx); BSL_ERR_PUSH_ERROR(ret); return NULL; } return ctx; } static void DfI32ToByte(uint8_t values[4], uint32_t len) { values[0] = (uint8_t)(((len << 3) >> 24) & 0xff); /* leftward by 3, rightwards by 24 */ values[1] = (uint8_t)(((len << 3) >> 16) & 0xff); /* leftward by 3, rightwards by 16 */ values[2] = (uint8_t)(((len << 3) >> 8) & 0xff); /* leftward by 3, rightwards by 8 */ values[3] = (uint8_t)((len << 3) & 0xff); /* leftward by 3 */ return; } static int32_t ES_CfDfUpdateData(void *ctx, uint8_t *data, uint32_t dataLen) { ES_CfDfCtx *cfCtx = (ES_CfDfCtx *)ctx; uint8_t tmp[1] = { 0x01}; int32_t ret = cfCtx->meth.update(cfCtx->ctx, tmp, 1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } uint8_t values[4] = {0}; // 4 is sizeof(uint32_t) DfI32ToByte(values, cfCtx->meth.mdSize); ret = cfCtx->meth.update(cfCtx->ctx, values, sizeof(values)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = cfCtx->meth.update(cfCtx->ctx, data, dataLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static uint8_t *ES_CfDfGetEntropyData(void *cfCtx, uint32_t *len) { ES_CfDfCtx *ctx = (ES_CfDfCtx *)cfCtx; uint32_t bufLen = ctx->meth.mdSize; uint8_t *buf = BSL_SAL_Malloc(bufLen); if (buf == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } int32_t ret = ctx->meth.final(ctx->ctx, buf, &bufLen); if (ret != CRYPT_SUCCESS) { BSL_SAL_Free(buf); BSL_ERR_PUSH_ERROR(ret); return NULL; } ctx->meth.deinit(ctx->ctx); ret = ctx->meth.init(ctx->ctx, NULL); if (ret != CRYPT_SUCCESS) { BSL_SAL_Free(buf); BSL_ERR_PUSH_ERROR(ret); return NULL; } *len = bufLen; return buf; } static uint32_t ES_CfDfGetCfOutLen(void *cfCtx) { ES_CfDfCtx *ctx = (ES_CfDfCtx *)cfCtx; return ctx->meth.mdSize; } static uint32_t ES_CfDfGetNeedEntropy(void *cfCtx) { ES_CfDfCtx *ctx = (ES_CfDfCtx *)cfCtx; return ctx->meth.mdSize * CF_BYTE_TO_BIT + CF_FE_EXLEN; } ES_CfMethod *ES_CFGetDfMethod(EAL_MdMethod *mdMeth) { ES_CfMethod *meth = BSL_SAL_Malloc(sizeof(ES_CfMethod)); if (meth == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } meth->ctx = NULL; meth->meth.mdMeth = *mdMeth; meth->init = ES_CfDfInit; meth->update = ES_CfDfUpdateData; meth->deinit = ES_CfDfDeinit; meth->getCfOutLen = ES_CfDfGetCfOutLen; meth->getEntropyData = ES_CfDfGetEntropyData; meth->getNeedEntropy = ES_CfDfGetNeedEntropy; return meth; } #endif
2302_82127028/openHiTLS-examples_1508
crypto/entropy/src/es_cf_df.c
C
unknown
5,155
/* * 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_ENTROPY) && defined(HITLS_CRYPTO_ENTROPY_SYS) #include <stdint.h> #include "securec.h" #include "bsl_err_internal.h" #include "bsl_list.h" #include "crypt_errno.h" #include "crypt_entropy.h" #include "crypt_eal_entropy.h" #include "es_entropy_pool.h" #include "es_cf.h" #include "es_noise_source.h" struct ES_Entropy { bool isWork; // Whether in working state bool enableTest; // Whether to enable the health test uint32_t poolSize; // Entropy pool size ES_EntropyPool *pool; // Entropy pool ES_CfMethod *cfMeth; // compression function handle BslList *nsList; CRYPT_EAL_EsLogFunc runLog; }; #define ENTROPY_POOL_SIZE_DEFAULT 4096 #define ENTROPY_POOL_SIZE_MIN 512 #define ENTROPY_POOL_SIZE_MAX 4096 ENTROPY_EntropySource *ENTROPY_EsNew(void) { ENTROPY_EntropySource *es = BSL_SAL_Malloc(sizeof(ENTROPY_EntropySource)); if (es == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } (void)memset_s(es, sizeof(ENTROPY_EntropySource), 0, sizeof(ENTROPY_EntropySource)); es->nsList = ES_NsListCreat(); if (es->nsList == NULL) { BSL_SAL_Free(es); return NULL; } es->poolSize = ENTROPY_POOL_SIZE_DEFAULT; es->enableTest = false; return es; } void ENTROPY_EsFree(ENTROPY_EntropySource *es) { if (es == NULL) { return; } if (es->isWork == true) { ENTROPY_EsDeinit(es); } BSL_SAL_FREE(es->cfMeth); ES_NsListFree(es->nsList); es->nsList = NULL; BSL_SAL_Free(es); return; } int32_t ENTROPY_EsInit(ENTROPY_EntropySource *es) { if (es == NULL || es->cfMeth == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (es->isWork) { return CRYPT_SUCCESS; } ES_CfMethod *meth = es->cfMeth; if (meth->init != NULL) { meth->ctx = meth->init(&meth->meth); if (meth->ctx == NULL) { ENTROPY_EsDeinit(es); return CRYPT_ENTROPY_ES_CF_ERROR; } } int32_t ret = ES_NsListInit(es->nsList, es->enableTest); if (ret != CRYPT_SUCCESS) { ENTROPY_EsDeinit(es); return ret; } ES_EntropyPool *pool = ES_EntropyPoolInit(es->poolSize); if (pool == NULL) { ENTROPY_EsDeinit(es); return CRYPT_ENTROPY_ES_POOL_ERROR; } es->pool = pool; es->isWork = true; return CRYPT_SUCCESS; } void ENTROPY_EsDeinit(ENTROPY_EntropySource *es) { if (es == NULL) { return; } es->isWork = false; ES_EntropyPoolDeInit(es->pool); es->pool = NULL; if (es->cfMeth != NULL && es->cfMeth->deinit != NULL) { es->cfMeth->deinit(es->cfMeth->ctx); es->cfMeth->ctx = NULL; } ES_NsListDeinit(es->nsList); return; } static int32_t EsPoolSizeSet(ENTROPY_EntropySource *es, void *data, uint32_t len) { if (es->isWork) { BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ES_STATE_ERROR); return CRYPT_ENTROPY_ES_STATE_ERROR; } if (len != sizeof(uint32_t) || *(uint32_t *)data < ENTROPY_POOL_SIZE_MIN || *(uint32_t *)data > ENTROPY_POOL_SIZE_MAX) { BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_CTRL_INVALID_PARAM); return CRYPT_ENTROPY_CTRL_INVALID_PARAM; } es->poolSize = *(uint32_t *)data; return CRYPT_SUCCESS; } static int32_t EsNsAdd(ENTROPY_EntropySource *es, void *data, uint32_t len) { if (es->isWork) { BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ES_STATE_ERROR); return CRYPT_ENTROPY_ES_STATE_ERROR; } if (data == NULL || len != sizeof(CRYPT_EAL_NsPara)) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_EAL_NsPara *para = (CRYPT_EAL_NsPara *)data; return ES_NsAdd(es->nsList, para->name, para->autoTest, para->minEntropy, &para->nsMeth, (const CRYPT_EAL_NsTestPara *)&(para->nsPara)); } static int32_t EsEnableTest(ENTROPY_EntropySource *es, void *data, uint32_t len) { if (es->isWork) { BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ES_STATE_ERROR); return CRYPT_ENTROPY_ES_STATE_ERROR; } if (data == NULL || len != sizeof(bool)) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } es->enableTest = *(bool *)data; return CRYPT_SUCCESS; } static int32_t EsNsRemove(ENTROPY_EntropySource *es, void *data, uint32_t len) { if (es->isWork) { BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ES_STATE_ERROR); return CRYPT_ENTROPY_ES_STATE_ERROR; } if (data == NULL || len == 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } return ES_NsRemove(es->nsList, (const char *)data); } static int32_t EsSetCF(ENTROPY_EntropySource *es, ENTROPY_CFPara *data) { if (es->isWork) { BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ES_STATE_ERROR); return CRYPT_ENTROPY_ES_STATE_ERROR; } if (es->cfMeth != NULL) { BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ES_CF_ERROR); return CRYPT_ENTROPY_ES_CF_ERROR; } es->cfMeth = ES_CFGetMethod(data->algId, data->md); if (es->cfMeth == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ES_CF_NOT_SUPPORT); return CRYPT_ENTROPY_ES_CF_NOT_SUPPORT; } return CRYPT_SUCCESS; } static int32_t EsGetSize(ENTROPY_EntropySource *es, int32_t cmd, void *data, uint32_t len) { if (data == NULL || len != sizeof(uint32_t)) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (!es->isWork) { BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ES_STATE_ERROR); return CRYPT_ENTROPY_ES_STATE_ERROR; } switch (cmd) { case CRYPT_ENTROPY_GET_POOL_SIZE: *(uint32_t *)data = es->poolSize; return CRYPT_SUCCESS; case CRYPT_ENTROPY_POOL_GET_CURRSIZE: *(uint32_t *)data = ES_EntropyPoolGetCurSize(es->pool); return CRYPT_SUCCESS; case CRYPT_ENTROPY_GET_CF_SIZE: *(uint32_t *)data = es->cfMeth->getCfOutLen(es->cfMeth->ctx); return CRYPT_SUCCESS; default: BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ES_CTRL_ERROR); return CRYPT_ENTROPY_ES_CTRL_ERROR; } } static int32_t EsGetState(ENTROPY_EntropySource *es, void *data, uint32_t len) { if (data == NULL || len != sizeof(bool)) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } *(bool *)data = es->isWork; return CRYPT_SUCCESS; } static int32_t EsSetLogCallback(ENTROPY_EntropySource *es, void *data, uint32_t len) { (void)len; if (es == NULL || data == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } es->runLog = (CRYPT_EAL_EsLogFunc)data; return CRYPT_SUCCESS; } int32_t ENTROPY_EsCtrl(ENTROPY_EntropySource *es, int32_t cmd, void *data, uint32_t len) { if (es == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } switch (cmd) { case CRYPT_ENTROPY_SET_POOL_SIZE: return EsPoolSizeSet(es, data, len); case CRYPT_ENTROPY_ADD_NS: return EsNsAdd(es, data, len); case CRYPT_ENTROPY_REMOVE_NS: return EsNsRemove(es, data, len); case CRYPT_ENTROPY_ENABLE_TEST: return EsEnableTest(es, data, len); case CRYPT_ENTROPY_SET_CF: return EsSetCF(es, data); case CRYPT_ENTROPY_GET_STATE: return EsGetState(es, data, len); case CRYPT_ENTROPY_SET_LOG_CALLBACK: return EsSetLogCallback(es, data, len); default: return EsGetSize(es, cmd, data, len); } } uint32_t ENTROPY_EsEntropyGet(ENTROPY_EntropySource *es, uint8_t *data, uint32_t len) { if (es == NULL || !es->isWork || data == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return 0; } if (ES_EntropyPoolGetCurSize(es->pool) <= 0) { int32_t ret = ENTROPY_EsEntropyGather(es); if (ret != CRYPT_SUCCESS) { return 0; } } return ES_EntropyPoolPopBytes(es->pool, data, len); } static uint32_t EsGetEntropy(ENTROPY_EntropySource *es, uint8_t *buf, uint32_t bufLen, uint32_t entropy) { ES_NoiseSource *ns = NULL; uint32_t needLen = 0; uint32_t curEntropy = 0; uint8_t *data = buf; while (curEntropy < entropy) { uint32_t tmpEntropy = curEntropy; for (ns = BSL_LIST_GET_FIRST(es->nsList); ns != NULL && needLen < bufLen; ns = BSL_LIST_GET_NEXT(es->nsList)) { int32_t ret = ES_NsRead(ns, data, 1); if (ret == CRYPT_SUCCESS) { data++; needLen++; curEntropy += ns->minEntropy; } if (es->runLog != NULL) { es->runLog(ret); } if (curEntropy >= entropy) { return needLen; } } if (curEntropy == tmpEntropy) { BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ES_NS_NOT_AVA); needLen = 0; break; } } return needLen; } static uint32_t GetMinLen(uint32_t entropy, uint32_t minEntropy) { return (uint32_t)(((uint64_t)entropy + (uint64_t)minEntropy - 1) / (uint64_t)minEntropy); } int32_t ENTROPY_EsEntropyGather(ENTROPY_EntropySource *es) { if (es == NULL || es->isWork == false || es->cfMeth == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } ES_CfMethod *meth = es->cfMeth; if ((meth->getCfOutLen(meth->ctx) > (uint32_t)ES_EntropyPoolGetMaxSize(es->pool) - ES_EntropyPoolGetCurSize(es->pool))) { BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ES_POOL_INSUFFICIENT); return CRYPT_ENTROPY_ES_POOL_INSUFFICIENT; } uint32_t minEntropy = ES_NsListGetMinEntropy(es->nsList); uint32_t needEntropy = meth->getNeedEntropy(meth->ctx); uint32_t bufLen = GetMinLen(needEntropy, minEntropy); uint8_t *buf = BSL_SAL_Malloc(bufLen); if (buf == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } uint32_t needLen = EsGetEntropy(es, buf, bufLen, needEntropy); if (needLen == 0) { BSL_SAL_Free(buf); BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ES_ENTROPY_NOT_ENOUGH); return CRYPT_ENTROPY_ES_ENTROPY_NOT_ENOUGH; } int32_t ret = meth->update(meth->ctx, buf, needLen); BSL_SAL_Free(buf); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } uint32_t len; uint8_t *data = meth->getEntropyData(meth->ctx, &len); if (data == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ret = ES_EntropyPoolPushBytes(es->pool, data, len); (void)memset_s(data, len, 0, len); BSL_SAL_Free(data); return ret; } #endif
2302_82127028/openHiTLS-examples_1508
crypto/entropy/src/es_entropy.c
C
unknown
11,765
/* * 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_ENTROPY) && defined(HITLS_CRYPTO_ENTROPY_SYS) #include <stdint.h> #include "securec.h" #include "bsl_err_internal.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "es_entropy_pool.h" ES_EntropyPool *ES_EntropyPoolInit(uint32_t size) { ES_EntropyPool *pool = NULL; uint32_t maxSize = size + 1; if (size == 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return NULL; } pool = (ES_EntropyPool *)BSL_SAL_Malloc(sizeof(ES_EntropyPool)); if (pool == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } pool->buf = (uint8_t *)BSL_SAL_Malloc(maxSize); if (pool->buf == NULL) { BSL_SAL_FREE(pool); BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } pool->front = 0; pool->rear = 0; pool->maxSize = maxSize; return pool; } void ES_EntropyPoolDeInit(ES_EntropyPool *pool) { if (pool == NULL) { return; } (void)memset_s(pool->buf, pool->maxSize, 0, pool->maxSize); BSL_SAL_FREE(pool->buf); BSL_SAL_Free(pool); return; } int32_t ES_EntropyPoolGetMaxSize(ES_EntropyPool *pool) { return pool->maxSize - 1; } uint32_t ES_EntropyPoolGetCurSize(ES_EntropyPool *pool) { return (pool->rear - pool->front + pool->maxSize) % pool->maxSize; } int32_t ES_EntropyPoolPushBytes(ES_EntropyPool *pool, uint8_t *buf, uint32_t bufLen) { uint32_t partA, partB; partA = (bufLen > (pool->maxSize - pool->rear)) ? pool->maxSize - pool->rear : bufLen; (void)memcpy_s(&pool->buf[pool->rear], pool->maxSize - pool->rear, buf, partA); pool->rear = (pool->rear + partA) % pool->maxSize; if (partA < bufLen) { partB = bufLen - partA; (void)memcpy_s(&pool->buf[pool->rear], pool->maxSize - pool->rear, buf + partA, partB); pool->rear = (pool->rear + partB) % pool->maxSize; } return CRYPT_SUCCESS; } uint32_t ES_EntropyPoolPopBytes(ES_EntropyPool *pool, uint8_t *data, uint32_t size) { uint32_t bufLen, partA, partB; if (ES_EntropyPoolGetMaxSize(pool) == 0 || size == 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return 0; } bufLen = (ES_EntropyPoolGetCurSize(pool) < size) ? ES_EntropyPoolGetCurSize(pool) : size; partA = (bufLen <= pool->maxSize - pool->front) ? bufLen : pool->maxSize - pool->front; (void)memcpy_s(data, bufLen, &pool->buf[pool->front], partA); pool->front = (pool->front + partA) % pool->maxSize; partB = bufLen - partA; if (partB != 0) { (void)memcpy_s(data + partA, bufLen - partA, &pool->buf[pool->front], partB); pool->front = (pool->front + partB) % pool->maxSize; } return bufLen; } #endif
2302_82127028/openHiTLS-examples_1508
crypto/entropy/src/es_entropy_pool.c
C
unknown
3,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. */ #ifndef ES_ENTROPY_POOL_H #define ES_ENTROPY_POOL_H #include "hitls_build.h" #if defined(HITLS_CRYPTO_ENTROPY) && defined(HITLS_CRYPTO_ENTROPY_SYS) #include <stdint.h> #ifdef __cplusplus extern "C" { #endif typedef struct { uint8_t *buf; // queue data uint32_t front; // queue head uint32_t rear; // queue tail uint32_t maxSize; // queue capacity + 1 } ES_EntropyPool; /* Entropy pool initialization. */ ES_EntropyPool *ES_EntropyPoolInit(uint32_t size); /* Entropy pool deinitialization. */ void ES_EntropyPoolDeInit(ES_EntropyPool *pool); /* Obtains the maximum capacity of the entropy pool. */ int32_t ES_EntropyPoolGetMaxSize(ES_EntropyPool *pool); /* Obtains the current data volume of the entropy pool. */ uint32_t ES_EntropyPoolGetCurSize(ES_EntropyPool *pool); /* Obtains entropy data from the entropy pool. */ int32_t ES_EntropyPoolPushBytes(ES_EntropyPool *pool, uint8_t *buf, uint32_t bufLen); /* Compress entropy data into the entropy pool. */ uint32_t ES_EntropyPoolPopBytes(ES_EntropyPool *pool, uint8_t *data, uint32_t size); #ifdef __cplusplus } #endif #endif #endif
2302_82127028/openHiTLS-examples_1508
crypto/entropy/src/es_entropy_pool.h
C
unknown
1,711
/* * 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_ENTROPY) && defined(HITLS_CRYPTO_ENTROPY_SYS) #include <stdint.h> #include <stddef.h> #include "bsl_err_internal.h" #include "crypt_errno.h" #include "es_health_test.h" int32_t ES_HealthTestRct(ES_HealthTest *state, uint64_t data) { if (data == state->lastData) { state->rctCount++; if (state->rctCount >= state->rctCutoff) { BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_RCT_FAILURE); return CRYPT_ENTROPY_RCT_FAILURE; } } else { state->lastData = data; state->rctCount = 1; } return CRYPT_SUCCESS; } int32_t ES_HealthTestApt(ES_HealthTest *state, uint64_t data) { if (state->aptBaseSet == 0) { // NIST SP800-90B section 4.4.2 step 1/2 state->aptBaseSet = 1; state->aptBaseData = data; state->aptCount = 1; state->aptI = 1; return CRYPT_SUCCESS; } if (state->aptBaseData == data) { state->aptCount++; if (state->aptCount >= state->aptCutOff) { state->aptBaseSet = 0; // Restart an APT window next time. BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_APT_FAILURE); return CRYPT_ENTROPY_APT_FAILURE; } } state->aptI++; if (state->aptI >= state->aptWindowSize) { state->aptBaseSet = 0; } return CRYPT_SUCCESS; } #endif
2302_82127028/openHiTLS-examples_1508
crypto/entropy/src/es_health_test.c
C
unknown
1,976
/* * 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 ES_HEALTH_TEST_H #define ES_HEALTH_TEST_H #include "hitls_build.h" #if defined(HITLS_CRYPTO_ENTROPY) && defined(HITLS_CRYPTO_ENTROPY_SYS) #include <stdint.h> #ifdef __cplusplus extern "C" { #endif typedef struct { // RCT uint32_t rctCutoff; // NIST SP800-90B 4.4.1 Parameter C uint32_t rctCount; // NIST SP800-90B 4.4.1 Parameter B // APT uint32_t aptBaseSet; // Indicates whether aptBaseData has been set. The value must be initialized to 0. uint32_t aptCount; // NIST SP800-90B 4.4.2 Parameter B uint32_t aptWindowSize; // NIST SP800-90B 4.4.2 Parameter W uint32_t aptI; // counters uint32_t aptCutOff; // NIST SP800-90B 4.4.2 Parameter C uint64_t aptBaseData; // NIST SP800-90B 4.4.2 Parameter A uint64_t lastData; // NIST SP800-90B 4.4.1 Parameter A } ES_HealthTest; /* Repetition Count Test */ int32_t ES_HealthTestRct(ES_HealthTest *state, uint64_t data); /* Adaptive Proportion Test */ int32_t ES_HealthTestApt(ES_HealthTest *state, uint64_t data); #ifdef __cplusplus } #endif #endif #endif
2302_82127028/openHiTLS-examples_1508
crypto/entropy/src/es_health_test.h
C
unknown
1,655
/* * 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_ENTROPY) && defined(HITLS_CRYPTO_ENTROPY_SYS) #include <stdint.h> #include "securec.h" #include "crypt_errno.h" #include "bsl_list_internal.h" #include "bsl_err_internal.h" #include "es_noise_source.h" #define ES_NS_MAX_SIZE 16 #define ES_MIN_ENTROPY_MAX 8 /* Noise source non-blocking reading. Set the maximum reading time to 10s. */ #define ES_MAX_TIMEOUT_MAX 10 static int32_t NsRead(ES_NoiseSource *ns, uint8_t *buf, uint32_t bufLen); /* * GM/T 0105-2021 Section 5.5 * The Power-Up Health Test requires a continuous health test of at least 1024 consecutive samples. */ #define ENTROPY_START_UP_TEST_SIZE 1024 int32_t ES_NoiseSourceStartupTest(ES_NoiseSource *ns) { uint8_t buf[ENTROPY_START_UP_TEST_SIZE] = {0}; return NsRead(ns, buf, ENTROPY_START_UP_TEST_SIZE); } static ES_NoiseSource *ES_NsCreate(const char *name, bool autoTest, uint32_t minEntropy, const CRYPT_EAL_NsMethod *method, const CRYPT_EAL_NsTestPara *para) { ES_NoiseSource *ctx = BSL_SAL_Malloc(sizeof(ES_NoiseSource)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } (void)memset_s(ctx, sizeof(ES_NoiseSource), 0, sizeof(ES_NoiseSource)); uint32_t len = strlen(name) + 1; ctx->name = BSL_SAL_Malloc(len); if (ctx->name == NULL) { BSL_SAL_FREE(ctx); BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } (void)strncpy_s(ctx->name, len, name, len - 1); // Initializing ctx->autoTest = autoTest; ctx->para = method->para; ctx->init = method->init; ctx->read = method->read; ctx->deinit = method->deinit; ctx->minEntropy = minEntropy; ctx->state.rctCutoff = para->rctCutoff; ctx->state.aptCutOff = para->aptCutoff; ctx->state.aptWindowSize = para->aptWinSize; return ctx; } static void ES_NsFree(ES_NoiseSource *ns) { if (ns->usrdata != NULL && ns->deinit != NULL) { ns->deinit(ns->usrdata); } BSL_SAL_FREE(ns->name); BSL_SAL_Free(ns); return; } BslList *ES_NsListCreat(void) { BslList *ns = BSL_LIST_New(sizeof(BslListNode)); if (ns == NULL) { BSL_ERR_PUSH_ERROR(BSL_LIST_MALLOC_FAIL); return NULL; } ES_NoiseSource *jitterCtx = ES_CpuJitterGetCtx(); if (jitterCtx == NULL) { goto ERR; } int32_t ret = BSL_LIST_AddElement(ns, jitterCtx, BSL_LIST_POS_AFTER); if (ret != CRYPT_SUCCESS) { ES_NsFree(jitterCtx); goto ERR; } ES_NoiseSource *stampCtx = ES_TimeStampGetCtx(); if (stampCtx == NULL) { goto ERR; } ret = BSL_LIST_AddElement(ns, stampCtx, BSL_LIST_POS_AFTER); if (ret != CRYPT_SUCCESS) { ES_NsFree(stampCtx); goto ERR; } return ns; ERR: BSL_LIST_FREE(ns, (BSL_LIST_PFUNC_FREE)ES_NsFree); return NULL; } int32_t ES_NsListInit(BslList *nsList, bool enableTest) { if (BSL_LIST_COUNT(nsList) == 0) { BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ES_NO_NS); return CRYPT_ENTROPY_ES_NO_NS; } bool nsUsed = false; ES_NoiseSource *ns = NULL; for (ns = BSL_LIST_GET_FIRST(nsList); ns != NULL; ns = BSL_LIST_GET_NEXT(nsList)) { /* * If the health check is automatically performed when the noise source is generated, no additional health * check is required. Otherwise, determine whether to perform the health check based on the configuration. */ ns->enableTest = (ns->autoTest) ? false : enableTest; if (ns->init != NULL) { ns->usrdata = ns->init(ns->para); if (ns->usrdata == NULL) { ns->isEnable = false; continue; } } ns->isInit = true; if (enableTest) { int32_t ret = ES_NoiseSourceStartupTest(ns); if (ret != CRYPT_SUCCESS) { ns->isEnable = false; BSL_ERR_PUSH_ERROR(ret); continue; } } ns->isEnable = true; nsUsed = true; } if (!nsUsed) { ES_NsListDeinit(nsList); return CRYPT_ENTROPY_ES_NO_NS; } return CRYPT_SUCCESS; } void ES_NsListDeinit(BslList *nsList) { if (BSL_LIST_COUNT(nsList) == 0) { return; } ES_NoiseSource *ns = NULL; for (ns = BSL_LIST_GET_FIRST(nsList); ns != NULL; ns = BSL_LIST_GET_NEXT(nsList)) { ns->isInit = false; ns->isEnable = false; if (ns->deinit != NULL) { ns->deinit(ns->usrdata); ns->usrdata = NULL; } } return; } void ES_NsListFree(BslList *nsList) { BSL_LIST_FREE(nsList, (BSL_LIST_PFUNC_FREE)ES_NsFree); } static int32_t ES_NsComp(const ES_NoiseSource *ns, const char *name) { return strcmp(ns->name, name); } int32_t ES_NsAdd(BslList *nsList, const char *name, bool autoTest, uint32_t minEntropy, const CRYPT_EAL_NsMethod *method, const CRYPT_EAL_NsTestPara *para) { if (name == NULL || minEntropy > ES_MIN_ENTROPY_MAX) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (method->read == NULL || (method->init == NULL && method->deinit != NULL) || (method->init != NULL && method->deinit == NULL)) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (BSL_LIST_COUNT(nsList) >= ES_NS_MAX_SIZE) { BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ES_NS_FULL); return CRYPT_ENTROPY_ES_NS_FULL; } if (BSL_LIST_SearchEx(nsList, name, (BSL_LIST_PFUNC_CMP)ES_NsComp) != NULL) { BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ES_DUP_NS); return CRYPT_ENTROPY_ES_DUP_NS; } ES_NoiseSource *ns = ES_NsCreate(name, autoTest, minEntropy, method, para); if (ns == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ES_CREATE_ERROR); return CRYPT_ENTROPY_ES_CREATE_ERROR; } int32_t ret = BSL_LIST_AddElement(nsList, ns, BSL_LIST_POS_AFTER); if (ret != CRYPT_SUCCESS) { ES_NsFree(ns); } return ret; } int32_t ES_NsRemove(BslList *nsList, const char *name) { BslListNode *tmpNode = NULL; for (BslListNode *node = BSL_LIST_FirstNode(nsList); node != NULL;) { tmpNode = node; ES_NoiseSource *ns = BSL_LIST_GetData(tmpNode); if (ns == NULL) { continue; } if (strcmp(ns->name, name) == 0) { BSL_LIST_DeleteNode(nsList, (const BslListNode *)tmpNode, (BSL_LIST_PFUNC_FREE)ES_NsFree); return CRYPT_SUCCESS; } node = BSL_LIST_GetNextNode(nsList, tmpNode); } BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ES_NS_NOT_FOUND); return CRYPT_ENTROPY_ES_NS_NOT_FOUND; } static int32_t NsRead(ES_NoiseSource *ns, uint8_t *buf, uint32_t bufLen) { int32_t ret = ns->read(ns->usrdata, ES_MAX_TIMEOUT_MAX, buf, bufLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (!ns->enableTest) { return CRYPT_SUCCESS; } for (uint32_t iter = 0; iter < bufLen; iter++) { ret = ES_HealthTestRct(&(ns->state), buf[iter]); if (ret != CRYPT_SUCCESS) { return ret; } ret = ES_HealthTestApt(&(ns->state), buf[iter]); if (ret != CRYPT_SUCCESS) { return ret; } } return ret; } int32_t ES_NsRead(ES_NoiseSource *ns, uint8_t *buf, uint32_t bufLen) { if (ns->isInit != true || ns->isEnable != true) { BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ES_NS_NOT_AVA); return CRYPT_ENTROPY_ES_NS_NOT_AVA; } return NsRead(ns, buf, bufLen); } uint32_t ES_NsListGetMinEntropy(BslList *nsList) { if (BSL_LIST_COUNT(nsList) == 0) { BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ES_NO_NS); return 0; } uint32_t minEntropy = 8; ES_NoiseSource *ns = NULL; for (ns = BSL_LIST_GET_FIRST(nsList); ns != NULL; ns = BSL_LIST_GET_NEXT(nsList)) { minEntropy = (ns->minEntropy < minEntropy) ? ns->minEntropy : minEntropy; } return minEntropy; } #endif
2302_82127028/openHiTLS-examples_1508
crypto/entropy/src/es_noise_source.c
C
unknown
8,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 ES_NOISE_SOURCE_H #define ES_NOISE_SOURCE_H #include "hitls_build.h" #if defined(HITLS_CRYPTO_ENTROPY) && defined(HITLS_CRYPTO_ENTROPY_SYS) #include <stdint.h> #include "bsl_list.h" #include "es_health_test.h" #include "crypt_types.h" #ifdef __cplusplus extern "C" { #endif typedef struct { /* Whether to enable the health test */ bool enableTest; /* Whether the noise source automatically performs the health test */ bool autoTest; /* Whether the noise source is available */ bool isEnable; /* Whether the noise source is initialized */ bool isInit; /* Noise source name, which must be unique. */ char *name; /* Initialization parameters of the noise source */ void *para; /* Noise Source Handle */ void *usrdata; /* Noise Source Initialization Interface. */ void *(*init)(void *para); /* Interface for Obtaining Noise Sources. */ int32_t (*read)(void *usrdata, uint32_t timeout, uint8_t *buf, uint32_t bufLen); /* Noise Source Deinitialization Interface. */ void (*deinit)(void *usrdata); /* minimum entropy, bit entropy contained in a byte. */ uint32_t minEntropy; ES_HealthTest state; } ES_NoiseSource; /* Noise Source List create. */ BslList *ES_NsListCreat(void); /* Noise Source List Initialization. */ int32_t ES_NsListInit(BslList *nsList, bool enableTest); /* Noise Source List deinitialization. */ void ES_NsListDeinit(BslList *nsList); /* Noise Source List release. */ void ES_NsListFree(BslList *nsList); /** * @brief add ns * * @param nsList [IN] noise source list * @param name [IN] Noise source name, which must be unique. * @param autoTest [IN] Whether the noise source automatically performs the health test. * @param minEntropy [IN] minimum entropy, bit entropy contained in a byte. * @param method [IN] noise source callback Interface. * @param para [IN] noise source health test parameter. * * @return CRYPT_SUCCESS succeeded. * For other error codes, see crypt_error.h. */ int32_t ES_NsAdd(BslList *nsList, const char *name, bool autoTest, uint32_t minEntropy, const CRYPT_EAL_NsMethod *method, const CRYPT_EAL_NsTestPara *para); /** * @brief remove ns * * @param nsList [IN] noise source list * @param name [IN] Noise source name, which must be unique. * * @return CRYPT_SUCCESS succeeded. * For other error codes, see crypt_error.h. */ int32_t ES_NsRemove(BslList *nsList, const char *name); /** * @brief Read the raw noise data. * * @param ns [IN] noise source handle * @param buf [IN] the raw noise data buffer. * @param bufLen [IN] the length of the raw noise data. * * @return CRYPT_SUCCESS succeeded. * For other error codes, see crypt_error.h. */ int32_t ES_NsRead(ES_NoiseSource *ns, uint8_t *buf, uint32_t bufLen); /** * @brief Obtains the minimum value of the minimum entropy. * * @param nsList [IN] noise source list * * @return CRYPT_SUCCESS succeeded. * For other error codes, see crypt_error.h. */ uint32_t ES_NsListGetMinEntropy(BslList *nsList); /* Obtains the handle of the cpu-jiiter. */ ES_NoiseSource *ES_CpuJitterGetCtx(void); /* Obtains the handle of the timestamp. */ ES_NoiseSource *ES_TimeStampGetCtx(void); #ifdef __cplusplus } #endif #endif #endif
2302_82127028/openHiTLS-examples_1508
crypto/entropy/src/es_noise_source.h
C
unknown
3,925
/* * 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_ENTROPY) && defined(HITLS_CRYPTO_ENTROPY_SYS) #include <stdint.h> #include <time.h> #include "securec.h" #include "bsl_err_internal.h" #include "crypt_errno.h" #include "es_noise_source.h" #ifndef HITLS_CACHE_LINE_SIZE #define HITLS_CACHE_LINE_SIZE 64 #endif #ifndef HITLS_CACHE_ROW_COUNT #define HITLS_CACHE_ROW_COUNT 1025 #endif #ifndef HITLS_JITTER_APT_CUT_OFF /** * Binary WINDOW 1024, 0.8 Entropy CUT off 664 0.6 Entropy CUT off 748 * reference to SP800-90B sec 4.4.2 */ #define HITLS_JITTER_APT_CUT_OFF 592 #endif #ifndef HITLS_JITTER_RCT_CUT_OFF /** * C = 1 + ceil(-log_2(alpha)/H), H = 1(MIN_ENTROPY), alpha = 2^(-20) * alpha value reference SP800-90B sec 4.4.1 * following SP800-90B. Thus C = ceil(-log_2(alpha)/H) = 20. */ #define HITLS_JITTER_RCT_CUT_OFF 20 #endif #ifndef HITLS_JITTER_MINENTROPY /** * HITLS_JITTER_RCT_CUT_OFF and HITLS_JITTER_APT_CUT_OFF are calculated based on HITLS_JITTER_MINENTROPY. * If HITLS_JITTER_MINENTROPY is configured manually, HITLS_JITTER_RCT_CUT_OFF and must be * configured simultaneously. */ #define HITLS_JITTER_MINENTROPY 5 #endif #define NS_APT_BIN_WINDOW_SIZE 1024 #define NS_ENTROPY_HASH_SIZE 32 // hash size #define NS_ENTROPY_DATA_SIZE (NS_ENTROPY_HASH_SIZE * 4) // 4 * 32, 128 bytes,1024 bits,one APT window /* Mainstream CPU cache access unit (cache line) 32 或者64 */ #define NS_CACHE_SIZE (HITLS_CACHE_LINE_SIZE * HITLS_CACHE_ROW_COUNT) // total operation memory size #define NS_CACHE_MIN_SIZE 33 // minimum Length #define NS_ENTROPY_RCT_FAILURE (-1) #define NS_ENTROPY_APT_FAILURE (-2) #define NS_ENTROPY_MAX_LIFE 30 // maximum lifetime of entropy data: 30 seconds typedef struct ES_JitterState { int8_t testFailure; uint8_t rctCount; uint8_t aptBase; uint8_t aptBaseSet; uint16_t aptCount; uint16_t aptObservations; uint8_t data[NS_ENTROPY_DATA_SIZE]; uint64_t lastDelta; uint32_t remainCount; uint32_t memLocation; uint8_t mem[HITLS_CACHE_ROW_COUNT][HITLS_CACHE_LINE_SIZE]; volatile uint32_t mID; uint64_t lastTime; void (*hashFunc)(uint8_t *, int, uint8_t *, int); } ES_JitterState; static void UpdateRctHealth(ES_JitterState *e, int stuck) { if (e->rctCount > HITLS_JITTER_RCT_CUT_OFF) { return; } if (stuck > 0) { e->rctCount++; if (e->rctCount > HITLS_JITTER_RCT_CUT_OFF) { e->testFailure = NS_ENTROPY_RCT_FAILURE; // If the RCT test fails, the entropy source can be restarted. } } else { e->rctCount = 0; } } static void UpdateAptHealth(ES_JitterState *e, uint8_t data) { if (e->aptBaseSet == 0) { e->aptBase = data; e->aptBaseSet = 1; e->aptCount = 1; e->aptObservations = 1; return; } if (e->aptBase == data) { e->aptCount++; if (e->aptCount > HITLS_JITTER_APT_CUT_OFF) { e->testFailure = NS_ENTROPY_APT_FAILURE; // If APT detection fails, the entropy source can be restarted. } } e->aptObservations++; if (e->aptObservations >= NS_APT_BIN_WINDOW_SIZE) { e->aptBaseSet = 0; } } static uint64_t NS_ENTROPY_Gettick(void) { uint64_t ticks = 0; struct timespec time; if (clock_gettime(CLOCK_REALTIME, &time) == 0) { ticks = ((uint64_t)time.tv_sec & 0xFFFFFFFF) * 1000000000UL; ticks = ticks + (uint64_t)time.tv_nsec; } return ticks; } #define NS_MOVE_LEVEL 128 static void __attribute__((optimize("O0"))) EntropyMemeryAccess(ES_JitterState *e, uint8_t det) { /* * 1. Random read/write start position * 2. Read and write position change by position value * 3. Multiple data reads and writes * 4. branch prediction mitigation */ e->mID = (e->mID + det) % NS_CACHE_SIZE; uint32_t bound = HITLS_CACHE_ROW_COUNT + det; for (uint32_t i = 0; i < bound; i++) { // c, l Calculate the row and column coordinate points. uint32_t c = e->mID / HITLS_CACHE_LINE_SIZE; uint32_t l = e->mID % HITLS_CACHE_LINE_SIZE; volatile uint8_t *volatile cur = e->mem[c] + l; *cur ^= det; e->memLocation = (e->memLocation + (*cur & 0x0f) + NS_CACHE_MIN_SIZE) % NS_CACHE_SIZE; } } /** * Get a random position: keep moving right until there is a non-zero bit in the lower eight bits, * then return the lower eight bits */ static uint8_t GetUChar(uint64_t tick) { size_t i; volatile uint64_t data = tick; for (i = 0; i < sizeof(uint64_t); i++) { if ((data & 1) == 1) { return (uint8_t)data; } data >>= 1; } return (uint8_t)((data % HITLS_CACHE_LINE_SIZE) + NS_CACHE_MIN_SIZE); } static void EntropyMeasure(ES_JitterState *e, int32_t index) { uint8_t data = 0; int i; // One byte has eight bits. Only the status of one bit can be obtained each time the memory is read or written. for (i = 0; i < 8; i++) { // 8 bit uint64_t tick1 = NS_ENTROPY_Gettick(); EntropyMemeryAccess(e, GetUChar(tick1)); uint64_t tick = NS_ENTROPY_Gettick(); uint64_t delta = tick - tick1; uint8_t bit; if (delta & 0x01) { bit = (delta >> 3) & 0x01; // 3:4th bits } else { bit = (delta >> 7) & 0x01; // 7:8th bits } data = (uint8_t)(data << 1); // Move to the left first to prevent entropy overflow. data |= bit; UpdateRctHealth(e, e->lastDelta == bit); UpdateAptHealth(e, bit); e->lastDelta = bit; } e->data[index] = data; data = 0; // clean } static void EntropyProcess(ES_JitterState *e) { int32_t i, start; uint8_t buf[NS_ENTROPY_HASH_SIZE + 1]; for (i = 0; i < NS_ENTROPY_DATA_SIZE; i++) { EntropyMeasure(e, i); // Obtains 1-byte entropy. start = (i / NS_ENTROPY_HASH_SIZE) * NS_ENTROPY_HASH_SIZE; /** * Copy 32 bytes to buf at a time, but only one byte of entropy is added to e-data in each loop. Subsequently, * the latest entropy is attached to the tail of the buffer each time, and the 33-byte content is hashed. * The hashed content is written to the internal entropy pool of the entropy source. */ (void)memcpy_s(buf, NS_ENTROPY_HASH_SIZE + 1, e->data + start, NS_ENTROPY_HASH_SIZE); // The latest entropy 1 byte is placed at the end. The 33-byte data is hashed to form a new 32-byte entropy. buf[NS_ENTROPY_HASH_SIZE] = e->data[i]; e->hashFunc(buf, sizeof(buf), (e->data + start), NS_ENTROPY_HASH_SIZE); } (void)memset_s(buf, sizeof(buf), 0, sizeof(buf)); } static int32_t EsCpuJitterGen(ES_JitterState *jitter, uint8_t *buf, uint32_t bufLen) { const uint32_t entropySize = sizeof(jitter->data); EntropyProcess(jitter); uint8_t *out = buf; uint32_t left = bufLen; while (left > 0) { EntropyProcess(jitter); // 1024 if (jitter->testFailure != CRYPT_SUCCESS) { jitter->remainCount = 0; break; } uint32_t length = left > entropySize ? entropySize : left; (void)memcpy_s(out, length, jitter->data, length); left -= length; if (left <= 0) { jitter->remainCount = entropySize - length; jitter->lastTime = BSL_SAL_CurrentSysTimeGet(); break; } out += length; } return jitter->testFailure; } static uint32_t EsCpuJitterGet(ES_JitterState *jitter, uint8_t *buf, uint32_t bufLen) { if (jitter->remainCount == 0) { return bufLen; } uint64_t nowTime = BSL_SAL_CurrentSysTimeGet(); if (nowTime == 0 || nowTime - jitter->lastTime > NS_ENTROPY_MAX_LIFE) { return bufLen; } uint32_t length = (bufLen < jitter->remainCount) ? bufLen : jitter->remainCount; (void)memcpy_s(buf, bufLen, jitter->data + (NS_ENTROPY_DATA_SIZE - jitter->remainCount), length); jitter->remainCount -= length; return bufLen - length; } static int32_t ES_CpuJitterRead(void *ctx, uint32_t timeout, uint8_t *buf, uint32_t bufLen) { ES_JitterState *jitter = (ES_JitterState *)ctx; (void)timeout; if (ctx == NULL || buf == NULL || bufLen <= 0) { return CRYPT_NULL_INPUT; } uint32_t left = EsCpuJitterGet(jitter, buf, bufLen); if (left == 0) { return CRYPT_SUCCESS; } return EsCpuJitterGen(jitter, buf + (bufLen -left), left); } static void ES_CpuJitterFree(void *ctx) { if (ctx == NULL) { return; } (void)memset_s(ctx, sizeof(ES_JitterState), 0, sizeof(ES_JitterState)); BSL_SAL_FREE(ctx); } static void *ES_CpuJitterInit(void *para) { if (para == NULL) { return NULL; } ES_JitterState *e = (ES_JitterState *)BSL_SAL_Malloc(sizeof(ES_JitterState)); if (e == NULL) { return NULL; } e->rctCount = 0; e->aptBaseSet = 0; e->mID = 0; e->hashFunc = para; e->testFailure = CRYPT_SUCCESS; // Try to read 32 bytes once to check whether the environment is normal. uint8_t data[32] = {0}; if (ES_CpuJitterRead(e, true, data, sizeof(data)) != CRYPT_SUCCESS) { (void)memset_s(data, sizeof(data), 0, 32); // 32, Zeroed 32-byte array ES_CpuJitterFree(e); return NULL; } return e; } static void EmptyConditionComp(uint8_t *out, int32_t outLen, uint8_t *in, int32_t inLen) { (void)out; (void)outLen; (void)in; (void)inLen; } ES_NoiseSource *ES_CpuJitterGetCtx(void) { ES_NoiseSource *ctx = BSL_SAL_Malloc(sizeof(ES_NoiseSource)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(BSL_LIST_MALLOC_FAIL); return NULL; } (void)memset_s(ctx, sizeof(ES_NoiseSource), 0, sizeof(ES_NoiseSource)); uint32_t len = strlen("CPU-Jitter"); ctx->name = BSL_SAL_Malloc(len + 1); if (ctx->name == NULL) { BSL_SAL_Free(ctx); BSL_ERR_PUSH_ERROR(BSL_LIST_MALLOC_FAIL); return NULL; } (void)strncpy_s(ctx->name, len + 1, "CPU-Jitter", len); ctx->autoTest = true; ctx->para = (void *)EmptyConditionComp; ctx->init = ES_CpuJitterInit; ctx->read = ES_CpuJitterRead; ctx->deinit = ES_CpuJitterFree; ctx->minEntropy = HITLS_JITTER_MINENTROPY; // one byte bring 5 bits entropy return ctx; } #endif
2302_82127028/openHiTLS-examples_1508
crypto/entropy/src/es_ns_jitter.c
C
unknown
11,286
/* * 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_ENTROPY) && defined(HITLS_CRYPTO_ENTROPY_SYS) #include <stdint.h> #include <time.h> #include "securec.h" #include "bsl_err_internal.h" #include "crypt_errno.h" #include "es_noise_source.h" #define TIME_STAMP_ENTROPY_RCT_CUT_OFF 5 #define TIME_STAMP_ENTROPY_APT_WINDOW_SIZE 512 #define TIME_STAMP_ENTROPY_APT_CUT_OFF 39 static uint64_t CRPT_Gettick(void) { uint64_t tick = 0; struct timespec time; if (clock_gettime(CLOCK_MONOTONIC, &time) == 0) { tick = ((uint64_t)time.tv_sec & 0xFFFFFFFF) * 1000000000UL; tick = tick + (uint64_t)time.tv_nsec; } return tick; } static int32_t ES_TimeStampRead(void *ctx, uint32_t timeout, uint8_t *buf, uint32_t bufLen) { if (buf == NULL || bufLen == 0) { return -1; } (void)ctx; (void)timeout; for (uint32_t i = 0; i < bufLen; i++) { buf[i] = CRPT_Gettick() & 0xFF; } return CRYPT_SUCCESS; } ES_NoiseSource *ES_TimeStampGetCtx(void) { ES_NoiseSource *ctx = BSL_SAL_Malloc(sizeof(ES_NoiseSource)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(BSL_LIST_MALLOC_FAIL); return NULL; } (void)memset_s(ctx, sizeof(ES_NoiseSource), 0, sizeof(ES_NoiseSource)); uint32_t len = strlen("timestamp"); ctx->name = BSL_SAL_Malloc(len + 1); if (ctx->name == NULL) { BSL_SAL_Free(ctx); BSL_ERR_PUSH_ERROR(BSL_LIST_MALLOC_FAIL); return NULL; } (void)strncpy_s(ctx->name, len + 1, "timestamp", len); ctx->para = NULL; ctx->init = NULL; ctx->read = ES_TimeStampRead; ctx->deinit = NULL; ctx->minEntropy = 5; // one byte bring 5 bits entropy ctx->state.rctCutoff = TIME_STAMP_ENTROPY_RCT_CUT_OFF; ctx->state.aptCutOff = TIME_STAMP_ENTROPY_APT_CUT_OFF; ctx->state.aptWindowSize = TIME_STAMP_ENTROPY_APT_WINDOW_SIZE; return ctx; } #endif
2302_82127028/openHiTLS-examples_1508
crypto/entropy/src/es_ns_timestamp.c
C
unknown
2,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. */ #ifndef CRYPT_GMAC_H #define CRYPT_GMAC_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_GMAC #include <stdint.h> #include "crypt_types.h" #include "crypt_modes_gcm.h" #ifdef __cplusplus extern "C" { #endif /* __cpluscplus */ #define CRYPT_GMAC_SetParam NULL MODES_GCM_Ctx *CRYPT_GMAC_NewCtx(CRYPT_MAC_AlgId id); MODES_GCM_Ctx *CRYPT_GMAC_NewCtxEx(void *libCtx, CRYPT_MAC_AlgId id); int32_t CRYPT_GMAC_Init(MODES_GCM_Ctx *ctx, const uint8_t *key, uint32_t len, void *param); int32_t CRYPT_GMAC_Update(MODES_GCM_Ctx *ctx, const uint8_t *in, uint32_t len); int32_t CRYPT_GMAC_Final(MODES_GCM_Ctx *ctx, uint8_t *out, uint32_t *len); void CRYPT_GMAC_FreeCtx(MODES_GCM_Ctx *ctx); #define CRYPT_GMAC_Reinit NULL int32_t CRYPT_GMAC_Deinit(MODES_GCM_Ctx *ctx); int32_t CRYPT_GMAC_Ctrl(MODES_GCM_Ctx *ctx, int32_t opt, void *val, uint32_t len); #ifdef __cplusplus } #endif /* __cpluscplus */ #endif #endif
2302_82127028/openHiTLS-examples_1508
crypto/gmac/include/crypt_gmac.h
C
unknown
1,505
/* * 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_GMAC #include <stdlib.h> #include "crypt_gmac.h" #include "crypt_errno.h" #include "bsl_err_internal.h" static int32_t GmacIdToSymId(CRYPT_MAC_AlgId algId) { switch (algId) { case CRYPT_MAC_GMAC_AES128: return CRYPT_CIPHER_AES128_GCM; case CRYPT_MAC_GMAC_AES192: return CRYPT_CIPHER_AES192_GCM; case CRYPT_MAC_GMAC_AES256: return CRYPT_CIPHER_AES256_GCM; default: return CRYPT_CIPHER_MAX; } } MODES_GCM_Ctx *CRYPT_GMAC_NewCtx(CRYPT_MAC_AlgId id) { return MODES_GCM_NewCtx(GmacIdToSymId(id)); } MODES_GCM_Ctx *CRYPT_GMAC_NewCtxEx(void *libCtx, CRYPT_MAC_AlgId id) { (void)libCtx; return MODES_GCM_NewCtx(GmacIdToSymId(id)); } int32_t CRYPT_GMAC_Init(MODES_GCM_Ctx *ctx, const uint8_t *key, uint32_t len, void *param) { (void)param; return MODES_GCM_SetKey(&ctx->gcmCtx, key, len); } int32_t CRYPT_GMAC_Update(MODES_GCM_Ctx *ctx, const uint8_t *in, uint32_t len) { return MODES_GCM_Ctrl(ctx, CRYPT_CTRL_SET_AAD, (void *)(uintptr_t)in, len); } int32_t CRYPT_GMAC_Final(MODES_GCM_Ctx *ctx, uint8_t *out, uint32_t *len) { if (len == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } return MODES_GCM_Ctrl(ctx, CRYPT_CTRL_GET_TAG, (void *)(uintptr_t)out, *len); } void CRYPT_GMAC_FreeCtx(MODES_GCM_Ctx *ctx) { MODES_GCM_FreeCtx(ctx); } int32_t CRYPT_GMAC_Deinit(MODES_GCM_Ctx *ctx) { return MODES_GCM_DeInitCtx(ctx); } int32_t CRYPT_GMAC_Ctrl(MODES_GCM_Ctx *ctx, int32_t opt, void *val, uint32_t len) { switch (opt) { case CRYPT_CTRL_SET_IV: return MODES_GCM_Ctrl(ctx, CRYPT_CTRL_REINIT_STATUS, val, len); case CRYPT_CTRL_GET_MACLEN: return MODES_GCM_Ctrl(ctx, CRYPT_CTRL_GET_BLOCKSIZE, val, len); case CRYPT_CTRL_SET_TAGLEN: return MODES_GCM_Ctrl(ctx, CRYPT_CTRL_SET_TAGLEN, val, len); default: BSL_ERR_PUSH_ERROR(CRYPT_EAL_MAC_CTRL_TYPE_ERROR); return CRYPT_EAL_MAC_CTRL_TYPE_ERROR; } } #endif /* HITLS_CRYPTO_GMAC */
2302_82127028/openHiTLS-examples_1508
crypto/gmac/src/gmac.c
C
unknown
2,779
/* * 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_HKDF_H #define CRYPT_HKDF_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_HKDF #include <stdint.h> #include "crypt_local_types.h" #include "bsl_params.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus typedef struct CryptHkdfCtx CRYPT_HKDF_Ctx; /** * @ingroup HKDF * @brief Generate HKDF context. * * @retval Success: hkdf ctx. * Fails: NULL. */ CRYPT_HKDF_Ctx* CRYPT_HKDF_NewCtx(void); /** * @ingroup HKDF * @brief Generate HKDF context. * * @param libCtx [in] library context * @retval Success: hkdf ctx. * Fails: NULL. */ CRYPT_HKDF_Ctx* CRYPT_HKDF_NewCtxEx(void *libCtx); /** * @ingroup HKDF * @brief Set parameters for the HKDF context. * * @param ctx [in, out] Pointer to the HKDF context. * @param param [in] Either a MAC algorithm ID, a salt, a password, or an iteration count. * * @retval Success: CRYPT_SUCCESS * For other error codes, see crypt_errno.h. */ int32_t CRYPT_HKDF_SetParam(CRYPT_HKDF_Ctx *ctx, const BSL_Param *param); /** * @ingroup HKDF * @brief Obtain the derived key based on the passed HKDF context.. * * @param ctx [in, out] Pointer to the HKDF context. * @param out [out] Derived key buffer. * @param out [out] Derived key buffer size. * * @retval Success: CRYPT_SUCCESS * For other error codes, see crypt_errno.h. */ int32_t CRYPT_HKDF_Derive(CRYPT_HKDF_Ctx *ctx, uint8_t *out, uint32_t len); /** * @ingroup HKDF * @brief HKDF deinitialization API * * @param ctx [in, out] Pointer to the HKDF context. * * @retval #CRYPT_SUCCESS Deinitialization succeeded. * @retval #CRYPT_NULL_INPUT Pointer ctx is NULL */ int32_t CRYPT_HKDF_Deinit(CRYPT_HKDF_Ctx *ctx); /** * @ingroup HKDF * @brief free HKDF context. * * @param ctx [IN] HKDF handle */ void CRYPT_HKDF_FreeCtx(CRYPT_HKDF_Ctx *ctx); #ifdef __cplusplus } #endif // __cplusplus #endif // HITLS_CRYPTO_HKDF #endif // CRYPT_HKDF_H
2302_82127028/openHiTLS-examples_1508
crypto/hkdf/include/crypt_hkdf.h
C
unknown
2,483
/* * 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_HKDF #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 "eal_mac_local.h" #include "bsl_params.h" #include "crypt_params_key.h" #include "crypt_hkdf.h" #define HKDF_MAX_HMACSIZE 64 static const uint32_t HKDF_ID_LIST[] = { CRYPT_MAC_HMAC_MD5, CRYPT_MAC_HMAC_SHA1, CRYPT_MAC_HMAC_SHA224, CRYPT_MAC_HMAC_SHA256, CRYPT_MAC_HMAC_SHA384, CRYPT_MAC_HMAC_SHA512, }; bool CRYPT_HKDF_IsValidAlgId(CRYPT_MAC_AlgId id) { return ParamIdIsValid(id, HKDF_ID_LIST, sizeof(HKDF_ID_LIST) / sizeof(HKDF_ID_LIST[0])); } struct CryptHkdfCtx { CRYPT_MAC_AlgId macId; EAL_MacMethod macMeth; uint16_t mdSize; CRYPT_HKDF_MODE mode; void *macCtx; uint8_t *key; uint32_t keyLen; uint8_t *salt; uint32_t saltLen; uint8_t *prk; uint32_t prkLen; uint8_t *info; uint32_t infoLen; uint32_t *outLen; #ifdef HITLS_CRYPTO_PROVIDER void *libCtx; #endif bool hasGetMdSize; }; static bool CheckMacMethod(const EAL_MacMethod *macMeth) { return macMeth->freeCtx != NULL && macMeth->init != NULL && macMeth->update != NULL && macMeth->final != NULL && macMeth->deinit != NULL && macMeth->reinit != NULL; } int32_t CRYPT_HKDF_Extract(void *macCtx, const EAL_MacMethod *macMeth, const uint8_t *key, uint32_t keyLen, const uint8_t *salt, uint32_t saltLen, uint8_t *prk, uint32_t *prkLen) { int32_t ret; if (macCtx == NULL || macMeth == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (CheckMacMethod(macMeth) == false) { BSL_ERR_PUSH_ERROR(CRYPT_HKDF_ERR_MAC_METH); return CRYPT_HKDF_ERR_MAC_METH; } 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; } (void)macMeth->deinit(macCtx); GOTO_ERR_IF(macMeth->init(macCtx, salt, saltLen, NULL), ret); GOTO_ERR_IF(macMeth->update(macCtx, key, keyLen), ret); GOTO_ERR_IF(macMeth->final(macCtx, prk, prkLen), ret); ERR: (void)macMeth->deinit(macCtx); return ret; } static int32_t HKDF_ExpandParamCheck(void *macCtx, const EAL_MacMethod *macMeth, uint16_t mdSize, const uint8_t *prk, uint32_t prkLen, const uint8_t *info, uint32_t infoLen, const uint8_t *out, uint32_t outLen) { if (macCtx == NULL || macMeth == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (CheckMacMethod(macMeth) == false) { BSL_ERR_PUSH_ERROR(CRYPT_HKDF_ERR_MAC_METH); return CRYPT_HKDF_ERR_MAC_METH; } if (prk == NULL && prkLen > 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (info == NULL && infoLen > 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if ((out == NULL) || (outLen == 0)) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (mdSize == 0) { BSL_ERR_PUSH_ERROR(CRYPT_HKDF_PARAM_ERROR); return CRYPT_HKDF_PARAM_ERROR; } /* len cannot be larger than 255 * hashLen */ if (outLen > mdSize * 255) { BSL_ERR_PUSH_ERROR(CRYPT_HKDF_DKLEN_OVERFLOW); return CRYPT_HKDF_DKLEN_OVERFLOW; } return CRYPT_SUCCESS; } int32_t CRYPT_HKDF_Expand(void *macCtx, const EAL_MacMethod *macMeth, uint16_t mdSize, const uint8_t *prk, uint32_t prkLen, const uint8_t *info, uint32_t infoLen, uint8_t *out, uint32_t outLen) { int32_t ret = HKDF_ExpandParamCheck(macCtx, macMeth, mdSize, prk, prkLen, info, infoLen, out, outLen); if (ret != CRYPT_SUCCESS) { return ret; } uint8_t hash[HKDF_MAX_HMACSIZE]; uint32_t hashLen = mdSize; uint8_t counter = 1; uint32_t totalLen = 0; uint32_t n; (void)macMeth->deinit(macCtx); GOTO_ERR_IF(macMeth->init(macCtx, prk, prkLen, NULL), ret); /* ceil(a / b) = (a + b - 1) / b */ n = (outLen + hashLen - 1) / hashLen; for (uint32_t i = 1; i <= n; i++, counter++) { if (i > 1) { macMeth->reinit(macCtx); GOTO_ERR_IF(macMeth->update(macCtx, hash, hashLen), ret); } GOTO_ERR_IF(macMeth->update(macCtx, info, infoLen), ret); GOTO_ERR_IF(macMeth->update(macCtx, &counter, 1), ret); GOTO_ERR_IF(macMeth->final(macCtx, hash, &hashLen), ret); hashLen = hashLen > (outLen - totalLen) ? (outLen - totalLen) : hashLen; (void)memcpy_s(out + totalLen, outLen - totalLen, hash, hashLen); totalLen += hashLen; } ERR: (void)macMeth->deinit(macCtx); return ret; } int32_t CRYPT_HKDF(void *macCtx, const EAL_MacMethod *macMeth, uint16_t mdSize, const uint8_t *key, uint32_t keyLen, const uint8_t *salt, uint32_t saltLen, const uint8_t *info, uint32_t infoLen, uint8_t *out, uint32_t len) { int ret; uint8_t prk[HKDF_MAX_HMACSIZE]; uint32_t prkLen = HKDF_MAX_HMACSIZE; ret = CRYPT_HKDF_Extract(macCtx, macMeth, key, keyLen, salt, saltLen, prk, &prkLen); if (ret != CRYPT_SUCCESS) { return ret; } return CRYPT_HKDF_Expand(macCtx, macMeth, mdSize, prk, prkLen, info, infoLen, out, len); } CRYPT_HKDF_Ctx* CRYPT_HKDF_NewCtx(void) { CRYPT_HKDF_Ctx *ctx = BSL_SAL_Calloc(1, sizeof(CRYPT_HKDF_Ctx)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } return ctx; } #ifdef HITLS_CRYPTO_PROVIDER CRYPT_HKDF_Ctx* CRYPT_HKDF_NewCtxEx(void *libCtx) { (void)libCtx; CRYPT_HKDF_Ctx *ctx = BSL_SAL_Calloc(1, sizeof(CRYPT_HKDF_Ctx)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } #ifdef HITLS_CRYPTO_PROVIDER ctx->libCtx = libCtx; #endif return ctx; } #endif static int32_t HkdfGetMdSize(CRYPT_HKDF_Ctx *ctx, const char *mdAttr) { if (ctx->hasGetMdSize) { return CRYPT_SUCCESS; } void *libCtx = NULL; #ifdef HITLS_CRYPTO_PROVIDER libCtx = ctx->libCtx; #endif EAL_MdMethod mdMeth = {0}; EAL_MacDepMethod depMeth = {.method = {.md = &mdMeth}}; int32_t ret = EAL_MacFindDepMethod(ctx->macId, libCtx, mdAttr, &depMeth, NULL, true); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ctx->mdSize = mdMeth.mdSize; ctx->hasGetMdSize = true; return CRYPT_SUCCESS; } int32_t CRYPT_HKDF_SetMacMethod(CRYPT_HKDF_Ctx *ctx, const CRYPT_MAC_AlgId id) { if (!CRYPT_HKDF_IsValidAlgId(id)) { BSL_ERR_PUSH_ERROR(CRYPT_HKDF_PARAM_ERROR); return CRYPT_HKDF_PARAM_ERROR; } // free the old macCtx if (ctx->macCtx != NULL) { if (ctx->macMeth.freeCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_PBKDF2_ERR_MAC_METH); return CRYPT_PBKDF2_ERR_MAC_METH; } ctx->macMeth.freeCtx(ctx->macCtx); ctx->macCtx = NULL; (void)memset_s(&ctx->macMeth, sizeof(EAL_MacMethod), 0, sizeof(EAL_MacMethod)); } EAL_MacMethod *macMeth = EAL_MacFindMethod(id, &ctx->macMeth); if (macMeth == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_METH_NULL_MEMBER); return CRYPT_EAL_ERR_METH_NULL_MEMBER; } if (macMeth->newCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_HKDF_ERR_MAC_METH); return CRYPT_HKDF_ERR_MAC_METH; } #ifdef HITLS_CRYPTO_PROVIDER ctx->macCtx = macMeth->newCtx(ctx->libCtx, id); #else ctx->macCtx = macMeth->newCtx(NULL, id); #endif if (ctx->macCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ctx->macId = id; return CRYPT_SUCCESS; } int32_t CRYPT_HKDF_SetKey(CRYPT_HKDF_Ctx *ctx, const uint8_t *key, uint32_t keyLen) { if (key == NULL && keyLen > 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } BSL_SAL_ClearFree((void *)ctx->key, ctx->keyLen); ctx->key = BSL_SAL_Dump(key, keyLen); if (ctx->key == NULL && keyLen > 0) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ctx->keyLen = keyLen; return CRYPT_SUCCESS; } int32_t CRYPT_HKDF_SetSalt(CRYPT_HKDF_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_HKDF_SetPRK(CRYPT_HKDF_Ctx *ctx, const uint8_t *prk, uint32_t prkLen) { if (prk == NULL && prkLen > 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } BSL_SAL_ClearFree((void *)ctx->prk, ctx->prkLen); ctx->prk = BSL_SAL_Dump(prk, prkLen); if (ctx->prk == NULL && prkLen > 0) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ctx->prkLen = prkLen; return CRYPT_SUCCESS; } int32_t CRYPT_HKDF_SetInfo(CRYPT_HKDF_Ctx *ctx, const uint8_t *info, uint32_t infoLen) { if (info == NULL && infoLen > 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } BSL_SAL_ClearFree((void *)ctx->info, ctx->infoLen); ctx->info = BSL_SAL_Dump(info, infoLen); if (ctx->info == NULL && infoLen > 0) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ctx->infoLen = infoLen; return CRYPT_SUCCESS; } int32_t CRYPT_HKDF_SetOutLen(CRYPT_HKDF_Ctx *ctx, uint32_t *outLen) { if (outLen == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } ctx->outLen = outLen; return CRYPT_SUCCESS; } #ifdef HITLS_CRYPTO_PROVIDER static int32_t CRYPT_HKDF_SetMdAttr(CRYPT_HKDF_Ctx *ctx, const char *mdAttr, uint32_t valLen) { if (mdAttr == NULL || valLen == 0) { BSL_ERR_PUSH_ERROR(CRYPT_HKDF_PARAM_ERROR); return CRYPT_HKDF_PARAM_ERROR; } if (ctx->macCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_HKDF_ERR_MAC_ID_NOT_SET); return CRYPT_HKDF_ERR_MAC_ID_NOT_SET; } // Set mdAttr for macCtx if (ctx->macMeth.setParam == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_HKDF_ERR_MAC_METH); return CRYPT_HKDF_ERR_MAC_METH; } BSL_Param param[] = { {.key = CRYPT_PARAM_MD_ATTR, .valueType = BSL_PARAM_TYPE_UTF8_STR, .value = (void *)(uintptr_t)mdAttr, .valueLen = valLen, .useLen = 0}, BSL_PARAM_END }; int32_t ret = ctx->macMeth.setParam(ctx->macCtx, param); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return HkdfGetMdSize(ctx, mdAttr); } #endif int32_t CRYPT_HKDF_SetParam(CRYPT_HKDF_Ctx *ctx, const BSL_Param *param) { uint32_t val = 0; void *ptrVal = NULL; uint32_t len = 0; const BSL_Param *temp = NULL; int32_t ret = CRYPT_HKDF_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_MAC_ID)) != NULL) { len = sizeof(val); GOTO_ERR_IF(BSL_PARAM_GetValue(temp, CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &val, &len), ret); GOTO_ERR_IF(CRYPT_HKDF_SetMacMethod(ctx, val), ret); } if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_KDF_MODE)) != NULL) { len = sizeof(val); GOTO_ERR_IF(BSL_PARAM_GetValue(temp, CRYPT_PARAM_KDF_MODE, BSL_PARAM_TYPE_UINT32, &val, &len), ret); ctx->mode = val; } if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_KDF_KEY)) != NULL) { GOTO_ERR_IF(CRYPT_HKDF_SetKey(ctx, temp->value, temp->valueLen), ret); } if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_KDF_SALT)) != NULL) { GOTO_ERR_IF(CRYPT_HKDF_SetSalt(ctx, temp->value, temp->valueLen), ret); } if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_KDF_PRK)) != NULL) { GOTO_ERR_IF(CRYPT_HKDF_SetPRK(ctx, temp->value, temp->valueLen), ret); } if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_KDF_INFO)) != NULL) { GOTO_ERR_IF(CRYPT_HKDF_SetInfo(ctx, temp->value, temp->valueLen), ret); } if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_KDF_EXLEN)) != NULL) { len = sizeof(val); GOTO_ERR_IF(BSL_PARAM_GetPtrValue(temp, CRYPT_PARAM_KDF_EXLEN, BSL_PARAM_TYPE_UINT32_PTR, &ptrVal, &len), ret); GOTO_ERR_IF(CRYPT_HKDF_SetOutLen(ctx, ptrVal), ret); } #ifdef HITLS_CRYPTO_PROVIDER if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_MD_ATTR)) != NULL) { GOTO_ERR_IF(CRYPT_HKDF_SetMdAttr(ctx, temp->value, temp->valueLen), ret); } #endif ERR: return ret; } int32_t CRYPT_HKDF_Derive(CRYPT_HKDF_Ctx *ctx, uint8_t *out, uint32_t len) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } void *macCtx = ctx->macCtx; const EAL_MacMethod *macMeth = &ctx->macMeth; const uint8_t *key = ctx->key; uint32_t keyLen = ctx->keyLen; const uint8_t *salt = ctx->salt; uint32_t saltLen = ctx->saltLen; const uint8_t *prk = ctx->prk; uint32_t prkLen = ctx->prkLen; const uint8_t *info = ctx->info; uint32_t infoLen = ctx->infoLen; uint32_t *outLen = ctx->outLen; int32_t ret = HkdfGetMdSize(ctx, NULL); if (ret != CRYPT_SUCCESS) { return ret; } switch (ctx->mode) { case CRYPT_KDF_HKDF_MODE_FULL: return CRYPT_HKDF(macCtx, macMeth, ctx->mdSize, key, keyLen, salt, saltLen, info, infoLen, out, len); case CRYPT_KDF_HKDF_MODE_EXTRACT: return CRYPT_HKDF_Extract(macCtx, macMeth, key, keyLen, salt, saltLen, out, outLen); case CRYPT_KDF_HKDF_MODE_EXPAND: return CRYPT_HKDF_Expand(macCtx, macMeth, ctx->mdSize, prk, prkLen, info, infoLen, out, len); default: return CRYPT_HKDF_PARAM_ERROR; } } int32_t CRYPT_HKDF_Deinit(CRYPT_HKDF_Ctx *ctx) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->macMeth.freeCtx != NULL) { ctx->macMeth.freeCtx(ctx->macCtx); ctx->macCtx = NULL; } BSL_SAL_ClearFree((void *)ctx->key, ctx->keyLen); BSL_SAL_FREE(ctx->salt); BSL_SAL_ClearFree((void *)ctx->prk, ctx->prkLen); BSL_SAL_ClearFree((void *)ctx->info, ctx->infoLen); (void)memset_s(ctx, sizeof(CRYPT_HKDF_Ctx), 0, sizeof(CRYPT_HKDF_Ctx)); return CRYPT_SUCCESS; } void CRYPT_HKDF_FreeCtx(CRYPT_HKDF_Ctx *ctx) { if (ctx == NULL) { return; } if (ctx->macMeth.freeCtx != NULL) { ctx->macMeth.freeCtx(ctx->macCtx); } BSL_SAL_ClearFree((void *)ctx->key, ctx->keyLen); BSL_SAL_FREE(ctx->salt); BSL_SAL_ClearFree((void *)ctx->prk, ctx->prkLen); BSL_SAL_ClearFree((void *)ctx->info, ctx->infoLen); BSL_SAL_Free(ctx); } #endif // HITLS_CRYPTO_HKDF
2302_82127028/openHiTLS-examples_1508
crypto/hkdf/src/hkdf.c
C
unknown
15,939
/* * 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_HMAC_H #define CRYPT_HMAC_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_HMAC #include <stdint.h> #include "crypt_local_types.h" #include "bsl_params.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #define HMAC_MAXBLOCKSIZE 144 #define HMAC_MAXOUTSIZE 64 typedef struct HMAC_Ctx CRYPT_HMAC_Ctx; CRYPT_HMAC_Ctx *CRYPT_HMAC_NewCtx(CRYPT_MAC_AlgId id); CRYPT_HMAC_Ctx *CRYPT_HMAC_NewCtxEx(void *libCtx, CRYPT_MAC_AlgId id); int32_t CRYPT_HMAC_Init(CRYPT_HMAC_Ctx *ctx, const uint8_t *key, uint32_t len, BSL_Param *param); int32_t CRYPT_HMAC_Update(CRYPT_HMAC_Ctx *ctx, const uint8_t *in, uint32_t len); int32_t CRYPT_HMAC_Final(CRYPT_HMAC_Ctx *ctx, uint8_t *out, uint32_t *len); int32_t CRYPT_HMAC_Reinit(CRYPT_HMAC_Ctx *ctx); int32_t CRYPT_HMAC_Deinit(CRYPT_HMAC_Ctx *ctx); int32_t CRYPT_HMAC_Ctrl(CRYPT_HMAC_Ctx *ctx, CRYPT_MacCtrl opt, void *val, uint32_t len); #ifdef HITLS_CRYPTO_PROVIDER int32_t CRYPT_HMAC_SetParam(CRYPT_HMAC_Ctx *ctx, const BSL_Param *param); #else #define CRYPT_HMAC_SetParam NULL #endif // HITLS_CRYPTO_PROVIDER void CRYPT_HMAC_FreeCtx(CRYPT_HMAC_Ctx *ctx); #ifdef __cplusplus } #endif /* __cplusplus */ #endif // HITLS_CRYPTO_HMAC #endif // CRYPT_HMAC_H
2302_82127028/openHiTLS-examples_1508
crypto/hmac/include/crypt_hmac.h
C
unknown
1,760
/* * 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_HMAC #include <stdlib.h> #include "securec.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "bsl_err_internal.h" #include "crypt_utils.h" #include "eal_mac_local.h" #include "crypt_local_types.h" #include "crypt_hmac.h" struct HMAC_Ctx { CRYPT_MAC_AlgId hmacId; EAL_MdMethod method; void *mdCtx; /* md ctx */ void *oCtx; /* opad ctx */ void *iCtx; /* ipad ctx */ #ifdef HITLS_CRYPTO_PROVIDER void *libCtx; /* library context for external provider */ #endif }; CRYPT_HMAC_Ctx *CRYPT_HMAC_NewCtx(CRYPT_MAC_AlgId id) { CRYPT_HMAC_Ctx *ctx = BSL_SAL_Calloc(1, sizeof(CRYPT_HMAC_Ctx)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } ctx->hmacId = id; return ctx; } CRYPT_HMAC_Ctx *CRYPT_HMAC_NewCtxEx(void *libCtx, CRYPT_MAC_AlgId id) { CRYPT_HMAC_Ctx *ctx = BSL_SAL_Calloc(1, sizeof(CRYPT_HMAC_Ctx)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } ctx->hmacId = id; #ifdef HITLS_CRYPTO_PROVIDER ctx->libCtx = libCtx; #else (void)libCtx; #endif return ctx; } static void HmacCleanseData(uint8_t *tmp, uint32_t tmpLen, uint8_t *ipad, uint32_t ipadLen, uint8_t *opad, uint32_t opadLen) { BSL_SAL_CleanseData(tmp, tmpLen); BSL_SAL_CleanseData(ipad, ipadLen); BSL_SAL_CleanseData(opad, opadLen); } static int32_t HmacInitMdCtx(CRYPT_HMAC_Ctx *ctx, const char *attr) { if (ctx->mdCtx != NULL) { // already initialized at ctrl or init return CRYPT_SUCCESS; } #ifdef HITLS_CRYPTO_PROVIDER void *libCtx = ctx->libCtx; #else void *libCtx = NULL; #endif void *provCtx = NULL; EAL_MacDepMethod depMeth = {.method = {.md = &ctx->method}}; int32_t ret = EAL_MacFindDepMethod(ctx->hmacId, libCtx, attr, &depMeth, &provCtx, true); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (ctx->method.newCtx == NULL || ctx->method.freeCtx == NULL) { // Check the method will be used. BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } ctx->mdCtx = ctx->method.newCtx(provCtx, depMeth.id.mdId); if (ctx->mdCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); goto ERR; } ctx->iCtx = ctx->method.newCtx(provCtx, depMeth.id.mdId); if (ctx->iCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); goto ERR; } ctx->oCtx = ctx->method.newCtx(provCtx, depMeth.id.mdId); if (ctx->oCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); goto ERR; } return CRYPT_SUCCESS; ERR: ctx->method.freeCtx(ctx->mdCtx); ctx->mdCtx = NULL; ctx->method.freeCtx(ctx->iCtx); ctx->iCtx = NULL; ctx->method.freeCtx(ctx->oCtx); ctx->oCtx = NULL; return CRYPT_MEM_ALLOC_FAIL; } int32_t CRYPT_HMAC_Init(CRYPT_HMAC_Ctx *ctx, const uint8_t *key, uint32_t len, BSL_Param *param) { (void)param; if (ctx == NULL || (key == NULL && len != 0)) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } uint8_t tmp[HMAC_MAXBLOCKSIZE]; uint32_t tmpLen = HMAC_MAXBLOCKSIZE; const uint8_t *keyTmp = key; uint32_t i, keyLen = len; uint8_t ipad[HMAC_MAXBLOCKSIZE]; uint8_t opad[HMAC_MAXBLOCKSIZE]; int32_t ret = HmacInitMdCtx(ctx, NULL); if (ret != CRYPT_SUCCESS) { return ret; } if (ctx->method.init == NULL || ctx->method.update == NULL || ctx->method.final == NULL || ctx->method.deinit == NULL || ctx->method.copyCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (keyLen > ctx->method.blockSize) { keyTmp = tmp; GOTO_ERR_IF(ctx->method.init(ctx->mdCtx, NULL), ret); GOTO_ERR_IF(ctx->method.update(ctx->mdCtx, key, keyLen), ret); GOTO_ERR_IF(ctx->method.final(ctx->mdCtx, tmp, &tmpLen), ret); keyLen = ctx->method.mdSize; } for (i = 0; i < keyLen; i++) { ipad[i] = 0x36 ^ keyTmp[i]; opad[i] = 0x5c ^ keyTmp[i]; } for (i = keyLen; i < ctx->method.blockSize; i++) { ipad[i] = 0x36; opad[i] = 0x5c; } GOTO_ERR_IF(ctx->method.init(ctx->iCtx, NULL), ret); GOTO_ERR_IF(ctx->method.update(ctx->iCtx, ipad, ctx->method.blockSize), ret); GOTO_ERR_IF(ctx->method.init(ctx->oCtx, NULL), ret); GOTO_ERR_IF(ctx->method.update(ctx->oCtx, opad, ctx->method.blockSize), ret); GOTO_ERR_IF(ctx->method.copyCtx(ctx->mdCtx, ctx->iCtx), ret); HmacCleanseData(tmp, HMAC_MAXBLOCKSIZE, ipad, HMAC_MAXBLOCKSIZE, opad, HMAC_MAXBLOCKSIZE); return CRYPT_SUCCESS; ERR: HmacCleanseData(tmp, HMAC_MAXBLOCKSIZE, ipad, HMAC_MAXBLOCKSIZE, opad, HMAC_MAXBLOCKSIZE); ctx->method.deinit(ctx->mdCtx); ctx->method.deinit(ctx->iCtx); ctx->method.deinit(ctx->oCtx); return ret; } int32_t CRYPT_HMAC_Update(CRYPT_HMAC_Ctx *ctx, const uint8_t *in, uint32_t len) { if (ctx == NULL || ctx->method.update == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } return ctx->method.update(ctx->mdCtx, in, len); } int32_t CRYPT_HMAC_Final(CRYPT_HMAC_Ctx *ctx, uint8_t *out, uint32_t *len) { if (ctx == NULL || ctx->method.final == NULL || ctx->method.copyCtx == NULL || ctx->method.update == NULL || out == NULL || len == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } const EAL_MdMethod *method = &ctx->method; if (*len < method->mdSize) { BSL_ERR_PUSH_ERROR(CRYPT_HMAC_OUT_BUFF_LEN_NOT_ENOUGH); return CRYPT_HMAC_OUT_BUFF_LEN_NOT_ENOUGH; } *len = method->mdSize; uint8_t tmp[HMAC_MAXOUTSIZE]; uint32_t tmpLen = sizeof(tmp); int32_t ret = method->final(ctx->mdCtx, tmp, &tmpLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = method->copyCtx(ctx->mdCtx, ctx->oCtx); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = method->update(ctx->mdCtx, tmp, tmpLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } return method->final(ctx->mdCtx, out, len); } int32_t CRYPT_HMAC_Reinit(CRYPT_HMAC_Ctx *ctx) { if (ctx == NULL || ctx->method.copyCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } ctx->method.copyCtx(ctx->mdCtx, ctx->iCtx); return CRYPT_SUCCESS; } int32_t CRYPT_HMAC_Deinit(CRYPT_HMAC_Ctx *ctx) { if (ctx == NULL || ctx->method.deinit == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } (void)ctx->method.deinit(ctx->mdCtx); (void)ctx->method.deinit(ctx->iCtx); (void)ctx->method.deinit(ctx->oCtx); return CRYPT_SUCCESS; } static int32_t CRYPT_HMAC_GetMacLen(CRYPT_HMAC_Ctx *ctx) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return 0; } int32_t ret = HmacInitMdCtx(ctx, NULL); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return 0; } return ctx->method.mdSize; } static int32_t HmacGetLen(CRYPT_HMAC_Ctx *ctx, GetLenFunc func, void *val, uint32_t len) { if (len != sizeof(uint32_t)) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } *(uint32_t *)val = func(ctx); return CRYPT_SUCCESS; } int32_t CRYPT_HMAC_Ctrl(CRYPT_HMAC_Ctx *ctx, CRYPT_MacCtrl opt, void *val, uint32_t len) { if (ctx == NULL || val == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } switch (opt) { case CRYPT_CTRL_GET_MACLEN: return HmacGetLen(ctx, (GetLenFunc)CRYPT_HMAC_GetMacLen, val, len); default: BSL_ERR_PUSH_ERROR(CRYPT_HMAC_ERR_UNSUPPORTED_CTRL_OPTION); return CRYPT_HMAC_ERR_UNSUPPORTED_CTRL_OPTION; } } static void HmacFreeMdCtx(CRYPT_HMAC_Ctx *ctx) { if (ctx->method.freeCtx == NULL) { return; } ctx->method.freeCtx(ctx->mdCtx); ctx->mdCtx = NULL; ctx->method.freeCtx(ctx->iCtx); ctx->iCtx = NULL; ctx->method.freeCtx(ctx->oCtx); ctx->oCtx = NULL; } #ifdef HITLS_CRYPTO_PROVIDER int32_t CRYPT_HMAC_SetParam(CRYPT_HMAC_Ctx *ctx, const BSL_Param *param) { const BSL_Param *temp = NULL; int32_t ret = CRYPT_HMAC_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_MD_ATTR)) != NULL) { if (temp->valueLen == 0) { BSL_ERR_PUSH_ERROR(CRYPT_HMAC_PARAM_ERROR); return CRYPT_HMAC_PARAM_ERROR; } HmacFreeMdCtx(ctx); GOTO_ERR_IF(HmacInitMdCtx(ctx, (const char *)temp->value), ret); } ERR: return ret; } #endif // HITLS_CRYPTO_PROVIDER void CRYPT_HMAC_FreeCtx(CRYPT_HMAC_Ctx *ctx) { if (ctx == NULL) { return; } HmacFreeMdCtx(ctx); BSL_SAL_Free(ctx); } #endif // HITLS_CRYPTO_HMAC
2302_82127028/openHiTLS-examples_1508
crypto/hmac/src/hmac.c
C
unknown
9,767
/* * 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_EAL) && defined(HITLS_CRYPTO_HPKE) #include <string.h> #include "securec.h" #include "crypt_eal_pkey.h" #include "crypt_eal_kdf.h" #include "crypt_eal_cipher.h" #include "crypt_eal_rand.h" #include "crypt_algid.h" #include "crypt_errno.h" #include "crypt_bn.h" #include "crypt_params_key.h" #include "bsl_err_internal.h" #include "bsl_sal.h" #include "bsl_bytes.h" #include "crypt_eal_hpke.h" // Data from RFC9180 #define HPKE_HKDF_MAX_EXTRACT_KEY_LEN 64 #define HPKE_KEM_MAX_SHARED_KEY_LEN 64 #define HPKE_KEM_MAX_ENCAPSULATED_KEY_LEN 133 #define HPKE_KEM_MAX_PUBLIC_KEY_LEN 133 #define HPKE_KEM_MAX_PRIVATE_KEY_LEN 66 #define HPKE_KEM_DH_MAX_SHARED_KEY_LEN 66 // p521 key length #define MAX_ECC_PARAM_LEN 66 #define HPKE_AEAD_NONCE_LEN 12 #define HPKE_AEAD_TAG_LEN 16 #define HPKE_KEM_SUITEID_LEN 5 #define HPKE_HPKE_SUITEID_LEN 10 typedef struct { // PSK mode uint8_t *psk; uint32_t pskLen; uint8_t *pskId; uint32_t pskIdLen; // AUTH mode, Sender's private key held by the sender, Sender's public key held by the recipient CRYPT_EAL_PkeyCtx *authPkey; } AuthInfo; struct CRYPT_EAL_HpkeCtx { uint8_t role; // Sender or Recipient uint8_t mode; // HPKE mode uint8_t kemIndex; uint8_t kdfIndex; uint8_t aeadIndex; uint8_t *symKey; uint8_t *baseNonce; uint32_t symKeyLen; uint32_t baseNonceLen; uint8_t *exporterSecret; uint8_t *sharedSecret; uint32_t exporterSecretLen; uint32_t sharedSecretLen; uint64_t seq; // Message sequence number CRYPT_EAL_KdfCTX *kdfCtx; CRYPT_EAL_CipherCtx *cipherCtx; CRYPT_EAL_LibCtx *libCtx; char *attrName; AuthInfo *authInfo; }; typedef struct { uint16_t hpkeKemId; CRYPT_PKEY_AlgId pkeyId; CRYPT_PKEY_ParaId curveId; CRYPT_MAC_AlgId macId; uint16_t privateKeyLen; uint16_t sharedKeyLen; uint16_t encapsulatedKeyLen; uint16_t hkdfExtractKeyLen; } HPKE_KemAlgInfo; typedef struct { uint16_t hpkeKdfId; uint16_t hkdfExtractKeyLen; CRYPT_MAC_AlgId macId; } HPKE_KdfAlgInfo; typedef struct { uint16_t hpkeAeadId; uint16_t keyLen; CRYPT_CIPHER_AlgId cipherId; } HPKE_AeadAlgInfo; #define HPKE_INVALID_ALG_INDEX 0xFF static HPKE_KemAlgInfo g_hpkeKemAlgInfo[] = { {CRYPT_KEM_DHKEM_P256_HKDF_SHA256, CRYPT_PKEY_ECDH, CRYPT_ECC_NISTP256, CRYPT_MAC_HMAC_SHA256, 32, 32, 65, 32}, {CRYPT_KEM_DHKEM_P384_HKDF_SHA384, CRYPT_PKEY_ECDH, CRYPT_ECC_NISTP384, CRYPT_MAC_HMAC_SHA384, 48, 48, 97, 48}, {CRYPT_KEM_DHKEM_P521_HKDF_SHA512, CRYPT_PKEY_ECDH, CRYPT_ECC_NISTP521, CRYPT_MAC_HMAC_SHA512, 66, 64, 133, 64}, {CRYPT_KEM_DHKEM_X25519_HKDF_SHA256, CRYPT_PKEY_X25519, CRYPT_PKEY_PARAID_MAX, CRYPT_MAC_HMAC_SHA256, 32, 32, 32, 32}, }; static HPKE_KdfAlgInfo g_hpkeKdfAlgInfo[] = { {CRYPT_KDF_HKDF_SHA256, 32, CRYPT_MAC_HMAC_SHA256}, {CRYPT_KDF_HKDF_SHA384, 48, CRYPT_MAC_HMAC_SHA384}, {CRYPT_KDF_HKDF_SHA512, 64, CRYPT_MAC_HMAC_SHA512}, }; static HPKE_AeadAlgInfo g_hpkeAeadAlgInfo[] = { {CRYPT_AEAD_AES_128_GCM, 16, CRYPT_CIPHER_AES128_GCM}, {CRYPT_AEAD_AES_256_GCM, 32, CRYPT_CIPHER_AES256_GCM}, {CRYPT_AEAD_CHACHA20_POLY1305, 32, CRYPT_CIPHER_CHACHA20_POLY1305}, {CRYPT_AEAD_EXPORT_ONLY, 0, CRYPT_CIPHER_MAX}, }; static int32_t HpkeCheckCipherSuite(const CRYPT_HPKE_CipherSuite *cipherSuite, uint8_t *kemIndex, uint8_t *kdfIndex, uint8_t *aeadIndex) { uint8_t kemPosition = HPKE_INVALID_ALG_INDEX; uint8_t kdfPosition = HPKE_INVALID_ALG_INDEX; uint8_t aeadPosition = HPKE_INVALID_ALG_INDEX; uint8_t i; for (i = 0; i < sizeof(g_hpkeKemAlgInfo) / sizeof(HPKE_KemAlgInfo); i++) { if (cipherSuite->kemId == g_hpkeKemAlgInfo[i].hpkeKemId) { kemPosition = i; break; } } for (i = 0; i < sizeof(g_hpkeKdfAlgInfo) / sizeof(HPKE_KdfAlgInfo); i++) { if (cipherSuite->kdfId == g_hpkeKdfAlgInfo[i].hpkeKdfId) { kdfPosition = i; break; } } for (i = 0; i < sizeof(g_hpkeAeadAlgInfo) / sizeof(HPKE_AeadAlgInfo); i++) { if (cipherSuite->aeadId == g_hpkeAeadAlgInfo[i].hpkeAeadId) { aeadPosition = i; break; } } if (kemPosition == HPKE_INVALID_ALG_INDEX || kdfPosition == HPKE_INVALID_ALG_INDEX || aeadPosition == HPKE_INVALID_ALG_INDEX) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } if (kemIndex != NULL) { *kemIndex = kemPosition; } if (kdfIndex != NULL) { *kdfIndex = kdfPosition; } if (aeadIndex != NULL) { *aeadIndex = aeadPosition; } return CRYPT_SUCCESS; } static int32_t InitCipherSuiteCtx(CRYPT_EAL_HpkeCtx *ctx, uint8_t aeadIndex, CRYPT_EAL_LibCtx *libCtx, const char *attrName) { CRYPT_EAL_KdfCTX *kdfCtx = NULL; CRYPT_EAL_CipherCtx *cipherCtx = NULL; kdfCtx = CRYPT_EAL_ProviderKdfNewCtx(libCtx, CRYPT_KDF_HKDF, attrName); if (kdfCtx == NULL) { return CRYPT_HPKE_FAILED_FETCH_KDF; } if (g_hpkeAeadAlgInfo[aeadIndex].hpkeAeadId != CRYPT_AEAD_EXPORT_ONLY) { cipherCtx = CRYPT_EAL_ProviderCipherNewCtx(libCtx, g_hpkeAeadAlgInfo[aeadIndex].cipherId, attrName); if (cipherCtx == NULL) { CRYPT_EAL_KdfFreeCtx(kdfCtx); return CRYPT_HPKE_FAILED_FETCH_CIPHER; } } ctx->kdfCtx = kdfCtx; ctx->cipherCtx = cipherCtx; return CRYPT_SUCCESS; } static int32_t HpkeInitCipherSuite(CRYPT_EAL_HpkeCtx *ctx, CRYPT_HPKE_CipherSuite *cipherSuite, CRYPT_EAL_LibCtx *libCtx, const char *attrName) { uint8_t kemIndex; uint8_t kdfIndex; uint8_t aeadIndex; int32_t ret; ret = HpkeCheckCipherSuite(cipherSuite, &kemIndex, &kdfIndex, &aeadIndex); if (ret != CRYPT_SUCCESS) { return ret; } ret = InitCipherSuiteCtx(ctx, aeadIndex, libCtx, attrName); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ctx->kemIndex = kemIndex; ctx->aeadIndex = aeadIndex; ctx->kdfIndex = kdfIndex; return CRYPT_SUCCESS; } CRYPT_EAL_HpkeCtx *CRYPT_EAL_HpkeNewCtx(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_HPKE_Role role, CRYPT_HPKE_Mode mode, CRYPT_HPKE_CipherSuite cipherSuite) { if (role != CRYPT_HPKE_SENDER && role != CRYPT_HPKE_RECIPIENT) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return NULL; } if (mode != CRYPT_HPKE_MODE_BASE && mode != CRYPT_HPKE_MODE_PSK && mode != CRYPT_HPKE_MODE_AUTH && mode != CRYPT_HPKE_MODE_AUTH_PSK) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return NULL; } CRYPT_EAL_HpkeCtx *ctx = (CRYPT_EAL_HpkeCtx*)BSL_SAL_Calloc(1, sizeof(CRYPT_EAL_HpkeCtx)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } int32_t ret = HpkeInitCipherSuite(ctx, &cipherSuite, libCtx, attrName); if (ret != CRYPT_SUCCESS) { CRYPT_EAL_HpkeFreeCtx(ctx); return NULL; } if (attrName != NULL && strlen(attrName) > 0) { ctx->attrName = BSL_SAL_Dump(attrName, (uint32_t)strlen(attrName) + 1); if (ctx->attrName == NULL) { CRYPT_EAL_HpkeFreeCtx(ctx); BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } } if (mode == CRYPT_HPKE_MODE_PSK || mode == CRYPT_HPKE_MODE_AUTH || mode == CRYPT_HPKE_MODE_AUTH_PSK) { AuthInfo *authInfo = (AuthInfo *)BSL_SAL_Calloc(1, sizeof(AuthInfo)); if (authInfo == NULL) { CRYPT_EAL_HpkeFreeCtx(ctx); BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } ctx->authInfo = authInfo; } ctx->mode = mode; ctx->role = role; ctx->libCtx = libCtx; return ctx; } int32_t CRYPT_EAL_HpkeGetEncapKeyLen(CRYPT_HPKE_CipherSuite cipherSuite, uint32_t *encapKeyLen) { if (encapKeyLen == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } uint8_t kemIndex; int32_t ret = HpkeCheckCipherSuite(&cipherSuite, &kemIndex, NULL, NULL); if (ret != CRYPT_SUCCESS) { return ret; } *encapKeyLen = g_hpkeKemAlgInfo[kemIndex].encapsulatedKeyLen; return CRYPT_SUCCESS; } static int32_t HpkeCreatePkeyCtx(uint8_t kemIdex, CRYPT_EAL_PkeyCtx **pkeyCtx, CRYPT_EAL_LibCtx *libCtx, const char *attrName) { CRYPT_PKEY_AlgId algId = g_hpkeKemAlgInfo[kemIdex].pkeyId; CRYPT_EAL_PkeyCtx *pkey = NULL; #ifdef HITLS_CRYPTO_PROVIDER pkey = CRYPT_EAL_ProviderPkeyNewCtx(libCtx, algId, CRYPT_EAL_PKEY_EXCH_OPERATE, attrName); #else (void)libCtx; (void)attrName; pkey = CRYPT_EAL_PkeyNewCtx(algId); #endif if (pkey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_HPKE_FAILED_FETCH_PKEY); return CRYPT_HPKE_FAILED_FETCH_PKEY; } if (algId == CRYPT_PKEY_ECDH) { CRYPT_PKEY_ParaId curveId = g_hpkeKemAlgInfo[kemIdex].curveId; int32_t ret = CRYPT_EAL_PkeySetParaById(pkey, curveId); if (ret != CRYPT_SUCCESS) { CRYPT_EAL_PkeyFreeCtx(pkey); return ret; } } *pkeyCtx = pkey; return CRYPT_SUCCESS; } static int32_t HpkeCreatePubKey(uint8_t kemIdex, uint8_t *pubKey, uint32_t pubKeyLen, CRYPT_EAL_PkeyCtx **pkey, CRYPT_EAL_LibCtx *libCtx, const char *attrName) { CRYPT_EAL_PkeyCtx *tmpPkey = NULL; int32_t ret = HpkeCreatePkeyCtx(kemIdex, &tmpPkey, libCtx, attrName); if (ret != CRYPT_SUCCESS) { return ret; } CRYPT_EAL_PkeyPub pub = {0}; pub.id = CRYPT_EAL_PkeyGetId(tmpPkey); pub.key.eccPub.data = pubKey; // compatible curve25519Pub pub.key.eccPub.len = pubKeyLen; ret = CRYPT_EAL_PkeySetPub(tmpPkey, &pub); if (ret != CRYPT_SUCCESS) { CRYPT_EAL_PkeyFreeCtx(tmpPkey); return ret; } *pkey = tmpPkey; return CRYPT_SUCCESS; } static int32_t HpkeCreatePriKey(uint8_t kemIdex, uint8_t *priKey, uint32_t priKeyLen, CRYPT_EAL_PkeyCtx **pkey, CRYPT_EAL_LibCtx *libCtx, const char *attrName) { CRYPT_EAL_PkeyCtx *tmpPkey = *pkey; int32_t ret; if (tmpPkey == NULL) { ret = HpkeCreatePkeyCtx(kemIdex, &tmpPkey, libCtx, attrName); if (ret != CRYPT_SUCCESS) { return ret; } } CRYPT_EAL_PkeyPrv prv = {0}; prv.id = CRYPT_EAL_PkeyGetId(tmpPkey); prv.key.eccPrv.data = priKey; prv.key.eccPrv.len = priKeyLen; ret = CRYPT_EAL_PkeySetPrv(tmpPkey, &prv); if (ret != CRYPT_SUCCESS) { goto EXIT; } if (g_hpkeKemAlgInfo[kemIdex].hpkeKemId == CRYPT_KEM_DHKEM_X25519_HKDF_SHA256) { ret = CRYPT_EAL_PkeyCtrl(tmpPkey, CRYPT_CTRL_GEN_X25519_PUBLICKEY, NULL, 0); } else { ret = CRYPT_EAL_PkeyCtrl(tmpPkey, CRYPT_CTRL_GEN_ECC_PUBLICKEY, NULL, 0); } if (ret == CRYPT_SUCCESS) { *pkey = tmpPkey; return CRYPT_SUCCESS; } EXIT: if (*pkey == NULL) { CRYPT_EAL_PkeyFreeCtx(tmpPkey); } return ret; } static inline void HpkeGenerateHpkeSuiteId(uint8_t kemIndex, uint8_t kdfIndex, uint8_t aeadIndex, uint8_t *suiteId, uint32_t suiteIdLen) { (void)memcpy_s(suiteId, suiteIdLen, "HPKE", strlen("HPKE")); uint32_t offset = strlen("HPKE"); BSL_Uint16ToByte(g_hpkeKemAlgInfo[kemIndex].hpkeKemId, suiteId + offset); offset += sizeof(uint16_t); BSL_Uint16ToByte(g_hpkeKdfAlgInfo[kdfIndex].hpkeKdfId, suiteId + offset); offset += sizeof(uint16_t); BSL_Uint16ToByte(g_hpkeAeadAlgInfo[aeadIndex].hpkeAeadId, suiteId + offset); } static inline void HpkeGenerateKemSuiteId(uint8_t kemIdex, uint8_t *suiteId, uint32_t suiteIdLen) { uint16_t kemId = g_hpkeKemAlgInfo[kemIdex].hpkeKemId; (void)memcpy_s(suiteId, suiteIdLen, "KEM", strlen("KEM")); uint32_t offset = strlen("KEM"); BSL_Uint16ToByte(kemId, suiteId + offset); } typedef struct { int32_t macId; uint8_t *key; uint32_t keyLen; uint8_t *salt; uint32_t saltLen; } HPKE_HkdfExtractParams; typedef struct { int32_t macId; uint8_t *prk; uint32_t prkLen; uint8_t *info; uint32_t infoLen; } HPKE_HkdfExpandParam; static int32_t HpkeHkdfExtract(CRYPT_EAL_KdfCTX *hkdfCtx, HPKE_HkdfExtractParams *extractParams, uint8_t *out, uint32_t outLen) { int32_t ret; CRYPT_HKDF_MODE mode = CRYPT_KDF_HKDF_MODE_EXTRACT; BSL_Param params[6] = {{0}, {0}, {0}, {0}, {0}, BSL_PARAM_END}; // 6 parameters ret = BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, (void *)&extractParams->macId, sizeof(int32_t)); if (ret != CRYPT_SUCCESS) { return ret; } ret = BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_MODE, BSL_PARAM_TYPE_UINT32, (void *)&mode, sizeof(mode)); if (ret != CRYPT_SUCCESS) { return ret; } ret = BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_KEY, BSL_PARAM_TYPE_OCTETS, // param index 2 (void *)extractParams->key, extractParams->keyLen); if (ret != CRYPT_SUCCESS) { return ret; } ret = BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, // param index 3 (void *)extractParams->salt, extractParams->saltLen); if (ret != CRYPT_SUCCESS) { return ret; } ret = BSL_PARAM_InitValue(&params[4], CRYPT_PARAM_KDF_EXLEN, BSL_PARAM_TYPE_UINT32_PTR, // param index 4 (void *)&outLen, sizeof(outLen)); if (ret != CRYPT_SUCCESS) { return ret; } ret = CRYPT_EAL_KdfSetParam(hkdfCtx, params); if (ret != CRYPT_SUCCESS) { return ret; } ret = CRYPT_EAL_KdfDerive(hkdfCtx, out, outLen); CRYPT_EAL_KdfDeInitCtx(hkdfCtx); return ret; } static int32_t HpkeHkdfExpand(CRYPT_EAL_KdfCTX *hkdfCtx, HPKE_HkdfExpandParam *expandParams, uint8_t *out, uint32_t outLen) { int32_t ret; CRYPT_HKDF_MODE mode = CRYPT_KDF_HKDF_MODE_EXPAND; BSL_Param params[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END}; // 5 parameters ret = BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, (void *)&expandParams->macId, sizeof(int32_t)); if (ret != CRYPT_SUCCESS) { return ret; } ret = BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_MODE, BSL_PARAM_TYPE_UINT32, (void *)&mode, sizeof(mode)); if (ret != CRYPT_SUCCESS) { return ret; } ret = BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_PRK, BSL_PARAM_TYPE_OCTETS, // param index 2 (void *)expandParams->prk, expandParams->prkLen); if (ret != CRYPT_SUCCESS) { return ret; } ret = BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_INFO, BSL_PARAM_TYPE_OCTETS, // param index 3 (void *)expandParams->info, expandParams->infoLen); if (ret != CRYPT_SUCCESS) { return ret; } ret = CRYPT_EAL_KdfSetParam(hkdfCtx, params); if (ret != CRYPT_SUCCESS) { return ret; } ret = CRYPT_EAL_KdfDerive(hkdfCtx, out, outLen); CRYPT_EAL_KdfDeInitCtx(hkdfCtx); return ret; } typedef struct { int32_t macId; uint8_t *salt; uint32_t saltLen; uint8_t *label; uint32_t labelLen; uint8_t *ikm; uint32_t ikmLen; uint8_t *suiteId; uint32_t suiteIdLen; } HPKE_LabeledExtractParams; typedef struct { int32_t macId; uint8_t *prk; uint32_t prkLen; uint8_t *label; uint32_t labelLen; uint8_t *info; uint32_t infoLen; uint8_t *suiteId; uint32_t suiteIdLen; } HPKE_LabeledExpandParams; static int32_t HpkeLabeledExtract(CRYPT_EAL_KdfCTX *hkdfCtx, HPKE_LabeledExtractParams *params, uint8_t *out, uint32_t outLen) { // labeled_ikm = "HPKE-v1" || suite_id || label || ikm const uint8_t *version = (const uint8_t *)"HPKE-v1"; uint32_t versionLen = strlen("HPKE-v1"); uint32_t partialLen = versionLen + params->suiteIdLen + params->labelLen; if (params->ikmLen > (UINT32_MAX - partialLen)) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } uint32_t labeledIkmLen = partialLen + params->ikmLen; uint8_t *labeledIkm = (uint8_t *)BSL_SAL_Malloc(labeledIkmLen); if (labeledIkm == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } uint32_t offset = 0; (void)memcpy_s(labeledIkm + offset, labeledIkmLen - offset, version, versionLen); offset += versionLen; (void)memcpy_s(labeledIkm + offset, labeledIkmLen - offset, params->suiteId, params->suiteIdLen); offset += params->suiteIdLen; (void)memcpy_s(labeledIkm + offset, labeledIkmLen - offset, params->label, params->labelLen); offset += params->labelLen; (void)memcpy_s(labeledIkm + offset, labeledIkmLen - offset, params->ikm, params->ikmLen); HPKE_HkdfExtractParams extractParams = {params->macId, labeledIkm, labeledIkmLen, params->salt, params->saltLen}; int32_t ret = HpkeHkdfExtract(hkdfCtx, &extractParams, out, outLen); BSL_SAL_ClearFree(labeledIkm, labeledIkmLen); return ret; } static int32_t HpkeLabeledExpand(CRYPT_EAL_KdfCTX *hkdfCtx, HPKE_LabeledExpandParams *params, uint8_t *out, uint32_t outLen) { // labeled_info = I2OSP(L, 2) || "HPKE-v1" || suite_id || label || info const uint8_t *version = (const uint8_t *)"HPKE-v1"; uint32_t versionLen = strlen("HPKE-v1"); uint32_t partialLen = sizeof(uint16_t) + versionLen + params->suiteIdLen + params->labelLen; if (params->infoLen > (UINT32_MAX - partialLen)) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } uint32_t labeledInfoLen = partialLen + params->infoLen; uint8_t *labeledInfo = (uint8_t *)BSL_SAL_Malloc(labeledInfoLen); if (labeledInfo == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } BSL_Uint16ToByte((uint16_t)outLen, labeledInfo); uint32_t offset = sizeof(uint16_t); (void)memcpy_s(labeledInfo + offset, labeledInfoLen - offset, version, versionLen); offset += versionLen; (void)memcpy_s(labeledInfo + offset, labeledInfoLen - offset, params->suiteId, params->suiteIdLen); offset += params->suiteIdLen; (void)memcpy_s(labeledInfo + offset, labeledInfoLen - offset, params->label, params->labelLen); offset += params->labelLen; (void)memcpy_s(labeledInfo + offset, labeledInfoLen - offset, params->info, params->infoLen); HPKE_HkdfExpandParam expandParams = {params->macId, params->prk, params->prkLen, labeledInfo, labeledInfoLen}; int32_t ret = HpkeHkdfExpand(hkdfCtx, &expandParams, out, outLen); BSL_SAL_FREE(labeledInfo); return ret; } static int32_t GetPubKeyData(CRYPT_EAL_PkeyCtx *pkey, uint8_t *out, uint32_t *outLen) { CRYPT_EAL_PkeyPub ephemPub = { 0 }; ephemPub.id = CRYPT_EAL_PkeyGetId(pkey); ephemPub.key.eccPub.data = out; ephemPub.key.eccPub.len = *outLen; // compatible curve25519Pub, CRYPT_Data type. int32_t ret = CRYPT_EAL_PkeyGetPub(pkey, &ephemPub); if (ret != CRYPT_SUCCESS) { return ret; } *outLen = ephemPub.key.eccPub.len; return CRYPT_SUCCESS; } static int32_t HpkeComputeSharedSecret(CRYPT_EAL_HpkeCtx *ctx, CRYPT_EAL_PkeyCtx *priKey, CRYPT_EAL_PkeyCtx *pubKey, CRYPT_EAL_PkeyCtx *authKey, uint8_t *kemContext, uint32_t kemContextLen, uint8_t *sharedSecret, uint32_t sharedSecretLen) { uint8_t dh[HPKE_KEM_DH_MAX_SHARED_KEY_LEN * 2]; uint32_t dhLen = HPKE_KEM_DH_MAX_SHARED_KEY_LEN; int32_t ret = CRYPT_EAL_PkeyComputeShareKey(priKey, pubKey, dh, &dhLen); if (ret != CRYPT_SUCCESS) { memset_s(dh, dhLen, 0, dhLen); return ret; } if (ctx->mode == CRYPT_HPKE_MODE_AUTH || ctx->mode == CRYPT_HPKE_MODE_AUTH_PSK) { uint32_t dh0Len = HPKE_KEM_DH_MAX_SHARED_KEY_LEN; if (ctx->role == CRYPT_HPKE_SENDER) { ret = CRYPT_EAL_PkeyComputeShareKey(authKey, pubKey, dh + dhLen, &dh0Len); } if (ctx->role == CRYPT_HPKE_RECIPIENT) { ret = CRYPT_EAL_PkeyComputeShareKey(priKey, authKey, dh + dhLen, &dh0Len); } if (ret != CRYPT_SUCCESS) { memset_s(dh, dhLen + dh0Len, 0, dhLen + dh0Len); return ret; } dhLen = dhLen + dh0Len; } uint8_t suiteId[HPKE_KEM_SUITEID_LEN]; HpkeGenerateKemSuiteId(ctx->kemIndex, suiteId, HPKE_KEM_SUITEID_LEN); CRYPT_MAC_AlgId macId = g_hpkeKemAlgInfo[ctx->kemIndex].macId; uint32_t eaePrkLen = g_hpkeKemAlgInfo[ctx->kemIndex].hkdfExtractKeyLen; uint8_t eaePrk[HPKE_HKDF_MAX_EXTRACT_KEY_LEN]; HPKE_LabeledExtractParams extractParams = {macId, NULL, 0, (uint8_t *)"eae_prk", strlen("eae_prk"), dh, dhLen, suiteId, HPKE_KEM_SUITEID_LEN}; ret = HpkeLabeledExtract(ctx->kdfCtx, &extractParams, eaePrk, eaePrkLen); BSL_SAL_CleanseData(dh, dhLen); if (ret != CRYPT_SUCCESS) { return ret; } HPKE_LabeledExpandParams expandParams = {macId, eaePrk, eaePrkLen, (uint8_t *)"shared_secret", strlen("shared_secret"), kemContext, kemContextLen, suiteId, HPKE_KEM_SUITEID_LEN}; ret = HpkeLabeledExpand(ctx->kdfCtx, &expandParams, sharedSecret, sharedSecretLen); BSL_SAL_CleanseData(eaePrk, eaePrkLen); return ret; } static int32_t HpkeCreateKemContext(uint8_t *enc, uint32_t encLen, uint8_t *pkR, uint32_t pkRLen, CRYPT_EAL_PkeyCtx *authKey, uint8_t **out, uint32_t *outLen) { uint8_t pkSm[HPKE_KEM_MAX_PUBLIC_KEY_LEN] = { 0 }; uint32_t pkSmLen = HPKE_KEM_MAX_PUBLIC_KEY_LEN; if (authKey != NULL) { int32_t ret = GetPubKeyData(authKey, pkSm, &pkSmLen); if (ret != CRYPT_SUCCESS) { return ret; } } else { pkSmLen = 0; } // kemContext = enc || pkRm || pkSm uint32_t kemContextLen = encLen + pkRLen + pkSmLen; uint8_t *kemContext = (uint8_t *)BSL_SAL_Malloc(kemContextLen); if (kemContext == NULL) { return CRYPT_MEM_ALLOC_FAIL; } (void)memcpy_s(kemContext, encLen, enc, encLen); (void)memcpy_s(kemContext + encLen, pkRLen, pkR, pkRLen); if (authKey != NULL) { (void)memcpy_s(kemContext + encLen + pkRLen, pkSmLen, pkSm, pkSmLen); } *out = kemContext; *outLen = kemContextLen; return CRYPT_SUCCESS; } static int32_t HpkeEncap(CRYPT_EAL_HpkeCtx *ctx, CRYPT_EAL_PkeyCtx *pkey, uint8_t *pkR, uint32_t pkRLen, uint8_t *encapsulatedKey, uint32_t *encapsulatedKeyLen, uint8_t *sharedSecret, uint32_t sharedSecretLen) { int32_t ret; CRYPT_EAL_PkeyCtx *pkeyS = pkey; if (pkeyS == NULL) { CRYPT_HPKE_CipherSuite cipherSuite = {g_hpkeKemAlgInfo[ctx->kemIndex].hpkeKemId, g_hpkeKdfAlgInfo[ctx->kdfIndex].hpkeKdfId, g_hpkeAeadAlgInfo[ctx->aeadIndex].hpkeAeadId}; ret = CRYPT_EAL_HpkeGenerateKeyPair(ctx->libCtx, ctx->attrName, cipherSuite, NULL, 0, &pkeyS); if (ret != CRYPT_SUCCESS) { return ret; } } CRYPT_EAL_PkeyCtx *pkeyR = NULL; uint8_t enc[HPKE_KEM_MAX_PUBLIC_KEY_LEN] = { 0 }; uint32_t encLen = HPKE_KEM_MAX_PUBLIC_KEY_LEN; uint32_t kemContextLen = 0; uint8_t *kemContext = NULL; CRYPT_EAL_PkeyCtx *authKey = NULL; if (ctx->mode == CRYPT_HPKE_MODE_AUTH || ctx->mode == CRYPT_HPKE_MODE_AUTH_PSK) { authKey = ctx->authInfo->authPkey; } ret = GetPubKeyData(pkeyS, enc, &encLen); if (ret != CRYPT_SUCCESS) { goto EXIT; } ret = HpkeCreatePubKey(ctx->kemIndex, pkR, pkRLen, &pkeyR, ctx->libCtx, ctx->attrName); if (ret != CRYPT_SUCCESS) { goto EXIT; } ret = HpkeCreateKemContext(enc, encLen, pkR, pkRLen, authKey, &kemContext, &kemContextLen); if (ret != CRYPT_SUCCESS) { goto EXIT; } ret = HpkeComputeSharedSecret(ctx, pkeyS, pkeyR, authKey, kemContext, kemContextLen, sharedSecret, sharedSecretLen); if (ret == CRYPT_SUCCESS) { (void)memcpy_s(encapsulatedKey, *encapsulatedKeyLen, enc, encLen); *encapsulatedKeyLen = encLen; } EXIT: BSL_SAL_FREE(kemContext); CRYPT_EAL_PkeyFreeCtx(pkeyR); if (pkey == NULL) { CRYPT_EAL_PkeyFreeCtx(pkeyS); } return ret; } static int32_t HpkeGenKeyScheduleCtx(CRYPT_EAL_HpkeCtx *ctx, uint8_t *info, uint32_t infoLen, uint8_t *pskId, uint32_t pskIdLen, uint8_t *suiteId, uint32_t suiteIdLen, uint8_t **keyScheduleContext, uint32_t *keyScheduleContextLen) { uint32_t extractKeyLen = g_hpkeKdfAlgInfo[ctx->kdfIndex].hkdfExtractKeyLen; uint32_t contextLen = sizeof(uint8_t) + extractKeyLen + extractKeyLen; uint8_t *context = (uint8_t *)BSL_SAL_Malloc(contextLen); if (context == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } context[0] = ctx->mode; uint32_t offset = sizeof(uint8_t); CRYPT_MAC_AlgId macId = g_hpkeKdfAlgInfo[ctx->kdfIndex].macId; HPKE_LabeledExtractParams params = {macId, NULL, 0, (uint8_t*)"psk_id_hash", strlen("psk_id_hash"), pskId, pskIdLen, suiteId, suiteIdLen}; int32_t ret = HpkeLabeledExtract(ctx->kdfCtx, &params, context + offset, extractKeyLen); if (ret != CRYPT_SUCCESS) { goto EXIT; } offset += extractKeyLen; params.label = (uint8_t*)"info_hash"; params.labelLen = strlen("info_hash"); params.ikm = info; params.ikmLen = infoLen; ret = HpkeLabeledExtract(ctx->kdfCtx, &params, context + offset, extractKeyLen); if (ret != CRYPT_SUCCESS) { goto EXIT; } *keyScheduleContext = context; *keyScheduleContextLen = contextLen; return CRYPT_SUCCESS; EXIT: BSL_SAL_ClearFree(context, contextLen); return ret; } static void HpkeFreeKeyInfo(CRYPT_EAL_HpkeCtx *ctx) { BSL_SAL_ClearFree(ctx->symKey, ctx->symKeyLen); ctx->symKey = NULL; ctx->symKeyLen = 0; BSL_SAL_ClearFree(ctx->baseNonce, ctx->baseNonceLen); ctx->baseNonce = NULL; ctx->baseNonceLen = 0; BSL_SAL_ClearFree(ctx->exporterSecret, ctx->exporterSecretLen); ctx->exporterSecret = NULL; ctx->exporterSecretLen = 0; } static int32_t HpkeMallocKeyInfo(CRYPT_EAL_HpkeCtx *ctx) { if (g_hpkeAeadAlgInfo[ctx->aeadIndex].hpkeAeadId != CRYPT_AEAD_EXPORT_ONLY) { ctx->symKeyLen = g_hpkeAeadAlgInfo[ctx->aeadIndex].keyLen; ctx->symKey = BSL_SAL_Malloc(ctx->symKeyLen); ctx->baseNonceLen = HPKE_AEAD_NONCE_LEN; ctx->baseNonce = BSL_SAL_Malloc(HPKE_AEAD_NONCE_LEN); if (ctx->symKey == NULL || ctx->baseNonce == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); HpkeFreeKeyInfo(ctx); return CRYPT_MEM_ALLOC_FAIL; } } ctx->exporterSecretLen = g_hpkeKdfAlgInfo[ctx->kdfIndex].hkdfExtractKeyLen; ctx->exporterSecret = BSL_SAL_Malloc(ctx->exporterSecretLen); if (ctx->exporterSecret == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); HpkeFreeKeyInfo(ctx); return CRYPT_MEM_ALLOC_FAIL; } return CRYPT_SUCCESS; } static int32_t HpkeDeriveKeyInfo(CRYPT_EAL_HpkeCtx *ctx, HPKE_LabeledExpandParams *expandParams) { CRYPT_HPKE_AEAD_AlgId aeadId = g_hpkeAeadAlgInfo[ctx->aeadIndex].hpkeAeadId; if (aeadId != CRYPT_AEAD_EXPORT_ONLY) { int32_t ret = HpkeLabeledExpand(ctx->kdfCtx, expandParams, ctx->symKey, ctx->symKeyLen); if (ret != CRYPT_SUCCESS) { return ret; } expandParams->label = (uint8_t*)"base_nonce"; expandParams->labelLen = strlen("base_nonce"); ret = HpkeLabeledExpand(ctx->kdfCtx, expandParams, ctx->baseNonce, ctx->baseNonceLen); if (ret != CRYPT_SUCCESS) { return ret; } } expandParams->label = (uint8_t*)"exp"; expandParams->labelLen = strlen("exp"); return HpkeLabeledExpand(ctx->kdfCtx, expandParams, ctx->exporterSecret, ctx->exporterSecretLen); } static int32_t HpkeKeySchedule(CRYPT_EAL_HpkeCtx *ctx, uint8_t *sharedSecret, uint32_t sharedSecretLen, uint8_t *info, uint32_t infoLen) { uint8_t suiteId[HPKE_HPKE_SUITEID_LEN]; uint8_t suiteIdLen = HPKE_HPKE_SUITEID_LEN; HpkeGenerateHpkeSuiteId(ctx->kemIndex, ctx->kdfIndex, ctx->aeadIndex, suiteId, HPKE_HPKE_SUITEID_LEN); uint32_t contextLen; uint8_t *context = NULL; uint8_t *pskId = (uint8_t *)""; uint32_t pskIdLen = 0; uint8_t *psk = (uint8_t *)""; uint32_t pskLen = 0; if (ctx->mode == CRYPT_HPKE_MODE_PSK || ctx->mode == CRYPT_HPKE_MODE_AUTH_PSK) { pskId = ctx->authInfo->pskId; pskIdLen = ctx->authInfo->pskIdLen; psk = ctx->authInfo->psk; pskLen = ctx->authInfo->pskLen; } int32_t ret = HpkeGenKeyScheduleCtx(ctx, info, infoLen, pskId, pskIdLen, suiteId, suiteIdLen, &context, &contextLen); if (ret != CRYPT_SUCCESS) { return ret; } CRYPT_MAC_AlgId macId = g_hpkeKdfAlgInfo[ctx->kdfIndex].macId; uint8_t secret[HPKE_KEM_MAX_SHARED_KEY_LEN] = {0}; uint32_t secretLen = g_hpkeKdfAlgInfo[ctx->kdfIndex].hkdfExtractKeyLen; HPKE_LabeledExtractParams extractparams = {macId, sharedSecret, sharedSecretLen, (uint8_t*)"secret", strlen("secret"), psk, pskLen, suiteId, suiteIdLen}; HPKE_LabeledExpandParams expandParams = {macId, secret, secretLen, (uint8_t*)"key", strlen("key"), context, contextLen, suiteId, suiteIdLen}; ret = HpkeLabeledExtract(ctx->kdfCtx, &extractparams, secret, secretLen); if (ret != CRYPT_SUCCESS) { goto EXIT; } ret = HpkeMallocKeyInfo(ctx); if (ret != CRYPT_SUCCESS) { goto EXIT; } ret = HpkeDeriveKeyInfo(ctx, &expandParams); EXIT: BSL_SAL_CleanseData(secret, HPKE_KEM_MAX_SHARED_KEY_LEN); BSL_SAL_ClearFree(context, contextLen); if (ret != CRYPT_SUCCESS) { HpkeFreeKeyInfo(ctx); } return ret; } static int32_t HpkeCheckAuthInfo(CRYPT_EAL_HpkeCtx *ctx) { if (ctx->mode == CRYPT_HPKE_MODE_AUTH || ctx->mode == CRYPT_HPKE_MODE_AUTH_PSK) { if (ctx->authInfo == NULL || ctx->authInfo->authPkey == NULL) { return CRYPT_HPKE_ERR_CALL; } } if (ctx->mode == CRYPT_HPKE_MODE_PSK || ctx->mode == CRYPT_HPKE_MODE_AUTH_PSK) { if (ctx->authInfo == NULL || ctx->authInfo->psk == NULL || ctx->authInfo->pskId == NULL) { return CRYPT_HPKE_ERR_CALL; } } return CRYPT_SUCCESS; } static void HpkeFreeAuthInfo(CRYPT_EAL_HpkeCtx *ctx) { if (ctx->authInfo == NULL) { return; } BSL_SAL_ClearFree(ctx->authInfo->psk, ctx->authInfo->pskLen); ctx->authInfo->psk = NULL; ctx->authInfo->pskLen = 0; BSL_SAL_ClearFree(ctx->authInfo->pskId, ctx->authInfo->pskIdLen); ctx->authInfo->pskId = NULL; ctx->authInfo->pskIdLen = 0; CRYPT_EAL_PkeyFreeCtx(ctx->authInfo->authPkey); ctx->authInfo->authPkey = NULL; BSL_SAL_FREE(ctx->authInfo); } static int32_t HpkeCheckSenderParams(CRYPT_EAL_HpkeCtx *ctx, uint8_t *info, uint32_t infoLen, const uint8_t *pkR, uint32_t pkRLen, uint8_t *encapsulatedKey, uint32_t *encapsulatedKeyLen) { if (ctx == NULL) { return CRYPT_NULL_INPUT; } if (ctx->role != CRYPT_HPKE_SENDER) { return CRYPT_HPKE_ERR_CALL; } if (ctx->sharedSecret != NULL) { return CRYPT_HPKE_ERR_CALL; } if (pkR == NULL || encapsulatedKey == NULL || encapsulatedKeyLen == NULL) { return CRYPT_NULL_INPUT; } if ((info == NULL && infoLen != 0) || (info != NULL && infoLen == 0)) { return CRYPT_INVALID_ARG; } uint32_t encLen = g_hpkeKemAlgInfo[ctx->kemIndex].encapsulatedKeyLen; if (pkRLen != encLen) { return CRYPT_INVALID_ARG; } if (*encapsulatedKeyLen < encLen) { return CRYPT_INVALID_ARG; } return HpkeCheckAuthInfo(ctx); } int32_t CRYPT_EAL_HpkeSetupSender(CRYPT_EAL_HpkeCtx *ctx, CRYPT_EAL_PkeyCtx *pkey, uint8_t *info, uint32_t infoLen, uint8_t *pkR, uint32_t pkRLen, uint8_t *encapKey, uint32_t *encapKeyLen) { int32_t ret = HpkeCheckSenderParams(ctx, info, infoLen, pkR, pkRLen, encapKey, encapKeyLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } uint32_t sharedSecretLen = g_hpkeKemAlgInfo[ctx->kemIndex].sharedKeyLen; uint8_t *sharedSecret = BSL_SAL_Malloc(sharedSecretLen); if (sharedSecret == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ret = HpkeEncap(ctx, pkey, pkR, pkRLen, encapKey, encapKeyLen, sharedSecret, sharedSecretLen); if (ret != CRYPT_SUCCESS) { BSL_SAL_ClearFree(sharedSecret, sharedSecretLen); return ret; } ret = HpkeKeySchedule(ctx, sharedSecret, sharedSecretLen, info, infoLen); if (ret != CRYPT_SUCCESS) { BSL_SAL_ClearFree(sharedSecret, sharedSecretLen); return ret; } ctx->sharedSecret = sharedSecret; ctx->sharedSecretLen = sharedSecretLen; HpkeFreeAuthInfo(ctx); // Derived key successfully, no longer requires authinfo return ret; } static int32_t HpkeAeadEncrypt(CRYPT_EAL_HpkeCtx *ctx, const uint8_t *nonce, uint32_t nonceLen, uint8_t *aad, uint32_t aadLen, const uint8_t *plainText, uint32_t plainTextLen, uint8_t *cipherText, uint32_t *cipherTextLen) { CRYPT_EAL_CipherCtx *cipherCtx = ctx->cipherCtx; uint32_t outLen = *cipherTextLen; int32_t ret = CRYPT_EAL_CipherInit(cipherCtx, ctx->symKey, ctx->symKeyLen, nonce, nonceLen, true); if (ret != CRYPT_SUCCESS) { goto EXIT; } if (aad != NULL && aadLen > 0) { ret = CRYPT_EAL_CipherCtrl(cipherCtx, CRYPT_CTRL_SET_AAD, aad, aadLen); if (ret != CRYPT_SUCCESS) { goto EXIT; } } ret = CRYPT_EAL_CipherUpdate(cipherCtx, plainText, plainTextLen, cipherText, &outLen); if (ret != CRYPT_SUCCESS) { goto EXIT; } ret = CRYPT_EAL_CipherCtrl(cipherCtx, CRYPT_CTRL_GET_TAG, cipherText + outLen, HPKE_AEAD_TAG_LEN); if (ret != CRYPT_SUCCESS) { goto EXIT; } *cipherTextLen = outLen + HPKE_AEAD_TAG_LEN; EXIT: CRYPT_EAL_CipherDeinit(cipherCtx); return ret; } int32_t CRYPT_EAL_HpkeSetSeq(CRYPT_EAL_HpkeCtx *ctx, uint64_t seq) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (seq == UINT64_MAX) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } ctx->seq = seq; return CRYPT_SUCCESS; } int32_t CRYPT_EAL_HpkeGetSeq(CRYPT_EAL_HpkeCtx *ctx, uint64_t *seq) { if (ctx == NULL || seq == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } *seq = ctx->seq; return CRYPT_SUCCESS; } static void HpkeComputeNonce(CRYPT_EAL_HpkeCtx *ctx, uint8_t *nonce, uint32_t nonceLen) { uint64_t seq = ctx->seq; for (uint32_t i = 0; i < sizeof(seq); i++) { nonce[nonceLen - i - 1] = seq & UINT8_MAX; seq = seq >> 8; // 8 bits } for (uint32_t i = 0; i < nonceLen; i++) { nonce[i] ^= ctx->baseNonce[i]; } } static int32_t HpkeCheckSealParams(CRYPT_EAL_HpkeCtx *ctx, const uint8_t *plainText, uint32_t plainTextLen, uint32_t *cipherTextLen) { if (ctx == NULL) { return CRYPT_NULL_INPUT; } if (ctx->role != CRYPT_HPKE_SENDER) { return CRYPT_HPKE_ERR_CALL; } if (g_hpkeAeadAlgInfo[ctx->aeadIndex].hpkeAeadId == CRYPT_AEAD_EXPORT_ONLY) { return CRYPT_HPKE_ERR_CALL; } if (ctx->symKey == NULL || ctx->baseNonce == NULL) { return CRYPT_HPKE_ERR_CALL; } if (plainText == NULL || plainTextLen == 0 || cipherTextLen == NULL) { return CRYPT_NULL_INPUT; } if (plainTextLen > (UINT32_MAX - HPKE_AEAD_TAG_LEN)) { return CRYPT_INVALID_ARG; } return CRYPT_SUCCESS; } int32_t CRYPT_EAL_HpkeSeal(CRYPT_EAL_HpkeCtx *ctx, uint8_t *aad, uint32_t aadLen, const uint8_t *plainText, uint32_t plainTextLen, uint8_t *cipherText, uint32_t *cipherTextLen) { int32_t ret = HpkeCheckSealParams(ctx, plainText, plainTextLen, cipherTextLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (ctx->seq + 1 == 0) { BSL_ERR_PUSH_ERROR(CRYPT_HPKE_ERR_CALL); return CRYPT_HPKE_ERR_CALL; } if (cipherText == NULL) { *cipherTextLen = plainTextLen + HPKE_AEAD_TAG_LEN; return CRYPT_SUCCESS; } if (*cipherTextLen < (plainTextLen + HPKE_AEAD_TAG_LEN)) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } uint8_t nonce[HPKE_AEAD_NONCE_LEN] = { 0 }; HpkeComputeNonce(ctx, nonce, HPKE_AEAD_NONCE_LEN); ret = HpkeAeadEncrypt(ctx, nonce, HPKE_AEAD_NONCE_LEN, aad, aadLen, plainText, plainTextLen, cipherText, cipherTextLen); if (ret == CRYPT_SUCCESS) { ctx->seq++; } return ret; } static int32_t HpkeDecap(CRYPT_EAL_HpkeCtx *ctx, CRYPT_EAL_PkeyCtx *pkey, uint8_t *encKey, uint32_t encKeyLen, uint8_t *sharedSecret, uint32_t sharedSecretLen) { CRYPT_EAL_PkeyCtx *pkeyS = NULL; int32_t ret = HpkeCreatePubKey(ctx->kemIndex, encKey, encKeyLen, &pkeyS, ctx->libCtx, ctx->attrName); if (ret != CRYPT_SUCCESS) { return ret; } uint8_t *kemContext = NULL; uint32_t kemContextLen; uint8_t pubKeyData[HPKE_KEM_MAX_PUBLIC_KEY_LEN]; uint32_t pubKeyDataLen = HPKE_KEM_MAX_PUBLIC_KEY_LEN; CRYPT_EAL_PkeyCtx *authKey = NULL; if (ctx->mode == CRYPT_HPKE_MODE_AUTH || ctx->mode == CRYPT_HPKE_MODE_AUTH_PSK) { authKey = ctx->authInfo->authPkey; } ret = GetPubKeyData(pkey, pubKeyData, &pubKeyDataLen); if (ret != CRYPT_SUCCESS) { goto EXIT; } ret = HpkeCreateKemContext(encKey, encKeyLen, pubKeyData, pubKeyDataLen, authKey, &kemContext, &kemContextLen); if (ret != CRYPT_SUCCESS) { goto EXIT; } ret = HpkeComputeSharedSecret(ctx, pkey, pkeyS, authKey, kemContext, kemContextLen, sharedSecret, sharedSecretLen); EXIT: CRYPT_EAL_PkeyFreeCtx(pkeyS); BSL_SAL_FREE(kemContext); return ret; } static int32_t HpkeCheckRecipientParams(CRYPT_EAL_HpkeCtx *ctx, CRYPT_EAL_PkeyCtx *pkey, uint8_t *info, uint32_t infoLen, const uint8_t *encapsulatedKey, uint32_t encapsulatedKeyLen) { if (ctx == NULL) { return CRYPT_NULL_INPUT; } if (ctx->role != CRYPT_HPKE_RECIPIENT) { return CRYPT_HPKE_ERR_CALL; } if (ctx->sharedSecret != NULL) { return CRYPT_HPKE_ERR_CALL; } if ((info == NULL && infoLen != 0) || (info != NULL && infoLen == 0)) { return CRYPT_INVALID_ARG; } if (pkey == NULL || encapsulatedKey == NULL) { return CRYPT_NULL_INPUT; } if (encapsulatedKeyLen != g_hpkeKemAlgInfo[ctx->kemIndex].encapsulatedKeyLen) { return CRYPT_INVALID_ARG; } return HpkeCheckAuthInfo(ctx); } int32_t CRYPT_EAL_HpkeSetupRecipient(CRYPT_EAL_HpkeCtx *ctx, CRYPT_EAL_PkeyCtx *pkey, uint8_t *info, uint32_t infoLen, uint8_t *encapKey, uint32_t encapKeyLen) { int32_t ret = HpkeCheckRecipientParams(ctx, pkey, info, infoLen, encapKey, encapKeyLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } uint32_t sharedSecretLen = g_hpkeKemAlgInfo[ctx->kemIndex].sharedKeyLen; uint8_t *sharedSecret = BSL_SAL_Malloc(sharedSecretLen); if (sharedSecret == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ret = HpkeDecap(ctx, pkey, encapKey, encapKeyLen, sharedSecret, sharedSecretLen); if (ret != CRYPT_SUCCESS) { BSL_SAL_ClearFree(sharedSecret, sharedSecretLen); return ret; } ret = HpkeKeySchedule(ctx, sharedSecret, sharedSecretLen, info, infoLen); if (ret != CRYPT_SUCCESS) { BSL_SAL_ClearFree(sharedSecret, sharedSecretLen); return ret; } ctx->sharedSecret = sharedSecret; ctx->sharedSecretLen = sharedSecretLen; HpkeFreeAuthInfo(ctx); // Derived key successfully, no longer requires authinfo return ret; } static int32_t HpkeAeadDecrypt(CRYPT_EAL_HpkeCtx *ctx, const uint8_t *nonce, uint32_t nonceLen, uint8_t *aad, uint32_t aadLen, const uint8_t *cipherText, uint32_t cipherTextLen, uint8_t *plainText, uint32_t *plainTextLen) { CRYPT_EAL_CipherCtx *cipherCtx = ctx->cipherCtx; int32_t ret = CRYPT_EAL_CipherInit(cipherCtx, ctx->symKey, ctx->symKeyLen, nonce, nonceLen, false); if (ret != CRYPT_SUCCESS) { CRYPT_EAL_CipherDeinit(cipherCtx); return ret; } if (aad != NULL && aadLen > 0) { ret = CRYPT_EAL_CipherCtrl(cipherCtx, CRYPT_CTRL_SET_AAD, (void *)aad, aadLen); if (ret != CRYPT_SUCCESS) { CRYPT_EAL_CipherDeinit(cipherCtx); return ret; } } ret = CRYPT_EAL_CipherUpdate(cipherCtx, cipherText, cipherTextLen - HPKE_AEAD_TAG_LEN, plainText, plainTextLen); if (ret != CRYPT_SUCCESS) { CRYPT_EAL_CipherDeinit(cipherCtx); return ret; } uint8_t tag[HPKE_AEAD_TAG_LEN]; ret = CRYPT_EAL_CipherCtrl(cipherCtx, CRYPT_CTRL_GET_TAG, (void *)tag, HPKE_AEAD_TAG_LEN); if (ret != CRYPT_SUCCESS) { goto EXIT; } if (memcmp(tag, cipherText + (cipherTextLen - HPKE_AEAD_TAG_LEN), HPKE_AEAD_TAG_LEN) != 0) { ret = CRYPT_HPKE_ERR_AEAD_TAG; BSL_ERR_PUSH_ERROR(CRYPT_HPKE_ERR_AEAD_TAG); } EXIT: if (ret != CRYPT_SUCCESS) { BSL_SAL_CleanseData(plainText, *plainTextLen); } CRYPT_EAL_CipherDeinit(cipherCtx); return ret; } static int32_t HpkeCheckOpenParams(CRYPT_EAL_HpkeCtx *ctx, const uint8_t *cipherText, uint32_t cipherTextLen, uint32_t *plainTextLen) { if (ctx == NULL) { return CRYPT_NULL_INPUT; } if (ctx->role != CRYPT_HPKE_RECIPIENT) { return CRYPT_HPKE_ERR_CALL; } if (g_hpkeAeadAlgInfo[ctx->aeadIndex].hpkeAeadId == CRYPT_AEAD_EXPORT_ONLY) { return CRYPT_HPKE_ERR_CALL; } if (ctx->symKey == NULL || ctx->baseNonce == NULL) { return CRYPT_HPKE_ERR_CALL; } if (cipherText == NULL || cipherTextLen == 0 || plainTextLen == NULL) { return CRYPT_NULL_INPUT; } return CRYPT_SUCCESS; } int32_t CRYPT_EAL_HpkeOpen(CRYPT_EAL_HpkeCtx *ctx, uint8_t *aad, uint32_t aadLen, const uint8_t *cipherText, uint32_t cipherTextLen, uint8_t *plainText, uint32_t *plainTextLen) { int32_t ret = HpkeCheckOpenParams(ctx, cipherText, cipherTextLen, plainTextLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (ctx->seq + 1 == 0) { BSL_ERR_PUSH_ERROR(CRYPT_HPKE_ERR_CALL); return CRYPT_HPKE_ERR_CALL; } if (cipherTextLen <= HPKE_AEAD_TAG_LEN) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } if (plainText == NULL) { *plainTextLen = cipherTextLen - HPKE_AEAD_TAG_LEN; return CRYPT_SUCCESS; } uint8_t nonce[HPKE_AEAD_NONCE_LEN] = { 0 }; HpkeComputeNonce(ctx, nonce, HPKE_AEAD_NONCE_LEN); ret = HpkeAeadDecrypt(ctx, nonce, HPKE_AEAD_NONCE_LEN, aad, aadLen, cipherText, cipherTextLen, plainText, plainTextLen); if (ret == CRYPT_SUCCESS) { ctx->seq++; } return ret; } void CRYPT_EAL_HpkeFreeCtx(CRYPT_EAL_HpkeCtx *ctx) { if (ctx == NULL) { return; } BSL_SAL_ClearFree(ctx->sharedSecret, ctx->sharedSecretLen); HpkeFreeKeyInfo(ctx); CRYPT_EAL_CipherFreeCtx(ctx->cipherCtx); CRYPT_EAL_KdfFreeCtx(ctx->kdfCtx); BSL_SAL_FREE(ctx->attrName); HpkeFreeAuthInfo(ctx); BSL_SAL_ClearFree(ctx, sizeof(CRYPT_EAL_HpkeCtx)); } static int32_t HpkeGetEccOrder(CRYPT_EAL_PkeyCtx *pkey, BN_BigNum **order) { uint8_t ecP[MAX_ECC_PARAM_LEN]; uint8_t ecA[MAX_ECC_PARAM_LEN]; uint8_t ecB[MAX_ECC_PARAM_LEN]; uint8_t ecN[MAX_ECC_PARAM_LEN]; uint8_t ecH[MAX_ECC_PARAM_LEN]; uint8_t ecX[MAX_ECC_PARAM_LEN]; uint8_t ecY[MAX_ECC_PARAM_LEN]; CRYPT_EAL_PkeyPara para = {0}; para.id = CRYPT_EAL_PkeyGetId(pkey); para.para.eccPara.p = ecP; para.para.eccPara.a = ecA; para.para.eccPara.b = ecB; para.para.eccPara.n = ecN; para.para.eccPara.h = ecH; para.para.eccPara.x = ecX; para.para.eccPara.y = ecY; para.para.eccPara.pLen = MAX_ECC_PARAM_LEN; para.para.eccPara.aLen = MAX_ECC_PARAM_LEN; para.para.eccPara.bLen = MAX_ECC_PARAM_LEN; para.para.eccPara.nLen = MAX_ECC_PARAM_LEN; para.para.eccPara.hLen = MAX_ECC_PARAM_LEN; para.para.eccPara.xLen = MAX_ECC_PARAM_LEN; para.para.eccPara.yLen = MAX_ECC_PARAM_LEN; int32_t ret = CRYPT_EAL_PkeyGetPara(pkey, &para); if (ret != CRYPT_SUCCESS) { return ret; } BN_BigNum *bn = BN_Create(para.para.eccPara.nLen * 8); if (bn == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ret = BN_Bin2Bn(bn, para.para.eccPara.n, para.para.eccPara.nLen); if (ret != CRYPT_SUCCESS) { BN_Destroy(bn); return ret; } *order = bn; return CRYPT_SUCCESS; } static int32_t HpkeExpandEccPriKey(CRYPT_EAL_PkeyCtx *pkey, CRYPT_EAL_KdfCTX *hkdfCtx, uint32_t kemIndex, HPKE_LabeledExpandParams *params, uint8_t *sk, uint32_t skLen) { BN_BigNum *order = NULL; int32_t ret = HpkeGetEccOrder(pkey, &order); if (ret != CRYPT_SUCCESS) { return ret; } BN_BigNum *skBn = BN_Create(skLen * 8); if (skBn == NULL) { BN_Destroy(order); BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } uint8_t counter = 0; uint8_t bitmask = 0xFF; // 0xFF for P256 P384 if (g_hpkeKemAlgInfo[kemIndex].hpkeKemId == CRYPT_KEM_DHKEM_P521_HKDF_SHA512) { bitmask = 0x01; } do { if (counter == 255) { // RFC9180 7.1.3, up to 255 attempts. ret = CRYPT_HPKE_ERR_GEN_ASYM_KEY; BSL_ERR_PUSH_ERROR(CRYPT_HPKE_ERR_GEN_ASYM_KEY); break; } *(params->info) = counter; ret = HpkeLabeledExpand(hkdfCtx, params, sk, skLen); if (ret != CRYPT_SUCCESS) { break; } sk[0] = sk[0] & bitmask; ret = BN_Bin2Bn(skBn, sk, skLen); if (ret != CRYPT_SUCCESS) { break; } counter++; } while (BN_IsZero(skBn) || BN_Cmp(skBn, order) >= 0); BN_Destroy(skBn); BN_Destroy(order); if (ret != CRYPT_SUCCESS) { BSL_SAL_CleanseData(sk, skLen); } return ret; } static int32_t DeriveSk(uint8_t kemIndex, CRYPT_EAL_KdfCTX *kdfCtx, CRYPT_EAL_PkeyCtx *pkey, HPKE_LabeledExpandParams *expandParams, uint8_t *sk, uint32_t skLen) { if (g_hpkeKemAlgInfo[kemIndex].hpkeKemId == CRYPT_KEM_DHKEM_X25519_HKDF_SHA256) { return HpkeLabeledExpand(kdfCtx, expandParams, sk, skLen); } else { uint8_t counter = 0; expandParams->label = (uint8_t *)"candidate"; expandParams->labelLen = strlen("candidate"); expandParams->info = (uint8_t *)&counter; expandParams->infoLen = sizeof(uint8_t); return HpkeExpandEccPriKey(pkey, kdfCtx, kemIndex, expandParams, sk, skLen); } } static int32_t HpkeDeriveKeyPair(uint8_t kemIndex, uint8_t *ikm, uint32_t ikmLen, CRYPT_EAL_PkeyCtx **pctx, CRYPT_EAL_LibCtx *libCtx, const char *attrName) { uint8_t suiteId[HPKE_KEM_SUITEID_LEN]; HpkeGenerateKemSuiteId(kemIndex, suiteId, HPKE_KEM_SUITEID_LEN); uint8_t dkpPrk[HPKE_HKDF_MAX_EXTRACT_KEY_LEN]; uint8_t sk[HPKE_KEM_MAX_PRIVATE_KEY_LEN] = { 0 }; uint32_t dkpPrkLen = g_hpkeKemAlgInfo[kemIndex].hkdfExtractKeyLen; CRYPT_MAC_AlgId macId = g_hpkeKemAlgInfo[kemIndex].macId; uint32_t skLen = g_hpkeKemAlgInfo[kemIndex].privateKeyLen; CRYPT_EAL_KdfCTX *kdfCtx = NULL; kdfCtx = CRYPT_EAL_ProviderKdfNewCtx(libCtx, CRYPT_KDF_HKDF, attrName); if (kdfCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_HPKE_FAILED_FETCH_KDF); return CRYPT_HPKE_FAILED_FETCH_KDF; } CRYPT_EAL_PkeyCtx *pkey = NULL; int32_t ret = HpkeCreatePkeyCtx(kemIndex, &pkey, libCtx, attrName); if (ret != CRYPT_SUCCESS) { CRYPT_EAL_KdfFreeCtx(kdfCtx); return ret; } HPKE_LabeledExtractParams extractParams = {macId, (uint8_t *)"", 0, (uint8_t *)"dkp_prk", strlen("dkp_prk"), ikm, ikmLen, suiteId, HPKE_KEM_SUITEID_LEN}; HPKE_LabeledExpandParams expandParams = {macId, dkpPrk, dkpPrkLen, (uint8_t *)"sk", strlen("sk"), (uint8_t *)"", 0, suiteId, HPKE_KEM_SUITEID_LEN}; ret = HpkeLabeledExtract(kdfCtx, &extractParams, dkpPrk, dkpPrkLen); if (ret != CRYPT_SUCCESS) { goto EXIT; } ret = DeriveSk(kemIndex, kdfCtx, pkey, &expandParams, sk, skLen); if (ret != CRYPT_SUCCESS) { goto EXIT; } ret = HpkeCreatePriKey(kemIndex, sk, skLen, &pkey, libCtx, attrName); EXIT: CRYPT_EAL_KdfFreeCtx(kdfCtx); BSL_SAL_CleanseData(sk, skLen); BSL_SAL_CleanseData(dkpPrk, HPKE_HKDF_MAX_EXTRACT_KEY_LEN); if (ret != CRYPT_SUCCESS) { CRYPT_EAL_PkeyFreeCtx(pkey); return ret; } *pctx = pkey; return CRYPT_SUCCESS; } int32_t CRYPT_EAL_HpkeGenerateKeyPair(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_HPKE_CipherSuite cipherSuite, uint8_t *ikm, uint32_t ikmLen, CRYPT_EAL_PkeyCtx **pctx) { if (pctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (*pctx != NULL) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } uint8_t kemIndex; int32_t ret = HpkeCheckCipherSuite(&cipherSuite, &kemIndex, NULL, NULL); if (ret != CRYPT_SUCCESS) { return ret; } uint32_t ikmNewLen = g_hpkeKemAlgInfo[kemIndex].privateKeyLen; if (ikm != NULL && ikmLen != 0) { if (ikmLen < ikmNewLen) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } return HpkeDeriveKeyPair(kemIndex, ikm, ikmLen, pctx, libCtx, attrName); } uint8_t ikmNew[HPKE_KEM_MAX_PRIVATE_KEY_LEN]; ret = CRYPT_EAL_RandbytesEx(libCtx, ikmNew, ikmNewLen); if (ret != CRYPT_SUCCESS) { return ret; } ret = HpkeDeriveKeyPair(kemIndex, ikmNew, ikmNewLen, pctx, libCtx, attrName); BSL_SAL_CleanseData(ikmNew, ikmNewLen); return ret; } int32_t CRYPT_EAL_HpkeExportSecret(CRYPT_EAL_HpkeCtx *ctx, uint8_t *info, uint32_t infoLen, uint8_t *key, uint32_t keyLen) { if (ctx == NULL || key == NULL || keyLen == 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->exporterSecret == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_HPKE_ERR_CALL); return CRYPT_HPKE_ERR_CALL; } if ((info == NULL && infoLen != 0) || (info != NULL && infoLen == 0)) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } if (keyLen > 255 * g_hpkeKdfAlgInfo[ctx->kdfIndex].hkdfExtractKeyLen) { // RFC9180 5.3 max L is 255*Nh BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } uint8_t suiteId[HPKE_HPKE_SUITEID_LEN]; HpkeGenerateHpkeSuiteId(ctx->kemIndex, ctx->kdfIndex, ctx->aeadIndex, suiteId, HPKE_HPKE_SUITEID_LEN); CRYPT_MAC_AlgId macId = g_hpkeKdfAlgInfo[ctx->kdfIndex].macId; HPKE_LabeledExpandParams params = {macId, ctx->exporterSecret, ctx->exporterSecretLen, (uint8_t *)"sec", strlen("sec"), info, infoLen, suiteId, HPKE_HPKE_SUITEID_LEN}; return HpkeLabeledExpand(ctx->kdfCtx, &params, key, keyLen); } int32_t CRYPT_EAL_HpkeGetSharedSecret(CRYPT_EAL_HpkeCtx *ctx, uint8_t *buff, uint32_t *buffLen) { if (ctx == NULL || buffLen == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->sharedSecret == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_HPKE_ERR_CALL); return CRYPT_HPKE_ERR_CALL; } if (buff == NULL) { *buffLen = ctx->sharedSecretLen; return CRYPT_SUCCESS; } if (*buffLen < ctx->sharedSecretLen) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } (void)memcpy_s(buff, *buffLen, ctx->sharedSecret, ctx->sharedSecretLen); *buffLen = ctx->sharedSecretLen; return CRYPT_SUCCESS; } int32_t CRYPT_EAL_HpkeSetSharedSecret(CRYPT_EAL_HpkeCtx *ctx, uint8_t *info, uint32_t infoLen, uint8_t *buff, uint32_t buffLen) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->sharedSecret != NULL) { BSL_ERR_PUSH_ERROR(CRYPT_HPKE_ERR_CALL); return CRYPT_HPKE_ERR_CALL; } if (buff == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if ((info == NULL && infoLen != 0) || (info != NULL && infoLen == 0)) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } if (buffLen != g_hpkeKemAlgInfo[ctx->kemIndex].sharedKeyLen) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } if (ctx->mode == CRYPT_HPKE_MODE_PSK || ctx->mode == CRYPT_HPKE_MODE_AUTH_PSK) { if (ctx->authInfo == NULL || ctx->authInfo->psk == NULL || ctx->authInfo->pskId == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_HPKE_ERR_CALL); return CRYPT_HPKE_ERR_CALL; } } int32_t ret = HpkeKeySchedule(ctx, buff, buffLen, info, infoLen); if (ret != CRYPT_SUCCESS) { return ret; } ctx->sharedSecret = BSL_SAL_Dump(buff, buffLen); if (ctx->sharedSecret == NULL) { HpkeFreeKeyInfo(ctx); BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ctx->sharedSecretLen = buffLen; HpkeFreeAuthInfo(ctx); // Derived key successfully, no longer requires authinfo return CRYPT_SUCCESS; } int32_t CRYPT_EAL_HpkeSetPsk(CRYPT_EAL_HpkeCtx *ctx, uint8_t *psk, uint32_t pskLen, uint8_t *pskId, uint32_t pskIdLen) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->mode != CRYPT_HPKE_MODE_PSK && ctx->mode != CRYPT_HPKE_MODE_AUTH_PSK) { BSL_ERR_PUSH_ERROR(CRYPT_HPKE_ERR_CALL); return CRYPT_HPKE_ERR_CALL; } if (ctx->authInfo == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_HPKE_ERR_CALL); return CRYPT_HPKE_ERR_CALL; } if (ctx->authInfo->psk != NULL || ctx->authInfo->pskId != NULL) { BSL_ERR_PUSH_ERROR(CRYPT_HPKE_ERR_CALL); return CRYPT_HPKE_ERR_CALL; } // psk and pskId must appear together if (psk == NULL || pskIdLen == 0 || pskId == NULL || pskLen == 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } ctx->authInfo->psk = BSL_SAL_Dump(psk, pskLen); if (ctx->authInfo->psk == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ctx->authInfo->pskLen = pskLen; ctx->authInfo->pskId = BSL_SAL_Dump(pskId, pskIdLen); if (ctx->authInfo->pskId == NULL) { BSL_SAL_ClearFree(ctx->authInfo->psk, ctx->authInfo->pskLen); ctx->authInfo->psk = NULL; ctx->authInfo->pskLen = 0; BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ctx->authInfo->pskIdLen = pskIdLen; return CRYPT_SUCCESS; } int32_t CRYPT_EAL_HpkeSetAuthPriKey(CRYPT_EAL_HpkeCtx *ctx, CRYPT_EAL_PkeyCtx *pkey) { if (ctx == NULL || pkey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->mode != CRYPT_HPKE_MODE_AUTH && ctx->mode != CRYPT_HPKE_MODE_AUTH_PSK) { BSL_ERR_PUSH_ERROR(CRYPT_HPKE_ERR_CALL); return CRYPT_HPKE_ERR_CALL; } if (ctx->role != CRYPT_HPKE_SENDER) { BSL_ERR_PUSH_ERROR(CRYPT_HPKE_ERR_CALL); return CRYPT_HPKE_ERR_CALL; } if (ctx->authInfo == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_HPKE_ERR_CALL); return CRYPT_HPKE_ERR_CALL; } if (ctx->authInfo->authPkey != NULL) { BSL_ERR_PUSH_ERROR(CRYPT_HPKE_ERR_CALL); return CRYPT_HPKE_ERR_CALL; } CRYPT_EAL_PkeyCtx *skS = NULL; #ifdef HITLS_CRYPTO_PROVIDER skS = CRYPT_EAL_ProviderPkeyNewCtx(ctx->libCtx, g_hpkeKemAlgInfo[ctx->kemIndex].pkeyId, CRYPT_EAL_PKEY_EXCH_OPERATE, ctx->attrName); #else skS = CRYPT_EAL_PkeyNewCtx(g_hpkeKemAlgInfo[ctx->kemIndex].pkeyId); #endif if (skS == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_HPKE_FAILED_FETCH_PKEY); return CRYPT_HPKE_FAILED_FETCH_PKEY; } int32_t ret = CRYPT_EAL_PkeyCopyCtx(skS, pkey); if (ret != CRYPT_SUCCESS) { CRYPT_EAL_PkeyFreeCtx(skS); return ret; } ctx->authInfo->authPkey = skS; return CRYPT_SUCCESS; } int32_t CRYPT_EAL_HpkeSetAuthPubKey(CRYPT_EAL_HpkeCtx *ctx, uint8_t *pub, uint32_t pubLen) { if (ctx == NULL || pub == NULL || pubLen == 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->mode != CRYPT_HPKE_MODE_AUTH && ctx->mode != CRYPT_HPKE_MODE_AUTH_PSK) { BSL_ERR_PUSH_ERROR(CRYPT_HPKE_ERR_CALL); return CRYPT_HPKE_ERR_CALL; } if (ctx->role != CRYPT_HPKE_RECIPIENT) { BSL_ERR_PUSH_ERROR(CRYPT_HPKE_ERR_CALL); return CRYPT_HPKE_ERR_CALL; } if (ctx->authInfo == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_HPKE_ERR_CALL); return CRYPT_HPKE_ERR_CALL; } if (ctx->authInfo->authPkey != NULL) { BSL_ERR_PUSH_ERROR(CRYPT_HPKE_ERR_CALL); return CRYPT_HPKE_ERR_CALL; } CRYPT_EAL_PkeyCtx *pkS = NULL; int32_t ret = HpkeCreatePubKey(ctx->kemIndex, pub, pubLen, &pkS, ctx->libCtx, ctx->attrName); if (ret != CRYPT_SUCCESS) { return ret; } ctx->authInfo->authPkey = pkS; return CRYPT_SUCCESS; } #endif // HITLS_CRYPTO_HPKE
2302_82127028/openHiTLS-examples_1508
crypto/hpke/src/hpke.c
C
unknown
58,577
/* * 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_HYBRIDKEM_H #define CRYPT_HYBRIDKEM_H #include <stdint.h> #include "crypt_types.h" #include "hitls_build.h" #ifdef HITLS_CRYPTO_ECDH typedef struct HybridKemCtx CRYPT_HybridKemCtx; CRYPT_HybridKemCtx *CRYPT_HYBRID_KEM_NewCtx(void); CRYPT_HybridKemCtx *CRYPT_HYBRID_KEM_NewCtxEx(void *libCtx); void CRYPT_HYBRID_KEM_FreeCtx(CRYPT_HybridKemCtx *ctx); int32_t CRYPT_HYBRID_KEM_KeyCtrl(CRYPT_HybridKemCtx *ctx, int32_t opt, void *val, uint32_t len); int32_t CRYPT_HYBRID_KEM_GenKey(CRYPT_HybridKemCtx *ctx); int32_t CRYPT_HYBRID_KEM_SetEncapsKey(CRYPT_HybridKemCtx *ctx, const CRYPT_KemEncapsKey *ek); int32_t CRYPT_HYBRID_KEM_SetDecapsKey(CRYPT_HybridKemCtx *ctx, const CRYPT_KemDecapsKey *dk); int32_t CRYPT_HYBRID_KEM_GetEncapsKey(const CRYPT_HybridKemCtx *ctx, CRYPT_KemEncapsKey *ek); int32_t CRYPT_HYBRID_KEM_GetDecapsKey(const CRYPT_HybridKemCtx *ctx, CRYPT_KemDecapsKey *dk); int32_t CRYPT_HYBRID_KEM_GetEncapsKeyEx(const CRYPT_HybridKemCtx *ctx, BSL_Param *para); int32_t CRYPT_HYBRID_KEM_GetDecapsKeyEx(const CRYPT_HybridKemCtx *ctx, BSL_Param *para); int32_t CRYPT_HYBRID_KEM_SetEncapsKeyEx(CRYPT_HybridKemCtx *ctx, const BSL_Param *para); int32_t CRYPT_HYBRID_KEM_SetDecapsKeyEx(CRYPT_HybridKemCtx *ctx, const BSL_Param *para); int32_t CRYPT_HYBRID_KEM_Encaps(const CRYPT_HybridKemCtx *ctx, uint8_t *cipher, uint32_t *cipherLen, uint8_t *share, uint32_t *shareLen); int32_t CRYPT_HYBRID_KEM_Decaps(const CRYPT_HybridKemCtx *ctx, uint8_t *cipher, uint32_t cipherLen, uint8_t *share, uint32_t *shareLen); #endif #endif // CRYPT_HYBRIDKEM_H
2302_82127028/openHiTLS-examples_1508
crypto/hybridkem/include/crypt_hybridkem.h
C
unknown
2,129
/* * 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_HYBRIDKEM #include "securec.h" #include "bsl_sal.h" #include "sal_atomic.h" #include "eal_pkey_local.h" #include "crypt_eal_pkey.h" #include "crypt_utils.h" #include "crypt_algid.h" #include "crypt_hybridkem_local.h" #include "crypt_hybridkem.h" #include "crypt_ecdh.h" #include "crypt_curve25519.h" #include "crypt_mlkem.h" typedef struct { int32_t hybrId; int32_t pkeyParam; int32_t kemParam; int32_t pkeyAlg; int32_t kemAlg; } HybridKemIdList; static const HybridKemIdList HYBRID_KEY_LIST[] = { {CRYPT_HYBRID_X25519_MLKEM512, 0, CRYPT_KEM_TYPE_MLKEM_512, CRYPT_PKEY_X25519, CRYPT_PKEY_ML_KEM}, {CRYPT_HYBRID_X25519_MLKEM768, 0, CRYPT_KEM_TYPE_MLKEM_768, CRYPT_PKEY_X25519, CRYPT_PKEY_ML_KEM}, {CRYPT_HYBRID_X25519_MLKEM1024, 0, CRYPT_KEM_TYPE_MLKEM_1024, CRYPT_PKEY_X25519, CRYPT_PKEY_ML_KEM}, {CRYPT_HYBRID_ECDH_NISTP256_MLKEM512, CRYPT_ECC_NISTP256, CRYPT_KEM_TYPE_MLKEM_512, CRYPT_PKEY_ECDH, CRYPT_PKEY_ML_KEM}, {CRYPT_HYBRID_ECDH_NISTP256_MLKEM768, CRYPT_ECC_NISTP256, CRYPT_KEM_TYPE_MLKEM_768, CRYPT_PKEY_ECDH, CRYPT_PKEY_ML_KEM}, {CRYPT_HYBRID_ECDH_NISTP256_MLKEM1024, CRYPT_ECC_NISTP256, CRYPT_KEM_TYPE_MLKEM_1024, CRYPT_PKEY_ECDH, CRYPT_PKEY_ML_KEM}, {CRYPT_HYBRID_ECDH_NISTP384_MLKEM512, CRYPT_ECC_NISTP384, CRYPT_KEM_TYPE_MLKEM_512, CRYPT_PKEY_ECDH, CRYPT_PKEY_ML_KEM}, {CRYPT_HYBRID_ECDH_NISTP384_MLKEM768, CRYPT_ECC_NISTP384, CRYPT_KEM_TYPE_MLKEM_768, CRYPT_PKEY_ECDH, CRYPT_PKEY_ML_KEM}, {CRYPT_HYBRID_ECDH_NISTP384_MLKEM1024, CRYPT_ECC_NISTP384, CRYPT_KEM_TYPE_MLKEM_1024, CRYPT_PKEY_ECDH, CRYPT_PKEY_ML_KEM}, {CRYPT_HYBRID_ECDH_NISTP521_MLKEM512, CRYPT_ECC_NISTP521, CRYPT_KEM_TYPE_MLKEM_512, CRYPT_PKEY_ECDH, CRYPT_PKEY_ML_KEM}, {CRYPT_HYBRID_ECDH_NISTP521_MLKEM768, CRYPT_ECC_NISTP521, CRYPT_KEM_TYPE_MLKEM_768, CRYPT_PKEY_ECDH, CRYPT_PKEY_ML_KEM}, {CRYPT_HYBRID_ECDH_NISTP521_MLKEM1024, CRYPT_ECC_NISTP521, CRYPT_KEM_TYPE_MLKEM_1024, CRYPT_PKEY_ECDH, CRYPT_PKEY_ML_KEM}, }; static int32_t HybridGetCurveIdAndKemId(int32_t hybrId, const HybridKemIdList **algInfo) { for (uint32_t i = 0; i < (sizeof(HYBRID_KEY_LIST) / sizeof(HYBRID_KEY_LIST[0])); i++) { if (HYBRID_KEY_LIST[i].hybrId == hybrId) { *algInfo = &HYBRID_KEY_LIST[i]; return CRYPT_SUCCESS; } } return CRYPT_ERR_ALGID; } CRYPT_HybridKemCtx *CRYPT_HYBRID_KEM_NewCtx(void) { CRYPT_HybridKemCtx *hybridKey = BSL_SAL_Calloc(sizeof(CRYPT_HybridKemCtx), 1); if (hybridKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } BSL_SAL_ReferencesInit(&(hybridKey->references)); return hybridKey; } CRYPT_HybridKemCtx *CRYPT_HYBRID_KEM_NewCtxEx(void *libCtx) { CRYPT_HybridKemCtx *hybridKey = CRYPT_HYBRID_KEM_NewCtx(); if (hybridKey == NULL) { return NULL; } hybridKey->libCtx = libCtx; return hybridKey; } void CRYPT_HYBRID_KEM_FreeCtx(CRYPT_HybridKemCtx *hybridKey) { if (hybridKey == NULL) { return; } int ref = 0; BSL_SAL_AtomicDownReferences(&(hybridKey->references), &ref); if (ref > 0) { return; } BSL_SAL_ReferencesFree(&(hybridKey->references)); if (hybridKey->pKeyMethod != NULL && hybridKey->pKeyMethod->freeCtx != NULL) { hybridKey->pKeyMethod->freeCtx(hybridKey->pkeyCtx); } if (hybridKey->kemMethod != NULL && hybridKey->kemMethod->freeCtx != NULL) { hybridKey->kemMethod->freeCtx(hybridKey->kemCtx); } BSL_SAL_FREE(hybridKey); } static void *CRYPT_HybridNewPkeyCtx(CRYPT_HybridKemCtx *ctx, int32_t algId) { void *pkeyCtx = NULL; #ifdef HITLS_CRYPTO_PROVIDER if (algId == CRYPT_PKEY_X25519) { pkeyCtx = CRYPT_X25519_NewCtxEx(ctx->libCtx); } else { pkeyCtx = CRYPT_ECDH_NewCtxEx(ctx->libCtx); } #else (void) ctx; if (algId == CRYPT_PKEY_X25519) { pkeyCtx = CRYPT_X25519_NewCtx(); } else { pkeyCtx = CRYPT_ECDH_NewCtx(); } #endif return pkeyCtx; } static void *CRYPT_HybridNewKemCtx(CRYPT_HybridKemCtx *ctx, int32_t algId) { (void) algId; void *kemCtx = NULL; #ifdef HITLS_CRYPTO_PROVIDER kemCtx = CRYPT_ML_KEM_NewCtxEx(ctx->libCtx); #else (void) ctx; kemCtx = CRYPT_ML_KEM_NewCtx(); #endif return kemCtx; } static int32_t CRYPT_HybridSetKeyType(CRYPT_HybridKemCtx *ctx, int32_t val) { int32_t ret; const HybridKemIdList *algInfo = NULL; RETURN_RET_IF((ctx->pkeyCtx != NULL || ctx->kemCtx != NULL), CRYPT_INVALID_ARG); RETURN_RET_IF_ERR(HybridGetCurveIdAndKemId(val, &algInfo), ret); const EAL_PkeyMethod *pKeyMethod = CRYPT_EAL_PkeyFindMethod(algInfo->pkeyAlg); const EAL_PkeyMethod *kemMethod = CRYPT_EAL_PkeyFindMethod(algInfo->kemAlg); RETURN_RET_IF((pKeyMethod == NULL || kemMethod == NULL), CRYPT_NOT_SUPPORT); ctx->pkeyCtx = CRYPT_HybridNewPkeyCtx(ctx, algInfo->pkeyAlg); RETURN_RET_IF(ctx->pkeyCtx == NULL, CRYPT_MEM_ALLOC_FAIL); ctx->kemCtx = CRYPT_HybridNewKemCtx(ctx, algInfo->kemAlg); if (ctx->kemCtx == NULL) { pKeyMethod->freeCtx(ctx->pkeyCtx); ctx->pkeyCtx = NULL; return CRYPT_MEM_ALLOC_FAIL; } ctx->pKeyMethod = pKeyMethod; ctx->kemMethod = kemMethod; int32_t kemType = algInfo->kemParam; int32_t curveId = algInfo->pkeyParam; GOTO_ERR_IF_EX(ctx->kemMethod->ctrl(ctx->kemCtx, CRYPT_CTRL_SET_PARA_BY_ID, &kemType, sizeof(kemType)), ret); if (curveId == 0) { // For X25519, the curve ID does not need to be set. return CRYPT_SUCCESS; } GOTO_ERR_IF_EX(ctx->pKeyMethod->ctrl(ctx->pkeyCtx, CRYPT_CTRL_SET_PARA_BY_ID, &curveId, sizeof(curveId)), ret); return CRYPT_SUCCESS; ERR: pKeyMethod->freeCtx(ctx->pkeyCtx); ctx->pkeyCtx = NULL; kemMethod->freeCtx(ctx->kemCtx); ctx->kemCtx = NULL; return ret; } static int32_t CRYPT_HybridGetEncapsKeyLen(const CRYPT_HybridKemCtx *ctx, uint32_t *pubLen, uint32_t *ekLen) { int32_t ret; uint32_t val; RETURN_RET_IF((ctx->pKeyMethod == NULL || ctx->kemMethod == NULL), CRYPT_NULL_INPUT); RETURN_RET_IF_ERR(ctx->pKeyMethod->ctrl(ctx->pkeyCtx, CRYPT_CTRL_GET_PUBKEY_LEN, &val, sizeof(val)), ret); *pubLen = val; RETURN_RET_IF_ERR(ctx->kemMethod->ctrl(ctx->kemCtx, CRYPT_CTRL_GET_PUBKEY_LEN, &val, sizeof(val)), ret); *ekLen = val; return CRYPT_SUCCESS; } static int32_t CRYPT_HybridGetDecapsKeyLen(const CRYPT_HybridKemCtx *ctx, uint32_t *prvLen, uint32_t *dkLen) { int32_t ret; uint32_t val; RETURN_RET_IF((ctx->pKeyMethod == NULL || ctx->kemMethod == NULL), CRYPT_NULL_INPUT); RETURN_RET_IF_ERR(ctx->pKeyMethod->ctrl(ctx->pkeyCtx, CRYPT_CTRL_GET_PRVKEY_LEN, &val, sizeof(val)), ret); *prvLen = val; RETURN_RET_IF_ERR(ctx->kemMethod->ctrl(ctx->kemCtx, CRYPT_CTRL_GET_PRVKEY_LEN, &val, sizeof(val)), ret); *dkLen = val; return CRYPT_SUCCESS; } static int32_t CRYPT_HybridGetCipherTextLen(const CRYPT_HybridKemCtx *ctx, uint32_t *pubLen, uint32_t *ctLen) { int32_t ret; uint32_t val; RETURN_RET_IF((ctx->pKeyMethod == NULL || ctx->kemMethod == NULL), CRYPT_NULL_INPUT); RETURN_RET_IF_ERR(ctx->pKeyMethod->ctrl(ctx->pkeyCtx, CRYPT_CTRL_GET_PUBKEY_LEN, &val, sizeof(val)), ret); *pubLen = val; RETURN_RET_IF_ERR(ctx->kemMethod->ctrl(ctx->kemCtx, CRYPT_CTRL_GET_CIPHERTEXT_LEN, &val, sizeof(val)), ret); *ctLen = val; return CRYPT_SUCCESS; } static int32_t CRYPT_HybridGetShareKeyLen(const CRYPT_HybridKemCtx *ctx, uint32_t *pkeyLen, uint32_t *kemLen) { int32_t ret; uint32_t val; RETURN_RET_IF((ctx->pKeyMethod == NULL || ctx->kemMethod == NULL), CRYPT_NULL_INPUT); RETURN_RET_IF_ERR(ctx->pKeyMethod->ctrl(ctx->pkeyCtx, CRYPT_CTRL_GET_SHARED_KEY_LEN, &val, sizeof(val)), ret); *pkeyLen = val; RETURN_RET_IF_ERR(ctx->kemMethod->ctrl(ctx->kemCtx, CRYPT_CTRL_GET_SHARED_KEY_LEN, &val, sizeof(val)), ret); *kemLen = val; return CRYPT_SUCCESS; } static int32_t CRYPT_HybridSetEccPointFormit(const CRYPT_HybridKemCtx *ctx, void *val, uint32_t len) { RETURN_RET_IF((ctx->pKeyMethod == NULL || ctx->pkeyCtx == NULL), CRYPT_INVALID_ARG); return ctx->pKeyMethod->ctrl(ctx->pkeyCtx, CRYPT_CTRL_SET_ECC_POINT_FORMAT, val, len); } int32_t CRYPT_HYBRID_KEM_KeyCtrl(CRYPT_HybridKemCtx *ctx, int32_t opt, void *val, uint32_t len) { int32_t ret; RETURN_RET_IF(ctx == NULL || val == NULL, CRYPT_NULL_INPUT); RETURN_RET_IF(len != sizeof(uint32_t), CRYPT_INVALID_ARG); uint32_t pkeyLen = 0; uint32_t kemLen = 0; switch (opt) { case CRYPT_CTRL_SET_PARA_BY_ID: return CRYPT_HybridSetKeyType(ctx, *(int32_t *)val); case CRYPT_CTRL_GET_PUBKEY_LEN: ret = CRYPT_HybridGetEncapsKeyLen(ctx, &pkeyLen, &kemLen); break; case CRYPT_CTRL_GET_PRVKEY_LEN: ret = CRYPT_HybridGetDecapsKeyLen(ctx, &pkeyLen, &kemLen); break; case CRYPT_CTRL_GET_CIPHERTEXT_LEN: ret = CRYPT_HybridGetCipherTextLen(ctx, &pkeyLen, &kemLen); break; case CRYPT_CTRL_GET_SHARED_KEY_LEN: ret = CRYPT_HybridGetShareKeyLen(ctx, &pkeyLen, &kemLen); break; case CRYPT_CTRL_SET_ECC_POINT_FORMAT: return CRYPT_HybridSetEccPointFormit(ctx, val, len); default: BSL_ERR_PUSH_ERROR(CRYPT_NOT_SUPPORT); return CRYPT_NOT_SUPPORT; } RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); *(uint32_t *)val = pkeyLen + kemLen; return CRYPT_SUCCESS; } int32_t CRYPT_HYBRID_KEM_GenKey(CRYPT_HybridKemCtx *ctx) { int32_t ret; RETURN_RET_IF(ctx == NULL, CRYPT_NULL_INPUT); RETURN_RET_IF((ctx->pKeyMethod == NULL || ctx->kemMethod == NULL), CRYPT_NULL_INPUT); RETURN_RET_IF_ERR(ctx->pKeyMethod->gen(ctx->pkeyCtx), ret); return ctx->kemMethod->gen(ctx->kemCtx); } /* * According of <Post-quantum hybrid ECDHE-MLKEM Key Agreement for TLSv1.3>, when MLKEM and X25519 are mixed, * the key of MLKEM is before the key of X25519. * Protocol link: www.ietf.org/archive/id/draft-kwiatkowski-tls-ecdhe-mlkem-03.html#name-negotiated-groups */ static int32_t CRYPT_HybridGetKeyPtr(const CRYPT_HybridKemCtx *ctx, void *pub, uint32_t pubLen, BSL_Param *pkeyData, BSL_Param *kemData) { RETURN_RET_IF(pubLen < (pkeyData->valueLen + kemData->valueLen), CRYPT_INVALID_ARG); if (ctx->pKeyMethod->id == CRYPT_PKEY_X25519) { kemData->value = pub; pkeyData->value = pub + kemData->valueLen; } else { pkeyData->value = pub; kemData->value = pub + pkeyData->valueLen; } return CRYPT_SUCCESS; } // Get the local public Key and kem encapsulation key. int32_t CRYPT_HYBRID_KEM_GetEncapsKey(const CRYPT_HybridKemCtx *ctx, CRYPT_KemEncapsKey *ek) { int32_t ret; RETURN_RET_IF((ctx == NULL || ek == NULL || ek->data == NULL), CRYPT_NULL_INPUT); BSL_Param pubKey[2] = {{CRYPT_PARAM_EC_PUBKEY, BSL_PARAM_TYPE_OCTETS, NULL, 0, 0}, BSL_PARAM_END}; BSL_Param kemEK[2] = {{CRYPT_PARAM_ML_KEM_PUBKEY, BSL_PARAM_TYPE_OCTETS, NULL, 0, 0}, BSL_PARAM_END}; RETURN_RET_IF_ERR(CRYPT_HybridGetEncapsKeyLen(ctx, &(pubKey[0].valueLen), &(kemEK[0].valueLen)), ret); RETURN_RET_IF_ERR(CRYPT_HybridGetKeyPtr(ctx, ek->data, ek->len, pubKey, kemEK), ret); if (ctx->pKeyMethod->id == CRYPT_PKEY_X25519) { pubKey[0].key = CRYPT_PARAM_CURVE25519_PUBKEY; } RETURN_RET_IF_ERR(ctx->pKeyMethod->getPub(ctx->pkeyCtx, pubKey), ret); RETURN_RET_IF_ERR(ctx->kemMethod->getPub(ctx->kemCtx, kemEK), ret); ek->len = pubKey[0].useLen + kemEK[0].useLen; return CRYPT_SUCCESS; } int32_t CRYPT_HYBRID_KEM_GetDecapsKey(const CRYPT_HybridKemCtx *ctx, CRYPT_KemDecapsKey *dk) { int32_t ret; RETURN_RET_IF((ctx == NULL || dk == NULL || dk->data == NULL), CRYPT_NULL_INPUT); BSL_Param prvKey[2] = {{CRYPT_PARAM_EC_PRVKEY, BSL_PARAM_TYPE_OCTETS, NULL, 0, 0}, BSL_PARAM_END}; BSL_Param kemDK[2] = {{CRYPT_PARAM_ML_KEM_PRVKEY, BSL_PARAM_TYPE_OCTETS, NULL, 0, 0}, BSL_PARAM_END}; RETURN_RET_IF_ERR(CRYPT_HybridGetDecapsKeyLen(ctx, &prvKey[0].valueLen, &kemDK[0].valueLen), ret); RETURN_RET_IF_ERR(CRYPT_HybridGetKeyPtr(ctx, dk->data, dk->len, prvKey, kemDK), ret); if (ctx->pKeyMethod->id == CRYPT_PKEY_X25519) { prvKey[0].key = CRYPT_PARAM_CURVE25519_PRVKEY; } RETURN_RET_IF_ERR(ctx->pKeyMethod->getPrv(ctx->pkeyCtx, prvKey), ret); RETURN_RET_IF_ERR(ctx->kemMethod->getPrv(ctx->kemCtx, kemDK), ret); dk->len = prvKey[0].useLen + kemDK[0].useLen; return CRYPT_SUCCESS; } // Set the public key and kem encapsulation key. int32_t CRYPT_HYBRID_KEM_SetEncapsKey(CRYPT_HybridKemCtx *ctx, const CRYPT_KemEncapsKey *ek) { int32_t ret; RETURN_RET_IF((ctx == NULL || ek == NULL || ek->data == NULL), CRYPT_NULL_INPUT); BSL_Param pubKey[2] = {{CRYPT_PARAM_EC_PUBKEY, BSL_PARAM_TYPE_OCTETS, NULL, 0, 0}, BSL_PARAM_END}; BSL_Param kemEK[2] = {{CRYPT_PARAM_ML_KEM_PUBKEY, BSL_PARAM_TYPE_OCTETS, NULL, 0, 0}, BSL_PARAM_END}; RETURN_RET_IF_ERR(CRYPT_HybridGetEncapsKeyLen(ctx, &pubKey[0].valueLen, &kemEK[0].valueLen), ret); RETURN_RET_IF(ek->len < kemEK[0].valueLen, CRYPT_INVALID_ARG); pubKey[0].valueLen = ek->len - kemEK[0].valueLen; RETURN_RET_IF_ERR(CRYPT_HybridGetKeyPtr(ctx, ek->data, ek->len, pubKey, kemEK), ret); if (ctx->pKeyMethod->id == CRYPT_PKEY_X25519) { pubKey[0].key = CRYPT_PARAM_CURVE25519_PUBKEY; } RETURN_RET_IF_ERR(ctx->kemMethod->setPub(ctx->kemCtx, kemEK), ret); return ctx->pKeyMethod->setPub(ctx->pkeyCtx, pubKey); } int32_t CRYPT_HYBRID_KEM_SetDecapsKey(CRYPT_HybridKemCtx *ctx, const CRYPT_KemDecapsKey *dk) { int32_t ret; RETURN_RET_IF((ctx == NULL || dk == NULL || dk->data == NULL), CRYPT_NULL_INPUT); BSL_Param prvKey[2] = {{CRYPT_PARAM_EC_PRVKEY, BSL_PARAM_TYPE_OCTETS, NULL, 0, 0}, BSL_PARAM_END}; BSL_Param kemDK[2] = {{CRYPT_PARAM_ML_KEM_PRVKEY, BSL_PARAM_TYPE_OCTETS, NULL, 0, 0}, BSL_PARAM_END}; RETURN_RET_IF_ERR(CRYPT_HybridGetDecapsKeyLen(ctx, &(prvKey[0].valueLen), &(kemDK[0].valueLen)), ret); RETURN_RET_IF_ERR(CRYPT_HybridGetKeyPtr(ctx, dk->data, dk->len, prvKey, kemDK), ret); if (ctx->pKeyMethod->id == CRYPT_PKEY_X25519) { prvKey[0].key = CRYPT_PARAM_CURVE25519_PRVKEY; } RETURN_RET_IF_ERR(ctx->kemMethod->setPrv(ctx->kemCtx, kemDK), ret); return ctx->pKeyMethod->setPrv(ctx->pkeyCtx, prvKey); } int32_t CRYPT_HYBRID_KEM_GetEncapsKeyEx(const CRYPT_HybridKemCtx *ctx, BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_KemEncapsKey pub = {0}; BSL_Param *paramPub = GetParamValue(para, CRYPT_PARAM_HYBRID_PUBKEY, &pub.data, &(pub.len)); if (paramPub == NULL) { paramPub = GetParamValue(para, CRYPT_PARAM_PKEY_ENCODE_PUBKEY, &pub.data, &(pub.len)); } int32_t ret = CRYPT_HYBRID_KEM_GetEncapsKey(ctx, &pub); if (ret != CRYPT_SUCCESS) { return ret; } paramPub->useLen = pub.len; return CRYPT_SUCCESS; } int32_t CRYPT_HYBRID_KEM_GetDecapsKeyEx(const CRYPT_HybridKemCtx *ctx, BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_KemDecapsKey prv = {0}; BSL_Param *paramPrv = GetParamValue(para, CRYPT_PARAM_HYBRID_PRVKEY, &prv.data, &(prv.len)); int32_t ret = CRYPT_HYBRID_KEM_GetDecapsKey(ctx, &prv); if (ret != CRYPT_SUCCESS) { return ret; } paramPrv->useLen = prv.len; return CRYPT_SUCCESS; } int32_t CRYPT_HYBRID_KEM_SetEncapsKeyEx(CRYPT_HybridKemCtx *ctx, const BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_KemEncapsKey pub = {0}; if (GetConstParamValue(para, CRYPT_PARAM_HYBRID_PUBKEY, &pub.data, &pub.len) == NULL) { (void)GetConstParamValue(para, CRYPT_PARAM_PKEY_ENCODE_PUBKEY, &pub.data, &pub.len); } return CRYPT_HYBRID_KEM_SetEncapsKey(ctx, &pub); } int32_t CRYPT_HYBRID_KEM_SetDecapsKeyEx(CRYPT_HybridKemCtx *ctx, const BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_KemDecapsKey prv = {0}; (void)GetConstParamValue(para, CRYPT_PARAM_HYBRID_PRVKEY, &prv.data, &prv.len); return CRYPT_HYBRID_KEM_SetDecapsKey(ctx, &prv); } int32_t CRYPT_HYBRID_KEM_Encaps(const CRYPT_HybridKemCtx *ctx, uint8_t *cipher, uint32_t *cipherLen, uint8_t *sharekey, uint32_t *shareLen) { int32_t ret; RETURN_RET_IF((ctx == NULL || cipher == NULL || cipherLen == NULL || sharekey == NULL || shareLen == NULL), CRYPT_NULL_INPUT); BSL_Param kemCT = { 0 }; BSL_Param pubKey[2] = {{CRYPT_PARAM_EC_PUBKEY, BSL_PARAM_TYPE_OCTETS, NULL, 0, 0}, BSL_PARAM_END}; RETURN_RET_IF_ERR(CRYPT_HybridGetCipherTextLen(ctx, &(pubKey[0].valueLen), &(kemCT.valueLen)), ret); RETURN_RET_IF_ERR(CRYPT_HybridGetKeyPtr(ctx, cipher, *cipherLen, pubKey, &kemCT), ret); void *tmpKey = ctx->pKeyMethod->dupCtx(ctx->pkeyCtx); RETURN_RET_IF(tmpKey == NULL, CRYPT_MEM_ALLOC_FAIL); GOTO_ERR_IF(ctx->pKeyMethod->gen(tmpKey), ret); if (ctx->pKeyMethod->id == CRYPT_PKEY_X25519) { pubKey[0].key = CRYPT_PARAM_CURVE25519_PUBKEY; } GOTO_ERR_IF(ctx->pKeyMethod->getPub(tmpKey, pubKey), ret); BSL_Param kemSK = { 0 }; BSL_Param pkeyShared = { 0 }; GOTO_ERR_IF(CRYPT_HybridGetShareKeyLen(ctx, &pkeyShared.valueLen, &kemSK.valueLen), ret); GOTO_ERR_IF(CRYPT_HybridGetKeyPtr(ctx, sharekey, *shareLen, &pkeyShared, &kemSK), ret); GOTO_ERR_IF(ctx->pKeyMethod->computeShareKey(tmpKey, ctx->pkeyCtx, pkeyShared.value, &pkeyShared.valueLen), ret); GOTO_ERR_IF(ctx->kemMethod->encaps(ctx->kemCtx, kemCT.value, &kemCT.valueLen, kemSK.value, &kemSK.valueLen), ret); *shareLen = pkeyShared.valueLen + kemSK.valueLen; *cipherLen = pubKey[0].valueLen + kemCT.valueLen; ERR: ctx->pKeyMethod->freeCtx(tmpKey); return ret; } int32_t CRYPT_HYBRID_KEM_Decaps(const CRYPT_HybridKemCtx *ctx, uint8_t *cipher, uint32_t cipherLen, uint8_t *sharekey, uint32_t *shareLen) { int32_t ret; RETURN_RET_IF((ctx == NULL || cipher == NULL || sharekey == NULL || shareLen == NULL), CRYPT_NULL_INPUT); BSL_Param kemCT = { 0 }; BSL_Param pubKey[2] = {{CRYPT_PARAM_EC_PUBKEY, BSL_PARAM_TYPE_OCTETS, NULL, 0, 0}, BSL_PARAM_END}; RETURN_RET_IF_ERR(CRYPT_HybridGetCipherTextLen(ctx, &pubKey[0].valueLen, &kemCT.valueLen), ret); RETURN_RET_IF_ERR(CRYPT_HybridGetKeyPtr(ctx, cipher, cipherLen, pubKey, &kemCT), ret); void *tmpKey = ctx->pKeyMethod->dupCtx(ctx->pkeyCtx); RETURN_RET_IF(tmpKey == NULL, CRYPT_MEM_ALLOC_FAIL); if (ctx->pKeyMethod->id == CRYPT_PKEY_X25519) { pubKey[0].key = CRYPT_PARAM_CURVE25519_PUBKEY; } GOTO_ERR_IF(ctx->pKeyMethod->setPub(tmpKey, pubKey), ret); BSL_Param pkeyShared = { 0 }; BSL_Param kemSK = { 0 }; GOTO_ERR_IF(CRYPT_HybridGetShareKeyLen(ctx, &pkeyShared.valueLen, &kemSK.valueLen), ret); GOTO_ERR_IF(CRYPT_HybridGetKeyPtr(ctx, sharekey, *shareLen, &pkeyShared, &kemSK), ret); GOTO_ERR_IF(ctx->pKeyMethod->computeShareKey(ctx->pkeyCtx, tmpKey, pkeyShared.value, &pkeyShared.valueLen), ret); GOTO_ERR_IF(ctx->kemMethod->decaps(ctx->kemCtx, kemCT.value, kemCT.valueLen, kemSK.value, &kemSK.valueLen), ret); *shareLen = pkeyShared.valueLen + kemSK.valueLen; ERR: ctx->pKeyMethod->freeCtx(tmpKey); return ret; } #endif
2302_82127028/openHiTLS-examples_1508
crypto/hybridkem/src/crypt_hybridkem.c
C
unknown
20,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. */ #ifndef CRYPT_HYBRID_KEM_LOCAL_H #define CRYPT_HYBRID_KEM_LOCAL_H #include "crypt_local_types.h" #include "sal_atomic.h" struct HybridKemCtx { void *pkeyCtx; // CRYPT_CURVE25519_Ctx or CRYPT_ECDH_Ctx void *kemCtx; // CRYPT_ML_KEM_Ctx const EAL_PkeyMethod *pKeyMethod; const EAL_PkeyMethod *kemMethod; BSL_SAL_RefCount references; void *libCtx; }; #endif
2302_82127028/openHiTLS-examples_1508
crypto/hybridkem/src/crypt_hybridkem_local.h
C
unknown
963
/* * 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_ARM_H #define CRYPT_ARM_H #ifndef CRYPT_VAL #define CRYPT_VAL 16 #endif #ifndef CRYPT_VAL2 #define CRYPT_VAL2 26 #endif #if defined(__arm__) || defined (__arm) #define CRYPT_CAP CRYPT_VAL #define CRYPT_CE CRYPT_VAL2 #define CRYPT_ARM_NEON (1 << 12) #define CRYPT_ARM_AES (1 << 0) #define CRYPT_ARM_PMULL (1 << 1) #define CRYPT_ARM_SHA1 (1 << 2) #define CRYPT_ARM_SHA256 (1 << 3) #elif defined(__aarch64__) #define CRYPT_CAP CRYPT_VAL #define CRYPT_CE CRYPT_VAL #define CRYPT_ARM_NEON (1 << 1) #define CRYPT_ARM_AES (1 << 3) #define CRYPT_ARM_PMULL (1 << 4) #define CRYPT_ARM_SHA1 (1 << 5) #define CRYPT_ARM_SHA256 (1 << 6) #define CRYPT_ARM_SM3 (1 << 18) #define CRYPT_ARM_SM4 (1 << 19) #define CRYPT_ARM_SHA512 (1 << 21) #define CRYPT_CAP2 CRYPT_VAL2 #define CRYPT_ARM_CAP2_RNG (1 << 16) #endif #ifndef __ASSEMBLER__ extern uint32_t g_cryptArmCpuInfo; #else # ifdef HITLS_AARCH64_PACIASP # define AARCH64_PACIASP hint #25 # define AARCH64_AUTIASP hint #29 # else # define AARCH64_PACIASP # define AARCH64_AUTIASP # endif #endif #endif
2302_82127028/openHiTLS-examples_1508
crypto/include/crypt_arm.h
C
unknown
1,824
/* * 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_CMVP_SELFTEST_H #define CRYPT_CMVP_SELFTEST_H #include "hitls_build.h" #if defined(HITLS_CRYPTO_CMVP_ISO19790) || defined(HITLS_CRYPTO_CMVP_SM) || defined(HITLS_CRYPTO_CMVP_FIPS) #include <stdint.h> #include "crypt_cmvp.h" #include "crypt_types.h" #include "crypt_eal_pkey.h" #include "crypt_eal_rand.h" #include "crypt_eal_md.h" #include "crypt_eal_mac.h" #include "crypt_eal_cipher.h" #include "crypt_eal_kdf.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ bool CRYPT_CMVP_SelftestDrbg(CRYPT_RAND_AlgId id); bool CRYPT_CMVP_SelftestProviderDrbg(void *libCtx, const char *attrName, CRYPT_RAND_AlgId id); bool CRYPT_CMVP_SelftestMd(CRYPT_MD_AlgId id); bool CRYPT_CMVP_SelftestProviderMd(void *libCtx, const char *attrName, CRYPT_MD_AlgId id); bool CRYPT_CMVP_SelftestRsa(void); bool CRYPT_CMVP_SelftestProviderRsa(void *libCtx, const char *attrName); bool CRYPT_CMVP_SelftestCipher(CRYPT_CIPHER_AlgId id); bool CRYPT_CMVP_SelftestProviderCipher(void *libCtx, const char *attrName, CRYPT_CIPHER_AlgId id); bool CRYPT_CMVP_SelftestChacha20poly1305(void); bool CRYPT_CMVP_SelftestProviderChacha20poly1305(void *libCtx, const char *attrName); bool CRYPT_CMVP_SelftestDh(void); bool CRYPT_CMVP_SelftestProviderDh(void *libCtx, const char *attrName); bool CRYPT_CMVP_SelftestDsa(void); bool CRYPT_CMVP_SelftestProviderDsa(void *libCtx, const char *attrName); bool CRYPT_CMVP_SelftestEd25519(void); bool CRYPT_CMVP_SelftestProviderEd25519(void *libCtx, const char *attrName); bool CRYPT_CMVP_SelftestHkdf(void); bool CRYPT_CMVP_SelftestProviderHkdf(void *libCtx, const char *attrName); bool CRYPT_CMVP_SelftestMac(CRYPT_MAC_AlgId id); bool CRYPT_CMVP_SelftestProviderMac(void *libCtx, const char *attrName, CRYPT_MAC_AlgId id); bool CRYPT_CMVP_SelftestPbkdf2(CRYPT_MAC_AlgId id); bool CRYPT_CMVP_SelftestProviderPbkdf2(void *libCtx, const char *attrName, CRYPT_MAC_AlgId id); bool CRYPT_CMVP_SelftestScrypt(void); bool CRYPT_CMVP_SelftestProviderScrypt(void *libCtx, const char *attrName); bool CRYPT_CMVP_SelftestKdfTls12(void); bool CRYPT_CMVP_SelftestProviderKdfTls12(void *libCtx, const char *attrName); bool CRYPT_CMVP_SelftestX25519(void); bool CRYPT_CMVP_SelftestProviderX25519(void *libCtx, const char *attrName); bool CRYPT_CMVP_SelftestEcdsa(void); bool CRYPT_CMVP_SelftestProviderEcdsa(void *libCtx, const char *attrName); bool CRYPT_CMVP_SelftestEcdh(void); bool CRYPT_CMVP_SelftestProviderEcdh(void *libCtx, const char *attrName); bool CRYPT_CMVP_SelftestSM2(void); bool CRYPT_CMVP_SelftestProviderSM2(void *libCtx, const char *attrName); bool CRYPT_CMVP_SelftestMlkemEncapsDecaps(void); bool CRYPT_CMVP_SelftestProviderMlkemEncapsDecaps(void *libCtx, const char *attrName); bool CRYPT_CMVP_SelftestMldsaSignVerify(void); bool CRYPT_CMVP_SelftestProviderMldsaSignVerify(void *libCtx, const char *attrName); bool CRYPT_CMVP_SelftestSlhdsaSignVerify(void); bool CRYPT_CMVP_SelftestProviderSlhdsaSignVerify(void *libCtx, const char *attrName); bool CRYPT_CMVP_SelftestPkeyPct(void *ctx, int32_t algId); int32_t CRYPT_CMVP_RandomnessTest(const uint8_t *data, const uint32_t len); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* HITLS_CRYPTO_CMVP_ISO19790 || HITLS_CRYPTO_CMVP_SM || HITLS_CRYPTO_CMVP_FIPS */ #endif /* CRYPT_CMVP_SELFTEST_H */
2302_82127028/openHiTLS-examples_1508
crypto/include/crypt_cmvp_selftest.h
C
unknown
3,870
/* * 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 EAL_DRBG_LOCAL_H #define EAL_DRBG_LOCAL_H #include "hitls_build.h" #if defined(HITLS_CRYPTO_EAL) && defined(HITLS_CRYPTO_DRBG) #include <stdint.h> #include "bsl_sal.h" #include "crypt_eal_rand.h" #include "crypt_algid.h" #include "sal_atomic.h" #include "crypt_local_types.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus struct EAL_RndCtx { bool isProvider; CRYPT_RAND_AlgId id; EAL_RandUnitaryMethod *meth; void *ctx; bool working; // whether the system is in the working state bool isDefaultSeed; BSL_SAL_ThreadLockHandle lock; // thread lock }; typedef struct { CRYPT_RAND_AlgId id; // seed-drbg algorithm CRYPT_EAL_RndCtx *seed; // seed-drbg void *seedCtx; // seed-drbg entropy source handle CRYPT_RandSeedMethod seedMeth; // seed-drbg entropy source implementation function BSL_SAL_RefCount references; } EAL_SeedDrbg; int32_t EAL_SeedDrbgInit(EAL_SeedDrbg *seedDrbg); void EAL_SeedDrbgEntropyMeth(CRYPT_RandSeedMethod *meth); void EAL_SeedDrbgRandDeinit(CRYPT_EAL_RndCtx *rndCtx); int32_t EAL_RandFindMethod(CRYPT_RAND_AlgId id, EAL_RandMethLookup *lu); /** * @brief Global random deinitialization * * @param ctx handle of ctx */ void EAL_RandDeinit(CRYPT_EAL_RndCtx *ctx); /** * @brief Get default method. * * @param void */ EAL_RandUnitaryMethod* EAL_RandGetMethod(void); /** * @brief Get default seed method and ctx. * * @param seedMeth Seed method * @param seedCtx Seed context */ int32_t EAL_GetDefaultSeed(CRYPT_RandSeedMethod *seedMeth, void **seedCtx); #ifdef __cplusplus } #endif // __cplusplus #endif // HITLS_CRYPTO_DRBG #endif // EAL_DRBG_LOCAL_H
2302_82127028/openHiTLS-examples_1508
crypto/include/crypt_drbg_local.h
C
unknown
2,289
/* * 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_LOCAL_TYPES_H #define CRYPT_LOCAL_TYPES_H #include "crypt_algid.h" #include "crypt_types.h" #include "bsl_params.h" #include "crypt_params_key.h" #include "crypt_eal_provider.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus #define CRYPT_PKEY_FLAG_DUP 0x01 #define CRYPT_PKEY_FLAG_NEED_EXPORT_CB 0x02 /* length function */ typedef int32_t (*GetLenFunc)(const void *ctx); /* Prototype of the MD algorithm operation functions */ typedef void* (*MdNewCtx)(void *provCtx, int32_t algId); typedef int32_t (*MdInit)(void *data, const BSL_Param *param); typedef int32_t (*MdUpdate)(void *data, const uint8_t *input, uint32_t len); typedef int32_t (*MdFinal)(void *data, uint8_t *out, uint32_t *len); typedef int32_t (*MdDeinit)(void *data); typedef int32_t (*MdCopyCtx)(void *dst, const void *src); typedef void* (*MdDupCtx)(const void *src); typedef void (*MdFreeCtx)(void *data); typedef int32_t (*MdGetParam)(void *data, BSL_Param *param); typedef int32_t (*MdSqueeze)(void *data, uint8_t *out, uint32_t len); typedef struct { uint32_t id; uint16_t blockSize; // Block size processed by the hash algorithm at a time, which is used with other algorithms. uint16_t mdSize; // Output length of the HASH algorithm MdNewCtx newCtx; // generate md context MdInit init; // Initialize the MD context. MdUpdate update; // Add block data for MD calculation. MdFinal final; // Complete the MD calculation and obtain the MD result. MdDeinit deinit; // Clear the key information of the MD context. MdCopyCtx copyCtx; // Copy the MD context. MdDupCtx dupCtx; // Dup the MD context. MdFreeCtx freeCtx; // free md context MdGetParam getParam; // get/set md param MdSqueeze squeeze; // squeeze the MD context. } EAL_MdMethod; typedef struct { uint16_t hashSize; // Output length of the Siphash algorithm uint16_t compressionRounds; // the number of compression rounds uint16_t finalizationRounds; // the number of finalization rounds } EAL_SiphashMethod; /* provide asymmetric primitive method */ typedef void *(*PkeyNew)(void); typedef void* (*PkeyProvNew)(void *provCtx, int32_t algId); typedef void *(*PkeyDup)(void *key); typedef void (*PkeyFree)(void *key); typedef void *(*PkeyNewParaById)(int32_t id); typedef CRYPT_PKEY_ParaId (*PkeyGetParaId)(const void *key); typedef void (*PkeyFreePara)(void *para); typedef int32_t (*PkeySetPara)(void *key, const void *para); typedef int32_t (*PkeyGetPara)(const void *key, void *para); typedef int32_t (*PkeyGen)(void *key); typedef uint32_t (*PkeyBits)(void *key); typedef uint32_t (*PkeyGetSignLen)(void *key); typedef int32_t (*PkeyCtrl)(void *key, int32_t opt, void *val, uint32_t len); typedef int32_t (*PkeySetPrv)(void *key, const void *para); typedef int32_t (*PkeySetPub)(void *key, const void *para); typedef int32_t (*PkeyGetPrv)(const void *key, void *para); typedef int32_t (*PkeyGetPub)(const void *key, void *para); typedef void *(*PkeyNewPara)(const void *para); typedef int32_t (*PkeySign)(void *key, int32_t mdAlgId, const uint8_t *data, uint32_t dataLen, uint8_t *sign, uint32_t *signLen); typedef int32_t (*PkeySignData)(void *key, const uint8_t *data, uint32_t dataLen, uint8_t *sign, uint32_t *signLen); typedef int32_t (*PkeyVerify)(const void *key, int32_t mdAlgId, const uint8_t *data, uint32_t dataLen, const uint8_t *sign, uint32_t signLen); typedef int32_t (*PkeyVerifyData)(const void *key, const uint8_t *data, uint32_t dataLen, const uint8_t *sign, uint32_t signLen); typedef int32_t (*PkeyRecover)(const void *key, const uint8_t *sign, uint32_t signLen, uint8_t *data, uint32_t *dataLen); typedef int32_t (*PkeyComputeShareKey)(const void *key, const void *pub, uint8_t *share, uint32_t *shareLen); typedef int32_t (*PkeyCrypt)(const void *key, const uint8_t *data, uint32_t dataLen, uint8_t *out, uint32_t *outLen); typedef int32_t (*PkeyHEOperation)(const void *ctx, const BSL_Param *input, uint8_t *out, uint32_t *outLen); typedef int32_t (*PkeyCheck)(uint32_t checkType, const void *key1, const void *key2); typedef int32_t (*PkeyCmp)(const void *key1, const void *key2); typedef int32_t (*PkeyCopyParam)(const void *src, void *dest); typedef int32_t (*PkeyGetSecBits)(const void *key); typedef int32_t (*PkeyEncapsulate)(const void *key, uint8_t *cipher, uint32_t *cipherLen, uint8_t *share, uint32_t *shareLen); typedef int32_t (*PkeyDecapsulate)(const void *key, const uint8_t *cipher, uint32_t cipherLen, uint8_t *share, uint32_t *shareLen); typedef int32_t (*PkeyEncapsulateInit)(const void *key, const BSL_Param *params); typedef int32_t (*PkeyDecapsulateInit)(const void *key, const BSL_Param *params); typedef int32_t (*PkeyBlind)(void *pkey, int32_t mdAlgId, const uint8_t *input, uint32_t inputLen, uint8_t *out, uint32_t *outLen); typedef int32_t (*PkeyUnBlind)(const void *pkey, const uint8_t *input, uint32_t inputLen, uint8_t *out, uint32_t *outLen); typedef int32_t (*PkeyImport)(void *key, const BSL_Param *params); typedef int32_t (*PkeyExport)(const void *key, BSL_Param *params); /** * @ingroup EAL * * Method structure of the EAL */ typedef struct EAL_PkeyMethod { uint32_t id; PkeyNew newCtx; // Apply for a key pair structure resource. PkeyDup dupCtx; // Copy key pair structure resource. PkeyFree freeCtx; // Free the key structure. PkeySetPara setPara; // Set parameters of the key pair structure. PkeyGetPara getPara; // Obtain parameters from the key pair structure. PkeyGen gen; // Generate a key pair. PkeyCtrl ctrl; // Control function. PkeySetPub setPub; // Set the public key. PkeySetPrv setPrv; // Set the private key. PkeyGetPub getPub; // Obtain the public key. PkeyGetPrv getPrv; // Obtain the private key. PkeySign sign; // Sign the signature. PkeySignData signData; // sign the raw data PkeyVerify verify; // Verify the signature. PkeyVerifyData verifyData; // Verify the raw data PkeyRecover recover; // Signature recovery. PkeyComputeShareKey computeShareKey; // Calculate the shared key. PkeyCrypt encrypt; // Encrypt. PkeyCrypt decrypt; // Decrypt. PkeyHEOperation headd; // Add PkeyHEOperation hemul; // Multiply PkeyCheck check; // Check the consistency of the key pair. PkeyCmp cmp; // Compare keys and parameters. PkeyCopyParam copyPara; // Copy parameter from source to destination PkeyEncapsulate encaps; // Key encapsulation. PkeyDecapsulate decaps; // Key decapsulation. PkeyBlind blind; // msg blind PkeyUnBlind unBlind; // sig unBlind. } EAL_PkeyMethod; typedef struct EAL_PkeyUnitaryMethod { PkeyNew newCtx; // Apply for a key pair structure resource. PkeyProvNew provNewCtx; // Creat a key pair structure resource for provider PkeyDup dupCtx; // Copy key pair structure resource. PkeyFree freeCtx; // Free the key structure. PkeySetPara setPara; // Set parameters of the key pair structure. PkeyGetPara getPara; // Obtain parameters from the key pair structure. PkeyGen gen; // Generate a key pair. PkeyCtrl ctrl; // Control function. PkeySetPub setPub; // Set the public key. PkeySetPrv setPrv; // Set the private key. PkeyGetPub getPub; // Obtain the public key. PkeyGetPrv getPrv; // Obtain the private key. PkeySign sign; // Sign the signature. PkeySignData signData; // sign the raw data PkeyVerify verify; // Verify the signature. PkeyVerifyData verifyData; // Verify the raw data PkeyRecover recover; // Signature recovery. PkeyComputeShareKey computeShareKey; // Calculate the shared key. PkeyCrypt encrypt; // Encrypt. PkeyCrypt decrypt; // Decrypt. PkeyHEOperation headd; // Add PkeyHEOperation hemul; // Multiply PkeyCheck check; // Check the consistency of the key pair. PkeyCmp cmp; // Compare keys and parameters. PkeyEncapsulateInit encapsInit; // Key encapsulation init. PkeyDecapsulateInit decapsInit; // Key decapsulation init. PkeyEncapsulate encaps; // Key encapsulation. PkeyDecapsulate decaps; // Key decapsulation. PkeyBlind blind; // msg blind PkeyUnBlind unBlind; // sig unBlind. PkeyImport import; // import key PkeyExport export; // export key } EAL_PkeyUnitaryMethod; /** * @ingroup sym_algid * Symmetric encryption/decryption algorithm ID */ typedef enum { CRYPT_SYM_AES128 = 0, CRYPT_SYM_AES192, CRYPT_SYM_AES256, CRYPT_SYM_CHACHA20, CRYPT_SYM_SM4, CRYPT_SYM_MAX } CRYPT_SYM_AlgId; typedef void *(*CipherNewCtx)(int32_t alg); typedef void *(*CipherProvNewCtx)(void *provCtx, int32_t alg); typedef int32_t (*CipherInitCtx)(void *ctx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, const BSL_Param *param, bool enc); typedef int32_t (*CipherDeInitCtx)(void *ctx); typedef int32_t (*CipherUpdate)(void *ctx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); typedef int32_t (*CipherFinal)(void *ctx, uint8_t *out, uint32_t *outLen); typedef int32_t (*CipherCtrl)(void *ctx, int32_t opt, void *val, uint32_t len); typedef void (*CipherFreeCtx)(void *ctx); typedef int32_t (*SetEncryptKey)(void *ctx, const uint8_t *key, uint32_t len); typedef int32_t (*SetDecryptKey)(void *ctx, const uint8_t *key, uint32_t len); typedef int32_t (*SetKey)(void *ctx, const uint8_t *key, uint32_t len); // process block or blocks typedef int32_t (*EncryptBlock)(void *ctx, const uint8_t *in, uint8_t *out, uint32_t len); typedef int32_t (*DecryptBlock)(void *ctx, const uint8_t *in, uint8_t *out, uint32_t len); typedef void (*DeInitBlockCtx)(void *ctx); typedef int32_t (*CipherStreamProcess)(void *ctx, const uint8_t *in, uint8_t *out, uint32_t len); typedef struct { SetEncryptKey setEncryptKey; SetDecryptKey setDecryptKey; EncryptBlock encryptBlock; DecryptBlock decryptBlock; DeInitBlockCtx cipherDeInitCtx; CipherCtrl cipherCtrl; uint8_t blockSize; uint16_t ctxSize; CRYPT_SYM_AlgId algId; } EAL_SymMethod; typedef struct { CipherNewCtx newCtx; CipherInitCtx initCtx; CipherDeInitCtx deinitCtx; CipherUpdate update; CipherFinal final; CipherCtrl ctrl; CipherFreeCtx freeCtx; } EAL_CipherMethod; typedef struct { CipherNewCtx newCtx; CipherProvNewCtx provNewCtx; CipherInitCtx initCtx; CipherDeInitCtx deinitCtx; CipherUpdate update; CipherFinal final; CipherCtrl ctrl; CipherFreeCtx freeCtx; } EAL_CipherUnitaryMethod; /* prototype of MAC algorithm operation functions */ typedef void* (*MacNewCtx)(void *provCtx, int32_t algId); // Complete key initialization. typedef int32_t (*MacInit)(void *ctx, const uint8_t *key, uint32_t len, const BSL_Param *param); typedef int32_t (*MacUpdate)(void *ctx, const uint8_t *in, uint32_t len); typedef int32_t (*MacFinal)(void *ctx, const uint8_t *out, uint32_t *len); typedef int32_t (*MacDeinit)(void *ctx); // The action is opposite to the initCtx. Sensitive data is deleted. typedef int32_t (*MacReinit)(void *ctx); typedef int32_t (*MacCtrl)(void *data, int32_t cmd, void *val, uint32_t valLen); typedef int32_t (*MacSetParam)(void *data, const BSL_Param *param); typedef void (*MacFreeCtx)(void *ctx); /* set of MAC algorithm operation methods */ typedef struct { MacNewCtx newCtx; MacInit init; // Initialize the MAC context. MacUpdate update; // Add block data for MAC calculation. MacFinal final; // Complete MAC calculation and obtain the MAC result. MacDeinit deinit; // Clear the key information in MAC context. // Re-initialize the key. This method is used where the keys are the same during multiple MAC calculations. MacReinit reinit; MacCtrl ctrl; MacSetParam setParam; MacFreeCtx freeCtx; } EAL_MacMethod; typedef struct { union { CRYPT_MD_AlgId mdId; CRYPT_SYM_AlgId symId; } id; union { EAL_MdMethod *md; // MD algorithm which HMAC depends on const EAL_SymMethod *sym; // AES function wihch CMAC depends on EAL_SiphashMethod *sip; // siphash method } method; } EAL_MacDepMethod; /** * @ingroup mode_algid * Symmetric encryption/decryption mode ID */ typedef enum { CRYPT_MODE_CBC = 0, CRYPT_MODE_ECB, CRYPT_MODE_CTR, CRYPT_MODE_XTS, CRYPT_MODE_CCM, CRYPT_MODE_GCM, CRYPT_MODE_CHACHA20_POLY1305, CRYPT_MODE_CFB, CRYPT_MODE_OFB, CRYPT_MODE_MAX } CRYPT_MODE_AlgId; /** * @ingroup crypt_eal_pkey * * Structure of the PSS padding mode when RSA is used for signature */ typedef struct { int32_t saltLen; /**< pss salt length. -1 indicates hashLen, -2 indicates MaxLen, -3 is AutoLen */ EAL_MdMethod mdMeth; /**< pss mdid method when padding */ EAL_MdMethod mgfMeth; /**< pss mgfid method when padding */ CRYPT_MD_AlgId mdId; /**< pss mdid when padding */ CRYPT_MD_AlgId mgfId; /**< pss mgfid when padding */ void *mdProvCtx; void *mgfProvCtx; } RSA_PadingPara; /* Prototype of the KDF algorithm operation functions */ typedef void* (*KdfNewCtx)(void); typedef void* (*KdfProvNewCtx)(void *provCtx, int32_t algId); typedef int32_t (*KdfSetParam)(void *ctx, const BSL_Param *param); typedef int32_t (*KdfDerive)(void *ctx, uint8_t *key, uint32_t keyLen); typedef int32_t (*KdfDeinit)(void *ctx); typedef int32_t (*KdfCtrl)(void *data, int32_t cmd, void *val, uint32_t valLen); typedef void (*KdfFreeCtx)(void *ctx); typedef struct { KdfNewCtx newCtx; KdfSetParam setParam; KdfDerive derive; KdfDeinit deinit; KdfFreeCtx freeCtx; } EAL_KdfMethod; typedef struct { KdfNewCtx newCtx; KdfProvNewCtx provNewCtx; KdfSetParam setParam; KdfDerive derive; KdfDeinit deinit; KdfFreeCtx freeCtx; KdfCtrl ctrl; } EAL_KdfUnitaryMethod; typedef struct { uint32_t id; EAL_KdfMethod *kdfMeth; } EAL_CidToKdfMeth; /* Prototype of the RAND algorithm operation functions */ typedef void *(*RandDrbgNewCtx)(void *libCtx, int32_t algId, BSL_Param *param); typedef int32_t (*RandDrbgInst)(void *ctx, const uint8_t *pers, uint32_t persLen, BSL_Param *param); typedef int32_t (*RandDrbgUnInst)(void *ctx); typedef int32_t (*RandDrbgGen)(void *ctx, uint8_t *bytes, uint32_t len, const uint8_t *addin, uint32_t addinLen, BSL_Param *param); typedef int32_t (*RandDrbgReSeed)(void *ctx, const uint8_t *addin, uint32_t addinLen, BSL_Param *param); typedef int32_t (*RandDrbgCtrl)(void *ctx, int32_t cmd, void *val, uint32_t valLen); typedef void (*RandDrbgFreeCtx)(void *ctx); typedef struct { RandDrbgNewCtx newCtx; RandDrbgInst inst; RandDrbgUnInst unInst; RandDrbgGen gen; RandDrbgReSeed reSeed; RandDrbgCtrl ctrl; RandDrbgFreeCtx freeCtx; } EAL_RandUnitaryMethod; typedef struct { uint32_t type; int32_t methodId; const void *method; } EAL_RandMethLookup; /** * @ingroup crypt_ctrl_param * * Set and obtain internal parameters of Pbkdf2. */ typedef enum { CRYPT_CTRL_GET_MACID = 0, /* kdf get macId . */ CRYPT_CTRL_GET_SALTLEN, /* kdf get saltlen . */ CRYPT_CTRL_GET_ITER, /* kdf get iter . */ CRYPT_CTRL_GET_KEYLEN /* kdf get keyLen . */ } CRYPT_KdfCtrl; typedef enum { CRYPT_PKEY_CHECK_KEYPAIR = 1, /**< Check the key pair. */ CRYPT_PKEY_CHECK_PRVKEY = 2, /**< Check the private key. */ CRYPT_PKEY_CHECK_MAX, } CRYPT_KeyCheckType; #ifdef __cplusplus } #endif // __cplusplus #endif // EAL_LOCAL_TYPES_H
2302_82127028/openHiTLS-examples_1508
crypto/include/crypt_local_types.h
C
unknown
17,351
/* * 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_UTIL_RAND_H #define CRYPT_UTIL_RAND_H #include "hitls_build.h" #if defined(HITLS_CRYPTO_DRBG) || defined(HITLS_CRYPTO_CURVE25519) || \ defined(HITLS_CRYPTO_RSA) || defined(HITLS_CRYPTO_BN_RAND) #include <stdint.h> #include "crypt_eal_rand.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Random number registration * * @param func [IN] Interface for obtaining random numbers */ void CRYPT_RandRegist(CRYPT_EAL_RandFunc func); /** * @brief Get the registered random number function * * @return The registered random number function */ CRYPT_EAL_RandFunc CRYPT_RandRegistGet(void); /** * @brief Generate a random number * * @param rand [OUT] buffer of random number * @param randLen [IN] length of random number * * @retval CRYPT_SUCCESS A random number is generated successfully. * @retval CRYPT_NO_REGIST_RAND The random number function is not registered. * @retval Error returned when the registered random number fails during the generate. */ int32_t CRYPT_Rand(uint8_t *rand, uint32_t randLen); /** * @brief Random number registration * * @param func [IN] Interface for obtaining random numbers */ void CRYPT_RandRegistEx(CRYPT_EAL_RandFuncEx func); /** * @brief Get the registered random number function * * @return The registered random number function */ CRYPT_EAL_RandFuncEx CRYPT_RandRegistExGet(void); /** * @brief Generate a random number * * @param libCtx [IN] Library context * @param rand [OUT] buffer of random number * @param randLen [IN] length of random number * * @retval CRYPT_SUCCESS A random number is generated successfully. * @retval CRYPT_NO_REGIST_RAND The random number function is not registered. * @retval Error returned when the registered random number fails during the generate. */ int32_t CRYPT_RandEx(void *libCtx, uint8_t *rand, uint32_t randLen); #if defined(HITLS_CRYPTO_EAL) #ifdef HITLS_CRYPTO_ENTROPY /** * @brief Global seed-drbg lock initialization * * @param ctx handle of ctx */ int32_t EAL_SeedDrbgLockInit(void); /** * @brief Global seed-drbg lock deinitialization * * @param ctx handle of ctx */ void EAL_SeedDrbgLockDeInit(void); #endif #endif #ifdef __cplusplus } #endif #endif #endif
2302_82127028/openHiTLS-examples_1508
crypto/include/crypt_util_rand.h
C
unknown
2,816
/* * 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_UTILS_H #define CRYPT_UTILS_H #include <stdint.h> #include <stdlib.h> #include <stdbool.h> #include "bsl_err_internal.h" #include "crypt_errno.h" #include "crypt_algid.h" #include "crypt_local_types.h" #ifdef HITLS_BSL_PARAMS #include "bsl_params.h" #include "crypt_params_key.h" #endif #ifdef __cplusplus extern "C" { #endif // __cplusplus #if defined(__GNUC__) || defined(__clang__) #define LIKELY(x) __builtin_expect(!!(x), 1) #define UNLIKELY(x) __builtin_expect(!!(x), 0) #define ALIGN32 __attribute__((aligned(32))) #define ALIGN64 __attribute__((aligned(64))) #else #define LIKELY(x) x #define UNLIKELY(x) x #define ALIGN32 #define ALIGN64 #endif #define BITS_PER_BYTE 8 #define SHIFTS_PER_BYTE 3 #define BITSIZE(t) (sizeof(t) * BITS_PER_BYTE) #define PUT_UINT32_BE(v, p, i) \ do { \ (p)[(i) + 0] = (uint8_t)((v) >> 24); \ (p)[(i) + 1] = (uint8_t)((v) >> 16); \ (p)[(i) + 2] = (uint8_t)((v) >> 8); \ (p)[(i) + 3] = (uint8_t)((v) >> 0); \ } while (0) #define PUT_UINT64_BE(v, p, i) \ do { \ (p)[(i) + 0] = (uint8_t)((v) >> 56); \ (p)[(i) + 1] = (uint8_t)((v) >> 48); \ (p)[(i) + 2] = (uint8_t)((v) >> 40); \ (p)[(i) + 3] = (uint8_t)((v) >> 32); \ (p)[(i) + 4] = (uint8_t)((v) >> 24); \ (p)[(i) + 5] = (uint8_t)((v) >> 16); \ (p)[(i) + 6] = (uint8_t)((v) >> 8); \ (p)[(i) + 7] = (uint8_t)((v) >> 0); \ } while (0) #define GET_UINT32_BE(p, i) \ ( \ ((uint32_t)(p)[(i) + 0] << 24) | \ ((uint32_t)(p)[(i) + 1] << 16) | \ ((uint32_t)(p)[(i) + 2] << 8) | \ ((uint32_t)(p)[(i) + 3] << 0) \ ) #define PUT_UINT32_LE(v, p, i) \ do { \ (p)[(i) + 3] = (uint8_t)((v) >> 24); \ (p)[(i) + 2] = (uint8_t)((v) >> 16); \ (p)[(i) + 1] = (uint8_t)((v) >> 8); \ (p)[(i) + 0] = (uint8_t)((v) >> 0); \ } while (0) #define PUT_UINT64_LE(v, p, i) do { \ (p)[(i) + 7] = (uint8_t)((v) >> 56); \ (p)[(i) + 6] = (uint8_t)((v) >> 48); \ (p)[(i) + 5] = (uint8_t)((v) >> 40); \ (p)[(i) + 4] = (uint8_t)((v) >> 32); \ (p)[(i) + 3] = (uint8_t)((v) >> 24); \ (p)[(i) + 2] = (uint8_t)((v) >> 16); \ (p)[(i) + 1] = (uint8_t)((v) >> 8); \ (p)[(i) + 0] = (uint8_t)((v) >> 0); \ } while (0) #define GET_UINT64_LE(p, i) \ ( \ ((uint64_t)(p)[(i) + 7] << 56) | ((uint64_t)(p)[(i) + 6] << 48) | \ ((uint64_t)(p)[(i) + 5] << 40) | ((uint64_t)(p)[(i) + 4] << 32) | \ ((uint64_t)(p)[(i) + 3] << 24) | ((uint64_t)(p)[(i) + 2] << 16) | \ ((uint64_t)(p)[(i) + 1] << 8) | ((uint64_t)(p)[(i) + 0] << 0) \ ) /** * Check whether conditions are met. If yes, an error code is returned. */ #define RETURN_RET_IF(condition, ret) \ do { \ if (condition) { \ BSL_ERR_PUSH_ERROR(ret); \ return ret; \ } \ } while (0) /** * If the return value of func is not CRYPT_SUCCESS, go to the label ERR. */ #define GOTO_ERR_IF(func, ret) do { \ (ret) = (func); \ if ((ret) != CRYPT_SUCCESS) { \ BSL_ERR_PUSH_ERROR((ret)); \ goto ERR; \ } \ } while (0) #define GOTO_ERR_IF_EX(func, ret) do { \ (ret) = (func); \ if ((ret) != CRYPT_SUCCESS) { \ goto ERR; \ } \ } while (0) #define GOTO_ERR_IF_TRUE(condition, ret) do { \ if (condition) { \ BSL_ERR_PUSH_ERROR((ret)); \ goto ERR; \ } \ } while (0) /** * Check whether conditions are met. If yes, an error code is returned. */ #define RETURN_RET_IF_ERR(func, ret) \ do { \ (ret) = (func); \ if ((ret) != CRYPT_SUCCESS) { \ BSL_ERR_PUSH_ERROR((ret)); \ return ret; \ } \ } while (0) #define RETURN_RET_IF_ERR_EX(func, ret) \ do { \ (ret) = (func); \ if ((ret) != CRYPT_SUCCESS) { \ return ret; \ } \ } while (0) #define BREAK_IF(condition) \ do { \ if (condition) { \ break; \ } \ } while (0) /** * If src is not NULL, then execute the fun function. If the operation fails, go to the label ERR. */ #define GOTO_ERR_IF_SRC_NOT_NULL(dest, src, func, ret) \ do { \ if ((src) != NULL) { \ (dest) = (func); \ if ((dest) == NULL) { \ BSL_ERR_PUSH_ERROR((ret)); \ goto ERR; \ } \ } \ } while (0) /** * @brief Perform the XOR operation on the data of two arrays. * * @param a [IN] Input data a * @param b [IN] Input data b * @param r [out] Output the result data. * @param len [IN] Output result data length */ #define DATA_XOR(a, b, r, len) \ do { \ uint32_t subscript; \ for (subscript = 0; subscript < (len); subscript++) { \ (r)[subscript] = (a)[subscript] ^ (b)[subscript]; \ } \ } while (0) /** * @brief Perform the XOR operation on the data of 32 bits in two arrays each time. * Ensure that the input and output are integer multiples of 32 bits. * Type conversion is performed only when the address is 4-byte aligned. * * @param a [IN] Input data a * @param b [IN] Input data b * @param r [out] Output the result data. * @param len [IN] Output result data length */ #define DATA32_XOR(a, b, r, len) \ do { \ uint32_t ii; \ uintptr_t aPtr = (uintptr_t)(a); \ uintptr_t bPtr = (uintptr_t)(b); \ uintptr_t rPtr = (uintptr_t)(r); \ if (((aPtr & 0x3) != 0) || ((bPtr & 0x3) != 0) || ((rPtr & 0x3) != 0)) { \ for (ii = 0; ii < (len); ii++) { \ (r)[ii] = (a)[ii] ^ (b)[ii]; \ } \ } else { \ for (ii = 0; ii < (len); ii += 4) { \ *(uint32_t *)((r) + ii) = (*(const uint32_t *)((a) + ii)) ^ (*(const uint32_t *)((b) + ii)); \ } \ } \ } while (0) /** * @brief Perform the XOR operation on 64 bits of data in two arrays each time. * Ensure that the input and output are integer multiples of 64 bits. * Type conversion is performed only when the address is 8-byte aligned. * * @param a [IN] Input data a * @param b [IN] Input data b * @param r [out] Output the result data. * @param len [IN] Output result data length */ #define DATA64_XOR(a, b, r, len) \ do { \ uint32_t ii; \ uintptr_t aPtr = (uintptr_t)(a); \ uintptr_t bPtr = (uintptr_t)(b); \ uintptr_t rPtr = (uintptr_t)(r); \ if (((aPtr & 0x7) != 0) || ((bPtr & 0x7) != 0) || ((rPtr & 0x7) != 0)) { \ for (ii = 0; ii < (len); ii++) { \ (r)[ii] = (a)[ii] ^ (b)[ii]; \ } \ } else { \ for (ii = 0; ii < (len); ii += 8) { \ *(uint64_t *)((r) + ii) = (*(const uint64_t *)((a) + ii)) ^ (*(const uint64_t *)((b) + ii)); \ } \ } \ } while (0) /** * @brief Calculate the hash value of the input data. * * @param provCtx [IN] Provider context * @param hashMethod [IN] Hash method * @param hashData [IN] Hash data * @param size [IN] Size of hash data * @param out [OUT] Output hash value */ int32_t CRYPT_CalcHash(void *provCtx, const EAL_MdMethod *hashMethod, const CRYPT_ConstData *hashData, uint32_t size, uint8_t *out, uint32_t *outlen); /** * @ingroup rsa * @brief mgf1 of PKCS1 * * @param provCtx [IN] Provider context * @param hashMethod [IN] Hash method * @param seed [IN] Seed * @param seedLen [IN] Seed length * @param mask [OUT] Mask * @param maskLen [IN] Mask length * * @retval CRYPT_SUCCESS on success */ int32_t CRYPT_Mgf1(void *provCtx, const EAL_MdMethod *hashMethod, const uint8_t *seed, const uint32_t seedLen, uint8_t *mask, uint32_t maskLen); /** * @brief Retrieves the process function callback and its arguments from a parameter list. * * @param params A pointer to the BSL_Param list containing the parameters. * @param processCb A pointer to a pointer to the process function callback. * @param args A pointer to a pointer to the process function arguments. * @return int32_t Returns CRYPT_SUCCESS if the operation is successful, otherwise an error code. */ int32_t CRYPT_GetPkeyProcessParams(BSL_Param *params, CRYPT_EAL_ProcessFuncCb *processCb, void **args); #if (defined(HITLS_CRYPTO_DH_CHECK) || defined(HITLS_CRYPTO_DSA_CHECK)) /** * @brief check the key pair consistency * * @param x [IN] FFC private key * @param y [IN] FFC public key * @param p [IN] FFC prime * @param g [IN] FFC generator * * @retval CRYPT_SUCCESS check success. * Others. For details, see error code in errno. */ int32_t CRYPT_FFC_KeyPairCheck(const void *x, const void *y, const void *p, const void *g); /** * @brief check the private key * * @param x [IN] FFC private key * @param p [IN] FFC prime * @param q [IN] FFC subprime * * @retval CRYPT_SUCCESS check success. * Others. For details, see error code in errno. */ int32_t CRYPT_FFC_PrvCheck(const void *x, const void *p, const void *q); #endif // HITLS_CRYPTO_DH_CHECK || HITLS_CRYPTO_DSA_CHECK #if defined(HITLS_CRYPTO_PROVIDER) && defined(HITLS_CRYPTO_MD) /** * @brief Control the MD context. * * @param mdSize [IN] MD size * @param mdBlockSize [IN] MD block size * @param opt [IN] Option * @param val [IN] Value * @param len [IN] Length * * @retval #CRYPT_SUCCESS initialization succeeded. * @retval #CRYPT_NULL_INPUT Pointer ctx is NULL * @retval #CRYPT_NOT_SUPPORT Option is not supported */ int32_t CRYPT_MdCommonGetParam(uint16_t mdSize, uint16_t mdBlockSize, BSL_Param *param); #endif #if defined(HITLS_CRYPTO_PROVIDER) && (defined(HITLS_CRYPTO_RSA) || defined(HITLS_CRYPTO_ECDSA) || \ defined(HITLS_CRYPTO_DSA)) /** * @brief Set the MD attribute. * * @param mdAttr [IN] MD attribute * @param len [IN] MD attribute length * @param pkeyMdAttr [OUT] Output pkey MD attribute */ int32_t CRYPT_PkeySetMdAttr(const char *mdAttr, uint32_t len, char **pkeyMdAttr); #endif /* Assumes that x is uint32_t and 0 < n < 32 */ #define ROTL32(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) #define ROTR64(x, n) (((x) << (64 - (n))) | ((x) >> (n))) // Assumes that x is uint64_t and 0 < n < 64 #define IS_BUF_NON_ZERO(out, outLen) (((out) != NULL) && ((outLen) > 0)) #define CRYPT_IS_BUF_NON_ZERO(out, outLen) (((out) != NULL) && ((outLen) > 0)) #define CRYPT_CHECK_DATA_INVALID(d) (((d)->data == NULL && (d)->len != 0)) #define CRYPT_IsDataNull(d) ((d) == NULL || (d)->data == NULL || (d)->len == 0) #define CRYPT_IN_RANGE(x, range) ((x) >= (range)->min && (x) <= (range)->max) #define CRYPT_CHECK_BUF_INVALID(buf, len) (((buf) == NULL && (len) != 0)) #define CRYPT_SWAP32(x) ((((x) & 0xff000000) >> 24) | \ (((x) & 0x00ff0000) >> 8) | \ (((x) & 0x0000ff00) << 8) | \ (((x) & 0x000000ff) << 24)) #ifdef HITLS_BIG_ENDIAN #define CRYPT_HTONL(x) (x) // Interpret p + i as little endian order. The type of p must be uint8_t *. #define GET_UINT32_LE(p, i) \ ( \ ((uint32_t)((const uint8_t *)(p))[(i) + 3] << 24) | \ ((uint32_t)((const uint8_t *)(p))[(i) + 2] << 16) | \ ((uint32_t)((const uint8_t *)(p))[(i) + 1] << 8) | \ ((uint32_t)((const uint8_t *)(p))[(i) + 0] << 0) \ ) // Convert little-endian order to host order #define CRYPT_LE32TOH(x) CRYPT_SWAP32(x) // Convert host order to little-endian order #define CRYPT_HTOLE32(x) CRYPT_SWAP32(x) #else #define CRYPT_HTONL(x) CRYPT_SWAP32(x) // Interpret p + i as little endian. #define GET_UINT32_LE(p, i) \ ( \ (((uintptr_t)(p) & 0x7) != 0) ? ((uint32_t)((const uint8_t *)(p))[(i) + 3] << 24) | \ ((uint32_t)((const uint8_t *)(p))[(i) + 2] << 16) | \ ((uint32_t)((const uint8_t *)(p))[(i) + 1] << 8) | \ ((uint32_t)((const uint8_t *)(p))[(i) + 0] << 0) \ : (*(uint32_t *)((uint8_t *)(uintptr_t)(p) + (i))) \ ) // Convert little-endian order to host order #define CRYPT_LE32TOH(x) (x) // Convert host order to little-endian order #define CRYPT_HTOLE32(x) (x) #endif #ifdef HITLS_BIG_ENDIAN // Interpret p + i as little endian. The type of p must be uint8_t *. #define GET_UINT16_LE(p, i) \ ( \ ((uint16_t)((const uint8_t *)(p))[(i) + 1] << 8) | \ ((uint16_t)((const uint8_t *)(p))[(i) + 0] << 0) \ ) #else // Interpret p + i as little endian. #define GET_UINT16_LE(p, i) \ ( \ (((uintptr_t)(p) & 0x7) != 0) ? ((uint16_t)((const uint8_t *)(p))[(i) + 1] << 8) | \ ((uint16_t)((const uint8_t *)(p))[(i) + 0] << 0) \ : (*(uint16_t *)((uint8_t *)(uintptr_t)(p) + (i))) \ ) #endif #define PUT_UINT16_LE(v, p, i) \ do \ { \ (p)[(i) + 1] = (uint8_t)((v) >> 8); \ (p)[(i) + 0] = (uint8_t)((v) >> 0); \ } while (0) /** * 64-bit integer manipulation functions (big endian) */ static inline uint64_t Uint64FromBeBytes(const uint8_t *bytes) { return (((uint64_t)bytes[0] << 56) | ((uint64_t)bytes[1] << 48) | ((uint64_t)bytes[2] << 40) | ((uint64_t)bytes[3] << 32) | ((uint64_t)bytes[4] << 24) | ((uint64_t)bytes[5] << 16) | ((uint64_t)bytes[6] << 8) | (uint64_t)bytes[7]); } static inline void Uint64ToBeBytes(uint64_t v, uint8_t *bytes) { bytes[0] = (uint8_t)(v >> 56); bytes[1] = (uint8_t)(v >> 48); bytes[2] = (uint8_t)(v >> 40); bytes[3] = (uint8_t)(v >> 32); bytes[4] = (uint8_t)(v >> 24); bytes[5] = (uint8_t)(v >> 16); bytes[6] = (uint8_t)(v >> 8); bytes[7] = (uint8_t)(v & 0xffu); } #if defined(HITLS_CRYPTO_RSA_SIGN) || defined(HITLS_CRYPTO_RSA_VERIFY) uint32_t CRYPT_GetMdSizeById(CRYPT_MD_AlgId id); #endif static inline bool ParamIdIsValid(uint32_t id, const uint32_t *list, uint32_t num) { for (uint32_t i = 0; i < num; i++) { if (id == list[i]) { return true; } } return false; } typedef uint32_t (*GetUintCallBack)(const void *key); static inline int32_t GetUintCtrl(const void *ctx, void *val, uint32_t len, GetUintCallBack getUint) { 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 *)val = getUint(ctx); return CRYPT_SUCCESS; } #ifdef HITLS_BSL_PARAMS static inline const BSL_Param *GetConstParamValue(const BSL_Param *params, int32_t type, uint8_t **value, uint32_t *valueLen) { const BSL_Param *temp = BSL_PARAM_FindConstParam(params, type); if (temp != NULL) { *value = temp->value; if (valueLen != NULL) { *valueLen = temp->valueLen; } } return temp; } static inline BSL_Param *GetParamValue(BSL_Param *params, int32_t type, uint8_t **value, uint32_t *valueLen) { BSL_Param *temp = BSL_PARAM_FindParam(params, type); if (temp != NULL) { *value = temp->value; if (valueLen != NULL) { *valueLen = temp->valueLen; } } return temp; } #endif void GetCpuInstrSupportState(void); #ifdef __x86_64__ #define CPU_ID_OUT_U32_CNT 4 #define EAX_OUT_IDX 0 #define EBX_OUT_IDX 1 #define ECX_OUT_IDX 2 #define EDX_OUT_IDX 3 /* %eax */ #define XCR0_BIT_SSE (1ULL << 1) #define XCR0_BIT_AVX (1ULL << 2) #define XCR0_BIT_OPMASK (1ULL << 5) #define XCR0_BIT_ZMM_LOW (1ULL << 6) #define XCR0_BIT_ZMM_HIGH (1ULL << 7) typedef struct { uint32_t code1Out[CPU_ID_OUT_U32_CNT]; uint32_t code7Out[CPU_ID_OUT_U32_CNT]; bool osSupportAVX; /* input ecx = 0, output edx:eax bit 2 */ bool osSupportAVX512; /* input ecx = 0, output edx:eax bit 6 */ } CpuInstrSupportState; bool IsSupportAES(void); bool IsSupportBMI1(void); bool IsSupportBMI2(void); bool IsSupportADX(void); bool IsSupportAVX(void); bool IsSupportAVX2(void); bool IsSupportSSE(void); bool IsSupportSSE2(void); bool IsSupportSSE3(void); bool IsSupportMOVBE(void); bool IsSupportAVX512F(void); bool IsSupportAVX512VL(void); bool IsSupportAVX512BW(void); bool IsSupportAVX512DQ(void); bool IsSupportXSAVE(void); bool IsSupportOSXSAVE(void); bool IsOSSupportAVX(void); bool IsOSSupportAVX512(void); void GetCpuId(uint32_t eax, uint32_t ecx, uint32_t cpuId[CPU_ID_OUT_U32_CNT]); #elif defined(__arm__) || defined(__arm) || defined(__aarch64__) bool IsSupportAES(void); bool IsSupportPMULL(void); bool IsSupportSHA1(void); bool IsSupportSHA256(void); bool IsSupportNEON(void); #if defined(__aarch64__) bool IsSupportSHA512(void); #endif // __aarch64__ #endif // __arm__ || __arm || __aarch64__ #ifdef __cplusplus } #endif // __cplusplus #endif // CRYPT_UTILS_H
2302_82127028/openHiTLS-examples_1508
crypto/include/crypt_utils.h
C
unknown
20,141
/* * 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_KDF_TLS12_H #define CRYPT_KDF_TLS12_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_KDFTLS12 #include <stdint.h> #include "crypt_local_types.h" #include "bsl_params.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus typedef struct CryptKdfTls12Ctx CRYPT_KDFTLS12_Ctx; /** * @ingroup KDFTLS12 * @brief Generate KDFTLS12 context. * * @retval Success: KDFTLS12 ctx. * Fails: NULL. */ CRYPT_KDFTLS12_Ctx* CRYPT_KDFTLS12_NewCtx(void); /** * @ingroup KDFTLS12 * @brief Generate KDFTLS12 context. * * @param libCtx [in] Library context. * * @retval Success: KDFTLS12 ctx. * Fails: NULL. */ CRYPT_KDFTLS12_Ctx *CRYPT_KDFTLS12_NewCtxEx(void *libCtx); /** * @ingroup KDFTLS12 * @brief Set parameters for the KDFTLS12 context. * * @param ctx [in, out] Pointer to the KDFTLS12 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_KDFTLS12_SetParam(CRYPT_KDFTLS12_Ctx *ctx, const BSL_Param *param); /** * @ingroup KDFTLS12 * @brief Obtain the derived key based on the passed KDFTLS12 context.. * * @param ctx [in, out] Pointer to the KDFTLS12 context. * @param out [out] Derived key buffer. * @param len [out] Derived key buffer size. * * @retval Success: CRYPT_SUCCESS * For other error codes, see crypt_errno.h. */ int32_t CRYPT_KDFTLS12_Derive(CRYPT_KDFTLS12_Ctx *ctx, uint8_t *out, uint32_t len); /** * @ingroup KDFTLS12 * @brief KDFTLS12 deinitialization API * * @param ctx [in, out] Pointer to the KDFTLS12 context. * * @retval #CRYPT_SUCCESS Deinitialization succeeded. * @retval #CRYPT_NULL_INPUT Pointer ctx is NULL */ int32_t CRYPT_KDFTLS12_Deinit(CRYPT_KDFTLS12_Ctx *ctx); /** * @ingroup KDFTLS12 * @brief free KDFTLS12 context. * * @param ctx [IN] KDFTLS12 handle */ void CRYPT_KDFTLS12_FreeCtx(CRYPT_KDFTLS12_Ctx *ctx); #ifdef __cplusplus } #endif // __cplusplus #endif // HITLS_CRYPTO_KDFTLS12 #endif // CRYPT_KDF_TLS12_H
2302_82127028/openHiTLS-examples_1508
crypto/kdf/include/crypt_kdf_tls12.h
C
unknown
2,628
/* * 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_KDFTLS12 #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 "eal_mac_local.h" #include "bsl_params.h" #include "crypt_params_key.h" #include "crypt_kdf_tls12.h" #define KDFTLS12_MAX_BLOCKSIZE 64 static const uint32_t KDFTLS12_ID_LIST[] = { CRYPT_MAC_HMAC_SHA256, CRYPT_MAC_HMAC_SHA384, CRYPT_MAC_HMAC_SHA512, CRYPT_MAC_HMAC_SM3, // for TLCP CRYPT_MAC_HMAC_MD5, // for TLS1.0 and TLS1.1 CRYPT_MAC_HMAC_SHA1, // for TLS1.0 and TLS1.1 }; struct CryptKdfTls12Ctx { CRYPT_MAC_AlgId macId; EAL_MacMethod macMeth; void *macCtx; uint8_t *key; uint32_t keyLen; uint8_t *label; uint32_t labelLen; uint8_t *seed; uint32_t seedLen; #ifdef HITLS_CRYPTO_PROVIDER void *libCtx; #endif }; bool CRYPT_KDFTLS12_IsValidAlgId(CRYPT_MAC_AlgId id) { return ParamIdIsValid(id, KDFTLS12_ID_LIST, sizeof(KDFTLS12_ID_LIST) / sizeof(KDFTLS12_ID_LIST[0])); } int32_t KDF_Hmac(const EAL_MacMethod *macMeth, void *macCtx, uint8_t *data, uint32_t *len) { macMeth->reinit(macCtx); int32_t ret = macMeth->update(macCtx, data, *len); if (ret != CRYPT_SUCCESS) { return ret; } return macMeth->final(macCtx, data, len); } // algorithm implementation see https://datatracker.ietf.org/doc/pdf/rfc5246.pdf, chapter 5, p_hash function int32_t KDF_PHASH(CRYPT_KDFTLS12_Ctx *ctx, uint8_t *out, uint32_t len) { int32_t ret; EAL_MacMethod *macMeth = &ctx->macMeth; uint32_t totalLen = 0; uint8_t nextIn[KDFTLS12_MAX_BLOCKSIZE]; uint32_t nextInLen = KDFTLS12_MAX_BLOCKSIZE; uint8_t outTmp[KDFTLS12_MAX_BLOCKSIZE]; uint32_t outTmpLen = KDFTLS12_MAX_BLOCKSIZE; while (len > totalLen) { if (totalLen == 0) { GOTO_ERR_IF(macMeth->init(ctx->macCtx, ctx->key, ctx->keyLen, NULL), ret); GOTO_ERR_IF(macMeth->update(ctx->macCtx, ctx->label, ctx->labelLen), ret); GOTO_ERR_IF(macMeth->update(ctx->macCtx, ctx->seed, ctx->seedLen), ret); GOTO_ERR_IF(macMeth->final(ctx->macCtx, nextIn, &nextInLen), ret); } else { GOTO_ERR_IF(KDF_Hmac(macMeth, ctx->macCtx, nextIn, &nextInLen), ret); } macMeth->reinit(ctx->macCtx); GOTO_ERR_IF(macMeth->update(ctx->macCtx, nextIn, nextInLen), ret); GOTO_ERR_IF(macMeth->update(ctx->macCtx, ctx->label, ctx->labelLen), ret); GOTO_ERR_IF(macMeth->update(ctx->macCtx, ctx->seed, ctx->seedLen), ret); GOTO_ERR_IF(macMeth->final(ctx->macCtx, outTmp, &outTmpLen), ret); uint32_t cpyLen = outTmpLen > (len - totalLen) ? (len - totalLen) : outTmpLen; (void)memcpy_s(out + totalLen, len - totalLen, outTmp, cpyLen); totalLen += cpyLen; } ret = CRYPT_SUCCESS; ERR: macMeth->deinit(ctx->macCtx); return ret; } CRYPT_KDFTLS12_Ctx* CRYPT_KDFTLS12_NewCtx(void) { CRYPT_KDFTLS12_Ctx *ctx = BSL_SAL_Calloc(1, sizeof(CRYPT_KDFTLS12_Ctx)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } return ctx; } CRYPT_KDFTLS12_Ctx *CRYPT_KDFTLS12_NewCtxEx(void *libCtx) { (void)libCtx; CRYPT_KDFTLS12_Ctx *ctx = CRYPT_KDFTLS12_NewCtx(); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } #ifdef HITLS_CRYPTO_PROVIDER ctx->libCtx = libCtx; #endif return ctx; } int32_t CRYPT_KDFTLS12_SetMacMethod(CRYPT_KDFTLS12_Ctx *ctx, const CRYPT_MAC_AlgId id) { if (!CRYPT_KDFTLS12_IsValidAlgId(id)) { BSL_ERR_PUSH_ERROR(CRYPT_KDFTLS12_PARAM_ERROR); return CRYPT_KDFTLS12_PARAM_ERROR; } // free the old macCtx if (ctx->macCtx != NULL) { if (ctx->macMeth.freeCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_KDFTLS12_ERR_MAC_METH); return CRYPT_KDFTLS12_ERR_MAC_METH; } ctx->macMeth.freeCtx(ctx->macCtx); ctx->macCtx = NULL; (void)memset_s(&ctx->macMeth, sizeof(EAL_MacMethod), 0, sizeof(EAL_MacMethod)); } EAL_MacMethod *macMeth = EAL_MacFindMethod(id, &ctx->macMeth); if (macMeth == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_METH_NULL_MEMBER); return CRYPT_EAL_ERR_METH_NULL_MEMBER; } if (macMeth->newCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_KDFTLS12_ERR_MAC_METH); return CRYPT_KDFTLS12_ERR_MAC_METH; } #ifdef HITLS_CRYPTO_PROVIDER ctx->macCtx = macMeth->newCtx(ctx->libCtx, id); #else ctx->macCtx = macMeth->newCtx(NULL, id); #endif if (ctx->macCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ctx->macId = id; return CRYPT_SUCCESS; } int32_t CRYPT_KDFTLS12_SetKey(CRYPT_KDFTLS12_Ctx *ctx, const uint8_t *key, uint32_t keyLen) { if (key == NULL && keyLen > 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } BSL_SAL_ClearFree((void *)ctx->key, ctx->keyLen); ctx->key = BSL_SAL_Dump(key, keyLen); if (ctx->key == NULL && keyLen > 0) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ctx->keyLen = keyLen; return CRYPT_SUCCESS; } int32_t CRYPT_KDFTLS12_SetLabel(CRYPT_KDFTLS12_Ctx *ctx, const uint8_t *label, uint32_t labelLen) { if (label == NULL && labelLen > 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } BSL_SAL_ClearFree((void *)ctx->label, ctx->labelLen); ctx->label = BSL_SAL_Dump(label, labelLen); if (ctx->label == NULL && labelLen > 0) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ctx->labelLen = labelLen; return CRYPT_SUCCESS; } int32_t CRYPT_KDFTLS12_SetSeed(CRYPT_KDFTLS12_Ctx *ctx, const uint8_t *seed, uint32_t seedLen) { if (seed == NULL && seedLen > 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } BSL_SAL_ClearFree((void *)ctx->seed, ctx->seedLen); ctx->seed = BSL_SAL_Dump(seed, seedLen); if (ctx->seed == NULL && seedLen > 0) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ctx->seedLen = seedLen; return CRYPT_SUCCESS; } #ifdef HITLS_CRYPTO_PROVIDER static int32_t CRYPT_KDFTLS12_SetMdAttr(CRYPT_KDFTLS12_Ctx *ctx, const char *mdAttr, uint32_t valLen) { if (mdAttr == NULL || valLen == 0) { BSL_ERR_PUSH_ERROR(CRYPT_KDFTLS12_PARAM_ERROR); return CRYPT_KDFTLS12_PARAM_ERROR; } if (ctx->macCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_KDFTLS12_ERR_MAC_ID_NOT_SET); return CRYPT_KDFTLS12_ERR_MAC_ID_NOT_SET; } // Set mdAttr for macCtx if (ctx->macMeth.setParam == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_KDFTLS12_ERR_MAC_METH); return CRYPT_KDFTLS12_ERR_MAC_METH; } BSL_Param param[] = { {.key = CRYPT_PARAM_MD_ATTR, .valueType = BSL_PARAM_TYPE_UTF8_STR, .value = (void *)(uintptr_t)mdAttr, .valueLen = valLen, .useLen = 0}, BSL_PARAM_END}; return ctx->macMeth.setParam(ctx->macCtx, param); } #endif int32_t CRYPT_KDFTLS12_SetParam(CRYPT_KDFTLS12_Ctx *ctx, const BSL_Param *param) { uint32_t val = 0; uint32_t len = 0; const BSL_Param *temp = NULL; int32_t ret = CRYPT_KDFTLS12_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_MAC_ID)) != NULL) { len = sizeof(val); GOTO_ERR_IF(BSL_PARAM_GetValue(temp, CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &val, &len), ret); GOTO_ERR_IF(CRYPT_KDFTLS12_SetMacMethod(ctx, val), ret); } if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_KDF_KEY)) != NULL) { GOTO_ERR_IF(CRYPT_KDFTLS12_SetKey(ctx, temp->value, temp->valueLen), ret); } if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_KDF_LABEL)) != NULL) { GOTO_ERR_IF(CRYPT_KDFTLS12_SetLabel(ctx, temp->value, temp->valueLen), ret); } if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_KDF_SEED)) != NULL) { GOTO_ERR_IF(CRYPT_KDFTLS12_SetSeed(ctx, temp->value, temp->valueLen), ret); } #ifdef HITLS_CRYPTO_PROVIDER if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_MD_ATTR)) != NULL) { GOTO_ERR_IF(CRYPT_KDFTLS12_SetMdAttr(ctx, temp->value, temp->valueLen), ret); } #endif ERR: return ret; } int32_t CRYPT_KDFTLS12_Derive(CRYPT_KDFTLS12_Ctx *ctx, uint8_t *out, uint32_t len) { if (ctx->macCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->macMeth.deinit == NULL || ctx->macMeth.freeCtx == NULL || ctx->macMeth.init == NULL || ctx->macMeth.reinit == NULL || ctx->macMeth.update == NULL || ctx->macMeth.final == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_KDFTLS12_ERR_MAC_METH); return CRYPT_KDFTLS12_ERR_MAC_METH; } if (ctx->key == NULL && ctx->keyLen > 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->label == NULL && ctx->labelLen > 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->seed == NULL && ctx->seedLen > 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if ((out == NULL) || (len == 0)) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } return KDF_PHASH(ctx, out, len); } int32_t CRYPT_KDFTLS12_Deinit(CRYPT_KDFTLS12_Ctx *ctx) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->macMeth.freeCtx != NULL) { ctx->macMeth.freeCtx(ctx->macCtx); ctx->macCtx = NULL; } BSL_SAL_ClearFree((void *)ctx->key, ctx->keyLen); BSL_SAL_ClearFree((void *)ctx->label, ctx->labelLen); BSL_SAL_ClearFree((void *)ctx->seed, ctx->seedLen); (void)memset_s(ctx, sizeof(CRYPT_KDFTLS12_Ctx), 0, sizeof(CRYPT_KDFTLS12_Ctx)); return CRYPT_SUCCESS; } void CRYPT_KDFTLS12_FreeCtx(CRYPT_KDFTLS12_Ctx *ctx) { if (ctx == NULL) { return; } if (ctx->macMeth.freeCtx != NULL) { ctx->macMeth.freeCtx(ctx->macCtx); } BSL_SAL_ClearFree((void *)ctx->key, ctx->keyLen); BSL_SAL_ClearFree((void *)ctx->label, ctx->labelLen); BSL_SAL_ClearFree((void *)ctx->seed, ctx->seedLen); BSL_SAL_Free(ctx); } #endif // HITLS_CRYPTO_KDFTLS12
2302_82127028/openHiTLS-examples_1508
crypto/kdf/src/kdf_tls12.c
C
unknown
11,222
/* * 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_MD5_H #define CRYPT_MD5_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_MD5 #include <stdlib.h> #include <stdint.h> #include "crypt_types.h" #include "bsl_params.h" #ifdef __cplusplus extern "C" { #endif #define CRYPT_MD5_DIGESTSIZE 16 #define CRYPT_MD5_BLOCKSIZE 64 typedef struct CryptMdCtx CRYPT_MD5_Ctx; #define CRYPT_MD5_Squeeze NULL /** * @ingroup MD5 * @brief Generate md context. * * @retval Success: md ctx. * Fails: NULL. */ CRYPT_MD5_Ctx *CRYPT_MD5_NewCtx(void); /** * @ingroup MD5 * @brief Generate md context. * * @param libCtx [IN] library context * @param algId [IN] algorithm id * * @retval Success: md ctx. * Fails: NULL. */ CRYPT_MD5_Ctx *CRYPT_MD5_NewCtxEx(void *libCtx, int32_t algId); /** * @ingroup MD5 * @brief free md context. * * @param ctx [IN] md handle */ void CRYPT_MD5_FreeCtx(CRYPT_MD5_Ctx *ctx); /** * @ingroup MD5 * @brief This API is used to initialize the MD5 context. * * @param ctx [in,out] Pointer to the MD5 context. * @param param [in] Pointer to the parameter. * * @retval #CRYPT_SUCCESS Initialization succeeded. * @retval #CRYPT_NULL_INPUT Pointer ctx is NULL */ int32_t CRYPT_MD5_Init(CRYPT_MD5_Ctx *ctx, BSL_Param *param); /** * @ingroup MD5 * @brief MD5 deinitialization API * @param ctx [in,out] Pointer to the MD5 context. * * @retval #CRYPT_SUCCESS Deinitialization succeeded. * @retval #CRYPT_NULL_INPUT Pointer ctx is NULL */ int32_t CRYPT_MD5_Deinit(CRYPT_MD5_Ctx *ctx); /** * @ingroup MD5 * @brief Encode the input text and update the message digest. * * @param ctx [in,out] Pointer to the MD5 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_MD5_INPUT_OVERFLOW The accumulated length of the input data exceeds the maximum (2^64 bits). */ int32_t CRYPT_MD5_Update(CRYPT_MD5_Ctx *ctx, const uint8_t *in, uint32_t len); /** * @ingroup MD5 * @brief Obtain the message digest based on the passed MD5 context. * * @param ctx [in,out] Pointer to the MD5 context. * @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_MD5_OUT_BUFF_LEN_NOT_ENOUGH The output buffer length is insufficient. */ int32_t CRYPT_MD5_Final(CRYPT_MD5_Ctx *ctx, uint8_t *out, uint32_t *outLen); /** * @ingroup MD5 * @brief MD5 copy CTX function * @param dst [out] Pointer to the new MD5 context. * @param src [in] Pointer to the original MD5 context. * * @retval #CRYPT_SUCCESS Copy succeeded. * @retval #CRYPT_NULL_INPUT Pointer src is NULL */ int32_t CRYPT_MD5_CopyCtx(CRYPT_MD5_Ctx *dst, const CRYPT_MD5_Ctx *src); /** * @ingroup MD5 * @brief MD5 dup CTX function * @param src [in] Pointer to the original MD5 context. * * @retval Success: md ctx. * Fails: NULL. */ CRYPT_MD5_Ctx *CRYPT_MD5_DupCtx(const CRYPT_MD5_Ctx *src); #ifdef HITLS_CRYPTO_PROVIDER /** * @ingroup MD5 * @brief MD5 get param function * @param ctx [in] Pointer to the MD5 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_MD5_GetParam(CRYPT_MD5_Ctx *ctx, BSL_Param *param); #else #define CRYPT_MD5_GetParam NULL #endif #ifdef __cplusplus } #endif #endif // HITLS_CRYPTO_MD5 #endif // CRYPT_MD5_H
2302_82127028/openHiTLS-examples_1508
crypto/md5/include/crypt_md5.h
C
unknown
4,353
/* * 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_MD5 .file "md5_x86_64.S" .set TEMP1, %r14d .set TEMP2, %r15d .set T, %r13d .set W, %r12d .set T_ORIGIN_ADDR, %rcx .set HASH, %rdi .set INPUT, %rsi .set NUM, %rdx .set S11, 7 .set S12, 12 .set S13, 17 .set S14, 22 .set S21, 5 .set S22, 9 .set S23, 14 .set S24, 20 .set S31, 4 .set S32, 11 .set S33, 16 .set S34, 23 .set S41, 6 .set S42, 10 .set S43, 15 .set S44, 21 .set A, %r8d .set B, %r9d .set C, %r10d .set D, %r11d /* MD5 Used constant value. For details about the data source, see the RFC1321 document. */ .text .align 64 .type g_tMd5, %object g_tMd5: .long 0xD76AA478, 0xE8C7B756, 0x242070DB, 0xC1BDCEEE .long 0xF57C0FAF, 0x4787C62A, 0xA8304613, 0xFD469501 .long 0x698098D8, 0x8B44F7AF, 0xFFFF5BB1, 0x895CD7BE .long 0x6B901122, 0xFD987193, 0xA679438E, 0x49B40821 .long 0xF61E2562, 0xC040B340, 0x265E5A51, 0xE9B6C7AA .long 0xD62F105D, 0x02441453, 0xD8A1E681, 0xE7D3FBC8 .long 0x21E1CDE6, 0xC33707D6, 0xF4D50D87, 0x455A14ED .long 0xA9E3E905, 0xFCEFA3F8, 0x676F02D9, 0x8D2A4C8A .long 0xFFFA3942, 0x8771F681, 0x6D9D6122, 0xFDE5380C .long 0xA4BEEA44, 0x4BDECFA9, 0xF6BB4B60, 0xBEBFBC70 .long 0x289B7EC6, 0xEAA127FA, 0xD4EF3085, 0x04881D05 .long 0xD9D4D039, 0xE6DB99E5, 0x1FA27CF8, 0xC4AC5665 .long 0xF4292244, 0x432AFF97, 0xAB9423A7, 0xFC93A039 .long 0x655B59C3, 0x8F0CCC92, 0xFFEFF47D, 0x85845DD1 .long 0x6FA87E4F, 0xFE2CE6E0, 0xA3014314, 0x4E0811A1 .long 0xF7537E82, 0xBD3AF235, 0x2AD7D2BB, 0xEB86D391 .size g_tMd5, .-g_tMd5 /* * Macro description: The FF function processes the update of a hash value in a round of 0-15 compression. * Input register: * wAddr: sequence corresponding to W (wi) * tAddr: order (ti) corresponding to t * a - d: intermediate variable of the hash value * Change register: r8d-r15d * Output register: * a: indicates the value after a round of cyclic update. * Function/Macro Call: None * Implementation description: * Parameter: S11->28, S12->48, S13->17, S14->22 * T2 = BSIG0(a) + MAJ(a,b,c) * a = b + ROTL32(F(a,b,c)+x+ac),s) * F(X,Y,Z) = XY v not(X) Z * G(X,Y,Z) = XZ v Y not(Z) * H(X,Y,Z) = X xor Y xor Z * I(X,Y,Z) = Y xor (X v not(Z)) */ .macro FF_ONE_ROUND a, b, c, d, wAddr, s, tAddr, w, t, temp1, temp2 mov \tAddr(T_ORIGIN_ADDR), \t mov \wAddr(INPUT), \w /* F(b, c, d) ((b & c) | ((~b) & d)) */ mov \b, \temp1 andn \d, \b, \temp2 // (~b) & d and \c, \temp1 // b & c or \temp1, \temp2 // (b & c) | ((~b) & d) /* (a) += F((b), (c), (d)) + (\w) + (\t) */ add \w, \a add \t, \a add \temp2, \a /* (a) = ROTL32((a), (s)) */ rol $\s, \a /* (a) += (b) */ add \b, \a .endm /* * Macro description: The GG function updates a round of hash values in rounds 16-31 compression. * Input register: * wAddr: sequence corresponding to W (wi) * tAddr: order (ti) corresponding to t * a - d: intermediate variable of the hash value * Change register: r8d-r15d * Output register: * a: indicates the value after a round of cyclic update. * Function/Macro Call: None * Implementation description: * 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 * G(x, y, z) (((x) & (z)) | ((y) & (~(z)))) * (a) += G((b), (c), (d)) + (x) + (ac); * (a) = ROTL32((a), (s)); * (a) += (b); */ .macro GG_ONE_ROUND a, b, c, d, wAddr, s, tAddr, w, t, temp1, temp2 mov \tAddr(T_ORIGIN_ADDR), \t mov \wAddr(INPUT), \w /* G(x, y, z) ((b & d) | (c & (~d))) */ mov \b, \temp1 and \d, \temp1 andn \c, \d, \temp2 or \temp1, \temp2 /* (a) += G((b), (c), (d)) + (\w) + (t) */ add \t, \a add \w, \a add \temp2, \a /* (a) = ROTL32((a), (s)) */ rol $\s, \a /* (a) += (b) */ add \b, \a .endm /* * Macro description: The HH function processes the update of a hash value in a round of 32-47 compression. * Input register: * wAddr: sequence corresponding to W (wi) * tAddr: order (ti) corresponding to t * a - d: intermediate variable of the hash value * Change register: r8d-r15d * Output register: * a: indicates the value after a round of cyclic update. * Function/Macro Call: None * Implementation description: * * H(x, y, z) ((x) ^ (y) ^ (z)) * (a) += H((b), (c), (d)) + (x) + (ac); * (a) = ROTL32((a), (s)); * (a) += (b); * b and c ->next c and d * swap \temp2 temp4 for next round */ .macro HH_ONE_ROUND a, b, c, d, wAddr, s, tAddr, w, t, temp1, temp2 mov \tAddr(T_ORIGIN_ADDR), \t mov \wAddr(INPUT), \w /* H(x, y, z) (b ^ c ^ d) */ mov \b, \temp1 xor \d, \temp1 xor \c, \temp1 /* (a) += H((b), (c), (d)) + (\w) + (\t) */ add \t, \a add \w, \a add \temp1, \a /* (a) = ROTL32((a), (s)) */ rol $\s, \a /* (a) += (b) */ add \b, \a .endm /* * Macro description: Processes the update of a hash value in a round of 48-63 compression. * Input register: * wAddr: Sequence corresponding to W (wi) * tAddr: Order (ti) corresponding to t * a - d: Intermediate variable of the hash value * Change register: r8d-r15d. * Output register: * a: indicates the value after a round of cyclic update. * Function/Macro Call: None * Implementation description: * 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 * I(x, y, z) ((y) ^ ((x) | (~(z)))) * (a) += I((b), (c), (d)) + (x) + (ac); \ * (a) = ROTL32((a), (s)); \ * (a) += (b); * swap \temp2 temp4 for next round */ .macro II_ONE_ROUND a, b, c, d, wAddr, s, tAddr, w, t, temp1, temp2 mov \tAddr(T_ORIGIN_ADDR), \t mov \wAddr(INPUT), \w /* I(b, c, d) (c ^ (b | (~d))) */ mov \d, \temp1 not \temp1 or \b, \temp1 xor \c, \temp1 /* (a) += I((b), (c), (d)) + (\w) + (\t); */ add \t, \a add \w, \a add \temp1, \a /* (a) = ROTL32((a), (s)) */ rol $\s, \a /* (a) += (b) */ add \b, \a .endm /* * Function description: Performs 64 rounds of compression calculation * based on the input plaintext data and updates the hash value. * Function prototype: void MD5_Compress(uint32_t hash[32], const uint8_t *in, uint32_t num); * Input register: * rdi: Indicates the storage address of the hash value. * rsi: Pointer to the input data address (Wi) * rdx: Indicates the number of 64 rounds of cycles. * (You need to do several blocks, that is, you need to do several loops.) * Change register: rsi, r8d-r15d, rcx. * Output register: None * Function/Macro Call: FF_ONE_ROUND, GG_ONE_ROUND, HH_ONE_ROUND, II_ONE_ROUND */ .text .globl MD5_Compress .type MD5_Compress,%function .align 4 MD5_Compress: .cfi_startproc /* Push stack and pop stack protection */ pushq %r14 pushq %rbx pushq %rbp pushq %r12 pushq %r13 pushq %r15 /* r8d-r10d: a-d */ mov 0(%rdi), A mov 4(%rdi), B mov 8(%rdi), C mov 12(%rdi), D .Lmd5_loop: leaq g_tMd5(%rip), T_ORIGIN_ADDR /* LEND_MD5_FF_ROUND_ROUND_0_15 */ /* FF_ONE_ROUND a, b, c, d, wAddr, s, tAddr, w, t, temp1, temp2 */ FF_ONE_ROUND A, B, C, D, 0, S11, 0, W, T, TEMP1, TEMP2 FF_ONE_ROUND D, A, B, C, 4, S12, 4, W, T, TEMP1, TEMP2 FF_ONE_ROUND C, D, A, B, 8, S13, 8, W, T, TEMP1, TEMP2 FF_ONE_ROUND B, C, D, A, 12, S14, 12, W, T, TEMP1, TEMP2 FF_ONE_ROUND A, B, C, D, 16, S11, 16, W, T, TEMP1, TEMP2 FF_ONE_ROUND D, A, B, C, 20, S12, 20, W, T, TEMP1, TEMP2 FF_ONE_ROUND C, D, A, B, 24, S13, 24, W, T, TEMP1, TEMP2 FF_ONE_ROUND B, C, D, A, 28, S14, 28, W, T, TEMP1, TEMP2 FF_ONE_ROUND A, B, C, D, 32, S11, 32, W, T, TEMP1, TEMP2 FF_ONE_ROUND D, A, B, C, 36, S12, 36, W, T, TEMP1, TEMP2 FF_ONE_ROUND C, D, A, B, 40, S13, 40, W, T, TEMP1, TEMP2 FF_ONE_ROUND B, C, D, A, 44, S14, 44, W, T, TEMP1, TEMP2 FF_ONE_ROUND A, B, C, D, 48, S11, 48, W, T, TEMP1, TEMP2 FF_ONE_ROUND D, A, B, C, 52, S12, 52, W, T, TEMP1, TEMP2 FF_ONE_ROUND C, D, A, B, 56, S13, 56, W, T, TEMP1, TEMP2 FF_ONE_ROUND B, C, D, A, 60, S14, 60, W, T, TEMP1, TEMP2 /* LEND_MD5_GG_ROUND_ROUND_16_31 */ /* GG_ONE_ROUND a, b, c, d, wAddr, s, tAddr, w, t, temp1, temp2 */ GG_ONE_ROUND A, B, C, D, 4, S21, 64, W, T, TEMP1, TEMP2 GG_ONE_ROUND D, A, B, C, 24, S22, 68, W, T, TEMP1, TEMP2 GG_ONE_ROUND C, D, A, B, 44, S23, 72, W, T, TEMP1, TEMP2 GG_ONE_ROUND B, C, D, A, 0, S24, 76, W, T, TEMP1, TEMP2 GG_ONE_ROUND A, B, C, D, 20, S21, 80, W, T, TEMP1, TEMP2 GG_ONE_ROUND D, A, B, C, 40, S22, 84, W, T, TEMP1, TEMP2 GG_ONE_ROUND C, D, A, B, 60, S23, 88, W, T, TEMP1, TEMP2 GG_ONE_ROUND B, C, D, A, 16, S24, 92, W, T, TEMP1, TEMP2 GG_ONE_ROUND A, B, C, D, 36, S21, 96, W, T, TEMP1, TEMP2 GG_ONE_ROUND D, A, B, C, 56, S22, 100, W, T, TEMP1, TEMP2 GG_ONE_ROUND C, D, A, B, 12, S23, 104, W, T, TEMP1, TEMP2 GG_ONE_ROUND B, C, D, A, 32, S24, 108, W, T, TEMP1, TEMP2 GG_ONE_ROUND A, B, C, D, 52, S21, 112, W, T, TEMP1, TEMP2 GG_ONE_ROUND D, A, B, C, 8, S22, 116, W, T, TEMP1, TEMP2 GG_ONE_ROUND C, D, A, B, 28, S23, 120, W, T, TEMP1, TEMP2 GG_ONE_ROUND B, C, D, A, 48, S24, 124, W, T, TEMP1, TEMP2 /* LEND_MD5_HH_ROUND_ROUND_32_47 */ /* HH_ONE_ROUND a,b,c,d,wAddr,s,tAddr, w, t, temp1, temp2 */ HH_ONE_ROUND A, B, C, D, 20, S31, 128, W, T, TEMP1, TEMP2 HH_ONE_ROUND D, A, B, C, 32, S32, 132, W, T, TEMP1, TEMP2 HH_ONE_ROUND C, D, A, B, 44, S33, 136, W, T, TEMP1, TEMP2 HH_ONE_ROUND B, C, D, A, 56, S34, 140, W, T, TEMP1, TEMP2 HH_ONE_ROUND A, B, C, D, 4, S31, 144, W, T, TEMP1, TEMP2 HH_ONE_ROUND D, A, B, C, 16, S32, 148, W, T, TEMP1, TEMP2 HH_ONE_ROUND C, D, A, B, 28, S33, 152, W, T, TEMP1, TEMP2 HH_ONE_ROUND B, C, D, A, 40, S34, 156, W, T, TEMP1, TEMP2 HH_ONE_ROUND A, B, C, D, 52, S31, 160, W, T, TEMP1, TEMP2 HH_ONE_ROUND D, A, B, C, 0, S32, 164, W, T, TEMP1, TEMP2 HH_ONE_ROUND C, D, A, B, 12, S33, 168, W, T, TEMP1, TEMP2 HH_ONE_ROUND B, C, D, A, 24, S34, 172, W, T, TEMP1, TEMP2 HH_ONE_ROUND A, B, C, D, 36, S31, 176, W, T, TEMP1, TEMP2 HH_ONE_ROUND D, A, B, C, 48, S32, 180, W, T, TEMP1, TEMP2 HH_ONE_ROUND C, D, A, B, 60, S33, 184, W, T, TEMP1, TEMP2 HH_ONE_ROUND B, C, D, A, 8, S34, 188, W, T, TEMP1, TEMP2 /* LEND_MD5_II_ROUND_ROUND_48_63 */ /* II_ONE_ROUND a, b,c,d,wAddr,s,tAddr, w, t, temp1, temp2 */ II_ONE_ROUND A, B, C, D, 0, S41, 192, W, T, TEMP1, TEMP2 II_ONE_ROUND D, A, B, C, 28, S42, 196, W, T, TEMP1, TEMP2 II_ONE_ROUND C, D, A, B, 56, S43, 200, W, T, TEMP1, TEMP2 II_ONE_ROUND B, C, D, A, 20, S44, 204, W, T, TEMP1, TEMP2 II_ONE_ROUND A, B, C, D, 48, S41, 208, W, T, TEMP1, TEMP2 II_ONE_ROUND D, A, B, C, 12, S42, 212, W, T, TEMP1, TEMP2 II_ONE_ROUND C, D, A, B, 40, S43, 216, W, T, TEMP1, TEMP2 II_ONE_ROUND B, C, D, A, 4, S44, 220, W, T, TEMP1, TEMP2 II_ONE_ROUND A, B, C, D, 32, S41, 224, W, T, TEMP1, TEMP2 II_ONE_ROUND D, A, B, C, 60, S42, 228, W, T, TEMP1, TEMP2 II_ONE_ROUND C, D, A, B, 24, S43, 232, W, T, TEMP1, TEMP2 II_ONE_ROUND B, C, D, A, 52, S44, 236, W, T, TEMP1, TEMP2 II_ONE_ROUND A, B, C, D, 16, S41, 240, W, T, TEMP1, TEMP2 II_ONE_ROUND D, A, B, C, 44, S42, 244, W, T, TEMP1, TEMP2 II_ONE_ROUND C, D, A, B, 8, S43, 248, W, T, TEMP1, TEMP2 II_ONE_ROUND B, C, D, A, 36, S44, 252, W, T, TEMP1, TEMP2 /* Update the storage hash value. */ add 0(%rdi), A add 4(%rdi), B add 8(%rdi), C add 12(%rdi), D mov A, 0(%rdi) mov B, 4(%rdi) mov C, 8(%rdi) mov D, 12(%rdi) lea 64(INPUT), INPUT sub $1, NUM ja .Lmd5_loop .LEND_MD5_FINFISH_INITIAL: /* Registers and pointers are reset. */ popq %r15 popq %r13 popq %r12 popq %rbp popq %rbx popq %r14 ret .cfi_endproc .size MD5_Compress, .-MD5_Compress #endif
2302_82127028/openHiTLS-examples_1508
crypto/md5/src/asm/md5_x86_64.S
Unix Assembly
unknown
13,655
/* * 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_MD5 #include "securec.h" #include "bsl_err_internal.h" #include "crypt_errno.h" #include "crypt_utils.h" #include "md5_core.h" #include "crypt_md5.h" #include "bsl_sal.h" #include "crypt_types.h" #ifdef __cplusplus extern "C" { #endif /* __cpluscplus */ #define CRYPT_MD5_DIGESTSIZE 16 #define CRYPT_MD5_BLOCKSIZE 64 /* md5 ctx */ struct CryptMdCtx { uint32_t h[CRYPT_MD5_DIGESTSIZE / sizeof(uint32_t)]; /* store the intermediate data of the hash value */ uint8_t block[CRYPT_MD5_BLOCKSIZE]; /* store the remaining data of less than one block */ uint32_t hNum, lNum; /* input data counter, maximum value 2 ^ 64 bits */ /* Number of remaining bytes in 'block' arrary that are stored less than one block */ uint32_t num; }; CRYPT_MD5_Ctx *CRYPT_MD5_NewCtx(void) { return BSL_SAL_Calloc(1, sizeof(CRYPT_MD5_Ctx)); } CRYPT_MD5_Ctx *CRYPT_MD5_NewCtxEx(void *libCtx, int32_t algId) { (void)libCtx; (void)algId; return BSL_SAL_Calloc(1, sizeof(CRYPT_MD5_Ctx)); } void CRYPT_MD5_FreeCtx(CRYPT_MD5_Ctx *ctx) { BSL_SAL_ClearFree(ctx, sizeof(CRYPT_MD5_Ctx)); } int32_t CRYPT_MD5_Init(CRYPT_MD5_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_MD5_Ctx), 0, sizeof(CRYPT_MD5_Ctx)); /* Set the initial values of A, B, C, and D according to step 3 in section 3.3 of RFC1321. */ ctx->h[0] = 0x67452301; ctx->h[1] = 0xefcdab89; ctx->h[2] = 0x98badcfe; ctx->h[3] = 0x10325476; return CRYPT_SUCCESS; } int32_t CRYPT_MD5_Deinit(CRYPT_MD5_Ctx *ctx) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } (void)memset_s(ctx, sizeof(CRYPT_MD5_Ctx), 0, sizeof(CRYPT_MD5_Ctx)); return CRYPT_SUCCESS; } static uint32_t IsInputOverflow(CRYPT_MD5_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_MD5_INPUT_OVERFLOW); return CRYPT_MD5_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_MD5_INPUT_OVERFLOW); return CRYPT_MD5_INPUT_OVERFLOW; } ctx->hNum = cnt1; ctx->lNum = cnt0; return CRYPT_SUCCESS; } static int32_t IsUpdateParamValid(CRYPT_MD5_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_MD5_INPUT_OVERFLOW); return CRYPT_MD5_INPUT_OVERFLOW; } return CRYPT_SUCCESS; } int32_t CRYPT_MD5_Update(CRYPT_MD5_Ctx *ctx, const uint8_t *in, uint32_t len) { int32_t ret = IsUpdateParamValid(ctx, in, len); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (len == 0) { return CRYPT_SUCCESS; } const uint8_t *data = in; uint32_t dataLen = len; uint32_t left = CRYPT_MD5_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); MD5_Compress(ctx->h, ctx->block, 1); dataLen -= left; data += left; ctx->num = 0; } uint32_t blockCnt = dataLen / CRYPT_MD5_BLOCKSIZE; if (blockCnt > 0) { MD5_Compress(ctx->h, data, blockCnt); blockCnt *= CRYPT_MD5_BLOCKSIZE; data += blockCnt; dataLen -= blockCnt; } if (dataLen != 0) { // Copy the remaining data to the cache array. (void)memcpy_s(ctx->block, CRYPT_MD5_BLOCKSIZE, data, dataLen); ctx->num = dataLen; } return CRYPT_SUCCESS; } static int32_t IsFinalParamValid(const CRYPT_MD5_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_MD5_DIGESTSIZE) { BSL_ERR_PUSH_ERROR(CRYPT_MD5_OUT_BUFF_LEN_NOT_ENOUGH); return CRYPT_MD5_OUT_BUFF_LEN_NOT_ENOUGH; } return CRYPT_SUCCESS; } int32_t CRYPT_MD5_Final(CRYPT_MD5_Ctx *ctx, uint8_t *out, uint32_t *outLen) { int32_t ret = IsFinalParamValid(ctx, out, outLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ctx->block[ctx->num++] = 0x80; /* 0x80 indicates that '1' is appended to the end of a message. */ uint8_t *block = ctx->block; uint32_t num = ctx->num; uint32_t left = CRYPT_MD5_BLOCKSIZE - num; if (left < 8) { /* Less than 8 bytes, insufficient for storing data of the accumulated data length(lNum&hNum). */ (void)memset_s(block + num, left, 0, left); MD5_Compress(ctx->h, ctx->block, 1); num = 0; left = CRYPT_MD5_BLOCKSIZE; } (void)memset_s(block + num, left - 8, 0, left - 8); /* 8 byte is used to store data of accumulated data length. */ block += CRYPT_MD5_BLOCKSIZE - 8; /* 8 byte is used to store data of the accumulated data length(lNum&hNum). */ PUT_UINT32_LE(ctx->lNum, block, 0); block += sizeof(uint32_t); PUT_UINT32_LE(ctx->hNum, block, 0); MD5_Compress(ctx->h, ctx->block, 1); ctx->num = 0; PUT_UINT32_LE(ctx->h[0], out, 0); PUT_UINT32_LE(ctx->h[1], out, 4); PUT_UINT32_LE(ctx->h[2], out, 8); PUT_UINT32_LE(ctx->h[3], out, 12); *outLen = CRYPT_MD5_DIGESTSIZE; return CRYPT_SUCCESS; } int32_t CRYPT_MD5_CopyCtx(CRYPT_MD5_Ctx *dst, const CRYPT_MD5_Ctx *src) { if (dst == NULL || src == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } (void)memcpy_s(dst, sizeof(CRYPT_MD5_Ctx), src, sizeof(CRYPT_MD5_Ctx)); return CRYPT_SUCCESS; } CRYPT_MD5_Ctx *CRYPT_MD5_DupCtx(const CRYPT_MD5_Ctx *src) { if (src == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return NULL; } CRYPT_MD5_Ctx *newCtx = CRYPT_MD5_NewCtx(); if (newCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } (void)memcpy_s(newCtx, sizeof(CRYPT_MD5_Ctx), src, sizeof(CRYPT_MD5_Ctx)); return newCtx; } #ifdef HITLS_CRYPTO_PROVIDER int32_t CRYPT_MD5_GetParam(CRYPT_MD5_Ctx *ctx, BSL_Param *param) { (void)ctx; return CRYPT_MdCommonGetParam(CRYPT_MD5_DIGESTSIZE, CRYPT_MD5_BLOCKSIZE, param); } #endif #ifdef __cplusplus } #endif /* __cpluscplus */ #endif // HITLS_CRYPTO_MD5
2302_82127028/openHiTLS-examples_1508
crypto/md5/src/md5.c
C
unknown
7,678
/* * 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 MD5_CORE_H #define MD5_CORE_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_MD5 #include <stdint.h> #ifdef __cplusplus extern "C" { #endif void MD5_Compress(uint32_t state[4], const uint8_t *data, uint32_t blockCnt); #ifdef __cplusplus } #endif #endif // HITLS_CRYPTO_MD5 #endif // MD5_CORE_H
2302_82127028/openHiTLS-examples_1508
crypto/md5/src/md5_core.h
C
unknown
851
/* * 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_MD5 #include "securec.h" #include "crypt_errno.h" #include "crypt_utils.h" #include "bsl_err_internal.h" #include "md5_core.h" #include "crypt_md5.h" #ifdef __cplusplus extern "C" { #endif /* __cpluscplus */ /* F, G, H and I are basic MD5 functions. */ #define F(x, y, z) (((x) & (y)) | ((~(x)) & (z))) #define G(x, y, z) (((x) & (z)) | ((y) & (~(z)))) #define H(x, y, z) ((x) ^ (y) ^ (z)) #define I(x, y, z) ((y) ^ ((x) | (~(z)))) #define FF(a, b, c, d, x, s, ac) \ do { \ (a) += F((b), (c), (d)) + (x) + (ac); \ (a) = ROTL32((a), (s)); \ (a) += (b); \ } while (0) #define GG(a, b, c, d, x, s, ac) \ do { \ (a) += G((b), (c), (d)) + (x) + (ac); \ (a) = ROTL32((a), (s)); \ (a) += (b); \ } while (0) #define HH(a, b, c, d, x, s, ac) \ do { \ (a) += H((b), (c), (d)) + (x) + (ac); \ (a) = ROTL32((a), (s)); \ (a) += (b); \ } while (0) #define II(a, b, c, d, x, s, ac) \ do { \ (a) += I((b), (c), (d)) + (x) + (ac); \ (a) = ROTL32((a), (s)); \ (a) += (b); \ } while (0) /* Constants for MD5_Compress routine. */ #define S11 7 #define S12 12 #define S13 17 #define S14 22 #define S21 5 #define S22 9 #define S23 14 #define S24 20 #define S31 4 #define S32 11 #define S33 16 #define S34 23 #define S41 6 #define S42 10 #define S43 15 #define S44 21 static const uint32_t T[64] = { 0xD76AA478, 0xE8C7B756, 0x242070DB, 0xC1BDCEEE, 0xF57C0FAF, 0x4787C62A, 0xA8304613, 0xFD469501, 0x698098D8, 0x8B44F7AF, 0xFFFF5BB1, 0x895CD7BE, 0x6B901122, 0xFD987193, 0xA679438E, 0x49B40821, 0xF61E2562, 0xC040B340, 0x265E5A51, 0xE9B6C7AA, 0xD62F105D, 0x02441453, 0xD8A1E681, 0xE7D3FBC8, 0x21E1CDE6, 0xC33707D6, 0xF4D50D87, 0x455A14ED, 0xA9E3E905, 0xFCEFA3F8, 0x676F02D9, 0x8D2A4C8A, 0xFFFA3942, 0x8771F681, 0x6D9D6122, 0xFDE5380C, 0xA4BEEA44, 0x4BDECFA9, 0xF6BB4B60, 0xBEBFBC70, 0x289B7EC6, 0xEAA127FA, 0xD4EF3085, 0x04881D05, 0xD9D4D039, 0xE6DB99E5, 0x1FA27CF8, 0xC4AC5665, 0xF4292244, 0x432AFF97, 0xAB9423A7, 0xFC93A039, 0x655B59C3, 0x8F0CCC92, 0xFFEFF47D, 0x85845DD1, 0x6FA87E4F, 0xFE2CE6E0, 0xA3014314, 0x4E0811A1, 0xF7537E82, 0xBD3AF235, 0x2AD7D2BB, 0xEB86D391, }; /* see RFC1321 chapter 3.4 Step 4 https://www.rfc-editor.org/rfc/rfc1321 */ void MD5_Compress(uint32_t state[4], const uint8_t *data, uint32_t blockCnt) { uint32_t w[16] = {0}; const uint8_t *input = data; uint32_t count = blockCnt; while (count > 0) { /* convert data to 32 bits for calculation */ w[0] = GET_UINT32_LE(input, 0); w[1] = GET_UINT32_LE(input, 4); w[2] = GET_UINT32_LE(input, 8); w[3] = GET_UINT32_LE(input, 12); w[4] = GET_UINT32_LE(input, 16); w[5] = GET_UINT32_LE(input, 20); w[6] = GET_UINT32_LE(input, 24); w[7] = GET_UINT32_LE(input, 28); w[8] = GET_UINT32_LE(input, 32); w[9] = GET_UINT32_LE(input, 36); w[10] = GET_UINT32_LE(input, 40); w[11] = GET_UINT32_LE(input, 44); w[12] = GET_UINT32_LE(input, 48); w[13] = GET_UINT32_LE(input, 52); w[14] = GET_UINT32_LE(input, 56); w[15] = GET_UINT32_LE(input, 60); uint32_t a = state[0]; uint32_t b = state[1]; uint32_t c = state[2]; uint32_t d = state[3]; FF(a, b, c, d, w[0], S11, T[0]); FF(d, a, b, c, w[1], S12, T[1]); FF(c, d, a, b, w[2], S13, T[2]); FF(b, c, d, a, w[3], S14, T[3]); FF(a, b, c, d, w[4], S11, T[4]); FF(d, a, b, c, w[5], S12, T[5]); FF(c, d, a, b, w[6], S13, T[6]); FF(b, c, d, a, w[7], S14, T[7]); FF(a, b, c, d, w[8], S11, T[8]); FF(d, a, b, c, w[9], S12, T[9]); FF(c, d, a, b, w[10], S13, T[10]); FF(b, c, d, a, w[11], S14, T[11]); FF(a, b, c, d, w[12], S11, T[12]); FF(d, a, b, c, w[13], S12, T[13]); FF(c, d, a, b, w[14], S13, T[14]); FF(b, c, d, a, w[15], S14, T[15]); GG(a, b, c, d, w[1], S21, T[16]); GG(d, a, b, c, w[6], S22, T[17]); GG(c, d, a, b, w[11], S23, T[18]); GG(b, c, d, a, w[0], S24, T[19]); GG(a, b, c, d, w[5], S21, T[20]); GG(d, a, b, c, w[10], S22, T[21]); GG(c, d, a, b, w[15], S23, T[22]); GG(b, c, d, a, w[4], S24, T[23]); GG(a, b, c, d, w[9], S21, T[24]); GG(d, a, b, c, w[14], S22, T[25]); GG(c, d, a, b, w[3], S23, T[26]); GG(b, c, d, a, w[8], S24, T[27]); GG(a, b, c, d, w[13], S21, T[28]); GG(d, a, b, c, w[2], S22, T[29]); GG(c, d, a, b, w[7], S23, T[30]); GG(b, c, d, a, w[12], S24, T[31]); HH(a, b, c, d, w[5], S31, T[32]); HH(d, a, b, c, w[8], S32, T[33]); HH(c, d, a, b, w[11], S33, T[34]); HH(b, c, d, a, w[14], S34, T[35]); HH(a, b, c, d, w[1], S31, T[36]); HH(d, a, b, c, w[4], S32, T[37]); HH(c, d, a, b, w[7], S33, T[38]); HH(b, c, d, a, w[10], S34, T[39]); HH(a, b, c, d, w[13], S31, T[40]); HH(d, a, b, c, w[0], S32, T[41]); HH(c, d, a, b, w[3], S33, T[42]); HH(b, c, d, a, w[6], S34, T[43]); HH(a, b, c, d, w[9], S31, T[44]); HH(d, a, b, c, w[12], S32, T[45]); HH(c, d, a, b, w[15], S33, T[46]); HH(b, c, d, a, w[2], S34, T[47]); II(a, b, c, d, w[0], S41, T[48]); II(d, a, b, c, w[7], S42, T[49]); II(c, d, a, b, w[14], S43, T[50]); II(b, c, d, a, w[5], S44, T[51]); II(a, b, c, d, w[12], S41, T[52]); II(d, a, b, c, w[3], S42, T[53]); II(c, d, a, b, w[10], S43, T[54]); II(b, c, d, a, w[1], S44, T[55]); II(a, b, c, d, w[8], S41, T[56]); II(d, a, b, c, w[15], S42, T[57]); II(c, d, a, b, w[6], S43, T[58]); II(b, c, d, a, w[13], S44, T[59]); II(a, b, c, d, w[4], S41, T[60]); II(d, a, b, c, w[11], S42, T[61]); II(c, d, a, b, w[2], S43, T[62]); II(b, c, d, a, w[9], S44, T[63]); state[0] += a; state[1] += b; state[2] += c; state[3] += d; input += CRYPT_MD5_BLOCKSIZE; count--; } } #ifdef __cplusplus } #endif /* __cpluscplus */ #endif // HITLS_CRYPTO_MD5
2302_82127028/openHiTLS-examples_1508
crypto/md5/src/noasm_md5.c
C
unknown
7,292
/* * 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_ML_DSA_H #define CRYPT_ML_DSA_H #include <stdint.h> #include "crypt_types.h" #include "bsl_params.h" typedef struct CryptMlDsaCtx CRYPT_ML_DSA_Ctx; CRYPT_ML_DSA_Ctx *CRYPT_ML_DSA_NewCtx(void); CRYPT_ML_DSA_Ctx *CRYPT_ML_DSA_NewCtxEx(void *libCtx); void CRYPT_ML_DSA_FreeCtx(CRYPT_ML_DSA_Ctx *ctx); CRYPT_ML_DSA_Ctx *CRYPT_ML_DSA_DupCtx(CRYPT_ML_DSA_Ctx *ctx); int32_t CRYPT_ML_DSA_Ctrl(CRYPT_ML_DSA_Ctx *ctx, CRYPT_PkeyCtrl opt, void *val, uint32_t len); int32_t CRYPT_ML_DSA_GenKey(CRYPT_ML_DSA_Ctx *ctx); int32_t CRYPT_ML_DSA_Sign(CRYPT_ML_DSA_Ctx *ctx, int32_t hashId, const uint8_t *data, uint32_t dataLen, uint8_t *sign, uint32_t *signLen); int32_t CRYPT_ML_DSA_Verify(CRYPT_ML_DSA_Ctx *ctx, int32_t hashId, const uint8_t *data, uint32_t dataLen, uint8_t *sign, uint32_t signLen); int32_t CRYPT_ML_DSA_SetPrvKey(CRYPT_ML_DSA_Ctx *ctx, CRYPT_MlDsaPrv *prv); int32_t CRYPT_ML_DSA_SetPubKey(CRYPT_ML_DSA_Ctx *ctx, CRYPT_MlDsaPub *pub); int32_t CRYPT_ML_DSA_GetPrvKey(const CRYPT_ML_DSA_Ctx *ctx, CRYPT_MlDsaPrv *prv); int32_t CRYPT_ML_DSA_GetPubKey(const CRYPT_ML_DSA_Ctx *ctx, CRYPT_MlDsaPub *pub); #ifdef HITLS_BSL_PARAMS int32_t CRYPT_ML_DSA_SetPrvKeyEx(CRYPT_ML_DSA_Ctx *ctx, const BSL_Param *para); int32_t CRYPT_ML_DSA_SetPubKeyEx(CRYPT_ML_DSA_Ctx *ctx, const BSL_Param *para); int32_t CRYPT_ML_DSA_GetPrvKeyEx(const CRYPT_ML_DSA_Ctx *ctx, BSL_Param *para); int32_t CRYPT_ML_DSA_GetPubKeyEx(const CRYPT_ML_DSA_Ctx *ctx, BSL_Param *para); #endif int32_t CRYPT_ML_DSA_Cmp(const CRYPT_ML_DSA_Ctx *a, const CRYPT_ML_DSA_Ctx *b); #ifdef HITLS_CRYPTO_MLDSA_CHECK /** * @ingroup mldsa * @brief check the key pair consistency * * @param checkType [IN] check type * @param pkey1 [IN] mldsa key context structure * @param pkey2 [IN] mldsa key context structure * * @retval CRYPT_SUCCESS check success. * Others. For details, see error code in errno. */ int32_t CRYPT_ML_DSA_Check(uint32_t checkType, const CRYPT_ML_DSA_Ctx *pkey1, const CRYPT_ML_DSA_Ctx *pkey2); #endif // HITLS_CRYPTO_MLDSA_CHECK #endif // CRYPT_ML_DSA_H
2302_82127028/openHiTLS-examples_1508
crypto/mldsa/include/crypt_mldsa.h
C
unknown
2,625
/* * 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_MLDSA #include "securec.h" #include "crypt_errno.h" #include "crypt_util_rand.h" #include "crypt_utils.h" #include "crypt_algid.h" #include "bsl_errno.h" #include "bsl_sal.h" #include "bsl_obj_internal.h" #include "bsl_err_internal.h" #include "ml_dsa_local.h" #include "eal_md_local.h" // These data from NIST.FIPS.204 Table 1 and Table 2. static const CRYPT_ML_DSA_Info MLDSA_PARAMETERTER_44 = {4, 4, 2, 39, 78, (1 << 17), ((MLDSA_Q - 1) / 88), 80, 128, 1312, 2560, 2420}; static const CRYPT_ML_DSA_Info MLDSA_PARAMETERTER_65 = {6, 5, 4, 49, 196, (1 << 19), ((MLDSA_Q - 1) / 32), 55, 192, 1952, 4032, 3309}; static const CRYPT_ML_DSA_Info MLDSA_PARAMETERTER_87 = {8, 7, 2, 60, 120, (1 << 19), ((MLDSA_Q - 1) / 32), 75, 256, 2592, 4896, 4627}; static const CRYPT_ML_DSA_Info *g_mldsaInfo[] = {&MLDSA_PARAMETERTER_44, &MLDSA_PARAMETERTER_65, &MLDSA_PARAMETERTER_87}; const CRYPT_ML_DSA_Info *CRYPT_ML_DSA_GetInfo(uint32_t k) { if (k == CRYPT_MLDSA_TYPE_MLDSA_44) { return g_mldsaInfo[0]; } else if (k == CRYPT_MLDSA_TYPE_MLDSA_65) { return g_mldsaInfo[1]; } else if (k == CRYPT_MLDSA_TYPE_MLDSA_87) { return g_mldsaInfo[2]; } return NULL; } CRYPT_ML_DSA_Ctx *CRYPT_ML_DSA_NewCtx(void) { CRYPT_ML_DSA_Ctx *keyCtx = BSL_SAL_Calloc(1, sizeof(CRYPT_ML_DSA_Ctx)); if (keyCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } keyCtx->needEncodeCtx = true; keyCtx->isMuMsg = false; keyCtx->deterministicSignFlag = false; keyCtx->needPreHash = false; BSL_SAL_ReferencesInit(&(keyCtx->references)); return keyCtx; } CRYPT_ML_DSA_Ctx *CRYPT_ML_DSA_NewCtxEx(void *libCtx) { CRYPT_ML_DSA_Ctx *ctx = CRYPT_ML_DSA_NewCtx(); if (ctx == NULL) { return NULL; } ctx->libCtx = libCtx; return ctx; } void CRYPT_ML_DSA_FreeCtx(CRYPT_ML_DSA_Ctx *ctx) { if (ctx == NULL) { return; } int ret = 0; BSL_SAL_AtomicDownReferences(&(ctx->references), &ret); if (ret > 0) { return; } BSL_SAL_ClearFree(ctx->prvKey, ctx->prvLen); BSL_SAL_FREE(ctx->pubKey); BSL_SAL_FREE(ctx->ctxInfo); BSL_SAL_ReferencesFree(&(ctx->references)); BSL_SAL_Free(ctx); } CRYPT_ML_DSA_Ctx *CRYPT_ML_DSA_DupCtx(CRYPT_ML_DSA_Ctx *ctx) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return NULL; } CRYPT_ML_DSA_Ctx *newCtx = CRYPT_ML_DSA_NewCtx(); if (newCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } newCtx->info = ctx->info; GOTO_ERR_IF_SRC_NOT_NULL(newCtx->pubKey, ctx->pubKey, BSL_SAL_Dump(ctx->pubKey, ctx->pubLen), CRYPT_MEM_ALLOC_FAIL); GOTO_ERR_IF_SRC_NOT_NULL(newCtx->prvKey, ctx->prvKey, BSL_SAL_Dump(ctx->prvKey, ctx->prvLen), CRYPT_MEM_ALLOC_FAIL); newCtx->pubLen = ctx->pubLen; newCtx->prvLen = ctx->prvLen; newCtx->needEncodeCtx = ctx->needEncodeCtx; newCtx->isMuMsg = ctx->isMuMsg; newCtx->deterministicSignFlag = ctx->deterministicSignFlag; newCtx->needPreHash = ctx->needPreHash; newCtx->libCtx = ctx->libCtx; return newCtx; ERR: CRYPT_ML_DSA_FreeCtx(newCtx); return NULL; } static int32_t MlDSASetAlgInfo(CRYPT_ML_DSA_Ctx *ctx, void *val, uint32_t len) { if (len != sizeof(int32_t) || val == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } if (ctx->info != NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_CTRL_INIT_REPEATED); return CRYPT_MLDSA_CTRL_INIT_REPEATED; } ctx->info = CRYPT_ML_DSA_GetInfo(*(int32_t *)val); if (ctx->info == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NOT_SUPPORT); return CRYPT_NOT_SUPPORT; } return CRYPT_SUCCESS; } static int32_t MLDSAGetSignLen(const CRYPT_ML_DSA_Ctx *ctx, void *val, uint32_t len) { if (ctx == NULL || 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->info == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_KEYINFO_NOT_SET); return CRYPT_MLDSA_KEYINFO_NOT_SET; } *(int32_t *)val = ctx->info->signatureLen; return CRYPT_SUCCESS; } static int32_t MLDSAGetSecBits(const CRYPT_ML_DSA_Ctx *ctx, void *val, uint32_t len) { if (ctx == NULL || val == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->info == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_KEYINFO_NOT_SET); return CRYPT_MLDSA_KEYINFO_NOT_SET; } if (len != sizeof(int32_t)) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } *(int32_t *)val = ctx->info->secBits; return CRYPT_SUCCESS; } static int32_t MlDSASetEncodeFlag(CRYPT_ML_DSA_Ctx *ctx, void *val, uint32_t len) { if (len != sizeof(int32_t) || val == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } ctx->needEncodeCtx = (*(int32_t *)val != 0); return CRYPT_SUCCESS; } static int32_t MlDSASetMsgFlag(CRYPT_ML_DSA_Ctx *ctx, void *val, uint32_t len) { if (len != sizeof(int32_t) || val == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } ctx->isMuMsg = (*(int32_t *)val != 0); return CRYPT_SUCCESS; } static int32_t MlDSASetDeterministicSignFlag(CRYPT_ML_DSA_Ctx *ctx, void *val, uint32_t len) { if (len != sizeof(int32_t) || val == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } ctx->deterministicSignFlag = (*(int32_t *)val != 0); return CRYPT_SUCCESS; } static int32_t MlDSASetPreHashFlag(CRYPT_ML_DSA_Ctx *ctx, void *val, uint32_t len) { if (len != sizeof(int32_t) || val == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } ctx->needPreHash = (*(int32_t *)val != 0); return CRYPT_SUCCESS; } int32_t MLDSASetctxInfo(CRYPT_ML_DSA_Ctx *ctx, void *val, uint32_t len) { if (len > MLDSA_MAX_CTX_BYTES) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_KEYLEN_ERROR); return CRYPT_MLDSA_KEYLEN_ERROR; } if (ctx->ctxInfo != NULL) { BSL_SAL_FREE(ctx->ctxInfo); ctx->ctxLen = 0; } if (val == NULL && len == 0) { ctx->needEncodeCtx = true; return CRYPT_SUCCESS; } ctx->ctxInfo = BSL_SAL_Dump((uint8_t *)val, len); if (ctx->ctxInfo == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ctx->ctxLen = len; ctx->needEncodeCtx = true; return CRYPT_SUCCESS; } static int32_t MLDSAGetPubKeyLen(const CRYPT_ML_DSA_Ctx *ctx, void *val, uint32_t len) { RETURN_RET_IF(val == NULL, CRYPT_NULL_INPUT); RETURN_RET_IF((ctx->info == NULL), CRYPT_MLDSA_KEYINFO_NOT_SET); RETURN_RET_IF((len != sizeof(uint32_t)), CRYPT_INVALID_ARG); *(uint32_t *)val = ctx->info->publicKeyLen; return CRYPT_SUCCESS; } static int32_t MLDSAGetPrvKeyLen(const CRYPT_ML_DSA_Ctx *ctx, void *val, uint32_t len) { RETURN_RET_IF(val == NULL, CRYPT_NULL_INPUT); RETURN_RET_IF((ctx->info == NULL), CRYPT_MLDSA_KEYINFO_NOT_SET); RETURN_RET_IF((len != sizeof(uint32_t)), CRYPT_INVALID_ARG); *(uint32_t *)val = ctx->info->privateKeyLen; return CRYPT_SUCCESS; } static int32_t MLDSACleanPubKey(CRYPT_ML_DSA_Ctx *ctx) { if (ctx->pubKey != NULL) { BSL_SAL_CleanseData(ctx->pubKey, ctx->pubLen); BSL_SAL_FREE(ctx->pubKey); ctx->pubLen = 0; } return CRYPT_SUCCESS; } int32_t CRYPT_ML_DSA_Ctrl(CRYPT_ML_DSA_Ctx *ctx, CRYPT_PkeyCtrl opt, void *val, uint32_t len) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } switch ((uint32_t)opt) { case CRYPT_CTRL_SET_PARA_BY_ID: return MlDSASetAlgInfo(ctx, val, len); case CRYPT_CTRL_GET_SIGNLEN: return MLDSAGetSignLen(ctx, val, len); case CRYPT_CTRL_GET_SECBITS: return MLDSAGetSecBits(ctx, val, len); case CRYPT_CTRL_SET_CTX_INFO: return MLDSASetctxInfo(ctx, val, len); case CRYPT_CTRL_SET_MLDSA_ENCODE_FLAG: return MlDSASetEncodeFlag(ctx, val, len); case CRYPT_CTRL_SET_MLDSA_MUMSG_FLAG: return MlDSASetMsgFlag(ctx, val, len); case CRYPT_CTRL_SET_DETERMINISTIC_FLAG: return MlDSASetDeterministicSignFlag(ctx, val, len); case CRYPT_CTRL_SET_PREHASH_FLAG: return MlDSASetPreHashFlag(ctx, val, len); case CRYPT_CTRL_GET_PUBKEY_LEN: return MLDSAGetPubKeyLen(ctx, val, len); case CRYPT_CTRL_GET_PRVKEY_LEN: return MLDSAGetPrvKeyLen(ctx, val, len); case CRYPT_CTRL_CLEAN_PUB_KEY: return MLDSACleanPubKey(ctx); default: BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_CTRL_NOT_SUPPORT); return CRYPT_MLDSA_CTRL_NOT_SUPPORT; } } static int32_t MLDSACreateKeyBuf(CRYPT_ML_DSA_Ctx *ctx) { if (ctx->pubKey == NULL) { ctx->pubKey = BSL_SAL_Malloc(ctx->info->publicKeyLen); if (ctx->pubKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ctx->pubLen = ctx->info->publicKeyLen; } if (ctx->prvKey == NULL) { ctx->prvKey = BSL_SAL_Malloc(ctx->info->privateKeyLen); if (ctx->prvKey == NULL) { BSL_SAL_FREE(ctx->pubKey); BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ctx->prvLen = ctx->info->privateKeyLen; } return CRYPT_SUCCESS; } int32_t CRYPT_ML_DSA_GenKey(CRYPT_ML_DSA_Ctx *ctx) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->info == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_KEYINFO_NOT_SET); return CRYPT_MLDSA_KEYINFO_NOT_SET; } if (MLDSACreateKeyBuf(ctx) != CRYPT_SUCCESS) { return CRYPT_MEM_ALLOC_FAIL; } uint8_t seed[MLDSA_SEED_BYTES_LEN]; int32_t ret = CRYPT_RandEx(ctx->libCtx, seed, MLDSA_SEED_BYTES_LEN); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = MLDSA_KeyGenInternal(ctx, seed); BSL_SAL_CleanseData(seed, MLDSA_SEED_BYTES_LEN); return ret; } static int32_t MLDSA_SignArgCheck(CRYPT_ML_DSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint8_t *sign, uint32_t *signLen) { if (ctx == NULL || data == NULL || dataLen == 0 || sign == NULL || signLen == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->info == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_KEYINFO_NOT_SET); return CRYPT_MLDSA_KEYINFO_NOT_SET; } if (ctx->prvKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_KEY_NOT_SET); return CRYPT_MLDSA_KEY_NOT_SET; } if (*signLen < ctx->info->signatureLen) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_LEN_NOT_ENOUGH); return CRYPT_MLDSA_LEN_NOT_ENOUGH; } return CRYPT_SUCCESS; } static int32_t MLDSA_VerifyArgCheck(CRYPT_ML_DSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint8_t *sign, uint32_t signLen) { if (ctx == NULL || data == NULL || dataLen == 0 || sign == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->info == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_KEYINFO_NOT_SET); return CRYPT_MLDSA_KEYINFO_NOT_SET; } if (ctx->pubKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_KEY_NOT_SET); return CRYPT_MLDSA_KEY_NOT_SET; } if (signLen != ctx->info->signatureLen) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_LEN_NOT_ENOUGH); return CRYPT_MLDSA_LEN_NOT_ENOUGH; } return CRYPT_SUCCESS; } int32_t CRYPT_ML_DSA_SetPrvKey(CRYPT_ML_DSA_Ctx *ctx, CRYPT_MlDsaPrv *prv) { if (ctx == NULL || prv == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->info == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_KEYINFO_NOT_SET); return CRYPT_MLDSA_KEYINFO_NOT_SET; } if (prv->len != ctx->info->privateKeyLen) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_KEYLEN_ERROR); return CRYPT_MLDSA_KEYLEN_ERROR; } if (ctx->prvKey != NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_SET_KEY_FAILED); return CRYPT_MLDSA_SET_KEY_FAILED; } ctx->prvKey = BSL_SAL_Malloc(ctx->info->privateKeyLen); if (ctx->prvKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ctx->prvLen = ctx->info->privateKeyLen; (void)memcpy_s(ctx->prvKey, ctx->prvLen, prv->data, prv->len); return CRYPT_SUCCESS; } #ifdef HITLS_BSL_PARAMS int32_t CRYPT_ML_DSA_SetPrvKeyEx(CRYPT_ML_DSA_Ctx *ctx, const BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_MlDsaPrv prv = {0}; (void)GetConstParamValue(para, CRYPT_PARAM_ML_DSA_PRVKEY, &prv.data, &prv.len); return CRYPT_ML_DSA_SetPrvKey(ctx, &prv); } int32_t CRYPT_ML_DSA_SetPubKeyEx(CRYPT_ML_DSA_Ctx *ctx, const BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_MlDsaPub pub = {0}; (void)GetConstParamValue(para, CRYPT_PARAM_ML_DSA_PUBKEY, &pub.data, &pub.len); return CRYPT_ML_DSA_SetPubKey(ctx, &pub); } int32_t CRYPT_ML_DSA_GetPrvKeyEx(const CRYPT_ML_DSA_Ctx *ctx, BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_MlDsaPrv prv = {0}; BSL_Param *paramPrv = GetParamValue(para, CRYPT_PARAM_ML_DSA_PRVKEY, &prv.data, &(prv.len)); int32_t ret = CRYPT_ML_DSA_GetPrvKey(ctx, &prv); if (ret != CRYPT_SUCCESS) { return ret; } paramPrv->useLen = prv.len; return CRYPT_SUCCESS; } int32_t CRYPT_ML_DSA_GetPubKeyEx(const CRYPT_ML_DSA_Ctx *ctx, BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_MlDsaPub pub = {0}; BSL_Param *paramPub = GetParamValue(para, CRYPT_PARAM_ML_DSA_PUBKEY, &pub.data, &(pub.len)); int32_t ret = CRYPT_ML_DSA_GetPubKey(ctx, &pub); if (ret != CRYPT_SUCCESS) { return ret; } paramPub->useLen = pub.len; return CRYPT_SUCCESS; } #endif int32_t CRYPT_ML_DSA_SetPubKey(CRYPT_ML_DSA_Ctx *ctx, CRYPT_MlDsaPub *pub) { if (ctx == NULL || pub == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->info == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_KEYINFO_NOT_SET); return CRYPT_MLDSA_KEYINFO_NOT_SET; } if (pub->len != ctx->info->publicKeyLen) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_KEYLEN_ERROR); return CRYPT_MLDSA_KEYLEN_ERROR; } if (ctx->pubKey != NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_SET_KEY_FAILED); return CRYPT_MLDSA_SET_KEY_FAILED; } ctx->pubKey = BSL_SAL_Malloc(ctx->info->publicKeyLen); if (ctx->pubKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ctx->pubLen = ctx->info->publicKeyLen; (void)memcpy_s(ctx->pubKey, ctx->pubLen, pub->data, pub->len); return CRYPT_SUCCESS; } int32_t CRYPT_ML_DSA_GetPrvKey(const CRYPT_ML_DSA_Ctx *ctx, CRYPT_MlDsaPrv *prv) { if (ctx == NULL || prv == NULL || prv->data == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->prvKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_KEY_NOT_SET); return CRYPT_MLDSA_KEY_NOT_SET; } if (memcpy_s(prv->data, prv->len, ctx->prvKey, ctx->prvLen) != EOK) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_LEN_NOT_ENOUGH); return CRYPT_MLDSA_LEN_NOT_ENOUGH; } prv->len = ctx->prvLen; return CRYPT_SUCCESS; } int32_t CRYPT_ML_DSA_GetPubKey(const CRYPT_ML_DSA_Ctx *ctx, CRYPT_MlDsaPub *pub) { if (ctx == NULL || pub == NULL || pub->data == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->pubKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_KEY_NOT_SET); return CRYPT_MLDSA_KEY_NOT_SET; } if (memcpy_s(pub->data, pub->len, ctx->pubKey, ctx->pubLen) != EOK) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_LEN_NOT_ENOUGH); return CRYPT_MLDSA_LEN_NOT_ENOUGH; } pub->len = ctx->pubLen; return CRYPT_SUCCESS; } static int32_t MLDSACmpKey(uint8_t *a, uint32_t aLen, uint8_t *b, uint32_t bLen) { if (aLen != bLen) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_KEY_NOT_EQUAL); return CRYPT_MLDSA_KEY_NOT_EQUAL; } if (a != NULL && b != NULL) { if (memcmp(a, b, aLen) != 0) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_KEY_NOT_EQUAL); return CRYPT_MLDSA_KEY_NOT_EQUAL; } } if (a == NULL && b == NULL) { return CRYPT_SUCCESS; } if (a == NULL || b == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_KEY_NOT_EQUAL); return CRYPT_MLDSA_KEY_NOT_EQUAL; } return CRYPT_SUCCESS; } int32_t CRYPT_ML_DSA_Cmp(const CRYPT_ML_DSA_Ctx *a, const CRYPT_ML_DSA_Ctx *b) { if (a == NULL || b == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (a->info != b->info) { // The value of info must be one of the g_mldsaInfo arrays. BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_KEY_NOT_EQUAL); return CRYPT_MLDSA_KEY_NOT_EQUAL; } if (MLDSACmpKey(a->prvKey, a->prvLen, b->prvKey, b->prvLen) != CRYPT_SUCCESS) { return CRYPT_MLDSA_KEY_NOT_EQUAL; } if (MLDSACmpKey(a->pubKey, a->pubLen, b->pubKey, b->pubLen) != CRYPT_SUCCESS) { return CRYPT_MLDSA_KEY_NOT_EQUAL; } return CRYPT_SUCCESS; } static uint32_t MLDSAGetMdSize(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 MLDSAPreHashEncode(CRYPT_ML_DSA_Ctx *ctx, int32_t hashId, const uint8_t *data, uint32_t dataLen, CRYPT_Data *msg) { int32_t ret = CRYPT_SUCCESS; // The maximum value of ctx->ctxLen is 255. if (dataLen > (UINT32_MAX - MLDSA_SIGN_PREFIX_BYTES - ctx->ctxLen)) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } BslOidString *oidInfo = BSL_OBJ_GetOID(hashId); RETURN_RET_IF(oidInfo == NULL, CRYPT_ERR_ALGID); const EAL_MdMethod *hashMethod = EAL_MdFindDefaultMethod(hashId); RETURN_RET_IF(hashMethod == NULL, CRYPT_EAL_ALG_NOT_SUPPORT); uint32_t mdSize = MLDSAGetMdSize(hashMethod, hashId); msg->len = MLDSA_SIGN_PREFIX_BYTES + ctx->ctxLen + MLDSA_SIGN_PREFIX_BYTES + oidInfo->octetLen + mdSize; msg->data = BSL_SAL_Malloc(msg->len); RETURN_RET_IF(msg->data == NULL, CRYPT_MEM_ALLOC_FAIL); uint8_t *ptr = msg->data; uint32_t tmpLen = msg->len; ptr[0] = 1; ptr[1] = (uint8_t)ctx->ctxLen; ptr += MLDSA_SIGN_PREFIX_BYTES; tmpLen -= MLDSA_SIGN_PREFIX_BYTES; if (ctx->ctxInfo != NULL && ctx->ctxLen > 0) { (void)memcpy_s(ptr, msg->len - MLDSA_SIGN_PREFIX_BYTES, ctx->ctxInfo, ctx->ctxLen); ptr += ctx->ctxLen; tmpLen -= ctx->ctxLen; } ptr[0] = 0x06; // tag of objectId ptr[1] = (uint8_t)oidInfo->octetLen; ptr += MLDSA_SIGN_PREFIX_BYTES; tmpLen -= MLDSA_SIGN_PREFIX_BYTES; (void)memcpy_s(ptr, tmpLen, oidInfo->octs, oidInfo->octetLen); ptr += oidInfo->octetLen; tmpLen -= oidInfo->octetLen; void *mdCtx = hashMethod->newCtx(NULL, hashMethod->id); if (mdCtx == NULL) { BSL_SAL_Free(msg->data); BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } GOTO_ERR_IF(hashMethod->init(mdCtx, NULL), ret); GOTO_ERR_IF(hashMethod->update(mdCtx, data, dataLen), ret); GOTO_ERR_IF(hashMethod->final(mdCtx, ptr, &tmpLen), ret); ERR: hashMethod->freeCtx(mdCtx); if (ret != CRYPT_SUCCESS) { BSL_SAL_FREE(msg->data); } return ret; } static int32_t MLDSAEncodeInputData(CRYPT_ML_DSA_Ctx *ctx, int32_t hashId, const uint8_t *data, uint32_t dataLen, CRYPT_Data *msg) { int32_t ret; if (ctx->isMuMsg || ctx->needEncodeCtx == false) { msg->data = BSL_SAL_Dump(data, dataLen); RETURN_RET_IF(msg->data == NULL, CRYPT_MEM_ALLOC_FAIL); msg->len = dataLen; return CRYPT_SUCCESS; } // The maximum value of ctx->ctxLen is 255. if (dataLen > (UINT32_MAX - MLDSA_SIGN_PREFIX_BYTES - ctx->ctxLen)) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } if (ctx->needPreHash) { RETURN_RET_IF_ERR(MLDSAPreHashEncode(ctx, hashId, data, dataLen, msg), ret); return CRYPT_SUCCESS; } msg->len = dataLen + ctx->ctxLen + MLDSA_SIGN_PREFIX_BYTES; msg->data = BSL_SAL_Malloc(msg->len); if (msg->data == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } msg->data[0] = 0; msg->data[1] = (uint8_t)ctx->ctxLen; if (ctx->ctxInfo != NULL && ctx->ctxLen > 0) { (void)memcpy_s(msg->data + MLDSA_SIGN_PREFIX_BYTES, msg->len - MLDSA_SIGN_PREFIX_BYTES, ctx->ctxInfo, ctx->ctxLen); } (void)memcpy_s(msg->data + MLDSA_SIGN_PREFIX_BYTES + ctx->ctxLen, msg->len - MLDSA_SIGN_PREFIX_BYTES - ctx->ctxLen, data, dataLen); return CRYPT_SUCCESS; } // Algorithm 4 HashML-DSA.Sign(sk, M, ctx, PH) int32_t CRYPT_ML_DSA_Sign(CRYPT_ML_DSA_Ctx *ctx, int32_t hashId, const uint8_t *data, uint32_t dataLen, uint8_t *sign, uint32_t *signLen) { int32_t ret = MLDSA_SignArgCheck(ctx, data, dataLen, sign, signLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } uint8_t signSeed[MLDSA_SEED_BYTES_LEN] = { 0 }; if (ctx->deterministicSignFlag == false) { ret = CRYPT_RandEx(ctx->libCtx, signSeed, MLDSA_SEED_BYTES_LEN); RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); } CRYPT_Data msg = { 0 }; RETURN_RET_IF_ERR(MLDSAEncodeInputData(ctx, hashId, data, dataLen, &msg), ret); ret = MLDSA_SignInternal(ctx, &msg, sign, signLen, signSeed); BSL_SAL_Free(msg.data); BSL_SAL_CleanseData(signSeed, sizeof(signSeed)); return ret; } // Algorithm 5 HashML-DSA.Verify(pk, M, 𝜎, ctx, PH) int32_t CRYPT_ML_DSA_Verify(CRYPT_ML_DSA_Ctx *ctx, int32_t hashId, const uint8_t *data, uint32_t dataLen, uint8_t *sign, uint32_t signLen) { int32_t ret = MLDSA_VerifyArgCheck(ctx, data, dataLen, sign, signLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } CRYPT_Data msg = { 0 }; RETURN_RET_IF_ERR(MLDSAEncodeInputData(ctx, hashId, data, dataLen, &msg), ret); ret = MLDSA_VerifyInternal(ctx, &msg, sign, signLen); BSL_SAL_Free(msg.data); return ret; } #ifdef HITLS_CRYPTO_MLDSA_CHECK static int32_t MLDSAKeyPairCheck(const CRYPT_ML_DSA_Ctx *pubKey, const CRYPT_ML_DSA_Ctx *prvKey) { if (pubKey == NULL || prvKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (pubKey->info == NULL || prvKey->info == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_KEYINFO_NOT_SET); return CRYPT_MLDSA_KEYINFO_NOT_SET; } if (pubKey->info->secBits != prvKey->info->secBits) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_PAIRWISE_CHECK_FAIL); return CRYPT_MLDSA_PAIRWISE_CHECK_FAIL; } if (pubKey->pubKey == NULL || pubKey->pubLen != pubKey->info->publicKeyLen) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_INVALID_PUBKEY); return CRYPT_MLDSA_INVALID_PUBKEY; } if (prvKey->prvKey == NULL || prvKey->prvLen != prvKey->info->privateKeyLen) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_INVALID_PRVKEY); return CRYPT_MLDSA_INVALID_PRVKEY; } uint8_t *pub = BSL_SAL_Malloc(pubKey->info->publicKeyLen); if (pub == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = MLDSA_CalPub(prvKey, pub, pubKey->info->publicKeyLen); if (ret != CRYPT_SUCCESS) { BSL_SAL_Free(pub); return ret; } if (memcmp(pub, pubKey->pubKey, pubKey->info->publicKeyLen) != 0) { BSL_SAL_Free(pub); BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_PAIRWISE_CHECK_FAIL); return CRYPT_MLDSA_PAIRWISE_CHECK_FAIL; } BSL_SAL_Free(pub); return CRYPT_SUCCESS; } static int32_t MLDSAPrvKeyCheck(const CRYPT_ML_DSA_Ctx *prvKey) { if (prvKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (prvKey->info == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_KEYINFO_NOT_SET); return CRYPT_MLDSA_KEYINFO_NOT_SET; } if (prvKey->prvKey == NULL || prvKey->prvLen != prvKey->info->privateKeyLen) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_INVALID_PRVKEY); return CRYPT_MLDSA_INVALID_PRVKEY; } return CRYPT_SUCCESS; } int32_t CRYPT_ML_DSA_Check(uint32_t checkType, const CRYPT_ML_DSA_Ctx *pkey1, const CRYPT_ML_DSA_Ctx *pkey2) { switch (checkType) { case CRYPT_PKEY_CHECK_KEYPAIR: return MLDSAKeyPairCheck(pkey1, pkey2); case CRYPT_PKEY_CHECK_PRVKEY: return MLDSAPrvKeyCheck(pkey1); default: BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } } #endif // HITLS_CRYPTO_MLDSA_CHECK #endif
2302_82127028/openHiTLS-examples_1508
crypto/mldsa/src/ml_dsa.c
C
unknown
26,554
/* * 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_MLDSA #include "securec.h" #include "bsl_errno.h" #include "bsl_sal.h" #include "crypt_utils.h" #include "crypt_sha3.h" #include "crypt_errno.h" #include "crypt_util_rand.h" #include "bsl_err_internal.h" #include "ml_dsa_local.h" #include "eal_md_local.h" #define BITS_OF_BYTE 8 #define MLDSA_SET_VECTOR_MEM(ptr, buf) {ptr = buf; buf += MLDSA_N;} static int32_t HashFuncH(const uint8_t *inPutA, uint32_t lenA, const uint8_t *inPutB, uint32_t lenB, uint8_t *out, uint32_t outLen) { uint32_t len = outLen; int32_t ret = 0; const EAL_MdMethod *hashMethod = EAL_MdFindDefaultMethod(CRYPT_MD_SHAKE256); if (hashMethod == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_NOT_SUPPORT); return CRYPT_EAL_ALG_NOT_SUPPORT; } void *mdCtx = hashMethod->newCtx(NULL, hashMethod->id); if (mdCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } GOTO_ERR_IF(hashMethod->init(mdCtx, NULL), ret); GOTO_ERR_IF(hashMethod->update(mdCtx, inPutA, lenA), ret); if (inPutB != NULL) { GOTO_ERR_IF(hashMethod->update(mdCtx, inPutB, lenB), ret); } GOTO_ERR_IF(hashMethod->final(mdCtx, out, &len), ret); ERR: hashMethod->freeCtx(mdCtx); return ret; } typedef struct { int32_t *bufAddr; uint32_t bufSize; int32_t *matrix[MLDSA_K_MAX][MLDSA_L_MAX]; int32_t *s2[MLDSA_K_MAX]; int32_t *t0[MLDSA_K_MAX]; int32_t *t1[MLDSA_K_MAX]; int32_t *s1[MLDSA_L_MAX]; int32_t *s1Ntt[MLDSA_L_MAX]; } MLDSA_KeyGenMatrixSt; static void MLDSASetMatrixMem(uint8_t k, uint8_t l, int32_t *matrix[MLDSA_K_MAX][MLDSA_L_MAX], int32_t *buf) { for (uint8_t i = 0; i < k; i++) { for (uint8_t j = 0; j < l; j++) { matrix[i][j] = buf; buf += MLDSA_N; } } } static int32_t MLDSAKeyGenCreateMatrix(uint8_t k, uint8_t l, MLDSA_KeyGenMatrixSt *st) { // Key generation requires 3 two-dimensional arrays of length k and 2 of length l. st->bufSize = (k * l + 3 * k + 2 * l) * MLDSA_N * sizeof(int32_t); int32_t *buf = BSL_SAL_Malloc(st->bufSize); if (buf == NULL) { return BSL_MALLOC_FAIL; } st->bufAddr = buf; // Used to free memory. MLDSASetMatrixMem(k, l, st->matrix, buf); buf += k * l * MLDSA_N; for (uint8_t i = 0; i < k; i++) { MLDSA_SET_VECTOR_MEM(st->t0[i], buf); MLDSA_SET_VECTOR_MEM(st->t1[i], buf); MLDSA_SET_VECTOR_MEM(st->s2[i], buf); } for (uint8_t i = 0; i < l; i++) { MLDSA_SET_VECTOR_MEM(st->s1[i], buf); MLDSA_SET_VECTOR_MEM(st->s1Ntt[i], buf); } return CRYPT_SUCCESS; } typedef struct { int32_t *bufAddr; uint32_t bufSize; int32_t *matrix[MLDSA_K_MAX][MLDSA_L_MAX]; int32_t *t0[MLDSA_K_MAX]; int32_t *r0[MLDSA_K_MAX]; int32_t *s2[MLDSA_K_MAX]; int32_t *cs2[MLDSA_K_MAX]; int32_t *ct0[MLDSA_K_MAX]; int32_t *h[MLDSA_K_MAX]; int32_t *w[MLDSA_K_MAX]; int32_t *w1[MLDSA_K_MAX]; int32_t *s1[MLDSA_L_MAX]; int32_t *y[MLDSA_L_MAX]; int32_t *z[MLDSA_L_MAX]; } MLDSA_SignMatrixSt; static int32_t MLDSASignCreateMatrix(uint8_t k, uint8_t l, MLDSA_SignMatrixSt *st) { // The signature requires 8 two-dimensional arrays of length k and 3 of length l. st->bufSize = (k * l + 8 * k + 3 * l) * MLDSA_N * sizeof(int32_t); int32_t *buf = BSL_SAL_Malloc(st->bufSize); if (buf == NULL) { return BSL_MALLOC_FAIL; } st->bufAddr = buf; // Used to free memory. MLDSASetMatrixMem(k, l, st->matrix, buf); buf += k * l * MLDSA_N; for (uint8_t i = 0; i < k; i++) { MLDSA_SET_VECTOR_MEM(st->r0[i], buf); MLDSA_SET_VECTOR_MEM(st->t0[i], buf); MLDSA_SET_VECTOR_MEM(st->s2[i], buf); MLDSA_SET_VECTOR_MEM(st->cs2[i], buf); MLDSA_SET_VECTOR_MEM(st->ct0[i], buf); MLDSA_SET_VECTOR_MEM(st->h[i], buf); MLDSA_SET_VECTOR_MEM(st->w[i], buf); MLDSA_SET_VECTOR_MEM(st->w1[i], buf); } for (uint8_t i = 0; i < l; i++) { MLDSA_SET_VECTOR_MEM(st->s1[i], buf); MLDSA_SET_VECTOR_MEM(st->y[i], buf); MLDSA_SET_VECTOR_MEM(st->z[i], buf); } return CRYPT_SUCCESS; } typedef struct { int32_t *bufAddr; uint32_t bufSize; int32_t *matrix[MLDSA_K_MAX][MLDSA_L_MAX]; int32_t *t1[MLDSA_K_MAX]; int32_t *h[MLDSA_K_MAX]; int32_t *w[MLDSA_K_MAX]; int32_t *z[MLDSA_L_MAX]; } MLDSA_VerifyMatrixSt; static int32_t MLDSAVerifyCreateMatrix(uint8_t k, uint8_t l, MLDSA_VerifyMatrixSt *st) { // Signature verification requires 3 two-dimensional arrays of length k and 1 of length l. st->bufSize = (k * l + 3 * k + l) * MLDSA_N * sizeof(int32_t); int32_t *buf = BSL_SAL_Malloc(st->bufSize); if (buf == NULL) { return BSL_MALLOC_FAIL; } st->bufAddr = buf; // Used to free memory. MLDSASetMatrixMem(k, l, st->matrix, buf); buf += k * l * MLDSA_N; for (uint8_t i = 0; i < k; i++) { MLDSA_SET_VECTOR_MEM(st->t1[i], buf); MLDSA_SET_VECTOR_MEM(st->h[i], buf); MLDSA_SET_VECTOR_MEM(st->w[i], buf); } for (uint8_t i = 0; i < l; i++) { MLDSA_SET_VECTOR_MEM(st->z[i], buf); } return CRYPT_SUCCESS; } // NIST.FIPS.204 Algorithm 14 CoeffFromThreeBytes(b0, b1, b2) static int32_t CoeffFromThreeBytes(uint8_t b0, uint8_t b1, uint8_t b2) { uint8_t b = b2; if (b > 0x7f) { b = b - 0x80; } // 𝑧 ← 2^16 ⋅ b2′ + 2^8 ⋅ b1 + b0 return (((int32_t)b << 16) | ((int32_t)b1 << 8)) | b0; } // NIST.FIPS.204 Algorithm 30 RejNTTPoly(ρ) static int32_t RejNTTPoly(int32_t a[MLDSA_N], uint8_t seed[MLDSA_SEED_EXTEND_BYTES_LEN]) { int32_t ret; unsigned int buflen = CRYPT_SHAKE128_BLOCKSIZE; uint8_t buf[CRYPT_SHAKE128_BLOCKSIZE]; const EAL_MdMethod *hashMethod = EAL_MdFindDefaultMethod(CRYPT_MD_SHAKE128); if (hashMethod == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_NOT_SUPPORT); return CRYPT_EAL_ALG_NOT_SUPPORT; } void *mdCtx = hashMethod->newCtx(NULL, hashMethod->id); if (mdCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } GOTO_ERR_IF(hashMethod->init(mdCtx, NULL), ret); GOTO_ERR_IF(hashMethod->update(mdCtx, seed, MLDSA_SEED_EXTEND_BYTES_LEN), ret); GOTO_ERR_IF(hashMethod->squeeze(mdCtx, buf, buflen), ret); uint32_t j = 0; for (uint32_t i = 0; i < MLDSA_N;) { a[i] = CoeffFromThreeBytes(buf[j], buf[j + 1], buf[j + 2]); // Data from 3 uint8_t to int32_t. j += 3; if (a[i] < MLDSA_Q) { // a[i] is less than MLDSA_Q is an invalid value. i++; } if (j >= CRYPT_SHAKE128_BLOCKSIZE) { GOTO_ERR_IF(hashMethod->squeeze(mdCtx, buf, buflen), ret); j = 0; } } ERR: hashMethod->freeCtx(mdCtx); return ret; } // NIST.FIPS.204 Algorithm 32 ExpandA(ρ) static int32_t ExpandA(const CRYPT_ML_DSA_Ctx *ctx, const uint8_t *pubSeed, int32_t *matrix[MLDSA_K_MAX][MLDSA_L_MAX]) { uint8_t k = ctx->info->k; uint8_t l = ctx->info->l; uint8_t seed[MLDSA_SEED_EXTEND_BYTES_LEN]; (void)memcpy_s(seed, sizeof(seed), pubSeed, MLDSA_PUBLIC_SEED_LEN); for (uint8_t i = 0; i < k; i++) { for (uint8_t j = 0; j < l; j++) { seed[MLDSA_PUBLIC_SEED_LEN] = j; seed[MLDSA_PUBLIC_SEED_LEN + 1] = i; int32_t ret = RejNTTPoly(matrix[i][j], seed); RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); } } return CRYPT_SUCCESS; } // NIST.FIPS.204 Algorithm 31 RejBoundedPoly(ρ) static int32_t RejBoundedPoly(const CRYPT_ML_DSA_Ctx *ctx, int32_t *a, uint8_t *s) { uint8_t buf[CRYPT_SHAKE256_BLOCKSIZE]; uint32_t bufLen = CRYPT_SHAKE256_BLOCKSIZE; int32_t ret = CRYPT_SUCCESS; const EAL_MdMethod *hashMethod = EAL_MdFindDefaultMethod(CRYPT_MD_SHAKE256); if (hashMethod == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_NOT_SUPPORT); return CRYPT_EAL_ALG_NOT_SUPPORT; } void *mdCtx = hashMethod->newCtx(NULL, hashMethod->id); if (mdCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } GOTO_ERR_IF(hashMethod->init(mdCtx, NULL), ret); GOTO_ERR_IF(hashMethod->update(mdCtx, s, MLDSA_PRIVATE_SEED_LEN + 2), ret); // k and l used 2 bytes. GOTO_ERR_IF(hashMethod->squeeze(mdCtx, buf, bufLen), ret); for (uint32_t i = 0, j = 0; i < MLDSA_N; j++) { if (j == CRYPT_SHAKE256_BLOCKSIZE) { GOTO_ERR_IF(hashMethod->squeeze(mdCtx, buf, CRYPT_SHAKE256_BLOCKSIZE), ret); j = 0; } int32_t z0 = (int32_t)(buf[j] & 0x0F); int32_t z1 = (int32_t)(buf[j] >> 4u); // Algorithm 15 CoeffFromHalfByte(b) // if 𝜂 = 2 and b < 15 then return 2 − (b mod 5) if (ctx->info->eta == 2) { if (z0 < 0x0F) { // This is Barrett Modular Multiplication, 205 == 2^10 / 5 z0 = z0 - ((205 * z0) >> 10) * 5; // 2 − (b mod 5) a[i] = 2 - z0; i++; } if (z1 < 0x0F && i < MLDSA_N) { // Barrett Modular Multiplication, 205 == 2^10 / 5 z1 = z1 - ((205 * z1) >> 10) * 5; a[i] = 2 - z1; // 2 − (b mod 5) i++; } } else { if (z0 < 9) { // if 𝜂 = 4 and b < 9 then a[i] = 4 − b a[i] = 4 - z0; i++; } if (z1 < 9 && i < MLDSA_N) { // if 𝜂 = 4 and b < 9 then a[i + 1] = 4 − b a[i] = 4 - z1; i++; } } } ERR: hashMethod->freeCtx(mdCtx); return ret; } // Algorithm 33 ExpandS(ρ) static int32_t ExpandS(const CRYPT_ML_DSA_Ctx *ctx, const uint8_t *prvSeed, int32_t *s1[MLDSA_L_MAX], int32_t *s2[MLDSA_K_MAX]) { int32_t ret; uint8_t k = ctx->info->k; uint8_t l = ctx->info->l; uint8_t seed[MLDSA_PRIVATE_SEED_LEN + 2]; // 2 bytes are reserved. (void)memcpy_s(seed, sizeof(seed), prvSeed, MLDSA_PRIVATE_SEED_LEN); seed[MLDSA_PRIVATE_SEED_LEN + 1] = 0; for (uint8_t i = 0; i < l; i++) { seed[MLDSA_PRIVATE_SEED_LEN] = i; ret = RejBoundedPoly(ctx, s1[i], seed); RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); } for (uint8_t i = 0; i < k; i++) { seed[MLDSA_PRIVATE_SEED_LEN] = l + i; ret = RejBoundedPoly(ctx, s2[i], seed); RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); } return CRYPT_SUCCESS; } static void ComputesNTT(const CRYPT_ML_DSA_Ctx *ctx, int32_t *s[MLDSA_L_MAX], int32_t *sOut[MLDSA_L_MAX]) { for (uint8_t i = 0; i < ctx->info->l; i++) { (void)memcpy_s(sOut[i], sizeof(int32_t) * MLDSA_N, s[i], sizeof(int32_t) * MLDSA_N); MLDSA_ComputesNTT(sOut[i]); } return; } static void VectorsMul(int32_t *t, int32_t *matrix, int32_t *s) { for (uint32_t i = 0; i < MLDSA_N; i++) { t[i] = MLDSA_MontgomeryReduce((int64_t)matrix[i] * s[i]); } } static void MatrixMul(const CRYPT_ML_DSA_Ctx *ctx, int32_t *t, int32_t *matrix[MLDSA_L_MAX], int32_t *s[MLDSA_L_MAX]) { int32_t tmp[MLDSA_N] = { 0 }; VectorsMul(t, matrix[0], s[0]); for (uint32_t i = 1; i < ctx->info->l; i++) { VectorsMul(tmp, matrix[i], s[i]); for (uint32_t j = 0; j < MLDSA_N; j++) { t[j] = t[j] + tmp[j]; } } for (uint32_t j = 0; j < MLDSA_N; j++) { MLDSA_MOD_Q(t[j]); } } static void ComputesT(const CRYPT_ML_DSA_Ctx *ctx, int32_t *t[MLDSA_K_MAX], int32_t *matrix[MLDSA_K_MAX][MLDSA_L_MAX], int32_t *s1[MLDSA_L_MAX], int32_t *s2[MLDSA_K_MAX]) { for (uint8_t i = 0; i < ctx->info->k; i++) { MatrixMul(ctx, t[i], matrix[i], s1); MLDSA_ComputesINVNTT(t[i]); for (int32_t j = 0; j < MLDSA_N; j++) { t[i][j] = t[i][j] + s2[i][j]; t[i][j] = t[i][j] < 0 ? (t[i][j] + MLDSA_Q) : t[i][j]; } } } static void ComputesPower2Round(const CRYPT_ML_DSA_Ctx *ctx, int32_t *t0[MLDSA_K_MAX], int32_t *t1[MLDSA_K_MAX]) { for (uint32_t i = 0; i < ctx->info->k; i++) { for (int32_t j = 0; j < MLDSA_N; j++) { int32_t t = (t1[i][j] + (1 << (MLDSA_D - 1)) - 1) >> MLDSA_D; t0[i][j] = t1[i][j] - (t << MLDSA_D); t1[i][j] = t; } } } // The following encoding function encodes MLDSA_N int32_t data into the uint8_t array. static void ByteEncode(uint8_t *buf, uint32_t *t, uint32_t bits) { if (bits == 10u) { for (uint32_t i = 0; i < MLDSA_N / 4; i++) { buf[5 * i + 0] = (uint8_t)(t[4 * i + 0] >> 0); buf[5 * i + 1u] = (uint8_t)((t[4 * i + 0] >> 8u) | (t[4 * i + 1u] << 2u)); buf[5 * i + 2u] = (uint8_t)((t[4 * i + 1u] >> 6u) | (t[4 * i + 2u] << 4u)); buf[5 * i + 3u] = (uint8_t)((t[4 * i + 2u] >> 4u) | (t[4 * i + 3u] << 6u)); buf[5 * i + 4u] = (uint8_t)(t[4 * i + 3u] >> 2u); } } else if (bits == 6u) { for (uint32_t i = 0; i < MLDSA_N / 4; i++) { buf[3 * i + 0] = (uint8_t)(t[4 * i] | (t[4 * i + 1] << 6u)); buf[3 * i + 1u] = (uint8_t)(t[4 * i + 1u] >> 2 | (t[4 * i + 2u] << 4u)); buf[3 * i + 2u] = (uint8_t)(t[4 * i + 2u] >> 4 | (t[4 * i + 3u] << 2u)); } } else if (bits == 4u) { for (uint32_t i = 0; i < MLDSA_N / 2; i++) { buf[i] = (uint8_t)(t[2 * i] | (t[2 * i + 1] << 4u)); } } } static void ByteDecode(uint8_t *buf, uint32_t *t, uint32_t bits) { if (bits == 10u) { for (uint32_t i = 0; i < MLDSA_N / 4; i++) { t[4 * i + 0] = (buf[5 * i + 0] | ((uint32_t)buf[5 * i + 1] << 8)) & 0x03ff; t[4 * i + 1u] = ((buf[5 * i + 1u] >> 2u) | ((uint32_t)buf[5 * i + 2u] << 6u)) & 0x03ff; t[4 * i + 2u] = ((buf[5 * i + 2u] >> 4u) | ((uint32_t)buf[5 * i + 3u] << 4u)) & 0x03ff; t[4 * i + 3u] = ((buf[5 * i + 3u] >> 6u) | ((uint32_t)buf[5 * i + 4u] << 2u)) & 0x03ff; } } } static void BitPack(uint8_t *buf, uint32_t w[MLDSA_N], uint32_t bits, uint32_t b) { uint32_t t[8] = {0}; uint32_t i; uint32_t n; if (bits == 3u) { for (i = 0; i < MLDSA_N / 8; i++) { for (uint32_t j = 0; j < 8; j++) { t[j] = b - (uint32_t)w[i * 8 + j]; } n = bits * i; buf[n + 0] = (uint8_t)((t[0]) | (t[1] << 3u) | (t[2] << 6u)); buf[n + 1u] = (uint8_t)((t[2] >> 2u) | (t[3] << 1u) | (t[4] << 4u) | (t[5] << 7u)); buf[n + 2u] = (uint8_t)((t[5] >> 1u) | (t[6] << 2u) | (t[7] << 5u)); } } else if (bits == 4u) { for (i = 0; i < MLDSA_N / 2; i++) { t[0] = (int32_t)b - w[i * 2]; t[1] = (int32_t)b - w[i * 2 + 1]; buf[i] = (uint8_t)(t[0] | (t[1] << 4u)); } } else if (bits == MLDSA_D) { for (i = 0; i < MLDSA_N / 8; i++) { for (uint32_t j = 0; j < 8; j++) { t[j] = b - w[i * 8 + j]; } n = bits * i; buf[n + 0] = (uint8_t)t[0]; buf[n + 1] = (uint8_t)(t[0] >> 8u); buf[n + 1] |= (uint8_t)(t[1] << 5u); buf[n + 2] = (uint8_t)(t[1] >> 3u); buf[n + 3] = (uint8_t)(t[1] >> 11u); buf[n + 3] |= (uint8_t)(t[2] << 2u); buf[n + 4] = (uint8_t)(t[2] >> 6u); buf[n + 4] |= (uint8_t)(t[3] << 7u); buf[n + 5] = (uint8_t)(t[3] >> 1u); buf[n + 6] = (uint8_t)(t[3] >> 9u); buf[n + 6] |= (uint8_t)(t[4] << 4u); buf[n + 7] = (uint8_t)(t[4] >> 4u); buf[n + 8] = (uint8_t)(t[4] >> 12u); buf[n + 8] |= (uint8_t)(t[5] << 1u); buf[n + 9] = (uint8_t)(t[5] >> 7u); buf[n + 9] |= (uint8_t)(t[6] << 6u); buf[n + 10] = (uint8_t)(t[6] >> 2u); buf[n + 11] = (uint8_t)(t[6] >> 10u); buf[n + 11] |= (uint8_t)(t[7] << 3u); buf[n + 12] = (uint8_t)(t[7] >> 5u); } } // bits has only this three values. return; } static void BitUnPake(const uint8_t *v, uint32_t w[MLDSA_N], uint32_t bits, uint32_t b) { uint32_t t[8] = {0}; uint32_t i; uint32_t n; if (bits == 3u) { for (i = 0; i < MLDSA_N / 8; i++) { n = bits * i; t[0] = (v[n + 0]) & 0x07; t[1] = (v[n + 0] >> 3u) & 0x07; t[2] = ((v[n + 0] >> 6u) | (v[n + 1] << 2u)) & 0x07; t[3] = (v[n + 1u] >> 1u) & 0x07; t[4] = (v[n + 1u] >> 4u) & 0x07; t[5] = ((v[n + 1u] >> 7u) | (v[n + 2] << 1u)) & 0x07; t[6] = (v[n + 2u] >> 2u) & 0x07; t[7] = (v[n + 2u] >> 5u) & 0x07; for (uint32_t j = 0; j < 8; j++) { w[i * 8 + j] = b - t[j]; } } } else if (bits == 4u) { for (i = 0; i < MLDSA_N / 2; i++) { t[0] = v[i] & 0x0f; t[1] = (v[i] >> 4u) & 0x0f; w[i * 2] = b - t[0]; w[i * 2 + 1] = b - t[1]; } } else if (bits == MLDSA_D) { for (i = 0; i < MLDSA_N / 8; i++) { n = bits * i; t[0] = (v[n + 0] | ((uint32_t)v[n + 1] << 8u)) & 0x1fff; t[1] = (v[n + 1] >> 5u | ((uint32_t)v[n + 2u] << 3u) | ((uint32_t)v[n + 3u] << 11u)) & 0x1fff; t[2] = (v[n + 3u] >> 2u | ((uint32_t)v[n + 4u] << 6u)) & 0x1fff; t[3] = (v[n + 4u] >> 7u | ((uint32_t)v[n + 5u] << 1u) | ((uint32_t)v[n + 6u] << 9u)) & 0x1fff; t[4] = (v[n + 6u] >> 4u | ((uint32_t)v[n + 7u] << 4u) | ((uint32_t)v[n + 8u] << 12u)) & 0x1fff; t[5] = (v[n + 8u] >> 1u | ((uint32_t)v[n + 9u] << 7u)) & 0x1fff; t[6] = (v[n + 9u] >> 6u | ((uint32_t)v[n + 10u] << 2u) | ((uint32_t)v[n + 11u] << 10u)) & 0x1fff; t[7] = (v[n + 11u] >> 3u | ((uint32_t)v[n + 12u] << 5u)) & 0x1fff; for (uint32_t j = 0; j < 8; j++) { w[i * 8 + j] = b - t[j]; } } } // bits has only this three values. return; } static void SignBitPack(uint8_t *buf, uint32_t w[MLDSA_N], uint32_t bits, uint32_t b) { uint32_t t[4] = {0}; uint32_t i; uint32_t n; if (bits == GAMMA_BITS_OF_MLDSA_44) { for (i = 0; i < MLDSA_N / 4; i++) { for (uint32_t j = 0; j < 4; j++) { t[j] = b - w[i * 4 + j]; } n = 9 * i; buf[n + 0] = (uint8_t)t[0]; buf[n + 1u] = (uint8_t)(t[0] >> 8u); buf[n + 2u] = (uint8_t)(t[0] >> 16u | t[1] << 2u); buf[n + 3u] = (uint8_t)(t[1] >> 6u); buf[n + 4u] = (uint8_t)(t[1] >> 14u | t[2] << 4u); buf[n + 5u] = (uint8_t)(t[2] >> 4u); buf[n + 6u] = (uint8_t)(t[2] >> 12u | t[3] << 6u); buf[n + 7u] = (uint8_t)(t[3] >> 2u); buf[n + 8u] = (uint8_t)(t[3] >> 10u); } } else if (bits == GAMMA_BITS_OF_MLDSA_65_87) { for (i = 0; i < MLDSA_N / 2; i++) { t[0] = b - w[i * 2]; t[1] = b - w[i * 2 + 1u]; n = 5 * i; buf[n + 0] = (uint8_t)t[0]; buf[n + 1u] = (uint8_t)(t[0] >> 8u); buf[n + 2u] = (uint8_t)(t[0] >> 16u | t[1] << 4u); buf[n + 3u] = (uint8_t)(t[1] >> 4u); buf[n + 4u] = (uint8_t)(t[1] >> 12u); } } // bits has only this two values. return; } static void SignBitUnPake(const uint8_t *v, uint32_t w[MLDSA_N], uint32_t bits, uint32_t b) { uint32_t t[4] = {0}; uint32_t i; uint32_t n; if (bits == GAMMA_BITS_OF_MLDSA_44) { for (i = 0; i < MLDSA_N / 4; i++) { n = 9 * i; t[0] = (v[n + 0] | ((uint32_t)v[n + 1] << 8) | ((uint32_t)v[n + 2] << 16)) & 0x3ffff; t[1] = (v[n + 2u] >> 2u | ((uint32_t)v[n + 3u] << 6u) | ((uint32_t)v[n + 4u] << 14u)) & 0x3ffff; t[2] = (v[n + 4u] >> 4u | ((uint32_t)v[n + 5u] << 4u) | ((uint32_t)v[n + 6u] << 12u)) & 0x3ffff; t[3] = (v[n + 6u] >> 6u | ((uint32_t)v[n + 7u] << 2u) | ((uint32_t)v[n + 8u] << 10u)) & 0x3ffff; n = 4 * i; w[n] = b - t[0]; w[n + 1u] = b - t[1]; w[n + 2u] = b - t[2]; w[n + 3u] = b - t[3]; } } else if (bits == GAMMA_BITS_OF_MLDSA_65_87) { for (i = 0; i < MLDSA_N / 2; i++) { n = 5 * i; t[0] = (v[n + 0] | ((uint32_t)v[n + 1] << 8u) | ((uint32_t)v[n + 2u] << 16u)) & 0xfffff; t[1] = (v[n + 2u] >> 4u | ((uint32_t)v[n + 3u] << 4u) | ((uint32_t)v[n + 4u] << 12u)) & 0xfffff; w[i * 2] = b - t[0]; w[i * 2 + 1u] = b - t[1]; } } // bits has only this two values. return; } // Algorithm 22 pkEncode(ρ, t1) static void PkEncode(const CRYPT_ML_DSA_Ctx *ctx, uint8_t *seed, int32_t *t[MLDSA_K_MAX]) { (void)memcpy_s(ctx->pubKey, ctx->pubLen, seed, MLDSA_PUBLIC_SEED_LEN); for (int32_t i = 0; i < ctx->info->k; i++) { // 10 is bitlen(𝑞−1) − d ByteEncode(ctx->pubKey + MLDSA_PUBLIC_SEED_LEN + i * MLDSA_PUBKEY_POLYT_PACKEDBYTES, (uint32_t *)t[i], 10); } } // Algorithm 23 pkDecode(pk) static void PkDecode(const CRYPT_ML_DSA_Ctx *ctx, uint8_t *seed, int32_t *t[MLDSA_K_MAX]) { (void)memcpy_s(seed, MLDSA_PUBLIC_SEED_LEN, ctx->pubKey, MLDSA_PUBLIC_SEED_LEN); for (int32_t i = 0; i < ctx->info->k; i++) { // 10 is bitlen(𝑞−1) − d ByteDecode(ctx->pubKey + MLDSA_PUBLIC_SEED_LEN + i * MLDSA_PUBKEY_POLYT_PACKEDBYTES, (uint32_t *)t[i], 10); } } // Algorithm 24 skEncode(ρ, K,tr, 𝐬1, 𝐬2, t0) static void SkEncode(const CRYPT_ML_DSA_Ctx *ctx, uint8_t *pubSeed, uint8_t *signSeed, uint8_t *tr, MLDSA_KeyGenMatrixSt *st) { uint32_t i; uint32_t bitLen = ctx->info->eta == 2 ? 3 : 4; // 3 and 4 is bitlen(2𝜂) uint32_t index = MLDSA_PUBLIC_SEED_LEN; (void)memcpy_s(ctx->prvKey, ctx->prvLen, pubSeed, MLDSA_PUBLIC_SEED_LEN); (void)memcpy_s(ctx->prvKey + index, ctx->prvLen - index, signSeed, MLDSA_SIGNING_SEED_LEN); index += MLDSA_SIGNING_SEED_LEN; (void)memcpy_s(ctx->prvKey + index, ctx->prvLen - index, tr, MLDSA_PRIVATE_SEED_LEN); index += MLDSA_PRIVATE_SEED_LEN; for (i = 0; i < ctx->info->l; i++) { BitPack(ctx->prvKey + index, (uint32_t *)st->s1[i], bitLen, ctx->info->eta); index += MLDSA_N_BYTE * bitLen; } for (i = 0; i < ctx->info->k; i++) { BitPack(ctx->prvKey + index, (uint32_t *)st->s2[i], bitLen, ctx->info->eta); index += MLDSA_N_BYTE * bitLen; } for (i = 0; i < ctx->info->k; i++) { BitPack(ctx->prvKey + index, (uint32_t *)st->t0[i], MLDSA_D, 4096); // 2^(𝑑−1) == 4096 index += MLDSA_N_BYTE * MLDSA_D; } } // Algorithm 25 skDecode(sk) static void SkDecode(const CRYPT_ML_DSA_Ctx *ctx, uint8_t *pubSeed, uint8_t *signSeed, uint8_t *tr, MLDSA_SignMatrixSt *st) { uint32_t i; uint32_t bitLen = ctx->info->eta == 2 ? 3 : 4; // 3 and 4 is bitlen(2𝜂) uint32_t index = MLDSA_PUBLIC_SEED_LEN; (void)memcpy_s(pubSeed, MLDSA_PUBLIC_SEED_LEN, ctx->prvKey, MLDSA_PUBLIC_SEED_LEN); (void)memcpy_s(signSeed, MLDSA_SIGNING_SEED_LEN, ctx->prvKey + index, MLDSA_SIGNING_SEED_LEN); index += MLDSA_SIGNING_SEED_LEN; (void)memcpy_s(tr, MLDSA_PRIVATE_SEED_LEN, ctx->prvKey + index, MLDSA_PRIVATE_SEED_LEN); index += MLDSA_PRIVATE_SEED_LEN; for (i = 0; i < ctx->info->l; i++) { BitUnPake(ctx->prvKey + index, (uint32_t *)st->s1[i], bitLen, ctx->info->eta); index += MLDSA_N_BYTE * bitLen; } for (i = 0; i < ctx->info->k; i++) { BitUnPake(ctx->prvKey + index, (uint32_t *)st->s2[i], bitLen, ctx->info->eta); index += MLDSA_N_BYTE * bitLen; } for (i = 0; i < ctx->info->k; i++) { BitUnPake(ctx->prvKey + index, (uint32_t *)st->t0[i], MLDSA_D, 4096); // 2^(𝑑−1) == 4096 index += MLDSA_N_BYTE * MLDSA_D; } } static void SignCalNtt(const CRYPT_ML_DSA_Ctx *ctx, MLDSA_SignMatrixSt *st) { uint32_t i; for (i = 0; i < ctx->info->l; i++) { MLDSA_ComputesNTT(st->s1[i]); } for (i = 0; i < ctx->info->k; i++) { MLDSA_ComputesNTT(st->s2[i]); } for (i = 0; i < ctx->info->k; i++) { MLDSA_ComputesNTT(st->t0[i]); } } // Algorithm 34 ExpandMask(ρ, μ) static int32_t ExpandMask(const CRYPT_ML_DSA_Ctx *ctx, int32_t *y[MLDSA_L_MAX], uint8_t *p, uint16_t u) { uint16_t n = 0; uint8_t v[640]; // The maximum length is 20 * 32 == 640 byte. uint32_t bits = (ctx->info->k == K_VALUE_OF_MLDSA_44) ? GAMMA_BITS_OF_MLDSA_44 : GAMMA_BITS_OF_MLDSA_65_87; for (uint16_t i = 0; i < ctx->info->l; i++) { n = u + i; p[MLDSA_PRIVATE_SEED_LEN] = (uint8_t)n; p[MLDSA_PRIVATE_SEED_LEN + 1] = (uint8_t)(n >> BITS_OF_BYTE); // 𝑣 ← H(ρ′, 32𝑐) int32_t ret = HashFuncH(p, MLDSA_PRIVATE_SEED_LEN + 2, NULL, 0, v, 32 * bits); if (ret != CRYPT_SUCCESS) { return ret; } SignBitUnPake(v, (uint32_t *)y[i], bits, ctx->info->gamma1); } return CRYPT_SUCCESS; } // Algorithm 36 Decompose(r) static void Decompose(const CRYPT_ML_DSA_Ctx *ctx, int32_t r, int32_t *r1, int32_t *r0) { int32_t t = (int32_t)(((uint32_t)r + 0x7f) >> 7u); if (ctx->info->k == K_VALUE_OF_MLDSA_44) { // If is MLDSA44 // This is Barrett Modular Multiplication, mod is 2𝛾2. t = (t * 11275u + (1 << 23u)) >> 24u; t ^= ((43 - t) >> 31u) & t; } else { t = (t * 1025u + (1 << 21u)) >> 22u; t &= 0x0f; } *r0 = r - t * 2 * ctx->info->gamma2; // r1 ← (r+ − r0)/(2𝛾2) *r0 -= (((MLDSA_Q - 1) / 2 - *r0) >> 31u) & MLDSA_Q; *r1 = t; // high bits. return; } static void ComputesW(const CRYPT_ML_DSA_Ctx *ctx, int32_t *w[MLDSA_L_MAX], int32_t *w1[MLDSA_L_MAX], int32_t *matrix[MLDSA_K_MAX][MLDSA_L_MAX], int32_t *y[MLDSA_L_MAX]) { for (uint8_t i = 0; i < ctx->info->k; i++) { MatrixMul(ctx, w[i], matrix[i], y); MLDSA_ComputesINVNTT(w[i]); for (int32_t j = 0; j < MLDSA_N; j++) { w[i][j] = w[i][j] < 0 ? (w[i][j] + MLDSA_Q) : w[i][j]; Decompose(ctx, w[i][j], &w1[i][j], &w[i][j]); } } } // Algorithm 28 w1Encode(w1) static void W1Encode(const CRYPT_ML_DSA_Ctx *ctx, uint8_t *buf, int32_t *w[MLDSA_K_MAX]) { uint32_t bitLen = ctx->info->k == K_VALUE_OF_MLDSA_44 ? 6 : 4; // Only the bitLen value of MLDSA44 is 6. uint32_t blockSize = ctx->info->k == K_VALUE_OF_MLDSA_44 ? 192 : 128; // MLDSA44 blockSize is 192, other is 128. for (uint32_t i = 0; i < ctx->info->k; i++) { ByteEncode(buf + i * blockSize, (uint32_t *)w[i], bitLen); } } // Algorithm 29 SampleInBall(ρ) static int32_t SampleInBall(const CRYPT_ML_DSA_Ctx *ctx, const uint8_t *p, uint32_t pLen, int32_t c[MLDSA_N]) { uint8_t s[CRYPT_SHAKE256_BLOCKSIZE] = {0}; uint32_t sLen = CRYPT_SHAKE256_BLOCKSIZE; uint64_t h = 0; uint32_t index = 0; uint8_t j = 0; int32_t ret; const EAL_MdMethod *hashMethod = EAL_MdFindDefaultMethod(CRYPT_MD_SHAKE256); if (hashMethod == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_NOT_SUPPORT); return CRYPT_EAL_ALG_NOT_SUPPORT; } void *mdCtx = hashMethod->newCtx(NULL, hashMethod->id); if (mdCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } GOTO_ERR_IF(hashMethod->init(mdCtx, NULL), ret); GOTO_ERR_IF(hashMethod->update(mdCtx, p, pLen), ret); GOTO_ERR_IF(hashMethod->squeeze(mdCtx, s, sLen), ret); for (index = 0; index < 8; index++) { // 𝑠 ← H.Squeeze(ctx, 8) h = h | ((uint64_t)s[index] << (8 * index)); } for (uint32_t i = MLDSA_N - ctx->info->tau; i < MLDSA_N; i++) { do { if (index == CRYPT_SHAKE256_BLOCKSIZE) { GOTO_ERR_IF(hashMethod->squeeze(mdCtx, s, sLen), ret); index = 0; } j = s[index]; index++; } while (j > i); c[i] = c[j]; c[j] = 1 - ((h & 1) << 1); h >>= 1; } ERR: hashMethod->freeCtx(mdCtx); return ret; } static void MLDSA_VectorsAdd(int32_t *t, int32_t *a, int32_t *b) { for (uint32_t i = 0; i < MLDSA_N; i++) { t[i] = a[i] + b[i]; MLDSA_MOD_Q(t[i]); } } static void MLDSA_VectorsSub(int32_t *t, int32_t *a, int32_t *b) { for (uint32_t i = 0; i < MLDSA_N; i++) { t[i] = a[i] - b[i]; MLDSA_MOD_Q(t[i]); } } static void ComputesZ(const CRYPT_ML_DSA_Ctx *ctx, int32_t *y[MLDSA_L_MAX], int32_t *c, int32_t *s[MLDSA_L_MAX], int32_t *z[MLDSA_L_MAX]) { for (uint8_t i = 0; i < ctx->info->l; i++) { VectorsMul(z[i], c, s[i]); MLDSA_ComputesINVNTT(z[i]); MLDSA_VectorsAdd(z[i], y[i], z[i]); } } static bool ValidityChecks(int32_t *z, uint32_t t) { uint32_t n; for (uint32_t j = 0; j < MLDSA_N; j++) { n = z[j] >> 31; // Shift rightwards by 31 bits. n = z[j] - (n & ((uint32_t)z[j] << 1)); if (n >= t) { return false; } } return true; } static bool ValidityChecksL(const CRYPT_ML_DSA_Ctx *ctx, int32_t *z[MLDSA_L_MAX], uint32_t t) { for (uint8_t i = 0; i < ctx->info->l; i++) { if (ValidityChecks(z[i], t) == false) { return false; } } return true; } static bool ValidityChecksK(const CRYPT_ML_DSA_Ctx *ctx, int32_t *z[MLDSA_K_MAX], uint32_t t) { for (uint8_t i = 0; i < ctx->info->k; i++) { if (ValidityChecks(z[i], t) == false) { return false; } } return true; } static void ComputesR(const CRYPT_ML_DSA_Ctx *ctx, int32_t *c, MLDSA_SignMatrixSt *st) { for (uint8_t i = 0; i < ctx->info->k; i++) { VectorsMul(st->cs2[i], c, st->s2[i]); MLDSA_ComputesINVNTT(st->cs2[i]); MLDSA_VectorsSub(st->r0[i], st->w[i], st->cs2[i]); } } static void ComputesCT(const CRYPT_ML_DSA_Ctx *ctx, int32_t *c, int32_t *t[MLDSA_K_MAX], int32_t *ct[MLDSA_K_MAX]) { for (uint8_t i = 0; i < ctx->info->k; i++) { VectorsMul(ct[i], c, t[i]); MLDSA_ComputesINVNTT(ct[i]); for (uint32_t j = 0; j < MLDSA_N; j++) { int32_t m = (int32_t)(((uint32_t)ct[i][j] + (1 << 22)) >> 23); // m = (ct + 2^22) / 2^23 ct[i][j] = ct[i][j] - m * MLDSA_Q; } } } static uint32_t MakeHint(const CRYPT_ML_DSA_Ctx *ctx, MLDSA_SignMatrixSt *st) { uint32_t num = 0; for (uint32_t i = 0; i < ctx->info->k; i++) { MLDSA_VectorsAdd(st->w[i], st->w[i], st->ct0[i]); MLDSA_VectorsSub(st->w[i], st->w[i], st->cs2[i]); for (uint32_t j = 0; j < MLDSA_N; j++) { if (st->w[i][j] > (int32_t)ctx->info->gamma2 || st->w[i][j] < (0 - (int32_t)ctx->info->gamma2) || (st->w[i][j] == (0 - (int32_t)ctx->info->gamma2) && st->w1[i][j] != 0)) { st->h[i][j] = 1; num++; } else { st->h[i][j] = 0; } } } return num; } static void SigEncode(const CRYPT_ML_DSA_Ctx *ctx, uint8_t *out, uint32_t outLen, int32_t *z[MLDSA_L_MAX], int32_t *h[MLDSA_K_MAX]) { // // 𝛾1 bits of MLDSA44 is 18,𝛾1 bits of MLDSA65 and MLDSA87 is 20. uint32_t bits = (ctx->info->k == K_VALUE_OF_MLDSA_44) ? GAMMA_BITS_OF_MLDSA_44 : GAMMA_BITS_OF_MLDSA_65_87; uint32_t blockSize = MLDSA_N / BITS_OF_BYTE * bits; uint8_t *ptr = out; uint32_t index = 0; for (uint32_t i = 0; i < ctx->info->l; i++) { SignBitPack(ptr, (uint32_t *)z[i], bits, ctx->info->gamma1); ptr += blockSize; } (void)memset_s(ptr, outLen - blockSize * ctx->info->l, 0, outLen - blockSize * ctx->info->l); for (uint32_t i = 0; i < ctx->info->k; i++) { for (uint32_t j = 0; j < MLDSA_N; j++) { if (h[i][j] != 0) { ptr[index] = j; index++; } } ptr[ctx->info->omega + i] = index; } } static int32_t SigDecode(const CRYPT_ML_DSA_Ctx *ctx, const uint8_t *in, int32_t *z[MLDSA_L_MAX], int32_t *h[MLDSA_K_MAX]) { uint32_t bits = (ctx->info->k == K_VALUE_OF_MLDSA_44) ? GAMMA_BITS_OF_MLDSA_44 : GAMMA_BITS_OF_MLDSA_65_87; uint32_t blockSize = MLDSA_N / BITS_OF_BYTE * bits; const uint8_t *ptr = in; uint32_t index = 0; for (int32_t i = 0; i < ctx->info->l; i++) { SignBitUnPake(ptr, (uint32_t *)z[i], bits, ctx->info->gamma1); ptr += blockSize; } for (int32_t i = 0; i < ctx->info->k; i++) { if (ptr[ctx->info->omega + i] < index || ptr[ctx->info->omega + i] > ctx->info->omega) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_SIGN_DATA_ERROR); return CRYPT_MLDSA_SIGN_DATA_ERROR; } uint32_t first = index; (void)memset_s(h[i], sizeof(int32_t) * MLDSA_N, 0, sizeof(int32_t) * MLDSA_N); while (index < ptr[ctx->info->omega + i]) { if (index > first && (ptr[index - 1] >= ptr[index])) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_SIGN_DATA_ERROR); return CRYPT_MLDSA_SIGN_DATA_ERROR; } h[i][ptr[index]] = 1; index++; } } for (int32_t i = index; i < (ctx->info->omega - 1); i++) { RETURN_RET_IF(ptr[i] != 0, CRYPT_MLDSA_SIGN_DATA_ERROR); } return CRYPT_SUCCESS; } static void ComputesApproxW(const CRYPT_ML_DSA_Ctx *ctx, MLDSA_VerifyMatrixSt *st, int32_t *c, int32_t *w[MLDSA_K_MAX]) { MLDSA_ComputesNTT(c); for (uint8_t i = 0; i < ctx->info->l; i++) { MLDSA_ComputesNTT(st->z[i]); } for (uint8_t i = 0; i < ctx->info->k; i++) { for (int32_t j = 0; j < MLDSA_N; j++) { // t1 ⋅ 2^𝑑 st->t1[i][j] = (int32_t)((uint32_t)st->t1[i][j] << MLDSA_D); } // NTT(t1 ⋅ 2^𝑑) MLDSA_ComputesNTT(st->t1[i]); // NTT(𝑐) ∘ NTT(t1 ⋅ 2^𝑑) VectorsMul(st->t1[i], st->t1[i], c); // A ∘ NTT(z) MatrixMul(ctx, w[i], st->matrix[i], st->z); MLDSA_VectorsSub(w[i], w[i], st->t1[i]); MLDSA_ComputesINVNTT(w[i]); } } static void UseHint(const CRYPT_ML_DSA_Ctx *ctx, int32_t *h[MLDSA_K_MAX], int32_t *w[MLDSA_K_MAX]) { int32_t r1; int32_t r0; for (uint8_t i = 0; i < ctx->info->k; i++) { for (uint32_t j = 0; j < MLDSA_N; j++) { if (w[i][j] < 0) { w[i][j] += MLDSA_Q; } Decompose(ctx, w[i][j], &r1, &r0); if (h[i][j] == 0) { w[i][j] = r1; continue; } if (ctx->info->gamma2 == 95232) { // 95232 is (MLDSA_Q-1) / 88; // 𝑚 ← (𝑞 − 1)/(2𝛾2) = 44 // If r0 > 0 return (r1 + 1) mod m else return (r1 − 1) mod m w[i][j] = (r0 > 0) ? ((r1 == 43) ? 0 : (r1 + 1)) : ((r1 == 0) ? 43 : (r1 - 1)); // 43 is (m - 1) continue; } w[i][j] = ((r0 > 0) ? (r1 + 1) : (r1 - 1)) & 0x0f; } } } // Referenced from NIST.FIPS.204 Algorithm 6 ML-DSA.KeyGen_internal(𝑑) int32_t MLDSA_KeyGenInternal(CRYPT_ML_DSA_Ctx *ctx, uint8_t *d) { uint8_t k = ctx->info->k; uint8_t l = ctx->info->l; uint8_t seed[MLDSA_SEED_EXTEND_BYTES_LEN] = { 0 }; uint8_t digest[MLDSA_EXPANDED_SEED_BYTES_LEN] = { 0 }; uint8_t tr[MLDSA_TR_MSG_LEN] = { 0 }; MLDSA_KeyGenMatrixSt st = { 0 }; int32_t ret; GOTO_ERR_IF(MLDSAKeyGenCreateMatrix(k, l, &st), ret); // 32-byte random seed + 1 byte 'k' + 1 byte 'l' (void)memcpy_s(seed, sizeof(seed), d, MLDSA_SEED_BYTES_LEN); seed[MLDSA_SEED_BYTES_LEN] = k; seed[MLDSA_SEED_BYTES_LEN + 1] = l; // (ρ, ρ′, K) ∈ B32 × B64 × B32 ← H(𝜉||IntegerToBytes(k, 1)||IntegerToBytes(ℓ, 1), 128) GOTO_ERR_IF(HashFuncH(seed, sizeof(seed), NULL, 0, digest, MLDSA_EXPANDED_SEED_BYTES_LEN), ret); uint8_t *pubSeed = digest; uint8_t *prvSeed = digest + MLDSA_PUBLIC_SEED_LEN; uint8_t *signSeed = digest + MLDSA_PUBLIC_SEED_LEN + MLDSA_PRIVATE_SEED_LEN; // A ← ExpandA(ρ) GOTO_ERR_IF(ExpandA(ctx, pubSeed, st.matrix), ret); // (𝐬1, 𝐬2) ← ExpandS(ρ′) GOTO_ERR_IF(ExpandS(ctx, prvSeed, st.s1, st.s2), ret); // t ← NTT^−1(A ∘ NTT(𝐬1)) + 𝐬2 ComputesNTT(ctx, st.s1, st.s1Ntt); ComputesT(ctx, st.t1, st.matrix, st.s1Ntt, st.s2); // t = As1 + s2 // (t1, t0) ← Power2Round(t) ComputesPower2Round(ctx, st.t0, st.t1); // pk ← pkEncode(ρ, t1) PkEncode(ctx, pubSeed, st.t1); // tr ← H(pk, 64) GOTO_ERR_IF(HashFuncH(ctx->pubKey, ctx->pubLen, NULL, 0, tr, MLDSA_TR_MSG_LEN), ret); // Step 9 // sk ← skEncode(ρ, K, tr, 𝐬1, 𝐬2, t0) SkEncode(ctx, pubSeed, signSeed, tr, &st); // Step 10 ERR: BSL_SAL_ClearFree(st.bufAddr, st.bufSize); BSL_SAL_CleanseData(seed, sizeof(seed)); BSL_SAL_CleanseData(digest, sizeof(digest)); return ret; } // Referenced from NIST.FIPS.204 Algorithm 7 ML-DSA.Sign_internal(sk, 𝑀′, r𝑛𝑑) int32_t MLDSA_SignInternal(const CRYPT_ML_DSA_Ctx *ctx, CRYPT_Data *msg, uint8_t *out, uint32_t *outLen, uint8_t *rand) { int32_t ret = CRYPT_SUCCESS; uint8_t pubSeed[MLDSA_PUBLIC_SEED_LEN]; uint8_t uBuf[MLDSA_XOF_MSG_LEN]; uint8_t tr[MLDSA_TR_MSG_LEN]; uint8_t signSeed[MLDSA_SIGNING_SEED_LEN + MLDSA_SEED_BYTES_LEN]; (void)memcpy_s(signSeed + MLDSA_SIGNING_SEED_LEN, MLDSA_SEED_BYTES_LEN, rand, MLDSA_SEED_BYTES_LEN); // The w1Len length of MLDSA44 and MLDSA65 is 768, and the w1Len length of MLDSA87 is 1024. uint32_t w1Len = (ctx->info->k == 4 || ctx->info->k == 6) ? 768 : 1024; uint8_t *w1Buf = BSL_SAL_Malloc(w1Len); RETURN_RET_IF(w1Buf == NULL, CRYPT_MEM_ALLOC_FAIL); MLDSA_SignMatrixSt st = { 0 }; GOTO_ERR_IF(MLDSASignCreateMatrix(ctx->info->k, ctx->info->l, &st), ret); // (ρ, K, tr, 𝐬1, 𝐬2, t0) ← skDecode(sk) SkDecode(ctx, pubSeed, signSeed, tr, &st); // NTT(s1), NTT(s2), NTT(t0) SignCalNtt(ctx, &st); // A ← ExpandA(ρ) GOTO_ERR_IF(ExpandA(ctx, pubSeed, st.matrix), ret); if (ctx->isMuMsg) { (void)memcpy_s(uBuf, MLDSA_XOF_MSG_LEN, msg->data, msg->len); } else { // μ ← H(BytesToBits(tr)||𝑀′, 64) GOTO_ERR_IF(HashFuncH(tr, MLDSA_TR_MSG_LEN, msg->data, msg->len, uBuf, MLDSA_XOF_MSG_LEN), ret); } // ρ″ ← H(K||r𝑛𝑑||μ, 64) uint8_t p[MLDSA_XOF_MSG_LEN + 2]; // The counter used 2 bytes. GOTO_ERR_IF(HashFuncH(signSeed, sizeof(signSeed), uBuf, MLDSA_XOF_MSG_LEN, p, MLDSA_XOF_MSG_LEN), ret); uint16_t u = 0; // The length of c is λ/4. uint32_t cBufLen = ctx->info->secBits / 4; int32_t c[MLDSA_N]; do { // y ← ExpandMask(ρ″, 𝜅) GOTO_ERR_IF(ExpandMask(ctx, st.y, p, u), ret); u = u + ctx->info->l; ComputesNTT(ctx, st.y, st.z); // w ← NTT−1(A ∘ NTT(y)); w1 ← HighBits(w) ComputesW(ctx, st.w, st.w1, st.matrix, st.z); // 𝑐 ← H(μ||w1Encode(w1), 𝜆/4) W1Encode(ctx, w1Buf, st.w1); GOTO_ERR_IF(HashFuncH(uBuf, MLDSA_XOF_MSG_LEN, w1Buf, w1Len, out, cBufLen), ret); (void)memset_s(c, sizeof(c), 0, sizeof(c)); // 𝑐 ∈ 𝑅𝑞 ← SampleInBall(c) SampleInBall(ctx, out, cBufLen, c); // 𝑐 ← NTT(𝑐) MLDSA_ComputesNTT(c); // ⟨⟨𝑐𝐬1⟩⟩ ← NTT^−1(𝑐 ∘ 𝐬1); z ← y + ⟨⟨𝑐𝐬1⟩⟩ ComputesZ(ctx, st.y, c, st.s1, st.z); // if ||z||∞ ≥ 𝛾1 − β if (ValidityChecksL(ctx, st.z, ctx->info->gamma1 - ctx->info->beta) == false) { continue; } // ⟨⟨𝑐𝐬2⟩⟩ ← NTT^−1(𝑐 ∘ 𝐬2); 𝐫0 ← LowBits(w − ⟨⟨𝑐𝐬2⟩⟩) ComputesR(ctx, c, &st); // if ||𝐫0||∞ ≥ 𝛾2 − β if (ValidityChecksK(ctx, st.r0, ctx->info->gamma2 - ctx->info->beta) == false) { continue; } // ⟨⟨𝑐t0⟩⟩ ← NTT^−1(𝑐 ∘ t0) ComputesCT(ctx, c, st.t0, st.ct0); // if ||⟨⟨𝑐t0⟩⟩||∞ ≥ 𝛾2 if (ValidityChecksK(ctx, st.ct0, ctx->info->gamma2) == false) { continue; } // h ← MakeHint(−⟨⟨𝑐t0⟩⟩, w − ⟨⟨𝑐𝐬2⟩⟩ + ⟨⟨𝑐t0⟩⟩) if (MakeHint(ctx, &st) > ctx->info->omega) { continue; } break; } while (true); *outLen = ctx->info->signatureLen; // σ ← sigEncode(𝑐, z̃ mod±𝑞, h) SigEncode(ctx, out + cBufLen, *outLen - cBufLen, st.z, st.h); ERR: BSL_SAL_ClearFree(st.bufAddr, st.bufSize); BSL_SAL_ClearFree(w1Buf, w1Len); BSL_SAL_CleanseData(signSeed, sizeof(signSeed)); return ret; } // Referenced from NIST.FIPS.204 Algorithm 8 ML-DSA.Verify_internal(pk, 𝑀′, σ) int32_t MLDSA_VerifyInternal(const CRYPT_ML_DSA_Ctx *ctx, CRYPT_Data *msg, const uint8_t *sign, uint32_t signLen) { (void)signLen; uint8_t k = ctx->info->k; uint8_t l = ctx->info->l; uint8_t pubSeed[MLDSA_PUBLIC_SEED_LEN]; uint8_t uBuf[MLDSA_XOF_MSG_LEN]; uint8_t cBuf[MLDSA_XOF_MSG_LEN]; uint8_t tr[MLDSA_TR_MSG_LEN]; uint32_t cBufLen = ctx->info->secBits / 4; MLDSA_VerifyMatrixSt st = { 0 }; int32_t c[MLDSA_N] = { 0 }; int32_t ret; // The w1Len length of MLDSA44 and MLDSA65 is 768, and the w1Len length of MLDSA87 is 1024. uint32_t w1Len = (k == 4 || k == 6) ? 768 : 1024; uint8_t *w1Buf = BSL_SAL_Malloc(w1Len); RETURN_RET_IF(w1Buf == NULL, CRYPT_MEM_ALLOC_FAIL); GOTO_ERR_IF(MLDSAVerifyCreateMatrix(k, l, &st), ret); // (ρ, t1) ← pkDecode(pk) PkDecode(ctx, pubSeed, st.t1); // (c,z,h) ← sigDecode(σ) GOTO_ERR_IF(SigDecode(ctx, sign + cBufLen, st.z, st.h), ret); // if ||z||∞ < 𝛾1 − β if (ValidityChecksL(ctx, st.z, ctx->info->gamma1 - ctx->info->beta) == false) { ret = CRYPT_MLDSA_SIGN_DATA_ERROR; goto ERR; } // A ← ExpandA(ρ) GOTO_ERR_IF(ExpandA(ctx, pubSeed, st.matrix), ret); if (ctx->isMuMsg) { (void)memcpy_s(uBuf, MLDSA_XOF_MSG_LEN, msg->data, msg->len); } else { // tr ← H(pk, 64) GOTO_ERR_IF(HashFuncH(ctx->pubKey, ctx->pubLen, NULL, 0, tr, MLDSA_TR_MSG_LEN), ret); // μ ← (H(BytesToBits(tr)||𝑀′, 64)) GOTO_ERR_IF(HashFuncH(tr, MLDSA_TR_MSG_LEN, msg->data, msg->len, uBuf, MLDSA_XOF_MSG_LEN), ret); } // 𝑐 ∈ 𝑅𝑞 ← SampleInBall(𝑐) SampleInBall(ctx, sign, cBufLen, c); // w′ ← NTT−1(A ∘ NTT(z) − NTT(𝑐) ∘ NTT(t1 ⋅ 2𝑑)) ComputesApproxW(ctx, &st, c, st.w); // w1′ ← UseHint(h, w′) UseHint(ctx, st.h, st.w); // c′← H(μ||w1Encode(w1′), 𝜆/4) W1Encode(ctx, w1Buf, st.w); GOTO_ERR_IF(HashFuncH(uBuf, MLDSA_XOF_MSG_LEN, w1Buf, w1Len, cBuf, cBufLen), ret); // If c and c' are not equal, verify failed. if (memcmp(sign, cBuf, cBufLen) != 0) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_VERIFY_FAIL); ret = CRYPT_MLDSA_VERIFY_FAIL; goto ERR; } ERR: BSL_SAL_Free(st.bufAddr); BSL_SAL_Free(w1Buf); return ret; } #ifdef HITLS_CRYPTO_MLDSA_CHECK // calculate public key from private key int32_t MLDSA_CalPub(const CRYPT_ML_DSA_Ctx *ctx, uint8_t *pub, uint32_t pubLen) { int32_t ret; MLDSA_SignMatrixSt st = { 0 }; uint8_t pubSeed[MLDSA_PUBLIC_SEED_LEN]; uint8_t kValue[MLDSA_SIGNING_SEED_LEN + MLDSA_SEED_BYTES_LEN]; int32_t tmp0[MLDSA_K_MAX][MLDSA_N]; int32_t tmp1[MLDSA_K_MAX][MLDSA_N]; int32_t tmp2[MLDSA_L_MAX][MLDSA_N]; uint8_t tr[MLDSA_TR_MSG_LEN]; int32_t *s1Ntt[MLDSA_L_MAX]; int32_t *t0[MLDSA_K_MAX]; int32_t *t1[MLDSA_K_MAX]; for (int32_t i = 0; i < ctx->info->k; i++) { t0[i] = tmp0[i]; t1[i] = tmp1[i]; } for (int32_t i = 0; i < ctx->info->l; i++) { s1Ntt[i] = tmp2[i]; } GOTO_ERR_IF(MLDSASignCreateMatrix(ctx->info->k, ctx->info->l, &st), ret); SkDecode(ctx, pubSeed, kValue, tr, &st); // get ρ, K, tr, s1, s2, t0 // A <- ExpandA(ρ) GOTO_ERR_IF(ExpandA(ctx, pubSeed, st.matrix), ret); // t <- NTT^−1(A ∘ NTT(s1)) + s2 ComputesNTT(ctx, st.s1, s1Ntt); ComputesT(ctx, t1, st.matrix, s1Ntt, st.s2); // t = As1 + s2 // (t1, t0) <- Power2Round(t) ComputesPower2Round(ctx, t0, t1); for (int32_t i = 0; i < ctx->info->k; i++) { if (memcmp(t0[i], st.t0[i], MLDSA_N) != 0) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_PAIRWISE_CHECK_FAIL); ret = CRYPT_MLDSA_PAIRWISE_CHECK_FAIL; goto ERR; } } // pk <- pkEncode(ρ, t1) if (memcpy_s(pub, pubLen, pubSeed, MLDSA_PUBLIC_SEED_LEN) != EOK) { BSL_ERR_PUSH_ERROR(CRYPT_MLDSA_LEN_NOT_ENOUGH); ret = CRYPT_MLDSA_LEN_NOT_ENOUGH; goto ERR; } for (int32_t i = 0; i < ctx->info->k; i++) { // 10 is bitlen(q − 1) − d ByteEncode(pub + MLDSA_PUBLIC_SEED_LEN + i * MLDSA_PUBKEY_POLYT_PACKEDBYTES, (uint32_t *)t1[i], 10); } ERR: BSL_SAL_ClearFree(st.bufAddr, st.bufSize); BSL_SAL_CleanseData(kValue, sizeof(kValue)); BSL_SAL_CleanseData(pubSeed, sizeof(pubSeed)); return ret; } #endif // HITLS_CRYPTO_MLDSA_CHECK #endif
2302_82127028/openHiTLS-examples_1508
crypto/mldsa/src/ml_dsa_core.c
C
unknown
46,137
/* * 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_ML_DSA_LOCAL_H #define CRYPT_ML_DSA_LOCAL_H #include "crypt_mldsa.h" #include "sal_atomic.h" #include "crypt_local_types.h" #define MLDSA_SEED_BYTES_LEN 32 #define MLDSA_PUBLIC_SEED_LEN 32 #define MLDSA_PRIVATE_SEED_LEN 64 #define MLDSA_SIGNING_SEED_LEN 32 #define MLDSA_EXPANDED_SEED_BYTES_LEN (MLDSA_PUBLIC_SEED_LEN + MLDSA_PRIVATE_SEED_LEN + MLDSA_SIGNING_SEED_LEN) #define MLDSA_SEED_EXTEND_BYTES_LEN (MLDSA_SEED_BYTES_LEN + 2) #define MLDSA_K_MAX 8 #define MLDSA_L_MAX 7 #define MLDSA_TR_MSG_LEN 64 #define MLDSA_XOF_MSG_LEN 64 #define MLDSA_N 256 #define MLDSA_N_BYTE 32 #define GAMMA_BITS_OF_MLDSA_44 18 #define GAMMA_BITS_OF_MLDSA_65_87 20 #define K_VALUE_OF_MLDSA_44 4 #define MLDSA_Q 8380417 #define MLDSA_QINV 58728449 // MLDSA_Q^(-1) mod 2^32 #define MLDSA_D 13 #define MLDSA_PUBKEY_POLYT_PACKEDBYTES 320 #define MLDSA_MAX_CTX_BYTES 255 #define MLDSA_SIGN_PREFIX_BYTES 2 // This is Barrett Modular Multiplication, mod is MLDSA_Q. #define MLDSA_MOD_Q(val) {int32_t m = ((val) + (1 << 22u)) >> 23u; (val) = (val) - m * MLDSA_Q;} typedef struct { uint8_t k; uint8_t l; uint8_t eta; uint8_t tau; uint32_t beta; uint32_t gamma1; uint32_t gamma2; uint8_t omega; uint32_t secBits; uint32_t publicKeyLen; uint32_t privateKeyLen; uint32_t signatureLen; } CRYPT_ML_DSA_Info; struct CryptMlDsaCtx { const CRYPT_ML_DSA_Info *info; uint8_t *pubKey; uint32_t pubLen; uint8_t *prvKey; uint32_t prvLen; uint8_t *ctxInfo; uint32_t ctxLen; bool isMuMsg; bool needEncodeCtx; bool needPreHash; bool deterministicSignFlag; BSL_SAL_RefCount references; void *libCtx; }; void MLDSA_ComputesNTT(int32_t w[MLDSA_N]); void MLDSA_ComputesINVNTT(int32_t w[MLDSA_N]); int32_t MLDSA_MontgomeryReduce(int64_t a); int32_t MLDSA_KeyGenInternal(CRYPT_ML_DSA_Ctx *ctx, uint8_t *d); int32_t MLDSA_SignInternal(const CRYPT_ML_DSA_Ctx *ctx, CRYPT_Data *msg, uint8_t *out, uint32_t *outLen, uint8_t *rand); int32_t MLDSA_VerifyInternal(const CRYPT_ML_DSA_Ctx *ctx, CRYPT_Data *msg, const uint8_t *sign, uint32_t signLen); #ifdef HITLS_CRYPTO_MLDSA_CHECK // calculate public key from private key int32_t MLDSA_CalPub(const CRYPT_ML_DSA_Ctx *ctx, uint8_t *pub, uint32_t pubLen); #endif // HITLS_CRYPTO_MLDSA_CHECK #endif // ML_DSA_LOCAL_H
2302_82127028/openHiTLS-examples_1508
crypto/mldsa/src/ml_dsa_local.h
C
unknown
2,913
/* * 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_MLDSA #include "ml_dsa_local.h" // mont = 2^32 mod q = -4186625 // ZETAS is NIST.FIPS.204 Zetas * mont static const int32_t ZETAS[MLDSA_N] = { 0, 25847, -2608894, -518909, 237124, -777960, -876248, 466468, 1826347, 2353451, -359251, -2091905, 3119733, -2884855, 3111497, 2680103, 2725464, 1024112, -1079900, 3585928, -549488, -1119584, 2619752, -2108549, -2118186, -3859737, -1399561, -3277672, 1757237, -19422, 4010497, 280005, 2706023, 95776, 3077325, 3530437, -1661693, -3592148, -2537516, 3915439, -3861115, -3043716, 3574422, -2867647, 3539968, -300467, 2348700, -539299, -1699267, -1643818, 3505694, -3821735, 3507263, -2140649, -1600420, 3699596, 811944, 531354, 954230, 3881043, 3900724, -2556880, 2071892, -2797779, -3930395, -1528703, -3677745, -3041255, -1452451, 3475950, 2176455, -1585221, -1257611, 1939314, -4083598, -1000202, -3190144, -3157330, -3632928, 126922, 3412210, -983419, 2147896, 2715295, -2967645, -3693493, -411027, -2477047, -671102, -1228525, -22981, -1308169, -381987, 1349076, 1852771, -1430430, -3343383, 264944, 508951, 3097992, 44288, -1100098, 904516, 3958618, -3724342, -8578, 1653064, -3249728, 2389356, -210977, 759969, -1316856, 189548, -3553272, 3159746, -1851402, -2409325, -177440, 1315589, 1341330, 1285669, -1584928, -812732, -1439742, -3019102, -3881060, -3628969, 3839961, 2091667, 3407706, 2316500, 3817976, -3342478, 2244091, -2446433, -3562462, 266997, 2434439, -1235728, 3513181, -3520352, -3759364, -1197226, -3193378, 900702, 1859098, 909542, 819034, 495491, -1613174, -43260, -522500, -655327, -3122442, 2031748, 3207046, -3556995, -525098, -768622, -3595838, 342297, 286988, -2437823, 4108315, 3437287, -3342277, 1735879, 203044, 2842341, 2691481, -2590150, 1265009, 4055324, 1247620, 2486353, 1595974, -3767016, 1250494, 2635921, -3548272, -2994039, 1869119, 1903435, -1050970, -1333058, 1237275, -3318210, -1430225, -451100, 1312455, 3306115, -1962642, -1279661, 1917081, -2546312, -1374803, 1500165, 777191, 2235880, 3406031, -542412, -2831860, -1671176, -1846953, -2584293, -3724270, 594136, -3776993, -2013608, 2432395, 2454455, -164721, 1957272, 3369112, 185531, -1207385, -3183426, 162844, 1616392, 3014001, 810149, 1652634, -3694233, -1799107, -3038916, 3523897, 3866901, 269760, 2213111, -975884, 1717735, 472078, -426683, 1723600, -1803090, 1910376, -1667432, -1104333, -260646, -3833893, -2939036, -2235985, -420899, -2286327, 183443, -976891, 1612842, -3545687, -554416, 3919660, -48306, -1362209, 3937738, 1400424, -846154, 1976782 }; // Referenced from NIST.FIPS.204 Algorithm 49 MontgomeryReduce(a) int32_t MLDSA_MontgomeryReduce(int64_t a) { int32_t t = (int32_t)(a * MLDSA_QINV); t = (int32_t)((a - (int64_t)t * MLDSA_Q) >> 32); // (a - t * q)/2^32 return t; } // Algorithm 41 NTT(w) void MLDSA_ComputesNTT(int32_t w[MLDSA_N]) { uint32_t m = 0; for (uint32_t len = MLDSA_N / 2; len > 0; len >>= 1) { for (uint32_t start = 0; start < MLDSA_N;) { m++; int32_t z = ZETAS[m]; for (uint32_t j = start; j < start + len; ++j) { int32_t t = MLDSA_MontgomeryReduce((int64_t)z * w[j + len]); w[j + len] = w[j] - t; w[j] = w[j] + t; } start = start + 2 * len; } } } // Algorithm 42 NTT^−1(w) void MLDSA_ComputesINVNTT(int32_t w[MLDSA_N]) { const int64_t f = 41978; // 41978 is mont^2/256 uint32_t m = MLDSA_N; for (uint32_t len = 1; len < MLDSA_N; len <<= 1) { for (uint32_t start = 0; start < MLDSA_N;) { m--; int32_t zeta = -ZETAS[m]; for (uint32_t j = start; j < start + len; j++) { int32_t t = w[j]; w[j] = t + w[j + len]; w[j + len] = t - w[j + len]; w[j + len] = MLDSA_MontgomeryReduce((int64_t)zeta * w[j + len]); } start = start + 2 * len; } } for (uint32_t j = 0; j < MLDSA_N; j++) { w[j] = MLDSA_MontgomeryReduce((int64_t)f * w[j]); } } #endif
2302_82127028/openHiTLS-examples_1508
crypto/mldsa/src/ml_dsa_ntt.c
C
unknown
4,782
/* * 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_ML_KEM_H #define CRYPT_ML_KEM_H #include <stdint.h> #include "crypt_types.h" #include "bsl_params.h" typedef struct CryptMlKemCtx CRYPT_ML_KEM_Ctx; CRYPT_ML_KEM_Ctx *CRYPT_ML_KEM_NewCtx(void); CRYPT_ML_KEM_Ctx *CRYPT_ML_KEM_NewCtxEx(void *libCtx); void CRYPT_ML_KEM_FreeCtx(CRYPT_ML_KEM_Ctx *ctx); CRYPT_ML_KEM_Ctx *CRYPT_ML_KEM_DupCtx(CRYPT_ML_KEM_Ctx *ctx); int32_t CRYPT_ML_KEM_Ctrl(CRYPT_ML_KEM_Ctx *ctx, int32_t opt, void *val, uint32_t len); int32_t CRYPT_ML_KEM_GenKey(CRYPT_ML_KEM_Ctx *ctx); int32_t CRYPT_ML_KEM_SetEncapsKey(CRYPT_ML_KEM_Ctx *ctx, const CRYPT_KemEncapsKey *ek); int32_t CRYPT_ML_KEM_GetEncapsKey(const CRYPT_ML_KEM_Ctx *ctx, CRYPT_KemEncapsKey *ek); int32_t CRYPT_ML_KEM_SetDecapsKey(CRYPT_ML_KEM_Ctx *ctx, const CRYPT_KemDecapsKey *dk); int32_t CRYPT_ML_KEM_GetDecapsKey(const CRYPT_ML_KEM_Ctx *ctx, CRYPT_KemDecapsKey *dk); #ifdef HITLS_BSL_PARAMS int32_t CRYPT_ML_KEM_SetEncapsKeyEx(CRYPT_ML_KEM_Ctx *ctx, const BSL_Param *para); int32_t CRYPT_ML_KEM_GetEncapsKeyEx(const CRYPT_ML_KEM_Ctx *ctx, BSL_Param *para); int32_t CRYPT_ML_KEM_SetDecapsKeyEx(CRYPT_ML_KEM_Ctx *ctx, const BSL_Param *para); int32_t CRYPT_ML_KEM_GetDecapsKeyEx(const CRYPT_ML_KEM_Ctx *ctx, BSL_Param *para); #endif int32_t CRYPT_ML_KEM_Cmp(const CRYPT_ML_KEM_Ctx *a, const CRYPT_ML_KEM_Ctx *b); int32_t CRYPT_ML_KEM_GetSecBits(const CRYPT_ML_KEM_Ctx *ctx); int32_t CRYPT_ML_KEM_Encaps(const CRYPT_ML_KEM_Ctx *ctx, uint8_t *cipher, uint32_t *cipherLen, uint8_t *share, uint32_t *shareLen); int32_t CRYPT_ML_KEM_Decaps(const CRYPT_ML_KEM_Ctx *ctx, uint8_t *cipher, uint32_t cipherLen, uint8_t *share, uint32_t *shareLen); #ifdef HITLS_CRYPTO_MLKEM_CHECK /** * @ingroup mlkem * @brief check the key pair consistency * * @param checkType [IN] check type * @param pkey1 [IN] mlkem key context structure * @param pkey2 [IN] mlkem key context structure * * @retval CRYPT_SUCCESS check success. * Others. For details, see error code in errno. */ int32_t CRYPT_ML_KEM_Check(uint32_t checkType, const CRYPT_ML_KEM_Ctx *pkey1, const CRYPT_ML_KEM_Ctx *pkey2); #endif // HITLS_CRYPTO_MLKEM_CHECK #endif // CRYPT_ML_KEM_H
2302_82127028/openHiTLS-examples_1508
crypto/mlkem/include/crypt_mlkem.h
C
unknown
2,713
/* * 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_MLKEM #include "securec.h" #include "crypt_errno.h" #include "crypt_algid.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "eal_pkey_local.h" #include "crypt_util_rand.h" #include "crypt_utils.h" #include "ml_kem_local.h" static const CRYPT_MlKemInfo ML_KEM_INFO[] = { {2, 3, 2, 10, 4, 128, 800, 1632, 768, 32, 512}, {3, 2, 2, 10, 4, 192, 1184, 2400, 1088, 32, 768}, {4, 2, 2, 11, 5, 256, 1568, 3168, 1568, 32, 1024} }; static const CRYPT_MlKemInfo *MlKemGetInfo(uint32_t bits) { for (uint32_t i = 0; i < sizeof(ML_KEM_INFO) / sizeof(ML_KEM_INFO[0]); i++) { if (ML_KEM_INFO[i].bits == bits) { return &ML_KEM_INFO[i]; } } return NULL; } CRYPT_ML_KEM_Ctx *CRYPT_ML_KEM_NewCtx(void) { CRYPT_ML_KEM_Ctx *keyCtx = BSL_SAL_Malloc(sizeof(CRYPT_ML_KEM_Ctx)); if (keyCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } (void)memset_s(keyCtx, sizeof(CRYPT_ML_KEM_Ctx), 0, sizeof(CRYPT_ML_KEM_Ctx)); BSL_SAL_ReferencesInit(&(keyCtx->references)); return keyCtx; } CRYPT_ML_KEM_Ctx *CRYPT_ML_KEM_NewCtxEx(void *libCtx) { CRYPT_ML_KEM_Ctx *ctx = CRYPT_ML_KEM_NewCtx(); if (ctx == NULL) { return NULL; } ctx->libCtx = libCtx; return ctx; } void CRYPT_ML_KEM_FreeCtx(CRYPT_ML_KEM_Ctx *ctx) { if (ctx == NULL) { return; } int ret = 0; BSL_SAL_AtomicDownReferences(&(ctx->references), &ret); if (ret > 0) { return; } BSL_SAL_CleanseData(ctx->dk, ctx->dkLen); BSL_SAL_FREE(ctx->dk); BSL_SAL_FREE(ctx->ek); BSL_SAL_ReferencesFree(&(ctx->references)); BSL_SAL_FREE(ctx); } static int32_t MlKemSetAlgInfo(CRYPT_ML_KEM_Ctx *ctx, void *val, uint32_t len) { if (len != sizeof(uint32_t)) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } if (ctx->info != NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_CTRL_INIT_REPEATED); return CRYPT_MLKEM_CTRL_INIT_REPEATED; } uint32_t bits = 0; int32_t keyType = *(int32_t*)val; if (keyType == CRYPT_KEM_TYPE_MLKEM_512) { bits = 512; // MLKEM512 } else if (keyType == CRYPT_KEM_TYPE_MLKEM_768) { bits = 768; // MLKEM768 } else if (keyType == CRYPT_KEM_TYPE_MLKEM_1024) { bits = 1024; // MLKEM1024 } const CRYPT_MlKemInfo *info = MlKemGetInfo(bits); if (info == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NOT_SUPPORT); return CRYPT_NOT_SUPPORT; } ctx->info = info; return CRYPT_SUCCESS; } CRYPT_ML_KEM_Ctx *CRYPT_ML_KEM_DupCtx(CRYPT_ML_KEM_Ctx *ctx) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return NULL; } CRYPT_ML_KEM_Ctx *newCtx = CRYPT_ML_KEM_NewCtx(); if (newCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } if (ctx->info != NULL) { newCtx->info = ctx->info; } if (ctx->ek != NULL) { newCtx->ek = BSL_SAL_Dump(ctx->ek, ctx->ekLen); if (newCtx->ek == NULL) { CRYPT_ML_KEM_FreeCtx(newCtx); return NULL; } newCtx->ekLen = ctx->ekLen; } if (ctx->dk != NULL) { newCtx->dk = BSL_SAL_Dump(ctx->dk, ctx->dkLen); if (newCtx->dk == NULL) { CRYPT_ML_KEM_FreeCtx(newCtx); return NULL; } newCtx->dkLen = ctx->dkLen; } newCtx->libCtx = ctx->libCtx; return newCtx; } static int32_t MlKemGetEncapsKeyLen(CRYPT_ML_KEM_Ctx *ctx, void *val, uint32_t len) { if (ctx->info == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_KEYINFO_NOT_SET); return CRYPT_MLKEM_KEYINFO_NOT_SET; } if (len != sizeof(uint32_t)) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } *(uint32_t*)val = ctx->info->encapsKeyLen; return CRYPT_SUCCESS; } static int32_t MlKemGetDecapsKeyLen(CRYPT_ML_KEM_Ctx *ctx, void *val, uint32_t len) { if (ctx->info == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_KEYINFO_NOT_SET); return CRYPT_MLKEM_KEYINFO_NOT_SET; } if (len != sizeof(uint32_t)) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } *(uint32_t*)val = ctx->info->decapsKeyLen; return CRYPT_SUCCESS; } static int32_t MlKemGetCipherTextLen(CRYPT_ML_KEM_Ctx *ctx, void *val, uint32_t len) { if (ctx->info == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_KEYINFO_NOT_SET); return CRYPT_MLKEM_KEYINFO_NOT_SET; } if (len != sizeof(uint32_t)) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } *(uint32_t*)val = ctx->info->cipherLen; return CRYPT_SUCCESS; } static int32_t MlKemGetSharedLen(CRYPT_ML_KEM_Ctx *ctx, void *val, uint32_t len) { if (ctx->info == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_KEYINFO_NOT_SET); return CRYPT_MLKEM_KEYINFO_NOT_SET; } if (len != sizeof(uint32_t)) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } *(uint32_t*)val = ctx->info->sharedLen; return CRYPT_SUCCESS; } int32_t CRYPT_ML_KEM_SetEncapsKey(CRYPT_ML_KEM_Ctx *ctx, const CRYPT_KemEncapsKey *ek) { if (ctx == NULL || ctx->info == NULL || ek == NULL || ek->data == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ek->len != ctx->info->encapsKeyLen) { BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_KEYLEN_ERROR); return CRYPT_MLKEM_KEYLEN_ERROR; } uint8_t *data = BSL_SAL_Dump(ek->data, ek->len); if (data == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } if (ctx->ek != NULL) { BSL_SAL_Free(ctx->ek); } ctx->ek = data; ctx->ekLen = ek->len; return CRYPT_SUCCESS; } int32_t CRYPT_ML_KEM_GetEncapsKey(const CRYPT_ML_KEM_Ctx *ctx, CRYPT_KemEncapsKey *ek) { if (ctx == NULL || ctx->info == NULL || ek == NULL || ek->data == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->ek == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_KEY_NOT_SET); return CRYPT_MLKEM_KEY_NOT_SET; } if (memcpy_s(ek->data, ek->len, ctx->ek, ctx->ekLen) != EOK) { BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_KEYLEN_ERROR); return CRYPT_MLKEM_KEYLEN_ERROR; } ek->len = ctx->ekLen; return CRYPT_SUCCESS; } int32_t CRYPT_ML_KEM_SetDecapsKey(CRYPT_ML_KEM_Ctx *ctx, const CRYPT_KemDecapsKey *dk) { if (ctx == NULL || ctx->info == NULL || dk == NULL || dk->data == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (dk->len != ctx->info->decapsKeyLen) { BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_KEYLEN_ERROR); return CRYPT_MLKEM_KEYLEN_ERROR; } uint8_t *data = BSL_SAL_Dump(dk->data, dk->len); if (data == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } if (ctx->dk != NULL) { BSL_SAL_CleanseData(ctx->dk, ctx->dkLen); BSL_SAL_Free(ctx->dk); } ctx->dk = data; ctx->dkLen = dk->len; return CRYPT_SUCCESS; } int32_t CRYPT_ML_KEM_GetDecapsKey(const CRYPT_ML_KEM_Ctx *ctx, CRYPT_KemDecapsKey *dk) { if (ctx == NULL || ctx->info == NULL || dk == NULL || dk->data == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->dk == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_KEY_NOT_SET); return CRYPT_MLKEM_KEY_NOT_SET; } if (memcpy_s(dk->data, dk->len, ctx->dk, ctx->dkLen) != EOK) { BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_KEYLEN_ERROR); return CRYPT_MLKEM_KEYLEN_ERROR; } dk->len = ctx->dkLen; return CRYPT_SUCCESS; } #ifdef HITLS_BSL_PARAMS int32_t CRYPT_ML_KEM_SetEncapsKeyEx(CRYPT_ML_KEM_Ctx *ctx, const BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_KemEncapsKey pub = {0}; (void)GetConstParamValue(para, CRYPT_PARAM_ML_KEM_PUBKEY, &pub.data, &pub.len); return CRYPT_ML_KEM_SetEncapsKey(ctx, &pub); } int32_t CRYPT_ML_KEM_GetEncapsKeyEx(const CRYPT_ML_KEM_Ctx *ctx, BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_KemEncapsKey pub = {0}; BSL_Param *paramPub = GetParamValue(para, CRYPT_PARAM_ML_KEM_PUBKEY, &pub.data, &(pub.len)); int32_t ret = CRYPT_ML_KEM_GetEncapsKey(ctx, &pub); if (ret != CRYPT_SUCCESS) { return ret; } paramPub->useLen = pub.len; return CRYPT_SUCCESS; } int32_t CRYPT_ML_KEM_SetDecapsKeyEx(CRYPT_ML_KEM_Ctx *ctx, const BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_KemDecapsKey prv = {0}; (void)GetConstParamValue(para, CRYPT_PARAM_ML_KEM_PRVKEY, &prv.data, &prv.len); return CRYPT_ML_KEM_SetDecapsKey(ctx, &prv); } int32_t CRYPT_ML_KEM_GetDecapsKeyEx(const CRYPT_ML_KEM_Ctx *ctx, BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_KemDecapsKey prv = {0}; BSL_Param *paramPrv = GetParamValue(para, CRYPT_PARAM_ML_KEM_PRVKEY, &prv.data, &(prv.len)); int32_t ret = CRYPT_ML_KEM_GetDecapsKey(ctx, &prv); if (ret != CRYPT_SUCCESS) { return ret; } paramPrv->useLen = prv.len; return CRYPT_SUCCESS; } #endif static int32_t MlKemCmpKey(uint8_t *a, uint32_t aLen, uint8_t *b, uint32_t bLen) { if (aLen != bLen) { BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_KEY_NOT_EQUAL); return CRYPT_MLKEM_KEY_NOT_EQUAL; } if (a != NULL && b != NULL) { if (memcmp(a, b, aLen) != 0) { BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_KEY_NOT_EQUAL); return CRYPT_MLKEM_KEY_NOT_EQUAL; } } if ((a != NULL) != (b != NULL)) { BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_KEY_NOT_EQUAL); return CRYPT_MLKEM_KEY_NOT_EQUAL; } return CRYPT_SUCCESS; } int32_t CRYPT_ML_KEM_Cmp(const CRYPT_ML_KEM_Ctx *a, const CRYPT_ML_KEM_Ctx *b) { if (a == NULL || b == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (a->info != b->info) { // The value of info must be one of the ML_KEM_INFO arrays. BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_KEY_NOT_EQUAL); return CRYPT_MLKEM_KEY_NOT_EQUAL; } if (MlKemCmpKey(a->ek, a->ekLen, b->ek, b->ekLen) != CRYPT_SUCCESS) { return CRYPT_MLKEM_KEY_NOT_EQUAL; } if (MlKemCmpKey(a->dk, a->dkLen, b->dk, b->dkLen) != CRYPT_SUCCESS) { return CRYPT_MLKEM_KEY_NOT_EQUAL; } return CRYPT_SUCCESS; } int32_t CRYPT_ML_KEM_GetSecBits(const CRYPT_ML_KEM_Ctx *ctx) { if (ctx == NULL || ctx->info == NULL) { return 0; } return (int32_t)ctx->info->secBits; } static int32_t CRYPT_ML_KEM_GetLen(const CRYPT_ML_KEM_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; } static int32_t MlKemCleanPubKey(CRYPT_ML_KEM_Ctx *ctx) { if (ctx->ek != NULL) { BSL_SAL_CleanseData(ctx->ek, ctx->ekLen); BSL_SAL_FREE(ctx->ek); ctx->ekLen = 0; } return CRYPT_SUCCESS; } int32_t CRYPT_ML_KEM_Ctrl(CRYPT_ML_KEM_Ctx *ctx, int32_t opt, void *val, uint32_t len) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (opt == CRYPT_CTRL_GET_SECBITS) { return CRYPT_ML_KEM_GetLen(ctx, (GetLenFunc)CRYPT_ML_KEM_GetSecBits, val, len); } if (opt == CRYPT_CTRL_CLEAN_PUB_KEY) { return MlKemCleanPubKey(ctx); } if (val == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } switch (opt) { case CRYPT_CTRL_SET_PARA_BY_ID: return MlKemSetAlgInfo(ctx, val, len); case CRYPT_CTRL_GET_PUBKEY_LEN: return MlKemGetEncapsKeyLen(ctx, val, len); case CRYPT_CTRL_GET_PRVKEY_LEN: return MlKemGetDecapsKeyLen(ctx, val, len); case CRYPT_CTRL_GET_CIPHERTEXT_LEN: return MlKemGetCipherTextLen(ctx, val, len); case CRYPT_CTRL_GET_SHARED_KEY_LEN: return MlKemGetSharedLen(ctx, val, len); default: BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_CTRL_NOT_SUPPORT); return CRYPT_MLKEM_CTRL_NOT_SUPPORT; } } static int32_t MlKemCreateKeyBuf(CRYPT_ML_KEM_Ctx *ctx) { if (ctx->dk == NULL) { uint8_t *dk = BSL_SAL_Malloc(ctx->info->decapsKeyLen); if (dk == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ctx->dk = dk; ctx->dkLen = ctx->info->decapsKeyLen; } if (ctx->ek == NULL) { uint8_t *ek = BSL_SAL_Malloc(ctx->info->encapsKeyLen); if (ek == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ctx->ek = ek; ctx->ekLen = ctx->info->encapsKeyLen; } return CRYPT_SUCCESS; } int32_t CRYPT_ML_KEM_GenKey(CRYPT_ML_KEM_Ctx *ctx) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->info == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_KEYINFO_NOT_SET); return CRYPT_MLKEM_KEYINFO_NOT_SET; } if (MlKemCreateKeyBuf(ctx) != CRYPT_SUCCESS) { return CRYPT_MEM_ALLOC_FAIL; } uint8_t d[MLKEM_SEED_LEN]; uint8_t z[MLKEM_SEED_LEN]; int32_t ret = CRYPT_RandEx(ctx->libCtx, d, MLKEM_SEED_LEN); RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); ret = CRYPT_RandEx(ctx->libCtx, z, MLKEM_SEED_LEN); RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); ret = MLKEM_KeyGenInternal(ctx, d, z); BSL_SAL_CleanseData(d, MLKEM_SEED_LEN); BSL_SAL_CleanseData(z, MLKEM_SEED_LEN); return ret; } static int32_t EncCapsInputCheck(const CRYPT_ML_KEM_Ctx *ctx, uint8_t *ct, uint32_t *ctLen, uint8_t *sk, uint32_t *skLen) { if (ctx == NULL || ctx->ek == NULL || ct == NULL || ctLen == NULL || sk == NULL || skLen == NULL) { return CRYPT_NULL_INPUT; } if (ctx->info == NULL) { return CRYPT_MLKEM_KEYINFO_NOT_SET; } if (*ctLen < ctx->info->cipherLen || *skLen < MLKEM_SHARED_KEY_LEN) { return CRYPT_MLKEM_LEN_NOT_ENOUGH; } return CRYPT_SUCCESS; } int32_t CRYPT_ML_KEM_Encaps(const CRYPT_ML_KEM_Ctx *ctx, uint8_t *cipher, uint32_t *cipherLen, uint8_t *share, uint32_t *shareLen) { int32_t ret = EncCapsInputCheck(ctx, cipher, cipherLen, share, shareLen); RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); uint8_t m[MLKEM_SEED_LEN]; ret = CRYPT_RandEx(ctx->libCtx, m, MLKEM_SEED_LEN); RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); ret = MLKEM_EncapsInternal(ctx, cipher, cipherLen, share, shareLen, m); BSL_SAL_CleanseData(m, MLKEM_SEED_LEN); return ret; } static int32_t DecCapsInputCheck(const CRYPT_ML_KEM_Ctx *ctx, uint8_t *ct, uint32_t ctLen, uint8_t *sk, uint32_t *skLen) { if (ctx == NULL || ctx->dk == NULL || ct == NULL || sk == NULL || skLen == NULL) { return CRYPT_NULL_INPUT; } if (ctx->info == NULL) { return CRYPT_MLKEM_KEYINFO_NOT_SET; } if (ctLen != ctx->info->cipherLen || *skLen < MLKEM_SHARED_KEY_LEN) { return CRYPT_MLKEM_LEN_NOT_ENOUGH; } return CRYPT_SUCCESS; } int32_t CRYPT_ML_KEM_Decaps(const CRYPT_ML_KEM_Ctx *ctx, uint8_t *cipher, uint32_t cipherLen, uint8_t *share, uint32_t *shareLen) { int32_t ret = DecCapsInputCheck(ctx, cipher, cipherLen, share, shareLen); RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); return MLKEM_DecapsInternal(ctx, cipher, cipherLen, share, shareLen); } #ifdef HITLS_CRYPTO_MLKEM_CHECK static int32_t MlKemKeyPairCheck(const CRYPT_ML_KEM_Ctx *pubKey, const CRYPT_ML_KEM_Ctx *prvKey) { if (pubKey == NULL || prvKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (pubKey->info == NULL || prvKey->info == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_KEYINFO_NOT_SET); return CRYPT_MLKEM_KEYINFO_NOT_SET; } if (pubKey->info->bits != prvKey->info->bits) { BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_PAIRWISE_CHECK_FAIL); return CRYPT_MLKEM_PAIRWISE_CHECK_FAIL; } uint32_t cipherLen = pubKey->info->cipherLen; uint8_t *ciphertext = BSL_SAL_Malloc(pubKey->info->cipherLen); if (ciphertext == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret; uint32_t sharedLen1 = MLKEM_SHARED_KEY_LEN; uint8_t sharedKey1[MLKEM_SHARED_KEY_LEN]; uint32_t sharedLen2 = MLKEM_SHARED_KEY_LEN; uint8_t sharedKey2[MLKEM_SHARED_KEY_LEN]; GOTO_ERR_IF(CRYPT_ML_KEM_Encaps(pubKey, ciphertext, &cipherLen, sharedKey1, &sharedLen1), ret); GOTO_ERR_IF(CRYPT_ML_KEM_Decaps(prvKey, ciphertext, cipherLen, sharedKey2, &sharedLen2), ret); if (sharedLen1 != sharedLen2 || memcmp(sharedKey1, sharedKey2, sharedLen1) != 0) { ret = CRYPT_MLKEM_PAIRWISE_CHECK_FAIL; BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_PAIRWISE_CHECK_FAIL); } ERR: BSL_SAL_CleanseData(sharedKey1, MLKEM_SHARED_KEY_LEN); BSL_SAL_ClearFree(ciphertext, pubKey->info->cipherLen); return ret; } static int32_t MlKemPrvKeyCheck(const CRYPT_ML_KEM_Ctx *prvKey) { if (prvKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (prvKey->info == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_KEYINFO_NOT_SET); return CRYPT_MLKEM_KEYINFO_NOT_SET; } if (prvKey->dk == NULL || prvKey->dkLen != prvKey->info->decapsKeyLen) { BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_INVALID_PRVKEY); return CRYPT_MLKEM_INVALID_PRVKEY; } return CRYPT_SUCCESS; } int32_t CRYPT_ML_KEM_Check(uint32_t checkType, const CRYPT_ML_KEM_Ctx *pkey1, const CRYPT_ML_KEM_Ctx *pkey2) { switch (checkType) { case CRYPT_PKEY_CHECK_KEYPAIR: return MlKemKeyPairCheck(pkey1, pkey2); case CRYPT_PKEY_CHECK_PRVKEY: return MlKemPrvKeyCheck(pkey1); default: BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } } #endif // HITLS_CRYPTO_MLKEM_CHECK #endif
2302_82127028/openHiTLS-examples_1508
crypto/mlkem/src/ml_kem.c
C
unknown
19,202
/* * 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_ML_KEM_LOCAL_H #define CRYPT_ML_KEM_LOCAL_H #include "crypt_mlkem.h" #include "sal_atomic.h" #include "crypt_local_types.h" #define MLKEM_N 256 #define MLKEM_N_HALF 128 #define MLKEM_CIPHER_LEN 384 #define MLKEM_SEED_LEN 32 #define MLKEM_SHARED_KEY_LEN 32 #define MLKEM_PRF_BLOCKSIZE 64 #define MLKEM_ENCODE_BLOCKSIZE 32 // 9 = 8.38 = (((MLKEM_BITS_OF_Q * (MLKEM_N/8) * 2^MLKEM_BITS_OF_Q) / MLKEM_Q) + 64) / 64; // array_B_arbitrary_length = 9 * 64 + 2 = 578 #define MLKEM_XOF_OUTPUT_LENGTH 578 #define MLKEM_Q 3329 #define MLKEM_BITS_OF_Q 12 #define MLKEM_INVN 3303 // MLKEM_N_HALF * MLKEM_INVN = 1 mod MLKEM_Q typedef int32_t (*MlKemHashFunc)(uint32_t id, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); static inline void MlKemAddModQ(int16_t *val) { while (*val < 0) { *val += MLKEM_Q; } } typedef struct { uint8_t k; uint8_t eta1; uint8_t eta2; uint8_t du; uint8_t dv; uint32_t secBits; uint32_t encapsKeyLen; uint32_t decapsKeyLen; uint32_t cipherLen; uint32_t sharedLen; uint32_t bits; } CRYPT_MlKemInfo; struct CryptMlKemCtx { int32_t algId; const CRYPT_MlKemInfo *info; uint8_t *ek; uint32_t ekLen; uint8_t *dk; uint32_t dkLen; BSL_SAL_RefCount references; void *libCtx; }; void MLKEM_ComputNTT(int16_t *a, const int16_t *psi, uint32_t pruLength); void MLKEM_ComputINTT(int16_t *a, const int16_t *psiInv, uint32_t pruLength); void MLKEM_SamplePolyCBD(int16_t *polyF, uint8_t *buf, uint8_t eta); void MLKEM_MatrixMulAdd(uint8_t k, int16_t *matrix[], int16_t *vectorS[], int16_t *vectorE, int16_t *vectorT, const int16_t *factor); int32_t MLKEM_KeyGenInternal(CRYPT_ML_KEM_Ctx *ctx, uint8_t *d, uint8_t *z); int32_t MLKEM_EncapsInternal(const CRYPT_ML_KEM_Ctx *ctx, uint8_t *ct, uint32_t *ctLen, uint8_t *sk, uint32_t *skLen, uint8_t *m); int32_t MLKEM_DecapsInternal(const CRYPT_ML_KEM_Ctx *ctx, uint8_t *ct, uint32_t ctLen, uint8_t *sk, uint32_t *skLen); #endif // ML_KEM_LOCAL_H
2302_82127028/openHiTLS-examples_1508
crypto/mlkem/src/ml_kem_local.h
C
unknown
2,598
/* * 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_MLKEM #include "ml_kem_local.h" void MLKEM_ComputNTT(int16_t *a, const int16_t *psi, uint32_t pruLength) { uint32_t t = MLKEM_N; for (uint32_t m = 1; m < pruLength; m <<= 1) { t >>= 1; for (uint32_t i = 0; i < m; i++) { uint32_t j1 = (i << 1) * t; int16_t s = psi[m + i]; int16_t *x = a + j1; int16_t *y = x + (int16_t)t; for (uint32_t j = j1; j < j1 + t; j++) { int32_t ys = (*y) * s; *y = (*x - ys) % MLKEM_Q; *x = (*x + ys) % MLKEM_Q; MlKemAddModQ(y); MlKemAddModQ(x); y++; x++; } } } } void MLKEM_ComputINTT(int16_t *a, const int16_t *psiInv, uint32_t pruLength) { uint32_t t = MLKEM_N / pruLength; for (uint32_t m = pruLength; m > 1; m >>= 1) { uint32_t j1 = 0; uint32_t h = m >> 1; for (uint32_t i = 0; i < h; i++) { int16_t s = psiInv[h + i]; for (uint32_t j = j1; j < j1 + t; j++) { int16_t u = a[j]; int16_t v = a[j + t]; a[j] = (u + v) % MLKEM_Q; // Both u and v are smaller than MLKEM_Q, temp not overflow. int16_t temp = u - v; MlKemAddModQ(&a[j]); MlKemAddModQ(&temp); a[j + t] = ((int32_t)temp * s) % MLKEM_Q; } j1 += (t << 1); } t <<= 1; } for (uint32_t n = 0; n < MLKEM_N; n++) { a[n] = (a[n] * MLKEM_INVN) % MLKEM_Q; MlKemAddModQ(&a[n]); } } #endif
2302_82127028/openHiTLS-examples_1508
crypto/mlkem/src/ml_kem_ntt.c
C
unknown
2,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_MLKEM #include <stdlib.h> #include <string.h> #include <stdio.h> #include "securec.h" #include "bsl_errno.h" #include "bsl_sal.h" #include "crypt_utils.h" #include "crypt_sha3.h" #include "crypt_errno.h" #include "bsl_err_internal.h" #include "eal_md_local.h" #include "ml_kem_local.h" #define BITS_OF_BYTE 8 #define MLKEM_K_MAX 4 #define MLKEM_ETA1_MAX 3 #define MLKEM_ETA2_MAX 2 // A LUT of the primitive n-th roots of unity (psi) in bit-reversed order. static const int16_t PRE_COMPUT_TABLE_NTT[MLKEM_N_HALF] = { 1, 1729, 2580, 3289, 2642, 630, 1897, 848, 1062, 1919, 193, 797, 2786, 3260, 569, 1746, 296, 2447, 1339, 1476, 3046, 56, 2240, 1333, 1426, 2094, 535, 2882, 2393, 2879, 1974, 821, 289, 331, 3253, 1756, 1197, 2304, 2277, 2055, 650, 1977, 2513, 632, 2865, 33, 1320, 1915, 2319, 1435, 807, 452, 1438, 2868, 1534, 2402, 2647, 2617, 1481, 648, 2474, 3110, 1227, 910, 17, 2761, 583, 2649, 1637, 723, 2288, 1100, 1409, 2662, 3281, 233, 756, 2156, 3015, 3050, 1703, 1651, 2789, 1789, 1847, 952, 1461, 2687, 939, 2308, 2437, 2388, 733, 2337, 268, 641, 1584, 2298, 2037, 3220, 375, 2549, 2090, 1645, 1063, 319, 2773, 757, 2099, 561, 2466, 2594, 2804, 1092, 403, 1026, 1143, 2150, 2775, 886, 1722, 1212, 1874, 1029, 2110, 2935, 885, 2154 }; // A LUT of all powers of psi^{-1} in bit-reversed order. static const int16_t PRE_COMPUT_TABLE_INTT[MLKEM_N_HALF] = { 1, 1600, 40, 749, 2481, 1432, 2699, 687, 1583, 2760, 69, 543, 2532, 3136, 1410, 2267, 2508, 1355, 450, 936, 447, 2794, 1235, 1903, 1996, 1089, 3273, 283, 1853, 1990, 882, 3033, 2419, 2102, 219, 855, 2681, 1848, 712, 682, 927, 1795, 461, 1891, 2877, 2522, 1894, 1010, 1414, 2009, 3296, 464, 2697, 816, 1352, 2679, 1274, 1052, 1025, 2132, 1573, 76, 2998, 3040, 1175, 2444, 394, 1219, 2300, 1455, 2117, 1607, 2443, 554, 1179, 2186, 2303, 2926, 2237, 525, 735, 863, 2768, 1230, 2572, 556, 3010, 2266, 1684, 1239, 780, 2954, 109, 1292, 1031, 1745, 2688, 3061, 992, 2596, 941, 892, 1021, 2390, 642, 1868, 2377, 1482, 1540, 540, 1678, 1626, 279, 314, 1173, 2573, 3096, 48, 667, 1920, 2229, 1041, 2606, 1692, 680, 2746, 568, 3312 }; typedef struct { int16_t *bufAddr; int16_t *matrix[MLKEM_K_MAX][MLKEM_K_MAX]; int16_t *vectorS[MLKEM_K_MAX]; int16_t *vectorE[MLKEM_K_MAX]; int16_t *vectorT[MLKEM_K_MAX]; } MLKEM_MatrixSt; // Intermediate data of the key generation and encryption. typedef struct { int16_t *bufAddr; int16_t *vectorS[MLKEM_K_MAX]; int16_t *vectorC1[MLKEM_K_MAX]; int16_t *vectorC2; int16_t *polyM; } MLKEM_DecVectorSt; // Intermediate data of the decryption. static int32_t CreateMatrixBuf(uint8_t k, MLKEM_MatrixSt *st) { // A total of (k * k + 3 * k) data blocks are required. Each block has 512 bytes. int16_t *buf = BSL_SAL_Malloc((k * k + 3 * k) * MLKEM_N * sizeof(int16_t)); if (buf == NULL) { return BSL_MALLOC_FAIL; } st->bufAddr = buf; // Used to release memory. for (uint8_t i = 0; i < k; i++) { for (uint8_t j = 0; j < k; j++) { st->matrix[i][j] = buf + (i * k + j) * MLKEM_N; } // vectorS,vectorE,vectorT use 3 * k data blocks. st->vectorS[i] = buf + (k * k + i * 3) * MLKEM_N; st->vectorE[i] = buf + (k * k + i * 3 + 1) * MLKEM_N; st->vectorT[i] = buf + (k * k + i * 3 + 2) * MLKEM_N; } return CRYPT_SUCCESS; } static void MatrixBufFree(uint8_t k, MLKEM_MatrixSt *st) { // A total of (k * k + 3 * k) data blocks, each block has 512 bytes. BSL_SAL_ClearFree(st->bufAddr, (k * k + 3 * k) * MLKEM_N * sizeof(int16_t)); } static int32_t CreateDecVectorBuf(uint8_t k, MLKEM_DecVectorSt *st) { // A total of (k * 2 + 2) data blocks are required. Each block has 512 bytes. int16_t *buf = BSL_SAL_Malloc((k * 2 + 2) * MLKEM_N * sizeof(int16_t)); if (buf == NULL) { return BSL_MALLOC_FAIL; } st->bufAddr = buf; // Used to release memory. for (uint8_t i = 0; i < k; i++) { st->vectorS[i] = buf + (i) * MLKEM_N; st->vectorC1[i] = buf + (k + i) * MLKEM_N; } // vectorC2 and polyM use 2 * k data blocks. st->vectorC2 = buf + (k * 2) * MLKEM_N; st->polyM = buf + (k * 2 + 1) * MLKEM_N; return CRYPT_SUCCESS; } static void DecVectorBufFree(uint8_t k, MLKEM_DecVectorSt *st) { // A total of (k * 2 + 2) data blocks, each block has 512 bytes. BSL_SAL_ClearFree(st->bufAddr, (k * 2 + 2) * MLKEM_N * sizeof(int16_t)); } // Compress typedef struct { uint64_t barrettMultiplier; /* round(2 ^ barrettShift / MLKEM_Q) */ uint16_t barrettShift; uint16_t halfQ; /* rounded (MLKEM_Q / 2) down or up */ uint8_t bits; } MLKEM_BARRET_REDUCE; // The values of du and dv are from NIST.FIPS.203 Table 2. static const MLKEM_BARRET_REDUCE MLKEM_BARRETT_TABLE[] = { {80635 /* round(2^28/MLKEM_Q) */, 28, 1665 /* Ceil(MLKEM_Q/2) */, 1}, {1290167 /* round(2^32/MLKEM_Q) */, 32, 1665 /* Ceil(MLKEM_Q/2) */, 10}, // 10 is mlkem768 du {80635 /* round(2^28/MLKEM_Q) */, 28, 1665 /* Ceil(MLKEM_Q/2) */, 4}, // 4 is mlkem768 dv {40318 /* round(2^27/MLKEM_Q) */, 27, 1664 /* Floor(MLKEM_Q/2) */, 5}, // 5 is mlkem1024 dv {645084 /* round(2^31/MLKEM_Q) */, 31, 1664 /* Floor(MLKEM_Q/2) */, 11} // 11 is mlkem1024 du }; static int16_t DivMlKemQ(uint16_t x, uint8_t bits, uint16_t halfQ, uint16_t barrettShift, uint64_t barrettMultiplier) { uint64_t round = ((uint64_t)x << bits) + halfQ; round *= barrettMultiplier; round >>= barrettShift; return (int16_t)(round & ((1 << bits) - 1)); } static int16_t Compress(int16_t x, uint8_t d) { int16_t value = 0; uint16_t t = (uint16_t)(x + MLKEM_Q) % MLKEM_Q; /* Computing (x << d) / MLKEM_Q by Barret Reduce */ for (uint32_t i = 0; i < sizeof(MLKEM_BARRETT_TABLE) / sizeof(MLKEM_BARRET_REDUCE); i++) { if (d == MLKEM_BARRETT_TABLE[i].bits) { value = DivMlKemQ(t, MLKEM_BARRETT_TABLE[i].bits, MLKEM_BARRETT_TABLE[i].halfQ, MLKEM_BARRETT_TABLE[i].barrettShift, MLKEM_BARRETT_TABLE[i].barrettMultiplier); break; } } return value; } // DeCompress static int16_t DeCompress(int16_t x, uint8_t bits) { uint32_t product = (uint32_t)x * MLKEM_Q; uint32_t power = 1 << bits; return (int16_t)((product >> bits) + ((product & (power - 1)) >> (bits - 1))); } // hash functions static int32_t HashFuncH(void *libCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t outLen) { uint32_t len = outLen; return EAL_Md(CRYPT_MD_SHA3_256, libCtx, NULL, in, inLen, out, &len); } static int32_t HashFuncG(void *libCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t outLen) { uint32_t len = outLen; return EAL_Md(CRYPT_MD_SHA3_512, libCtx, NULL, in, inLen, out, &len); } static int32_t HashFuncXOF(void *libCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t outLen) { uint32_t len = outLen; return EAL_Md(CRYPT_MD_SHAKE128, libCtx, NULL, in, inLen, out, &len); } static int32_t HashFuncJ(void *libCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t outLen) { uint32_t len = outLen; return EAL_Md(CRYPT_MD_SHAKE256, libCtx, NULL, in, inLen, out, &len); } static int32_t PRF(void *libCtx, uint8_t *extSeed, uint32_t extSeedLen, uint8_t *outBuf, uint32_t bufLen) { uint32_t len = bufLen; return EAL_Md(CRYPT_MD_SHAKE256, libCtx, NULL, extSeed, extSeedLen, outBuf, &len); } static int32_t Parse(uint16_t *polyNtt, uint8_t *arrayB, uint32_t arrayLen, uint32_t n) { uint32_t i = 0; uint32_t j = 0; while (j < n) { if (i + 3 > arrayLen) { // 3 bytes of arrayB are read in each round. BSL_ERR_PUSH_ERROR(CRYPT_MLKEM_KEYLEN_ERROR); return CRYPT_MLKEM_KEYLEN_ERROR; } // The 4 bits of each byte are combined with the 8 bits of another byte into 12 bits. uint16_t d1 = ((uint16_t)arrayB[i]) + (((uint16_t)arrayB[i + 1] & 0x0f) << 8); // 4 bits. uint16_t d2 = (((uint16_t)arrayB[i + 1]) >> 4) + (((uint16_t)arrayB[i + 2]) << 4); if (d1 < MLKEM_Q) { polyNtt[j] = d1; j++; } if (d2 < MLKEM_Q && j < n) { polyNtt[j] = d2; j++; } i += 3; // 3 bytes are processed in each round. } return CRYPT_SUCCESS; } static void EncodeBits1(uint8_t *r, uint16_t *polyF) { for (uint32_t i = 0; i < MLKEM_N / BITS_OF_BYTE; i++) { r[i] = (uint8_t)polyF[BITS_OF_BYTE * i]; for (uint32_t j = 1; j < BITS_OF_BYTE; j++) { r[i] = (uint8_t)(polyF[BITS_OF_BYTE * i + j] << j) | r[i]; } } } static void EncodeBits4(uint8_t *r, uint16_t *polyF) { for (uint32_t i = 0; i < MLKEM_N / 2; i++) { // Two 4 bits are combined into 1 byte. r[i] = ((uint8_t)polyF[2 * i] | ((uint8_t)polyF[2 * i + 1] << 4)); } } static void EncodeBits5(uint8_t *r, uint16_t *polyF) { uint32_t indexR; uint32_t indexF; for (uint32_t i = 0; i < MLKEM_N / 8; i++) { indexR = 5 * i; // Each element in polyF has 5 bits. indexF = 8 * i; // Each element in r has 8 bits. // 8 polyF elements are padded to 5 bytes. r[indexR + 0] = (uint8_t)(polyF[indexF] | (polyF[indexF + 1] << 5)); r[indexR + 1] = (uint8_t)((polyF[indexF + 1] >> 3) | (polyF[indexF + 2] << 2) | (polyF[indexF + 3] << 7)); r[indexR + 2] = (uint8_t)((polyF[indexF + 3] >> 1) | (polyF[indexF + 4] << 4)); r[indexR + 3] = (uint8_t)((polyF[indexF + 4] >> 4) | (polyF[indexF + 5] << 1) | (polyF[indexF + 6] << 6)); r[indexR + 4] = (uint8_t)((polyF[indexF + 6] >> 2) | (polyF[indexF + 7] << 3)); } } static void EncodeBits10(uint8_t *r, uint16_t *polyF) { uint32_t indexR; uint32_t indexF; for (uint32_t i = 0; i < MLKEM_N / 4; i++) { // 4 polyF elements are padded to 5 bytes. indexR = 5 * i; indexF = 4 * i; r[indexR + 0] = (uint8_t)polyF[indexF]; r[indexR + 1] = (uint8_t)((polyF[indexF] >> 8) | (polyF[indexF + 1] << 2)); r[indexR + 2] = (uint8_t)((polyF[indexF + 1] >> 6) | (polyF[indexF + 2] << 4)); r[indexR + 3] = (uint8_t)((polyF[indexF + 2] >> 4) | (polyF[indexF + 3] << 6)); r[indexR + 4] = (uint8_t)(polyF[indexF + 3] >> 2); } } static void EncodeBits11(uint8_t *r, uint16_t *polyF) { uint32_t indexR; uint32_t indexF; for (uint32_t i = 0; i < MLKEM_N / 8; i++) { // 8 polyF elements are padded to 11 bytes. indexR = 11 * i; indexF = 8 * i; r[indexR + 0] = (uint8_t)polyF[indexF]; r[indexR + 1] = (uint8_t)((polyF[indexF] >> 8) | (polyF[indexF + 1] << 3)); r[indexR + 2] = (uint8_t)((polyF[indexF + 1] >> 5) | (polyF[indexF + 2] << 6)); r[indexR + 3] = (uint8_t)((polyF[indexF + 2] >> 2)); r[indexR + 4] = (uint8_t)((polyF[indexF + 2] >> 10) | (polyF[indexF + 3] << 1)); r[indexR + 5] = (uint8_t)((polyF[indexF + 3] >> 7) | (polyF[indexF + 4] << 4)); r[indexR + 6] = (uint8_t)((polyF[indexF + 4] >> 4) | (polyF[indexF + 5] << 7)); r[indexR + 7] = (uint8_t)((polyF[indexF + 5] >> 1)); r[indexR + 8] = (uint8_t)((polyF[indexF + 5] >> 9) | (polyF[indexF + 6] << 2)); r[indexR + 9] = (uint8_t)((polyF[indexF + 6] >> 6) | (polyF[indexF + 7] << 5)); r[indexR + 10] = (uint8_t)(polyF[indexF + 7] >> 3); } } static void EncodeBits12(uint8_t *r, uint16_t *polyF) { uint32_t i; uint16_t t0; uint16_t t1; for (i = 0; i < MLKEM_N / 2; i++) { // 2 polyF elements are padded to 3 bytes. t0 = polyF[2 * i]; t1 = polyF[2 * i + 1]; r[3 * i + 0] = (uint8_t)(t0 >> 0); r[3 * i + 1] = (uint8_t)((t0 >> 8) | (t1 << 4)); r[3 * i + 2] = (uint8_t)(t1 >> 4); } } // Encodes an array of d-bit integers into a byte array for 1 ≤ d ≤ 12. static void ByteEncode(uint8_t *r, int16_t *polyF, uint8_t bit) { switch (bit) { // Valid bits of each element in polyF. case 1: // 1 Used for K-PKE.Decrypt Step 7. EncodeBits1(r, (uint16_t *)polyF); break; case 4: // From FIPS 203 Table 2, dv = 4 EncodeBits4(r, (uint16_t *)polyF); break; case 5: // dv = 5 EncodeBits5(r, (uint16_t *)polyF); break; case 10: // du = 10 EncodeBits10(r, (uint16_t *)polyF); break; case 11: // du = 11 EncodeBits11(r, (uint16_t *)polyF); break; case 12: // 12 Used for K-PKE.KeyGen Step 19. EncodeBits12(r, (uint16_t *)polyF); break; default: break; } } static void DecodeBits1(int16_t *polyF, const uint8_t *a) { uint32_t i; uint32_t j; for (i = 0; i < MLKEM_N / BITS_OF_BYTE; i++) { // 1 byte data is decoded into 8 polyF elements. for (j = 0; j < BITS_OF_BYTE; j++) { polyF[BITS_OF_BYTE * i + j] = (a[i] >> j) & 0x01; } } } static void DecodeBits4(int16_t *polyF, const uint8_t *a) { uint32_t i; for (i = 0; i < MLKEM_N / 2; i++) { // 1 byte data is decoded into 2 polyF elements. polyF[2 * i] = a[i] & 0xF; polyF[2 * i + 1] = (a[i] >> 4) & 0xF; } } static void DecodeBits5(int16_t *polyF, const uint8_t *a) { uint32_t indexF; uint32_t indexA; for (uint32_t i = 0; i < MLKEM_N / 8; i++) { // 8 byte data is decoded into 5 polyF elements. indexF = 8 * i; indexA = 5 * i; // value & 0x1F is used to obtain 5 bits. polyF[indexF + 0] = ((a[indexA + 0] >> 0)) & 0x1F; polyF[indexF + 1] = ((a[indexA + 0] >> 5) | (a[indexA + 1] << 3)) & 0x1F; polyF[indexF + 2] = ((a[indexA + 1] >> 2)) & 0x1F; polyF[indexF + 3] = ((a[indexA + 1] >> 7) | (a[indexA + 2] << 1)) & 0x1F; polyF[indexF + 4] = ((a[indexA + 2] >> 4) | (a[indexA + 3] << 4)) & 0x1F; polyF[indexF + 5] = ((a[indexA + 3] >> 1)) & 0x1F; polyF[indexF + 6] = ((a[indexA + 3] >> 6) | (a[indexA + 4] << 2)) & 0x1F; polyF[indexF + 7] = ((a[indexA + 4] >> 3)) & 0x1F; } } static void DecodeBits10(int16_t *polyF, const uint8_t *a) { uint32_t indexF; uint32_t indexA; for (uint32_t i = 0; i < MLKEM_N / 4; i++) { // 5 byte data is decoded into 4 polyF elements. indexF = 4 * i; indexA = 5 * i; // value & 0x3FF is used to obtain 10 bits. polyF[indexF + 0] = ((a[indexA + 0] >> 0) | ((uint16_t)a[indexA + 1] << 8)) & 0x3FF; polyF[indexF + 1] = ((a[indexA + 1] >> 2) | ((uint16_t)a[indexA + 2] << 6)) & 0x3FF; polyF[indexF + 2] = ((a[indexA + 2] >> 4) | ((uint16_t)a[indexA + 3] << 4)) & 0x3FF; polyF[indexF + 3] = ((a[indexA + 3] >> 6) | ((uint16_t)a[indexA + 4] << 2)) & 0x3FF; } } static void DecodeBits11(int16_t *polyF, const uint8_t *a) { uint32_t indexF; uint32_t indexA; for (uint32_t i = 0; i < MLKEM_N / 8; i++) { // use type conversion because 11 > 8 indexF = 8 * i; indexA = 11 * i; // value & 0x7FF is used to obtain 11 bits. polyF[indexF + 0] = ((a[indexA + 0] >> 0) | ((uint16_t)a[indexA + 1] << 8)) & 0x7FF; polyF[indexF + 1] = ((a[indexA + 1] >> 3) | ((uint16_t)a[indexA + 2] << 5)) & 0x7FF; polyF[indexF + 2] = ((a[indexA + 2] >> 6) | ((uint16_t)a[indexA + 3] << 2) | ((uint16_t)a[indexA + 4] << 10)) & 0x7FF; polyF[indexF + 3] = ((a[indexA + 4] >> 1) | ((uint16_t)a[indexA + 5] << 7)) & 0x7FF; polyF[indexF + 4] = ((a[indexA + 5] >> 4) | ((uint16_t)a[indexA + 6] << 4)) & 0x7FF; polyF[indexF + 5] = ((a[indexA + 6] >> 7) | ((uint16_t)a[indexA + 7] << 1) | ((uint16_t)a[indexA + 8] << 9)) & 0x7FF; polyF[indexF + 6] = ((a[indexA + 8] >> 2) | ((uint16_t)a[indexA + 9] << 6)) & 0x7FF; polyF[indexF + 7] = ((a[indexA + 9] >> 5) | ((uint16_t)a[indexA + 10] << 3)) & 0x7FF; } } static void DecodeBits12(int16_t *polyF, const uint8_t *a) { uint32_t i; for (i = 0; i < MLKEM_N / 2; i++) { // 3 byte data is decoded into 2 polyF elements, value & 0xFFF is used to obtain 12 bits. polyF[2 * i] = ((a[3 * i + 0] >> 0) | ((uint16_t)a[3 * i + 1] << 8)) & 0xFFF; polyF[2 * i + 1] = ((a[3 * i + 1] >> 4) | ((uint16_t)a[3 * i + 2] << 4)) & 0xFFF; } } // Decodes a byte array into an array of d-bit integers for 1 ≤ d ≤ 12. static void ByteDecode(int16_t *polyF, const uint8_t *a, uint8_t bit) { switch (bit) { case 1: DecodeBits1(polyF, a); break; case 4: DecodeBits4(polyF, a); break; case 5: DecodeBits5(polyF, a); break; case 10: DecodeBits10(polyF, a); break; case 11: DecodeBits11(polyF, a); break; case 12: DecodeBits12(polyF, a); break; default: break; } } static int32_t GenMatrix(const CRYPT_ML_KEM_Ctx *ctx, const uint8_t *digest, int16_t *polyMatrix[MLKEM_K_MAX][MLKEM_K_MAX], bool isEnc) { uint8_t k = ctx->info->k; uint8_t p[MLKEM_SEED_LEN + 2]; // Reserved lengths of i and j is 2 byte. uint8_t xofOut[MLKEM_XOF_OUTPUT_LENGTH]; (void)memcpy_s(p, MLKEM_SEED_LEN, digest, MLKEM_SEED_LEN); for (uint8_t i = 0; i < k; i++) { for (uint8_t j = 0; j < k; j++) { if (isEnc) { p[MLKEM_SEED_LEN] = i; p[MLKEM_SEED_LEN + 1] = j; } else { p[MLKEM_SEED_LEN] = j; p[MLKEM_SEED_LEN + 1] = i; } int32_t ret = HashFuncXOF(ctx->libCtx, p, MLKEM_SEED_LEN + 2, xofOut, MLKEM_XOF_OUTPUT_LENGTH); RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); ret = Parse((uint16_t *)polyMatrix[i][j], xofOut, MLKEM_XOF_OUTPUT_LENGTH, MLKEM_N); RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); } } return CRYPT_SUCCESS; } static int32_t SampleEta1(const CRYPT_ML_KEM_Ctx *ctx, uint8_t *digest, int16_t *polyS[], uint8_t *nonce) { uint8_t q[MLKEM_SEED_LEN + 1] = { 0 }; // Reserved lengths of nonce is 1 byte. uint8_t prfOut[MLKEM_PRF_BLOCKSIZE * MLKEM_ETA1_MAX] = { 0 }; (void)memcpy_s(q, MLKEM_SEED_LEN, digest, MLKEM_SEED_LEN); for (uint8_t i = 0; i < ctx->info->k; i++) { q[MLKEM_SEED_LEN] = *nonce; int32_t ret = PRF(ctx->libCtx, q, MLKEM_SEED_LEN + 1, prfOut, MLKEM_PRF_BLOCKSIZE * MLKEM_ETA1_MAX); RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); MLKEM_SamplePolyCBD(polyS[i], prfOut, ctx->info->eta1); *nonce = *nonce + 1; MLKEM_ComputNTT(polyS[i], PRE_COMPUT_TABLE_NTT, MLKEM_N_HALF); } return CRYPT_SUCCESS; } static int32_t SampleEta2(const CRYPT_ML_KEM_Ctx *ctx, uint8_t *digest, int16_t *polyS[], uint8_t *nonce) { uint8_t q[MLKEM_SEED_LEN + 1] = { 0 }; // Reserved lengths of nonce is 1 byte. uint8_t prfOut[MLKEM_PRF_BLOCKSIZE * MLKEM_ETA2_MAX] = { 0 }; (void)memcpy_s(q, MLKEM_SEED_LEN, digest, MLKEM_SEED_LEN); for (uint8_t i = 0; i < ctx->info->k; i++) { q[MLKEM_SEED_LEN] = *nonce; int32_t ret = PRF(ctx->libCtx, q, MLKEM_SEED_LEN + 1, prfOut, MLKEM_PRF_BLOCKSIZE * MLKEM_ETA2_MAX); RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); MLKEM_SamplePolyCBD(polyS[i], prfOut, ctx->info->eta2); *nonce = *nonce + 1; } return CRYPT_SUCCESS; } // NIST.FIPS.203 Algorithm 13 K-PKE.KeyGen(𝑑) static int32_t PkeKeyGen(const CRYPT_ML_KEM_Ctx *ctx, uint8_t *pk, uint8_t *dk, uint8_t *d) { uint8_t k = ctx->info->k; uint8_t nonce = 0; uint8_t seed[MLKEM_SEED_LEN + 1] = { 0 }; // Reserved lengths of k is 1 byte. uint8_t digest[CRYPT_SHA3_512_DIGESTSIZE] = { 0 }; // (p,q) = G(d || k) (void)memcpy_s(seed, MLKEM_SEED_LEN + 1, d, MLKEM_SEED_LEN); seed[MLKEM_SEED_LEN] = k; int32_t ret = HashFuncG(ctx->libCtx, seed, MLKEM_SEED_LEN + 1, digest, CRYPT_SHA3_512_DIGESTSIZE); // Step 1 RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); // expand 32+1 bytes to two pseudorandom 32-byte seeds uint8_t *p = digest; uint8_t *q = digest + CRYPT_SHA3_512_DIGESTSIZE / 2; MLKEM_MatrixSt st = { 0 }; ret = CreateMatrixBuf(k, &st); RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); GOTO_ERR_IF(GenMatrix(ctx, p, st.matrix, false), ret); // Step 3 - 7 GOTO_ERR_IF(SampleEta1(ctx, q, st.vectorS, &nonce), ret); // Step 8 - 11 GOTO_ERR_IF(SampleEta1(ctx, q, st.vectorE, &nonce), ret); // Step 12 - 15 for (uint8_t i = 0; i < k; i++) { // Step 18 MLKEM_MatrixMulAdd(k, st.matrix[i], st.vectorS, st.vectorE[i], st.vectorT[i], PRE_COMPUT_TABLE_NTT); } // output: pk, dk, ekPKE ← ByteEncode12(𝐭)‖p. for (uint8_t i = 0; i < k; i++) { // Step 19 ByteEncode(pk + MLKEM_SEED_LEN * MLKEM_BITS_OF_Q * i, st.vectorT[i], MLKEM_BITS_OF_Q); // Step 20 ByteEncode(dk + MLKEM_SEED_LEN * MLKEM_BITS_OF_Q * i, st.vectorS[i], MLKEM_BITS_OF_Q); } // The buffer of pk is sufficient, check it before calling this function. (void)memcpy_s(pk + MLKEM_SEED_LEN * MLKEM_BITS_OF_Q * k, MLKEM_SEED_LEN, p, MLKEM_SEED_LEN); ERR: MatrixBufFree(k, &st); return ret; } // NIST.FIPS.203 Algorithm 14 K-PKE.Encrypt(ekPKE,𝑚,𝑟) static int32_t PkeEncrypt(const CRYPT_ML_KEM_Ctx *ctx, uint8_t *ct, const uint8_t *ek, uint8_t *m, uint8_t *r) { uint8_t i; uint32_t n; uint8_t k = ctx->info->k; uint8_t nonce = 0; // Step 1 uint8_t seedE[MLKEM_SEED_LEN + 1]; uint8_t bufEncE[MLKEM_PRF_BLOCKSIZE * MLKEM_ETA1_MAX]; int16_t polyVectorE2[MLKEM_N] = { 0 }; int16_t polyVectorC2[MLKEM_N] = { 0 }; int16_t polyVectorM[MLKEM_N] = { 0 }; MLKEM_MatrixSt st = { 0 }; int32_t ret = CreateMatrixBuf(k, &st); RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); GOTO_ERR_IF(GenMatrix(ctx, ek + MLKEM_CIPHER_LEN * k, st.matrix, true), ret); // Step 3 - 8 GOTO_ERR_IF(SampleEta1(ctx, r, st.vectorS, &nonce), ret); // Step 9 - 12 GOTO_ERR_IF(SampleEta2(ctx, r, st.vectorE, &nonce), ret); // Step 13 - 16 // Step 17 (void)memcpy_s(seedE, MLKEM_SEED_LEN, r, MLKEM_SEED_LEN); seedE[MLKEM_SEED_LEN] = nonce; GOTO_ERR_IF(PRF(ctx->libCtx, seedE, MLKEM_SEED_LEN + 1, bufEncE, MLKEM_PRF_BLOCKSIZE * ctx->info->eta2), ret); MLKEM_SamplePolyCBD(polyVectorE2, bufEncE, ctx->info->eta2); // Step 18 for (i = 0; i < k; i++) { MLKEM_MatrixMulAdd(k, st.matrix[i], st.vectorS, NULL, st.vectorT[i], PRE_COMPUT_TABLE_NTT); } // Step 19 for (i = 0; i < k; i++) { MLKEM_ComputINTT(st.vectorT[i], PRE_COMPUT_TABLE_INTT, MLKEM_N_HALF); for (n = 0; n < MLKEM_N; n++) { st.vectorT[i][n] = Compress(st.vectorT[i][n] + st.vectorE[i][n], ctx->info->du); } } // Step 21 for (i = 0; i < k; i++) { ByteDecode(st.vectorE[i], ek + MLKEM_CIPHER_LEN * i, MLKEM_BITS_OF_Q); } MLKEM_MatrixMulAdd(k, st.vectorE, st.vectorS, NULL, polyVectorC2, PRE_COMPUT_TABLE_NTT); ByteDecode(polyVectorM, m, 1); MLKEM_ComputINTT(polyVectorC2, PRE_COMPUT_TABLE_INTT, MLKEM_N_HALF); for (n = 0; n < MLKEM_N; n++) { polyVectorM[n] = DeCompress(polyVectorM[n], 1); // Step 20 // Step 22 polyVectorC2[n] = Compress(polyVectorC2[n] + polyVectorE2[n] + polyVectorM[n], ctx->info->dv); } // Step 22 for (i = 0; i < k; i++) { ByteEncode(ct + MLKEM_ENCODE_BLOCKSIZE * ctx->info->du * i, st.vectorT[i], ctx->info->du); } // Step 23 ByteEncode(ct + MLKEM_ENCODE_BLOCKSIZE * ctx->info->du * k, polyVectorC2, ctx->info->dv); ERR: MatrixBufFree(k, &st); return ret; } // NIST.FIPS.203 Algorithm 15 K-PKE.Decrypt(dkPKE, 𝑐) static int32_t PkeDecrypt(const CRYPT_MlKemInfo *algInfo, uint8_t *result, const uint8_t *dk, const uint8_t *ciphertext) { uint8_t i; uint8_t k = algInfo->k; uint32_t n; MLKEM_DecVectorSt st = { 0 }; int32_t ret = CreateDecVectorBuf(k, &st); RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); for (i = 0; i < k; i++) { ByteDecode(st.vectorC1[i], ciphertext + MLKEM_ENCODE_BLOCKSIZE * algInfo->du * i, algInfo->du); // Step 3 ByteDecode(st.vectorS[i], dk + MLKEM_ENCODE_BLOCKSIZE * MLKEM_BITS_OF_Q * i, MLKEM_BITS_OF_Q); // Step 5 } ByteDecode(st.vectorC2, ciphertext + MLKEM_ENCODE_BLOCKSIZE * algInfo->du * k, algInfo->dv); // Step 4 for (i = 0; i < k; i++) { for (n = 0; n < MLKEM_N; n++) { st.vectorC1[i][n] = DeCompress(st.vectorC1[i][n], algInfo->du); // Step 3 if (i == 0) { st.vectorC2[n] = DeCompress(st.vectorC2[n], algInfo->dv); // Step 4 } } MLKEM_ComputNTT(st.vectorC1[i], PRE_COMPUT_TABLE_NTT, MLKEM_N_HALF); } MLKEM_MatrixMulAdd(k, st.vectorS, st.vectorC1, NULL, st.polyM, PRE_COMPUT_TABLE_NTT); // Step 6 // polyM = intt(polyM) MLKEM_ComputINTT(st.polyM, PRE_COMPUT_TABLE_INTT, MLKEM_N_HALF); // c2 - polyM for (n = 0; n < MLKEM_N; n++) { st.polyM[n] = Compress(st.vectorC2[n] - st.polyM[n], 1); } ByteEncode(result, st.polyM, 1); // Step 7 DecVectorBufFree(k, &st); return CRYPT_SUCCESS; } // NIST.FIPS.203 Algorithm 16 ML-KEM.KeyGen_internal(𝑑,𝑧) int32_t MLKEM_KeyGenInternal(CRYPT_ML_KEM_Ctx *ctx, uint8_t *d, uint8_t *z) { const CRYPT_MlKemInfo *algInfo = ctx->info; uint32_t dkPkeLen = MLKEM_CIPHER_LEN * algInfo->k; // (ekPKE,dkPKE) ← K-PKE.KeyGen(𝑑) int32_t ret = PkeKeyGen(ctx, ctx->ek, ctx->dk, d); RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); // dk ← (dkPKE‖ek‖H(ek)‖𝑧) if (memcpy_s(ctx->dk + dkPkeLen, ctx->dkLen - dkPkeLen, ctx->ek, ctx->ekLen) != EOK) { BSL_ERR_PUSH_ERROR(CRYPT_SECUREC_FAIL); return CRYPT_SECUREC_FAIL; } ret = HashFuncH(ctx->libCtx, ctx->ek, ctx->ekLen, ctx->dk + dkPkeLen + ctx->ekLen, CRYPT_SHA3_256_DIGESTSIZE); RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); if (memcpy_s(ctx->dk + dkPkeLen + ctx->ekLen + CRYPT_SHA3_256_DIGESTSIZE, ctx->dkLen - (dkPkeLen + ctx->ekLen + CRYPT_SHA3_256_DIGESTSIZE), z, MLKEM_SEED_LEN) != EOK) { BSL_ERR_PUSH_ERROR(CRYPT_SECUREC_FAIL); return CRYPT_SECUREC_FAIL; } return CRYPT_SUCCESS; } // NIST.FIPS.203 Algorithm 17 ML-KEM.Encaps_internal(ek,𝑚) int32_t MLKEM_EncapsInternal(const CRYPT_ML_KEM_Ctx *ctx, uint8_t *ct, uint32_t *ctLen, uint8_t *sk, uint32_t *skLen, uint8_t *m) { uint8_t mhek[MLKEM_SEED_LEN + CRYPT_SHA3_256_DIGESTSIZE]; // m and H(ek) uint8_t kr[CRYPT_SHA3_512_DIGESTSIZE]; // K and r // (K,r) = G(m || H(ek)) (void)memcpy_s(mhek, MLKEM_SEED_LEN, m, MLKEM_SEED_LEN); int32_t ret = HashFuncH(ctx->libCtx, ctx->ek, ctx->ekLen, mhek + MLKEM_SEED_LEN, CRYPT_SHA3_256_DIGESTSIZE); RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); ret = HashFuncG(ctx->libCtx, mhek, MLKEM_SEED_LEN + CRYPT_SHA3_256_DIGESTSIZE, kr, CRYPT_SHA3_512_DIGESTSIZE); RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); (void)memcpy_s(sk, *skLen, kr, MLKEM_SHARED_KEY_LEN); // 𝑐 ← K-PKE.Encrypt(ek,𝑚,𝑟) ret = PkeEncrypt(ctx, ct, ctx->ek, m, kr + MLKEM_SHARED_KEY_LEN); BSL_SAL_CleanseData(kr, CRYPT_SHA3_512_DIGESTSIZE); RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); *ctLen = ctx->info->cipherLen; *skLen = ctx->info->sharedLen; return CRYPT_SUCCESS; } // NIST.FIPS.203 Algorithm 18 ML-KEM.Decaps_internal(dk, 𝑐) int32_t MLKEM_DecapsInternal(const CRYPT_ML_KEM_Ctx *ctx, uint8_t *ct, uint32_t ctLen, uint8_t *sk, uint32_t *skLen) { const CRYPT_MlKemInfo *algInfo = ctx->info; const uint8_t *dk = ctx->dk; // Step 1 dkPKE ← dk[0 : 384k] const uint8_t *ek = dk + MLKEM_CIPHER_LEN * algInfo->k; // Step 2 ekPKE ← dk[384k : 768k +32] const uint8_t *h = ek + algInfo->encapsKeyLen; // Step 3 h ← dk[768k +32 : 768k +64] const uint8_t *z = h + MLKEM_SEED_LEN; // Step 4 z ← dk[768k +64 : 768k +96] uint8_t mh[MLKEM_SEED_LEN + CRYPT_SHA3_256_DIGESTSIZE]; // m′ and h uint8_t kr[CRYPT_SHA3_512_DIGESTSIZE]; // K' and r' int32_t ret = PkeDecrypt(algInfo, mh, dk, ct); // Step 5: 𝑚′ ← K-PKE.Decrypt(dkPKE, 𝑐) RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); // Step 6: (K′,r′) ← G(m′ || h) (void)memcpy_s(mh + MLKEM_SEED_LEN, CRYPT_SHA3_256_DIGESTSIZE, h, CRYPT_SHA3_256_DIGESTSIZE); ret = HashFuncG(ctx->libCtx, mh, MLKEM_SEED_LEN + CRYPT_SHA3_256_DIGESTSIZE, kr, CRYPT_SHA3_512_DIGESTSIZE); RETURN_RET_IF(ret != CRYPT_SUCCESS, ret); // Step 8: 𝑐′ ← K-PKE.Encrypt(ekPKE,𝑚′,𝑟′) uint8_t *r = kr + MLKEM_SHARED_KEY_LEN; uint8_t *newCt = BSL_SAL_Malloc(ctLen + MLKEM_SEED_LEN); RETURN_RET_IF(newCt == NULL, BSL_MALLOC_FAIL); GOTO_ERR_IF(PkeEncrypt(ctx, newCt, ek, mh, r), ret); // Step 9: if c != c′ if (memcmp(ct, newCt, ctLen) == 0) { (void)memcpy_s(sk, *skLen, kr, MLKEM_SHARED_KEY_LEN); } else { // Step 7: K = J(z || c) (void)memcpy_s(newCt, ctLen + MLKEM_SEED_LEN, z, MLKEM_SEED_LEN); (void)memcpy_s(newCt + MLKEM_SEED_LEN, ctLen, ct, ctLen); GOTO_ERR_IF(HashFuncJ(ctx->libCtx, newCt, ctLen + MLKEM_SEED_LEN, sk, MLKEM_SHARED_KEY_LEN), ret); } *skLen = MLKEM_SHARED_KEY_LEN; ERR: BSL_SAL_CleanseData(kr, CRYPT_SHA3_512_DIGESTSIZE); BSL_SAL_Free(newCt); return ret; } #endif
2302_82127028/openHiTLS-examples_1508
crypto/mlkem/src/ml_kem_pke.c
C
unknown
30,365
/* * 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_MLKEM #include "ml_kem_local.h" // basecase multiplication static void BaseMul(int16_t polyH[2], int16_t f0, int16_t f1, int16_t g0, int16_t g1, int16_t factor) { polyH[0] = (int16_t)(((int32_t)(f0 * g0) + (int32_t)(((int32_t)(f1 * g1) % MLKEM_Q) * factor)) % MLKEM_Q); polyH[1] = (int16_t)(((int32_t)(f0 * g1) + (int32_t)(f1 * g0)) % MLKEM_Q); MlKemAddModQ(&polyH[0]); MlKemAddModQ(&polyH[1]); } // circle multiplication static void CircMul(int16_t dest[MLKEM_N], int16_t src1[MLKEM_N], int16_t src2[MLKEM_N], const int16_t *factor) { for (uint32_t i = 0; i < MLKEM_N / 4; i++) { // 4-byte data is calculated in each round. BaseMul(&dest[4 * i], src1[4 * i], src1[4 * i + 1], src2[4 * i], src2[4 * i + 1], factor[i]); BaseMul(&dest[4 * i + 2], src1[4 * i + 2], src1[4 * i + 3], src2[4 * i + 2], src2[4 * i + 3], -1 * factor[i]); } } void MLKEM_MatrixMulAdd(uint8_t k, int16_t *matrix[], int16_t *vectorS[], int16_t *vectorE, int16_t *vectorT, const int16_t *factor) { int16_t dest[MLKEM_N] = { 0 }; for (uint8_t j = 0; j < k; j++) { // factor is a half of the NTT table. CircMul(dest, matrix[j], vectorS[j], factor + MLKEM_N_HALF / 2); for (uint32_t n = 0; n < MLKEM_N; n++) { if (j == 0) { vectorT[n] = (vectorE == NULL) ? dest[n] : (vectorE[n] + dest[n]); } else if (j != 0 && j != (k - 1)) { vectorT[n] += dest[n]; } else if (j == (k - 1)) { vectorT[n] = (vectorT[n] + dest[n]) % MLKEM_Q; } } } } void MLKEM_SamplePolyCBD(int16_t *polyF, uint8_t *buf, uint8_t eta) { uint32_t i; uint32_t j; uint8_t a; uint8_t b; uint32_t t1; if (eta == 3) { // The value of eta can only be 2 or 3. for (i = 0; i < MLKEM_N / 4; i++) { uint32_t temp = (uint32_t)buf[eta * i]; temp |= (uint32_t)buf[eta * i + 1] << 8; temp |= (uint32_t)buf[eta * i + 2] << 16; t1 = temp & 0x00249249; // temp & 0x00249249 is used to obtain a specific bit in temp. t1 += (temp >> 1) & 0x00249249; t1 += (temp >> 2) & 0x00249249; for (j = 0; j < 4; j++) { a = (t1 >> (6 * j)) & 0x3; b = (t1 >> (6 * j + eta)) & 0x3; polyF[4 * i + j] = a - b; } } } else if (eta == 2) { for (i = 0; i < MLKEM_N / 4; i++) { uint16_t temp = (uint16_t)buf[eta * i]; temp |= (uint16_t)buf[eta * i + 1] << 0x8; t1 = temp & 0x5555; // temp & 0x5555 is used to obtain a specific bit in temp. t1 += (temp >> 1) & 0x5555; for (j = 0; j < 4; j++) { a = (t1 >> (4 * j)) & 0x3; b = (t1 >> (4 * j + eta)) & 0x3; polyF[4 * i + j] = a - b; } } } } #endif
2302_82127028/openHiTLS-examples_1508
crypto/mlkem/src/ml_kem_poly.c
C
unknown
3,603
/* * 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_MODES_H #define CRYPT_MODES_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_MODES #include <stdint.h> #include "crypt_local_types.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus #define MODES_MAX_IV_LENGTH 24 #define MODES_MAX_BUF_LENGTH 24 #define MODES_IV_LENGTH 16 #define EAL_MAX_BLOCK_LENGTH 32 typedef struct { void *ciphCtx; /* Context defined by each algorithm */ const EAL_SymMethod *ciphMeth; /* Corresponding to the related methods for each symmetric algorithm */ uint8_t iv[MODES_MAX_IV_LENGTH]; /* IV information */ uint8_t buf[MODES_MAX_BUF_LENGTH]; /* Cache the information of the previous block. */ uint8_t blockSize; /* Save the block size. */ uint8_t offset; uint8_t flag3Iv; /* Indicates whether three IVs are used. */ uint32_t ivIndex; /* Indicates the sequence number of the IV block to be used. TDES may have three IV. */ } MODES_CipherCommonCtx; struct ModesCipherCtx { MODES_CipherCommonCtx commonCtx; int32_t algId; uint8_t data[EAL_MAX_BLOCK_LENGTH]; /**< last data block that may not be processed */ uint8_t dataLen; /**< size of the last data block that may not be processed. */ CRYPT_PaddingType pad; /**< padding type */ bool enc; }; typedef struct ModesCipherCtx MODES_CipherCtx; typedef struct { const uint8_t *in; uint8_t *out; const uint8_t *ctr; uint8_t *tag; } XorCryptData; void MODES_Clean(MODES_CipherCommonCtx *ctx); int32_t MODES_SetIv(MODES_CipherCommonCtx *ctx, const uint8_t *val, uint32_t len); int32_t MODES_GetIv(MODES_CipherCommonCtx *ctx, uint8_t *val, uint32_t len); #ifdef __cplusplus } #endif // __cplusplus #endif // HITLS_CRYPTO_MODES #endif // CRYPT_MODES_H
2302_82127028/openHiTLS-examples_1508
crypto/modes/include/crypt_modes.h
C
unknown
2,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. */ #ifndef CRYPT_MODES_CBC_H #define CRYPT_MODES_CBC_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_CBC #include "crypt_types.h" #include "crypt_modes.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus // CBC mode universal implementation MODES_CipherCtx *MODES_CBC_NewCtx(int32_t algId); int32_t MODES_CBC_InitCtx(MODES_CipherCtx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, bool enc); int32_t MODES_CBC_Update(MODES_CipherCtx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t MODES_CBC_Final(MODES_CipherCtx *modeCtx, uint8_t *out, uint32_t *outLen); int32_t MODES_CBC_DeInitCtx(MODES_CipherCtx *modeCtx); int32_t MODES_CBC_Ctrl(MODES_CipherCtx *modeCtx, int32_t cmd, void *val, uint32_t valLen); void MODES_CBC_FreeCtx(MODES_CipherCtx *modeCtx); #ifdef HITLS_CRYPTO_AES // AES CBC optimization implementation int32_t AES_CBC_Update(MODES_CipherCtx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t AES_CBC_Final(MODES_CipherCtx *modeCtx, uint8_t *out, uint32_t *outLen); #endif #ifdef HITLS_CRYPTO_SM4 // SM4 CBC optimization implementation int32_t SM4_CBC_Update(MODES_CipherCtx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t SM4_CBC_Final(MODES_CipherCtx *modeCtx, uint8_t *out, uint32_t *outLen); int32_t SM4_CBC_InitCtx(MODES_CipherCtx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, bool enc); #endif int32_t MODES_CBC_UpdateEx(MODES_CipherCtx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t MODES_CBC_InitCtxEx(MODES_CipherCtx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, void *param, bool enc); int32_t MODES_CBC_FinalEx(MODES_CipherCtx *modeCtx, uint8_t *out, uint32_t *outLen); #ifdef __cplusplus } #endif // __cplusplus #endif // HITLS_CRYPTO_CBC #endif // CRYPT_MODES_CBC_H
2302_82127028/openHiTLS-examples_1508
crypto/modes/include/crypt_modes_cbc.h
C
unknown
2,514
/* * 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_MODES_CCM_H #define CRYPT_MODES_CCM_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_CCM #include "crypt_types.h" #include "crypt_modes.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus #define CCM_BLOCKSIZE 16 typedef struct { void *ciphCtx; /* Context defined by each algorithm */ const EAL_SymMethod *ciphMeth; /* Corresponding to the related methods for each symmetric algorithm */ uint8_t nonce[CCM_BLOCKSIZE]; /* Data nonce, ctr encrypted data */ uint8_t tag[CCM_BLOCKSIZE]; /* Data tag, intermediate data encrypted by the CBC */ uint8_t last[CCM_BLOCKSIZE]; /* Previous data block in ctr mode */ uint64_t msgLen; /* The message length */ uint8_t lastLen; /* Unused data length of the previous data block in ctr mode. */ uint8_t tagLen; /* The length of the tag is 16 by default. The tag is reset each time the key is set. */ uint8_t tagInit; /* Indicate whether the tag is initialized. */ } MODES_CipherCCMCtx; struct ModesCcmCtx { int32_t algId; MODES_CipherCCMCtx ccmCtx; bool enc; }; typedef struct ModesCcmCtx MODES_CCM_Ctx; // CCM mode universal implementation MODES_CCM_Ctx *MODES_CCM_NewCtx(int32_t algId); int32_t MODES_CCM_InitCtx(MODES_CCM_Ctx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, void *param, bool enc); int32_t MODES_CCM_Update(MODES_CCM_Ctx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t MODES_CCM_Final(MODES_CCM_Ctx *modeCtx, uint8_t *out, uint32_t *outLen); int32_t MODES_CCM_DeInitCtx(MODES_CCM_Ctx *modeCtx); int32_t MODES_CCM_Ctrl(MODES_CCM_Ctx *modeCtx, int32_t opt, void *val, uint32_t len); void MODES_CCM_FreeCtx(MODES_CCM_Ctx *modeCtx); // AES CCM optimization implementation int32_t AES_CCM_Update(MODES_CCM_Ctx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t MODES_CCM_UpdateEx(MODES_CCM_Ctx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); #ifdef __cplusplus } #endif // __cplusplus #endif // HITLS_CRYPTO_CCM #endif // CRYPT_MODES_CCM_H
2302_82127028/openHiTLS-examples_1508
crypto/modes/include/crypt_modes_ccm.h
C
unknown
2,671
/* * 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_MODES_CFB_H #define CRYPT_MODES_CFB_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_CFB #include "crypt_types.h" #include "crypt_modes.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus #define DES_BLOCK_BYTE_NUM 8 typedef struct { MODES_CipherCommonCtx modeCtx; uint8_t feedbackBits; /* Save the FeedBack length. */ uint8_t cipherCache[3][DES_BLOCK_BYTE_NUM]; uint8_t cacheIndex; /* Used by the TDES that has 3IV. Indicate which cache is being used. */ } MODES_CipherCFBCtx; struct ModesCFBCtx { int32_t algId; MODES_CipherCFBCtx cfbCtx; bool enc; }; typedef struct ModesCFBCtx MODES_CFB_Ctx; // CFB mode universal implementation MODES_CFB_Ctx *MODES_CFB_NewCtx(int32_t algId); int32_t MODES_CFB_InitCtx(MODES_CFB_Ctx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, bool enc); int32_t MODES_CFB_Update(MODES_CFB_Ctx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t MODES_CFB_Final(MODES_CFB_Ctx *modeCtx, uint8_t *out, uint32_t *outLen); int32_t MODES_CFB_DeInitCtx(MODES_CFB_Ctx *modeCtx); int32_t MODES_CFB_Ctrl(MODES_CFB_Ctx *modeCtx, int32_t opt, void *val, uint32_t len); void MODES_CFB_FreeCtx(MODES_CFB_Ctx *modeCtx); // AES CFB optimization implementation int32_t AES_CFB_Update(MODES_CFB_Ctx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); // SM4 CFB optimization implementation int32_t SM4_CFB_InitCtx(MODES_CFB_Ctx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, bool enc); int32_t SM4_CFB_Update(MODES_CFB_Ctx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t MODES_CFB_InitCtxEx(MODES_CFB_Ctx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, void *param, bool enc); int32_t MODES_CFB_UpdateEx(MODES_CFB_Ctx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); #ifdef __cplusplus } #endif // __cplusplus #endif // HITLS_CRYPTO_CFB #endif // CRYPT_MODES_CFB_H
2302_82127028/openHiTLS-examples_1508
crypto/modes/include/crypt_modes_cfb.h
C
unknown
2,619
/* * 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_MODES_CHACHA20POLY1305_H #define CRYPT_MODES_CHACHA20POLY1305_H #include "hitls_build.h" #if defined(HITLS_CRYPTO_CHACHA20) && defined(HITLS_CRYPTO_CHACHA20POLY1305) #include "crypt_types.h" #include "crypt_modes.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus typedef struct { uint32_t acc[6]; // The intermediate data of the acc, must be greater than 130 bits. uint32_t r[4]; // Key information r, 16 bytes, that is, 4 * sizeof(uint32_t) uint32_t s[4]; // Key information s, 16 bytes, that is, 4 * sizeof(uint32_t) uint32_t table[36]; // Indicates the table used to accelerate the assembly calculation. uint8_t last[16]; // A block 16 bytes are cached for the last unprocessed data. uint32_t lastLen; // Indicates the remaining length of the last data. uint32_t flag; // Used to save the assembly status information. } Poly1305Ctx; typedef struct { void *key; // Handle for the method. const EAL_SymMethod *method; // algorithm method Poly1305Ctx polyCtx; uint64_t aadLen; // Status, indicating whether identification data is set. uint64_t cipherTextLen; // status, indicating whether the identification data is set. } MODES_CipherChaChaPolyCtx; struct ModesChaChaCtx { int32_t algId; MODES_CipherChaChaPolyCtx chachaCtx; bool enc; }; typedef struct ModesChaChaCtx MODES_CHACHAPOLY_Ctx; MODES_CHACHAPOLY_Ctx *MODES_CHACHA20POLY1305_NewCtx(int32_t algId); int32_t MODES_CHACHA20POLY1305_InitCtx(MODES_CHACHAPOLY_Ctx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, void *param, bool enc); int32_t MODES_CHACHA20POLY1305_Update(MODES_CHACHAPOLY_Ctx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t MODES_CHACHA20POLY1305_Final(MODES_CHACHAPOLY_Ctx *modeCtx, uint8_t *out, uint32_t *outLen); int32_t MODES_CHACHA20POLY1305_DeInitCtx(MODES_CHACHAPOLY_Ctx *modeCtx); int32_t MODES_CHACHA20POLY1305_Ctrl(MODES_CHACHAPOLY_Ctx *modeCtx, int32_t cmd, void *val, uint32_t len); void MODES_CHACHA20POLY1305_FreeCtx(MODES_CHACHAPOLY_Ctx *modeCtx); #ifdef __cplusplus } #endif // __cplusplus #endif // HITLS_CRYPTO_CHACHA20POLY1305 #endif // CRYPT_MODES_CHACHA20POLY1305_H
2302_82127028/openHiTLS-examples_1508
crypto/modes/include/crypt_modes_chacha20poly1305.h
C
unknown
2,798
/* * 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_MODES_CTR_H #define CRYPT_MODES_CTR_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_CTR #include "crypt_types.h" #include "crypt_modes.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus // CTR mode universal implementation MODES_CipherCtx *MODES_CTR_NewCtx(int32_t algId); int32_t MODES_CTR_InitCtx(MODES_CipherCtx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, bool enc); int32_t MODES_CTR_Update(MODES_CipherCtx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t MODES_CTR_Final(MODES_CipherCtx *modeCtx, uint8_t *out, uint32_t *outLen); int32_t MODES_CTR_DeInitCtx(MODES_CipherCtx *modeCtx); int32_t MODES_CTR_Ctrl(MODES_CipherCtx *modeCtx, int32_t cmd, void *val, uint32_t valLen); void MODES_CTR_FreeCtx(MODES_CipherCtx *modeCtx); // AES CTR optimization implementation int32_t AES_CTR_Update(MODES_CipherCtx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); // SM4 CTR optimization implementation int32_t SM4_CTR_Update(MODES_CipherCtx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t SM4_CTR_InitCtx(MODES_CipherCtx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, bool enc); int32_t MODES_CTR_InitCtxEx(MODES_CipherCtx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, void *param, bool enc); int32_t MODES_CTR_UpdateEx(MODES_CipherCtx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); #ifdef __cplusplus } #endif // __cplusplus #endif // HITLS_CRYPTO_CTR #endif // CRYPT_MODES_CTR_H
2302_82127028/openHiTLS-examples_1508
crypto/modes/include/crypt_modes_ctr.h
C
unknown
2,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. */ #ifndef CRYPT_MODES_ECB_H #define CRYPT_MODES_ECB_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_ECB #include "crypt_types.h" #include "crypt_modes.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus // ECB mode universal implementation MODES_CipherCtx *MODES_ECB_NewCtx(int32_t algId); int32_t MODES_ECB_InitCtx(MODES_CipherCtx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, bool enc); int32_t MODES_ECB_Update(MODES_CipherCtx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t MODES_ECB_Final(MODES_CipherCtx *modeCtx, uint8_t *out, uint32_t *outLen); int32_t MODES_ECB_DeinitCtx(MODES_CipherCtx *modeCtx); int32_t MODES_ECB_Ctrl(MODES_CipherCtx *modeCtx, int32_t cmd, void *val, uint32_t valLen); void MODES_ECB_FreeCtx(MODES_CipherCtx *modeCtx); // AES ECB optimization implementation int32_t AES_ECB_Update(MODES_CipherCtx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t AES_ECB_Final(MODES_CipherCtx *modeCtx, uint8_t *out, uint32_t *outLen); // SM4 ECB optimization implementation int32_t SM4_ECB_InitCtx(MODES_CipherCtx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, bool enc); int32_t SM4_ECB_Update(MODES_CipherCtx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t SM4_ECB_Final(MODES_CipherCtx *modeCtx, uint8_t *out, uint32_t *outLen); int32_t MODES_ECB_InitCtxEx(MODES_CipherCtx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, void *param, bool enc); int32_t MODES_ECB_UpdateEx(MODES_CipherCtx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t MODES_ECB_FinalEx(MODES_CipherCtx *modeCtx, uint8_t *out, uint32_t *outLen); #ifdef __cplusplus } #endif // __cplusplus #endif #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/include/crypt_modes_ecb.h
C
unknown
2,409
/* * 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_MODES_GCM_H #define CRYPT_MODES_GCM_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_GCM #include "crypt_types.h" #include "crypt_modes.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus #define GCM_MAX_COMBINED_LENGTH (((uint64_t)1 << 36) - 32) #define GCM_MAX_INVOCATIONS_TIMES ((uint32_t)(-1)) #define GCM_BLOCK_MASK (0xfffffff0) typedef struct { uint64_t h; uint64_t l; } MODES_GCM_GF128; #define GCM_BLOCKSIZE 16 typedef struct { uint8_t iv[GCM_BLOCKSIZE]; // Processed IV information. The length is 16 bytes. uint8_t ghash[GCM_BLOCKSIZE]; // Intermediate data for tag calculation. MODES_GCM_GF128 hTable[16]; // The window uses 4 bits, 2 ^ 4 = 16 entries need to be pre-calculated. void *ciphCtx; // Context defined by each symmetric algorithm. const EAL_SymMethod *ciphMeth; // algorithm method uint8_t tagLen; uint32_t cryptCnt; // Indicate the number of encryption times that the key can be used. uint8_t last[GCM_BLOCKSIZE]; // ctr mode last uint8_t remCt[GCM_BLOCKSIZE]; // Remaining ciphertext uint8_t ek0[GCM_BLOCKSIZE]; // ek0 uint64_t plaintextLen; // use for calc tag uint32_t aadLen; // use for calc tag uint32_t lastLen; // ctr mode lastLen } MODES_CipherGCMCtx; struct ModesGcmCtx { int32_t algId; MODES_CipherGCMCtx gcmCtx; bool enc; }; typedef struct ModesGcmCtx MODES_GCM_Ctx; // GCM mode universal implementation MODES_GCM_Ctx *MODES_GCM_NewCtx(int32_t algId); int32_t MODES_GCM_InitCtx(MODES_GCM_Ctx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, bool enc); int32_t MODES_GCM_Update(MODES_GCM_Ctx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t MODES_GCM_Final(MODES_GCM_Ctx *modeCtx, uint8_t *out, uint32_t *outLen); int32_t MODES_GCM_DeInitCtx(MODES_GCM_Ctx *modeCtx); int32_t MODES_GCM_Ctrl(MODES_GCM_Ctx *modeCtx, int32_t cmd, void *val, uint32_t len); void MODES_GCM_FreeCtx(MODES_GCM_Ctx *modeCtx); // AES GCM optimization implementation int32_t AES_GCM_Update(MODES_GCM_Ctx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); // SM4 GCM optimization implementation int32_t SM4_GCM_InitCtx(MODES_GCM_Ctx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, bool enc); int32_t SM4_GCM_Update(MODES_GCM_Ctx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t MODES_GCM_InitCtxEx(MODES_GCM_Ctx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, void *param, bool enc); int32_t MODES_GCM_UpdateEx(MODES_GCM_Ctx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t MODES_GCM_InitHashTable(MODES_CipherGCMCtx *ctx); int32_t MODES_GCM_SetKey(MODES_CipherGCMCtx *ctx, const uint8_t *key, uint32_t len); #ifdef __cplusplus } #endif // __cplusplus #endif // HITLS_CRYPTO_GCM #endif // CRYPT_MODES_GCM_H
2302_82127028/openHiTLS-examples_1508
crypto/modes/include/crypt_modes_gcm.h
C
unknown
3,545
/* * 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_MODES_OFB_H #define CRYPT_MODES_OFB_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_OFB #include "crypt_types.h" #include "crypt_modes.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus // OFB mode universal implementation MODES_CipherCtx *MODES_OFB_NewCtx(int32_t algId); int32_t MODES_OFB_InitCtx(MODES_CipherCtx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, bool enc); int32_t MODES_OFB_Update(MODES_CipherCtx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t MODES_OFB_Final(MODES_CipherCtx *modeCtx, uint8_t *out, uint32_t *outLen); int32_t MODES_OFB_DeInitCtx(MODES_CipherCtx *modeCtx); int32_t MODES_OFB_Ctrl(MODES_CipherCtx *modeCtx, int32_t cmd, void *val, uint32_t valLen); void MODES_OFB_FreeCtx(MODES_CipherCtx *modeCtx); // SM4 OFB optimization implementation int32_t SM4_OFB_InitCtx(MODES_CipherCtx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, bool enc); int32_t SM4_OFB_Update(MODES_CipherCtx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t MODES_OFB_InitCtxEx(MODES_CipherCtx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, void *param, bool enc); int32_t MODES_OFB_UpdateEx(MODES_CipherCtx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); #ifdef __cplusplus } #endif // __cplusplus #endif // HITLS_CRYPTO_OFB #endif // CRYPT_MODES_OFB_H
2302_82127028/openHiTLS-examples_1508
crypto/modes/include/crypt_modes_ofb.h
C
unknown
2,050
/* * 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_MODES_XTS_H #define CRYPT_MODES_XTS_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_XTS #include "crypt_types.h" #include "bsl_params.h" #include "crypt_modes.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus typedef struct { void *ciphCtx; /* Key defined by each algorithm */ const EAL_SymMethod *ciphMeth; /* corresponding to the encrypt and decrypt in the bottom layer, operate keyctx */ uint8_t iv[MODES_MAX_IV_LENGTH]; /* The length is blocksize */ uint8_t tweak[MODES_MAX_IV_LENGTH]; /* The length is blocksize */ uint8_t blockSize; /* Save the block size. */ } MODES_CipherXTSCtx; struct ModesXTSCtx { int32_t algId; MODES_CipherXTSCtx xtsCtx; uint8_t data[EAL_MAX_BLOCK_LENGTH]; /**< last data block that may not be processed */ uint8_t dataLen; /**< size of the last data block that may not be processed. */ CRYPT_PaddingType pad; bool enc; }; typedef struct ModesXTSCtx MODES_XTS_Ctx; // XTS mode universal implementation MODES_XTS_Ctx *MODES_XTS_NewCtx(int32_t algId); int32_t MODES_XTS_InitCtx(MODES_XTS_Ctx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, bool enc); int32_t MODES_XTS_Update(MODES_XTS_Ctx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t MODES_XTS_Final(MODES_XTS_Ctx *modeCtx, uint8_t *out, uint32_t *outLen); int32_t MODES_XTS_DeInitCtx(MODES_XTS_Ctx *modeCtx); int32_t MODES_XTS_Ctrl(MODES_XTS_Ctx *modeCtx, int32_t cmd, void *val, uint32_t len); void MODES_XTS_FreeCtx(MODES_XTS_Ctx *modeCtx); // XTS mode universal implementation int32_t SM4_XTS_Update(MODES_XTS_Ctx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t SM4_XTS_InitCtx(MODES_XTS_Ctx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, bool enc); int32_t SM4_XTS_Final(MODES_XTS_Ctx *modeCtx, uint8_t *out, uint32_t *outLen); int32_t MODES_XTS_InitCtxEx(MODES_XTS_Ctx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, void *param, bool enc); int32_t MODES_XTS_UpdateEx(MODES_XTS_Ctx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t AES_XTS_Update(MODES_XTS_Ctx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen); int32_t AES_XTS_Final(MODES_XTS_Ctx *modeCtx, uint8_t *out, uint32_t *outLen); #ifdef __cplusplus } #endif // __cplusplus #endif // HITLS_CRYPTO_XTS #endif // CRYPT_MODES_XTS_H
2302_82127028/openHiTLS-examples_1508
crypto/modes/include/crypt_modes_xts.h
C
unknown
3,133
/* * 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_AES) && defined(HITLS_CRYPTO_GCM) .macro GCM_ENC128_LOOP ldp x6, x7, [INPUT], #16 // AES[0] - load plaintext rev64 OUT0.16b, OUT0.16b // GHASH blocl[0] rev64 OUT2.16b, OUT2.16b // GHASH block[2] ROUND CTR2.16b, KEY0.16b #ifdef HITLS_BIG_ENDIAN rev x6, x6 rev x7, x7 #endif fmov d3, x10 // CTR[3] ext HASH0.16b, HASH0.16b, HASH0.16b, #8 // PRE 0 rev64 OUT1.16b, OUT1.16b // GHASH block[1] ROUND CTR1.16b, KEY0.16b add IV_W, IV_W, #1 // CTR3++ fmov CTR3.d[1], x9 // CTR[3]--OK ROUND CTR0.16b, KEY0.16b mov d31, OUT2.d[1] // GHASH block[2.1] ROUND CTR2.16b, KEY1.16b mov d30, OUT1.d[1] // GHASH block[1.1] ROUND CTR1.16b, KEY1.16b eor v4.16b, OUT0.16b, HASH0.16b // PRE 1 ROUND CTR3.16b, KEY0.16b eor x7, x7, KEND1 // AES[0] - round 10 high pmull2 v28.1q, OUT1.2d, HASH3.2d // GHASH block 4k+1 - high eor v31.8b, v31.8b, OUT2.8b // GHASH[2] - mid ldp x19, x20, [INPUT], #16 // AES[1] - load plaintext ROUND CTR0.16b, KEY1.16b rev w9, IV_W // CTR0--Start eor v30.8b, v30.8b, OUT1.8b // GHASH block 4k+1 - mid #ifdef HITLS_BIG_ENDIAN rev x19, x19 rev x20, x20 #endif mov d8, v4.d[1] // GHASH block 4k - mid orr x9, x11, x9, lsl #32 // CTR0 block 4k+8 pmull2 v9.1q, v4.2d, HASH4.2d // GHASH block 4k - high add IV_W, IV_W, #1 // CTR0++ mov d10, v17.d[1] // GHASH block 4k - mid ROUND CTR0.16b, KEY2.16b pmull HASH0.1q, v4.1d, HASH4.1d // GHASH block 4k - low eor v8.8b, v8.8b, v4.8b // GHASH block 4k - mid ROUND CTR1.16b, KEY2.16b ROUND CTR0.16b, KEY3.16b eor v9.16b, v9.16b, v28.16b // GHASH block 4k+1 - high pmull v28.1q, OUT2.1d, HASH2.1d // GHASH[2] - low pmull v10.1q, v8.1d, v10.1d // GHASH block 4k - mid rev64 OUT3.16b, OUT3.16b // GHASH[0] (t0, t1, t2 and t3 free) pmull v30.1q, v30.1d, v17.1d // GHASH block 4k+1 - mid pmull v29.1q, OUT1.1d, HASH3.1d // GHASH block 4k+1 - low ins v31.d[1], v31.d[0] // GHASH[2] - mid pmull2 v8.1q, OUT2.2d, HASH2.2d // GHASH[2] - high eor x20, x20, KEND1 // AES[1] - round 10 high eor v10.16b, v10.16b, v30.16b // GHASH block 4k+1 - mid mov d30, OUT3.d[1] // GHASH[0] - mid ROUND CTR3.16b, v19.16b eor HASH0.16b, HASH0.16b, v29.16b // GHASH block 4k+1 - low ROUND CTR2.16b, KEY2.16b eor x6, x6, KEND0 // AES[0] - round 10 low ROUND CTR1.16b, KEY3.16b eor v30.8b, v30.8b, OUT3.8b // GHASH[0] - mid pmull2 v4.1q, OUT3.2d, HASH1.2d // GHASH[0] - high ROUND CTR2.16b, KEY3.16b eor v9.16b, v9.16b, v8.16b // GHASH[2] - high pmull2 v31.1q, v31.2d, v16.2d // GHASH[2] - mid pmull v29.1q, OUT3.1d, HASH1.1d // GHASH[0] - low movi v8.8b, #0xc2 pmull v30.1q, v30.1d, v16.1d // GHASH[0] - mid eor HASH0.16b, HASH0.16b, v28.16b // GHASH[2] - low ROUND CTR1.16b, KEY4.16b ROUND CTR3.16b, v20.16b shl d8, d8, #56 // mod_constant ROUND CTR0.16b, KEY4.16b eor v9.16b, v9.16b, v4.16b // GHASH[0] - high ROUND CTR1.16b, KEY5.16b ldp x21, x22, [INPUT], #16 // AES[2] - load plaintext ROUND CTR3.16b, v21.16b eor v10.16b, v10.16b, v31.16b // GHASH[2] - mid #ifdef HITLS_BIG_ENDIAN rev x21, x21 rev x22, x22 #endif ROUND CTR0.16b, KEY5.16b ldp x23, x24, [INPUT], #16 // AES[3] - load plaintext pmull v31.1q, v9.1d, v8.1d // MODULO - top 64b align with mid eor HASH0.16b, HASH0.16b, v29.16b // GHASH[0] - low #ifdef HITLS_BIG_ENDIAN rev x23, x23 rev x24, x24 #endif ROUND CTR2.16b, KEY4.16b eor x19, x19, KEND0 // AES[1] - round 10 low ROUND CTR3.16b, v22.16b eor v10.16b, v10.16b, v30.16b // GHASH[0] - mid ROUND CTR1.16b, KEY6.16b eor x23, x23, KEND0 // AES[3] - round 10 low ROUND CTR2.16b, KEY5.16b eor v30.16b, HASH0.16b, v9.16b // MODULO - karatsuba tidy up fmov d4, x6 // AES[0] - mov low ROUND CTR0.16b, KEY6.16b fmov OUT0.d[1], x7 // AES[0] - mov high fmov d7, x23 // AES[3] - mov low ext v9.16b, v9.16b, v9.16b, #8 // MODULO - other top alignment ROUND CTR3.16b, v23.16b fmov d5, x19 // AES[2] - mov low ROUND CTR0.16b, KEY7.16b eor v10.16b, v10.16b, v30.16b // MODULO - karatsuba tidy up ROUND CTR2.16b, KEY6.16b eor x24, x24, KEND1 // AES[3] - round 10 high ROUND CTR1.16b, KEY7.16b fmov OUT1.d[1], x20 // AES[1] - mov high ROUND CTR0.16b, KEY8.16b fmov OUT3.d[1], x24 // AES[3] - mov high ROUND CTR3.16b, v24.16b subs COUNT, COUNT, #1 // count-- ROUND CTR1.16b, KEY8.16b eor v10.16b, v10.16b, v31.16b // MODULO - fold into mid aese CTR0.16b, KEY9.16b eor x21, x21, KEND0 // AES[2] - round 10 low eor x22, x22, KEND1 // AES[2] - round 10 high ROUND CTR3.16b, v25.16b fmov d6, x21 // AES[2] - mov low aese CTR1.16b, KEY9.16b // AES[1] - round 9 fmov OUT2.d[1], x22 // AES[2] - mov high ROUND CTR2.16b, KEY7.16b eor OUT0.16b, OUT0.16b, CTR0.16b // AES[0] - result fmov d0, x10 // CTR0-0 ROUND CTR3.16b, KEY8.16b fmov CTR0.d[1], x9 // CTR0-1--OK rev w9, IV_W // CTR1--start eor v10.16b, v10.16b, v9.16b // MODULO - fold into mid ROUND CTR2.16b, KEY8.16b eor OUT1.16b, OUT1.16b, CTR1.16b // AES[1] - result add IV_W, IV_W, #1 // CTR1++ orr x9, x11, x9, lsl #32 // CTR1 block 4k+9 fmov d1, x10 // CTR1-0 pmull v9.1q, v10.1d, v8.1d // MODULO - mid 64b align with low fmov CTR1.d[1], x9 // CTR1-1--OK rev w9, IV_W // CTR2--Start aese CTR2.16b, KEY9.16b st1 {OUT0.16b}, [OUT00], #16 // Write back - OUT0 eor OUT2.16b, OUT2.16b, CTR2.16b // AES[2]-result orr x9, x11, x9, lsl #32 // CTR2 block 4k+10 aese CTR3.16b, KEY9.16b add IV_W, IV_W, #1 // CTR2++ ext v10.16b, v10.16b, v10.16b, #8 // MODULO - other mid alignment fmov d2, x10 // CTR2-0 eor HASH0.16b, HASH0.16b, v9.16b // MODULO - fold into low st1 {OUT1.16b}, [OUT00], #16 // Write back - OUT1 fmov CTR2.d[1], x9 // CTR2-1--OK st1 {OUT2.16b}, [OUT00], #16 // Write back - OUT2 rev w9, IV_W // CTR3--start eor OUT3.16b, OUT3.16b, CTR3.16b // AES[3]-result orr x9, x11, x9, lsl #32 // CTR3 block 4k+11 eor HASH0.16b, HASH0.16b, v10.16b // MODULO - fold into low st1 {OUT3.16b}, [OUT00], #16 // Write back - OUT3 .endm .macro GCM_DEC128_LOOP eor CTR3.16b, OUT3.16b, CTR3.16b // AES[3] - result ext HASH0.16b, HASH0.16b, HASH0.16b, #8 // PRE 0 mov x21, CTR2.d[0] // AES[2] - mov low pmull2 v28.1q, v5.2d, HASH3.2d // GHASH block 4k+1 - high mov x22, CTR2.d[1] // AES[2] - mov high ROUND CTR1.16b, KEY0.16b fmov d2, x10 // CTR[3] #ifdef HITLS_BIG_ENDIAN rev x21, x21 rev x22, x22 #endif rev64 OUT2.16b, OUT2.16b // GHASH[2] fmov v2.d[1], x9 // CTR[3] rev w9, IV_W // CTR[0] mov x23, CTR3.d[0] // AES[3] - mov low eor v4.16b, v4.16b, HASH0.16b // PRE 1 mov d30, v5.d[1] // GHASH block 4k+1 - mid ROUND CTR1.16b, KEY1.16b rev64 v7.16b, v7.16b // GHASH[0] pmull v29.1q, v5.1d, HASH3.1d // GHASH block 4k+1 - low mov x24, CTR3.d[1] // AES[3] - mov high orr x9, x11, x9, lsl #32 // CTR[0] pmull HASH0.1q, v4.1d, HASH4.1d // GHASH block 4k - low #ifdef HITLS_BIG_ENDIAN rev x23, x23 rev x24, x24 #endif fmov d3, x10 // CTR[0] eor v30.8b, v30.8b, v5.8b // GHASH block 4k+1 - mid ROUND CTR1.16b, KEY2.16b fmov v3.d[1], x9 // CTR[0] ROUND CTR2.16b, KEY0.16b mov d10, v17.d[1] // GHASH block 4k - mid pmull2 v9.1q, v4.2d, HASH4.2d // GHASH block 4k - high eor HASH0.16b, HASH0.16b, v29.16b // GHASH block 4k+1 - low pmull v29.1q, v7.1d, HASH1.1d // GHASH[0] - low ROUND CTR1.16b, KEY3.16b mov d8, v4.d[1] // GHASH block 4k - mid ROUND CTR3.16b, KEY0.16b eor v9.16b, v9.16b, v28.16b // GHASH block 4k+1 - high ROUND CTR0.16b, KEY0.16b pmull v28.1q, v6.1d, HASH2.1d // GHASH[2] - low eor v8.8b, v8.8b, v4.8b // GHASH block 4k - mid ROUND CTR3.16b, KEY1.16b eor x23, x23, KEND0 // AES[3] - round 10 low pmull v30.1q, v30.1d, v17.1d // GHASH block 4k+1 - mid eor x22, x22, KEND1 // AES[2] - round 10 high mov d31, v6.d[1] // GHASH[2] - mid ROUND CTR0.16b, KEY1.16b eor HASH0.16b, HASH0.16b, v28.16b // GHASH[2] - low pmull v10.1q, v8.1d, v10.1d // GHASH block 4k - mid ROUND CTR3.16b, KEY2.16b eor v31.8b, v31.8b, v6.8b // GHASH[2] - mid ROUND CTR0.16b, KEY2.16b ROUND CTR1.16b, KEY4.16b eor v10.16b, v10.16b, v30.16b // GHASH block 4k+1 - mid pmull2 v8.1q, v6.2d, HASH2.2d // GHASH[2] - high ROUND CTR0.16b, KEY3.16b ins v31.d[1], v31.d[0] // GHASH[2] - mid pmull2 v4.1q, v7.2d, HASH1.2d // GHASH[0] - high ROUND CTR2.16b, KEY1.16b mov d30, v7.d[1] // GHASH[0] - mid ROUND CTR0.16b, KEY4.16b eor v9.16b, v9.16b, v8.16b // GHASH[2] - high pmull2 v31.1q, v31.2d, v16.2d // GHASH[2] - mid eor x24, x24, KEND1 // AES[3] - round 10 high ROUND CTR2.16b, KEY2.16b eor v30.8b, v30.8b, v7.8b // GHASH[0] - mid ROUND CTR1.16b, KEY5.16b eor x21, x21, KEND0 // AES[2] - round 10 low ROUND CTR0.16b, KEY5.16b movi v8.8b, #0xc2 ROUND CTR2.16b, KEY3.16b eor HASH0.16b, HASH0.16b, v29.16b // GHASH[0] - low ROUND CTR1.16b, KEY6.16b ROUND CTR0.16b, KEY6.16b eor v10.16b, v10.16b, v31.16b // GHASH[2] - mid ROUND CTR2.16b, KEY4.16b stp x21, x22, [OUT00], #16 // AES[2] - store result pmull v30.1q, v30.1d, v16.1d // GHASH[0] - mid eor v9.16b, v9.16b, v4.16b // GHASH[0] - high ld1 {OUT0.16b}, [INPUT], #16 // AES[0] - load ciphertext ROUND CTR1.16b, KEY7.16b add IV_W, IV_W, #1 // CTR++ ROUND CTR0.16b, KEY7.16b shl d8, d8, #56 // mod_constant ROUND CTR2.16b, KEY5.16b eor v10.16b, v10.16b, v30.16b // GHASH[0] - mid ROUND CTR1.16b, KEY8.16b stp x23, x24, [OUT00], #16 // AES[3] - store result ROUND CTR0.16b, KEY8.16b eor v30.16b, HASH0.16b, v9.16b // MODULO - karatsuba tidy up ROUND CTR3.16b, KEY3.16b rev w9, IV_W // CTR block 4k+8 pmull v31.1q, v9.1d, v8.1d // MODULO - top 64b align with mid ld1 {OUT1.16b}, [INPUT], #16 // AES[1] - load ext v9.16b, v9.16b, v9.16b, #8 // MODULO - other top alignment aese CTR0.16b, KEY9.16b // AES[0] - round 9 orr x9, x11, x9, lsl #32 // CTR block 4k+8 ROUND CTR3.16b, KEY4.16b eor v10.16b, v10.16b, v30.16b // MODULO - karatsuba tidy up aese CTR1.16b, KEY9.16b // AES[1] - round 9 ROUND CTR2.16b, KEY6.16b eor CTR0.16b, OUT0.16b, CTR0.16b // AES[0] - result ROUND CTR3.16b, KEY5.16b ld1 {OUT2.16b}, [INPUT], #16 // AES[2] - load add IV_W, IV_W, #1 // CTR++ eor v10.16b, v10.16b, v31.16b // MODULO - fold into mid eor CTR1.16b, OUT1.16b, CTR1.16b // AES[1] - result ROUND CTR2.16b, KEY7.16b ld1 {OUT3.16b}, [INPUT], #16 ROUND CTR3.16b, KEY6.16b rev64 OUT1.16b, OUT1.16b // GHASH block[1] eor v10.16b, v10.16b, v9.16b // MODULO - fold into mid mov x7, CTR0.d[1] // AES[0] - mov high ROUND CTR2.16b, KEY8.16b mov x6, CTR0.d[0] // AES[0] - mov low ROUND CTR3.16b, KEY7.16b fmov d0, x10 // CTR[0] #ifdef HITLS_BIG_ENDIAN rev x7, x7 rev x6, x6 #endif pmull v8.1q, v10.1d, v8.1d // MODULO - mid 64b align with low fmov CTR0.d[1], x9 // CTR[0] - OK rev w9, IV_W // CTR block 4k+9 aese CTR2.16b, KEY9.16b orr x9, x11, x9, lsl #32 // CTR block 4k+9 ext v10.16b, v10.16b, v10.16b, #8 // MODULO - other mid alignment ROUND CTR3.16b, KEY8.16b eor x7, x7, KEND1 // AES[0] - round 10 high eor HASH0.16b, HASH0.16b, v8.16b // MODULO - fold into low mov x20, CTR1.d[1] // AES[1] - mov high eor x6, x6, KEND0 // AES[0] - round 10 low eor CTR2.16b, OUT2.16b, CTR2.16b // AES[2] - result mov x19, CTR1.d[0] // AES[1] - mov low add IV_W, IV_W, #1 // CTR++ aese CTR3.16b, KEY9.16b fmov d1, x10 // CTR[1] #ifdef HITLS_BIG_ENDIAN rev x20, x20 rev x19, x19 #endif subs COUNT, COUNT, #1 // COUNT-- rev64 OUT0.16b, OUT0.16b // GHASH block[0] eor HASH0.16b, HASH0.16b, v10.16b // MODULO - fold into low fmov v1.d[1], x9 // CTR[1] - OK rev w9, IV_W // CTR block 4k+10 add IV_W, IV_W, #1 // CTR block 4k+10 eor x20, x20, KEND1 // AES[1] - round 10 high stp x6, x7, [OUT00], #16 // AES[0] - store result eor x19, x19, KEND0 // AES[1] - round 10 low stp x19, x20, [OUT00], #16 // AES[1] - store result orr x9, x11, x9, lsl #32 // CTR block 4k+10 .endm #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm/aes128_gcm_aarch64.S
Unix Assembly
unknown
16,590
/* * 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_AES) && defined(HITLS_CRYPTO_GCM) .macro GCM_ENC192_LOOP ROUND CTR2.16b, KEY0.16b rev64 OUT1.16b, OUT1.16b // GHASH block 4k+1 (t0 and t1 free) ROUND CTR1.16b, KEY0.16b ldp x6, x7, [INPUT], #16 // AES[0] - load plaintext ext HASH0.16b, HASH0.16b, HASH0.16b, #8 // PRE 0 fmov d3, x10 // CTR[3] rev64 OUT0.16b, OUT0.16b // GHASH block 4k (only t0 is free) ROUND CTR2.16b, KEY1.16b fmov CTR3.d[1], x9 // CTR[3]--OK #ifdef HITLS_BIG_ENDIAN rev x6, x6 rev x7, x7 #endif pmull2 v30.1q, v5.2d, HASH3.2d // GHASH block 4k+1 - high rev64 OUT3.16b, OUT3.16b // GHASH[0] (t0, t1, t2 and t3 free) ldp x19, x20, [INPUT], #16 // AES[1] - load plaintext ROUND CTR0.16b, KEY0.16b ldp x21, x22, [INPUT], #16 // AES[2] - load plaintext pmull v31.1q, v5.1d, HASH3.1d // GHASH block 4k+1 - low eor v4.16b, v4.16b, HASH0.16b // PRE 1 #ifdef HITLS_BIG_ENDIAN rev x19, x19 rev x20, x20 rev x21, x21 rev x22, x22 #endif ROUND CTR1.16b, KEY1.16b ROUND CTR0.16b, KEY1.16b rev64 OUT2.16b, OUT2.16b // GHASH[2] (t0, t1, and t2 free) ROUND CTR3.16b, KEY0.16b eor x7, x7, KEND1 // AES[0] - round 12 high pmull HASH0.1q, v4.1d, HASH4.1d // GHASH block 4k - low mov d8, v4.d[1] // GHASH block 4k - mid ROUND CTR0.16b, KEY2.16b ROUND CTR3.16b, KEY1.16b eor x6, x6, KEND0 // AES[0] - round 12 low eor v8.8b, v8.8b, v4.8b // GHASH block 4k - mid eor HASH0.16b, HASH0.16b, v31.16b // GHASH block 4k+1 - low ROUND CTR0.16b, KEY3.16b eor x19, x19, KEND0 // AES[1] - round 12 low ROUND CTR1.16b, KEY2.16b mov d31, v6.d[1] // GHASH[2] - mid pmull2 v9.1q, v4.2d, HASH4.2d // GHASH block 4k - high mov d4, v5.d[1] // GHASH block 4k+1 - mid ROUND CTR2.16b, KEY2.16b ROUND CTR1.16b, KEY3.16b mov d10, v17.d[1] // GHASH block 4k - mid eor v9.16b, v9.16b, v30.16b // GHASH block 4k+1 - high ROUND CTR3.16b, KEY2.16b eor v31.8b, v31.8b, v6.8b // GHASH[2] - mid pmull2 v30.1q, v6.2d, HASH2.2d // GHASH[2] - high ROUND CTR0.16b, KEY4.16b eor v4.8b, v4.8b, v5.8b // GHASH block 4k+1 - mid ROUND CTR3.16b, KEY3.16b pmull2 v5.1q, v7.2d, HASH1.2d // GHASH[0] - high eor x20, x20, KEND1 // AES[1] - round 12 high ins v31.d[1], v31.d[0] // GHASH[2] - mid ROUND CTR0.16b, KEY5.16b add IV_W, IV_W, #1 // CTR++ ROUND CTR3.16b, KEY4.16b eor v9.16b, v9.16b, v30.16b // GHASH[2] - high pmull v4.1q, v4.1d, v17.1d // GHASH block 4k+1 - mid eor x22, x22, KEND1 // AES[2] - round 12 high pmull2 v31.1q, v31.2d, v16.2d // GHASH[2] - mid eor x21, x21, KEND0 // AES[2] - round 12 low mov d30, v7.d[1] // GHASH[0] - mid pmull v10.1q, v8.1d, v10.1d // GHASH block 4k - mid rev w9, IV_W // CTR[0] pmull v8.1q, v6.1d, HASH2.1d // GHASH[2] - low orr x9, x11, x9, lsl #32 // CTR[0] ROUND CTR2.16b, KEY3.16b eor v30.8b, v30.8b, v7.8b // GHASH[0] - mid ROUND CTR1.16b, KEY4.16b ldp x23, x24, [INPUT], #16 // AES[3] - load plaintext ROUND CTR0.16b, KEY6.16b eor HASH0.16b, HASH0.16b, v8.16b // GHASH[2] - low ROUND CTR2.16b, KEY4.16b #ifdef HITLS_BIG_ENDIAN rev x23, x23 rev x24, x24 #endif ROUND CTR1.16b, KEY5.16b movi v8.8b, #0xc2 pmull v6.1q, v7.1d, HASH1.1d // GHASH[0] - low eor x24, x24, KEND1 // AES[3] - round 12 high eor v10.16b, v10.16b, v4.16b // GHASH block 4k+1 - mid ROUND CTR2.16b, KEY5.16b eor x23, x23, KEND0 // AES[3] - round 12 low ROUND CTR1.16b, KEY6.16b shl d8, d8, #56 // mod_constant ROUND CTR3.16b, KEY5.16b eor v9.16b, v9.16b, v5.16b // GHASH[0] - high ROUND CTR0.16b, KEY7.16b fmov d5, x19 // AES[1] - mov low ROUND CTR1.16b, KEY7.16b eor v10.16b, v10.16b, v31.16b // GHASH[2] - mid ROUND CTR3.16b, KEY6.16b fmov OUT1.d[1], x20 // AES[1] - mov high ROUND CTR0.16b, KEY8.16b eor HASH0.16b, HASH0.16b, v6.16b // GHASH[0] - low pmull v30.1q, v30.1d, v16.1d // GHASH[0] - mid subs COUNT, COUNT, #1 // count-- fmov d4, x6 // AES[0] - mov low ROUND CTR2.16b, KEY6.16b fmov OUT0.d[1], x7 // AES[0] - mov high ROUND CTR1.16b, KEY8.16b fmov d7, x23 // AES[0] - mov low eor v10.16b, v10.16b, v30.16b // GHASH[0] - mid eor v30.16b, HASH0.16b, v9.16b // MODULO - karatsuba tidy up add IV_W, IV_W, #1 // CTR++ ROUND CTR2.16b, KEY7.16b fmov OUT3.d[1], x24 // AES[3] - mov high pmull v31.1q, v9.1d, v8.1d // MODULO - top 64b align with mid ext v9.16b, v9.16b, v9.16b, #8 // MODULO - other top alignment fmov d6, x21 // AES[3] - mov low ROUND CTR3.16b, KEY7.16b ROUND CTR0.16b, KEY9.16b eor v10.16b, v10.16b, v30.16b // MODULO - karatsuba tidy up ROUND CTR2.16b, KEY8.16b ROUND CTR3.16b, KEY8.16b ROUND CTR1.16b, KEY9.16b ROUND CTR0.16b, KEY10.16b eor v10.16b, v10.16b, v31.16b // MODULO - fold into mid ROUND CTR3.16b, KEY9.16b ROUND CTR2.16b, KEY9.16b aese CTR0.16b, KEY11.16b // AES[1] - round 11 ROUND CTR1.16b, KEY10.16b eor v10.16b, v10.16b, v9.16b // MODULO - fold into mid ROUND CTR2.16b, KEY10.16b eor OUT0.16b, OUT0.16b, CTR0.16b // AES[0] - result fmov d0, x10 // CTR[0] aese CTR1.16b, KEY11.16b // AES[2] - round 11 fmov CTR0.d[1], x9 // CTR[0]--OK rev w9, IV_W // CTR[1] pmull v9.1q, v10.1d, v8.1d // MODULO - mid 64b align with low fmov OUT2.d[1], x22 // AES[2] - mov high st1 {OUT0.16b}, [OUT00], #16 // AES[0] - store result ROUND CTR3.16b, KEY10.16b orr x9, x11, x9, lsl #32 // CTR[1] eor OUT1.16b, OUT1.16b, CTR1.16b // AES[1] - result add IV_W, IV_W, #1 // CTR++ fmov d1, x10 // CTR[1] aese CTR2.16b, KEY11.16b fmov v1.d[1], x9 // CTR[1]--OK rev w9, IV_W // CTR[2] add IV_W, IV_W, #1 // CTR++ ext v10.16b, v10.16b, v10.16b, #8 // MODULO - other mid alignment orr x9, x11, x9, lsl #32 // CTR[2] st1 {OUT1.16b}, [OUT00], #16 // AES[1] - store result eor HASH0.16b, HASH0.16b, v9.16b // MODULO - fold into low aese CTR3.16b, KEY11.16b // AES[2] - round 11 eor OUT2.16b, OUT2.16b, CTR2.16b // AES[2] - result fmov d2, x10 // CTR[2] st1 {OUT2.16b}, [OUT00], #16 // AES[2] - store result fmov CTR2.d[1], x9 // CTR[2]--OK rev w9, IV_W // CTR[3] eor OUT3.16b, OUT3.16b, CTR3.16b // AES[3] - result eor HASH0.16b, HASH0.16b, v10.16b // MODULO - fold into low orr x9, x11, x9, lsl #32 // CTR[3] st1 {OUT3.16b}, [OUT00], #16 // AES[3] - store result .endm .macro GCM_DEC192_LOOP ROUND CTR1.16b, KEY0.16b ext HASH0.16b, HASH0.16b, HASH0.16b, #8 // PRE 0 pmull v31.1q, OUT1.1d, HASH3.1d // GHASH block 4k+1 - low mov x21, CTR2.d[0] // AES[2] block - mov low mov x22, CTR2.d[1] // AES[2] block - mov high eor CTR3.16b, OUT3.16b, CTR3.16b // AES[3] block - result rev64 v7.16b, v7.16b // GHASH[0] ROUND CTR1.16b, KEY1.16b fmov d2, x10 // CTR[2] block ROUND CTR0.16b, KEY0.16b #ifdef HITLS_BIG_ENDIAN rev x21, x21 rev x22, x22 #endif eor v4.16b, v4.16b, HASH0.16b // PRE 1 pmull2 v30.1q, v5.2d, HASH3.2d // GHASH block 4k+1 - high fmov CTR2.d[1], x9 // CTR[2]--OK ROUND CTR1.16b, KEY2.16b mov x24, CTR3.d[1] // AES[3] block - mov high ROUND CTR0.16b, KEY1.16b mov x23, CTR3.d[0] // AES[3] block - mov low pmull2 v9.1q, v4.2d, HASH4.2d // GHASH block 4k - high fmov d3, x10 // CTR[3] mov d8, v4.d[1] // GHASH block 4k - mid pmull HASH0.1q, v4.1d, HASH4.1d // GHASH block 4k - low #ifdef HITLS_BIG_ENDIAN rev x23, x23 rev x24, x24 #endif mov d10, v17.d[1] // GHASH block 4k - mid rev w9, IV_W // CTR[3] ROUND CTR2.16b, KEY0.16b orr x9, x11, x9, lsl #32 // CTR[3] fmov CTR3.d[1], x9 // CTR[3]--OK eor v8.8b, v8.8b, v4.8b // GHASH block 4k - mid mov d4, v5.d[1] // GHASH block 4k+1 - mid ROUND CTR1.16b, KEY3.16b ROUND CTR0.16b, KEY2.16b eor x22, x22, KEND1 // AES[2] block - round 12 high ROUND CTR2.16b, KEY1.16b eor v4.8b, v4.8b, v5.8b // GHASH block 4k+1 - mid pmull v10.1q, v8.1d, v10.1d // GHASH block 4k - mid ROUND CTR3.16b, KEY0.16b rev64 v6.16b, v6.16b // GHASH[2] ROUND CTR2.16b, KEY2.16b pmull v4.1q, v4.1d, v17.1d // GHASH block 4k+1 - mid eor HASH0.16b, HASH0.16b, v31.16b // GHASH block 4k+1 - low eor x21, x21, KEND0 // AES[2] block - round 12 low ROUND CTR1.16b, KEY4.16b ROUND CTR0.16b, KEY3.16b eor v10.16b, v10.16b, v4.16b // GHASH block 4k+1 - mid mov d31, v6.d[1] // GHASH[2] - mid ROUND CTR3.16b, KEY1.16b eor v9.16b, v9.16b, v30.16b // GHASH block 4k+1 - high ROUND CTR0.16b, KEY4.16b pmull2 v30.1q, v6.2d, HASH2.2d // GHASH[2] - high eor v31.8b, v31.8b, v6.8b // GHASH[2] - mid pmull v8.1q, v6.1d, HASH2.1d // GHASH[2] - low ROUND CTR0.16b, KEY5.16b eor v9.16b, v9.16b, v30.16b // GHASH[2] - high mov d30, v7.d[1] // GHASH[0] - mid ROUND CTR1.16b, KEY5.16b pmull2 v5.1q, v7.2d, HASH1.2d // GHASH[0] - high ROUND CTR3.16b, KEY2.16b eor v30.8b, v30.8b, v7.8b // GHASH[0] - mid ROUND CTR1.16b, KEY6.16b ROUND CTR0.16b, KEY6.16b ins v31.d[1], v31.d[0] // GHASH[2] - mid ROUND CTR3.16b, KEY3.16b pmull v30.1q, v30.1d, v16.1d // GHASH[0] - mid eor HASH0.16b, HASH0.16b, v8.16b // GHASH[2] - low ROUND CTR0.16b, KEY7.16b pmull2 v31.1q, v31.2d, v16.2d // GHASH[2] - mid eor v9.16b, v9.16b, v5.16b // GHASH[0] - high ROUND CTR1.16b, KEY7.16b ROUND CTR0.16b, KEY8.16b movi v8.8b, #0xc2 pmull v6.1q, v7.1d, HASH1.1d // GHASH[0] - low ROUND CTR1.16b, KEY8.16b eor v10.16b, v10.16b, v31.16b // GHASH[2] - mid ROUND CTR2.16b, KEY3.16b ROUND CTR0.16b, KEY9.16b eor HASH0.16b, HASH0.16b, v6.16b // GHASH[0] - low ROUND CTR3.16b, KEY4.16b ROUND CTR2.16b, KEY4.16b eor v10.16b, v10.16b, v30.16b // GHASH[0] - mid ROUND CTR0.16b, KEY10.16b ROUND CTR1.16b, KEY9.16b eor v30.16b, HASH0.16b, v9.16b // MODULO - karatsuba tidy up ROUND CTR2.16b, KEY5.16b ROUND CTR3.16b, KEY5.16b shl d8, d8, #56 // mod_constant ROUND CTR1.16b, KEY10.16b ROUND CTR2.16b, KEY6.16b ld1 {OUT0.16b}, [INPUT], #16 // AES load[0] ciphertext ROUND CTR3.16b, KEY6.16b eor v10.16b, v10.16b, v30.16b // MODULO - karatsuba tidy up pmull v31.1q, v9.1d, v8.1d // MODULO - top 64b align with mid ld1 {OUT1.16b}, [INPUT], #16 // AES load[1] ciphertext eor x23, x23, KEND0 // AES[3] block - round 12 low ROUND CTR2.16b, KEY7.16b ext v9.16b, v9.16b, v9.16b, #8 // MODULO - other top alignment aese CTR0.16b, KEY11.16b add IV_W, IV_W, #1 // CTR++ ROUND CTR3.16b, KEY7.16b eor v10.16b, v10.16b, v31.16b // MODULO - fold into mid ld1 {OUT2.16b}, [INPUT], #16 // AES load[2] ciphertext ROUND CTR2.16b, KEY8.16b aese CTR1.16b, KEY11.16b ld1 {OUT3.16b}, [INPUT], #16 // AES load[3] ciphertext rev w9, IV_W // CTR block 4k+8 ROUND CTR3.16b, KEY8.16b stp x21, x22, [OUT00], #16 // AES[2] block - store result ROUND CTR2.16b, KEY9.16b eor v10.16b, v10.16b, v9.16b // MODULO - fold into mid subs COUNT, COUNT, #1 // COUNT-- eor CTR0.16b, OUT0.16b, CTR0.16b // AES[0] block - result eor x24, x24, KEND1 // AES[3] block - round 12 high eor CTR1.16b, OUT1.16b, CTR1.16b // AES[1] block - result ROUND CTR2.16b, KEY10.16b orr x9, x11, x9, lsl #32 // CTR block 4k+8 ROUND CTR3.16b, KEY9.16b pmull v8.1q, v10.1d, v8.1d // MODULO - mid 64b align with low mov x19, CTR1.d[0] // AES[1] block - mov low mov x6, CTR0.d[0] // AES[0] block - mov low stp x23, x24, [OUT00], #16 // AES[3] - store result rev64 v5.16b, v5.16b // GHASH[2] aese CTR2.16b, KEY11.16b mov x7, CTR0.d[1] // AES[0] block - mov high ROUND CTR3.16b, KEY10.16b mov x20, CTR1.d[1] // AES[1] block - mov high #ifdef HITLS_BIG_ENDIAN rev x6, x6 rev x7, x7 rev x19, x19 rev x20, x20 #endif fmov d0, x10 // CTR[0] add IV_W, IV_W, #1 // CTR++ ext v10.16b, v10.16b, v10.16b, #8 // MODULO - other mid alignment eor CTR2.16b, OUT2.16b, CTR2.16b // AES[2] block - result fmov CTR0.d[1], x9 // CTR[0]--OK rev w9, IV_W // CTR block 4k+9 eor x6, x6, KEND0 // AES[0] block - round 12 low orr x9, x11, x9, lsl #32 // CTR block 4k+9 eor HASH0.16b, HASH0.16b, v8.16b // MODULO - fold into low fmov d1, x10 // CTR[1] add IV_W, IV_W, #1 // CTR++ eor x19, x19, KEND0 // AES[1] block - round 12 low fmov CTR1.d[1], x9 // CTR[1]--OK rev w9, IV_W // CTR block 4k+10 eor x20, x20, KEND1 // AES[2] - round 12 high eor x7, x7, KEND1 // AES[0] - round 12 high stp x6, x7, [OUT00], #16 // AES[0] block - store result eor HASH0.16b, HASH0.16b, v10.16b // MODULO - fold into low add IV_W, IV_W, #1 // CTR++ rev64 v4.16b, v4.16b // GHASH[1] orr x9, x11, x9, lsl #32 // CTR block 4k+10 aese CTR3.16b, KEY11.16b // AES[3] round 11 stp x19, x20, [OUT00], #16 // AES[1] block - store result .endm #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm/aes192_gcm_aarch64.S
Unix Assembly
unknown
17,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" #if defined(HITLS_CRYPTO_AES) && defined(HITLS_CRYPTO_GCM) .macro GCM_ENC256_LOOP ROUND CTR0.16b, KEY0.16b rev64 v4.16b, v4.16b // GHASH block 4k (only t0 is free) ROUND CTR1.16b, KEY0.16b fmov d3, x10 // CTR[3] ROUND CTR2.16b, KEY0.16b ext HASH0.16b, HASH0.16b, HASH0.16b, #8 // PRE 0 ROUND CTR0.16b, KEY1.16b fmov CTR3.d[1], x9 // CTR[3] - OK ROUND CTR1.16b, KEY1.16b ldp x6, x7, [INPUT], #16 // AES[0] - load plaintext ROUND CTR2.16b, KEY1.16b ldp x19, x20, [INPUT], #16 // AES[1] - load plaintext ROUND CTR0.16b, KEY2.16b #ifdef HITLS_BIG_ENDIAN rev x6, x6 rev x7, x7 rev x19, x19 rev x20, x20 #endif eor v4.16b, v4.16b, HASH0.16b // PRE 1 ROUND CTR1.16b, KEY2.16b ROUND CTR3.16b, KEY0.16b eor x6, x6, KEND0 // AES[0] - round 14 low ROUND CTR0.16b, KEY3.16b mov d10, v17.d[1] // GHASH block 4k - mid pmull2 v9.1q, v4.2d, HASH4.2d // GHASH block 4k - high eor x7, x7, KEND1 // AES[0] - round 14 high mov d8, v4.d[1] // GHASH block 4k - mid ROUND CTR3.16b, KEY1.16b rev64 v5.16b, v5.16b // GHASH block 4k+1 (t0 and t1 free) ROUND CTR0.16b, KEY4.16b pmull HASH0.1q, v4.1d, HASH4.1d // GHASH block 4k - low eor v8.8b, v8.8b, v4.8b // GHASH block 4k - mid ROUND CTR2.16b, KEY2.16b ROUND CTR0.16b, KEY5.16b rev64 v7.16b, v7.16b // GHASH[0] (t0, t1, t2 and t3 free) pmull2 v4.1q, v5.2d, HASH3.2d // GHASH block 4k+1 - high pmull v10.1q, v8.1d, v10.1d // GHASH block 4k - mid rev64 v6.16b, v6.16b // GHASH[2] (t0, t1, and t2 free) pmull v8.1q, v5.1d, HASH3.1d // GHASH block 4k+1 - low eor v9.16b, v9.16b, v4.16b // GHASH block 4k+1 - high mov d4, v5.d[1] // GHASH block 4k+1 - mid ROUND CTR1.16b, KEY3.16b ROUND CTR3.16b, KEY2.16b eor HASH0.16b, HASH0.16b, v8.16b // GHASH block 4k+1 - low ROUND CTR2.16b, KEY3.16b ROUND CTR1.16b, KEY4.16b mov d8, v6.d[1] // GHASH[2] - mid ROUND CTR3.16b, KEY3.16b eor v4.8b, v4.8b, v5.8b // GHASH block 4k+1 - mid ROUND CTR2.16b, KEY4.16b ROUND CTR0.16b, KEY6.16b eor v8.8b, v8.8b, v6.8b // GHASH[2] - mid ROUND CTR3.16b, KEY4.16b pmull v4.1q, v4.1d, v17.1d // GHASH block 4k+1 - mid ROUND CTR0.16b, KEY7.16b ROUND CTR3.16b, KEY5.16b ins v8.d[1], v8.d[0] // GHASH[2] - mid ROUND CTR1.16b, KEY5.16b ROUND CTR0.16b, KEY8.16b ROUND CTR2.16b, KEY5.16b ROUND CTR1.16b, KEY6.16b eor v10.16b, v10.16b, v4.16b // GHASH block 4k+1 - mid pmull2 v4.1q, v6.2d, HASH2.2d // GHASH[2] - high pmull v5.1q, v6.1d, HASH2.1d // GHASH[2] - low ROUND CTR1.16b, KEY7.16b pmull v6.1q, v7.1d, HASH1.1d // GHASH[0] - low eor v9.16b, v9.16b, v4.16b // GHASH[2] - high ROUND CTR3.16b, KEY6.16b ldp x21, x22, [INPUT], #16 // AES[2] - load plaintext ROUND CTR1.16b, KEY8.16b mov d4, v7.d[1] // GHASH[0] - mid #ifdef HITLS_BIG_ENDIAN rev x21, x21 rev x22, x22 #endif ROUND CTR2.16b, KEY6.16b eor HASH0.16b, HASH0.16b, v5.16b // GHASH[2] - low pmull2 v8.1q, v8.2d, v16.2d // GHASH[2] - mid pmull2 v5.1q, v7.2d, HASH1.2d // GHASH[0] - high eor v4.8b, v4.8b, v7.8b // GHASH[0] - mid ROUND CTR2.16b, KEY7.16b eor x19, x19, KEND0 // AES[1] - round 14 low ROUND CTR1.16b, KEY9.16b eor v10.16b, v10.16b, v8.16b // GHASH[2] - mid ROUND CTR3.16b, KEY7.16b eor x21, x21, KEND0 // AES[2] - round 14 low ROUND CTR0.16b, KEY9.16b movi v8.8b, #0xc2 pmull v4.1q, v4.1d, v16.1d // GHASH[0] - mid eor v9.16b, v9.16b, v5.16b // GHASH[0] - high fmov d5, x19 // AES[1] - mov low ROUND CTR2.16b, KEY8.16b ldp x23, x24, [INPUT], #16 // AES[3] - load plaintext ROUND CTR0.16b, KEY10.16b shl d8, d8, #56 // mod_constant #ifdef HITLS_BIG_ENDIAN rev x23, x23 rev x24, x24 #endif ROUND CTR3.16b, KEY8.16b eor HASH0.16b, HASH0.16b, v6.16b // GHASH[0] - low ROUND CTR2.16b, KEY9.16b ROUND CTR1.16b, KEY10.16b eor v10.16b, v10.16b, v4.16b // GHASH[0] - mid ROUND CTR3.16b, KEY9.16b add IV_W, IV_W, #1 // CTR++ ROUND CTR0.16b, KEY11.16b eor v4.16b, HASH0.16b, v9.16b // MODULO - karatsuba tidy up ROUND CTR1.16b, KEY11.16b pmull v7.1q, v9.1d, v8.1d // MODULO - top 64b align with mid rev w9, IV_W // CTR block 4k+8 ext v9.16b, v9.16b, v9.16b, #8 // MODULO - other top alignment ROUND CTR2.16b, KEY10.16b eor x23, x23, KEND0 // AES[3] - round 14 low ROUND CTR1.16b, KEY12.16b eor v10.16b, v10.16b, v4.16b // MODULO - karatsuba tidy up ROUND CTR3.16b, KEY10.16b eor x20, x20, KEND1 // AES[1] - round 14 high fmov d4, x6 // AES[0] - mov low orr x9, x11, x9, lsl #32 // CTR block 4k+8 eor v7.16b, v9.16b, v7.16b // MODULO - fold into mid ROUND CTR0.16b, KEY12.16b eor x22, x22, KEND1 // AES[2] - round 14 high ROUND CTR2.16b, KEY11.16b eor x24, x24, KEND1 // AES[3] - round 14 high ROUND CTR3.16b, KEY11.16b add IV_W, IV_W, #1 // CTR++ aese CTR0.16b, KEY13.16b // AES[0] - round 13 fmov OUT0.d[1], x7 // AES[0] - mov high eor v10.16b, v10.16b, v7.16b // MODULO - fold into mid ROUND CTR2.16b, KEY12.16b fmov d7, x23 // AES[3] - mov low aese CTR1.16b, KEY13.16b // AES[2] - round 13 fmov OUT1.d[1], x20 // AES[1] - mov high fmov d6, x21 // AES[2] - mov low subs COUNT, COUNT, #1 // COUNT-- fmov OUT2.d[1], x22 // AES[2] - mov high pmull v9.1q, v10.1d, v8.1d // MODULO - mid 64b align with low eor OUT0.16b, OUT0.16b, CTR0.16b // AES[0] - result fmov d0, x10 // CTR[0] fmov CTR0.d[1], x9 // CTR[0]--OK rev w9, IV_W // CTR[1] add IV_W, IV_W, #1 // CTR++ eor OUT1.16b, OUT1.16b, CTR1.16b // AES[1] - result fmov d1, x10 // CTR[1] orr x9, x11, x9, lsl #32 // CTR[1] ROUND CTR3.16b, KEY12.16b fmov v1.d[1], x9 // CTR[1]--OK aese CTR2.16b, KEY13.16b // AES[3] - round 13 rev w9, IV_W // CTR block 4k+10 st1 {OUT0.16b}, [OUT00], #16 // AES[0] - store result orr x9, x11, x9, lsl #32 // CTR block 4k+10 eor HASH0.16b, HASH0.16b, v9.16b // MODULO - fold into low fmov OUT3.d[1], x24 // AES[3] - mov high ext v10.16b, v10.16b, v10.16b, #8 // MODULO - other mid alignment st1 {OUT1.16b}, [OUT00], #16 // AES[1] - store result add IV_W, IV_W, #1 // CTR++ aese CTR3.16b, KEY13.16b // AES[0] - round 13 eor OUT2.16b, OUT2.16b, CTR2.16b // AES[2] - result fmov d2, x10 // CTR[2] st1 {OUT2.16b}, [OUT00], #16 // AES[2] - store result fmov v2.d[1], x9 // CTR[2]--OK rev w9, IV_W // CTR block 4k+11 eor OUT3.16b, OUT3.16b, CTR3.16b // AES[3] - result eor HASH0.16b, HASH0.16b, v10.16b // MODULO - fold into low orr x9, x11, x9, lsl #32 // CTR block 4k+11 st1 {OUT3.16b}, [OUT00], #16 // AES[3] - store result .endm .macro GCM_DEC256_LOOP mov x21, CTR2.d[0] // AES[2] block - mov low ext HASH0.16b, HASH0.16b, HASH0.16b, #8 // PRE 0 eor CTR3.16b, OUT3.16b, CTR3.16b // AES[3] block - result ROUND CTR0.16b, KEY0.16b mov x22, CTR2.d[1] // AES[2] block - mov high ROUND CTR1.16b, KEY0.16b fmov d2, x10 // CTR[2] fmov v2.d[1], x9 // CTR[2] eor v4.16b, v4.16b, HASH0.16b // PRE 1 #ifdef HITLS_BIG_ENDIAN rev x21, x21 rev x22, x22 #endif rev w9, IV_W // CTR[0] ROUND CTR0.16b, KEY1.16b mov x24, CTR3.d[1] // AES[3] block - mov high ROUND CTR1.16b, KEY1.16b mov x23, CTR3.d[0] // AES[3] block - mov low pmull2 v9.1q, v4.2d, HASH4.2d // GHASH block 4k - high mov d8, v4.d[1] // GHASH block 4k - mid fmov d3, x10 // CTR[0] #ifdef HITLS_BIG_ENDIAN rev x23, x23 rev x24, x24 #endif ROUND CTR0.16b, KEY2.16b orr x9, x11, x9, lsl #32 // CTR[0] ROUND CTR2.16b, KEY0.16b fmov v3.d[1], x9 // CTR[0] ROUND CTR1.16b, KEY2.16b eor v8.8b, v8.8b, v4.8b // GHASH block 4k - mid ROUND CTR0.16b, KEY3.16b eor x22, x22, KEND1 // AES[2] - round 14 high ROUND CTR2.16b, KEY1.16b mov d10, v17.d[1] // GHASH block 4k - mid ROUND CTR1.16b, KEY3.16b rev64 v6.16b, v6.16b // GHASH[2] ROUND CTR3.16b, KEY0.16b eor x21, x21, KEND0 // AES[2] - round 14 low ROUND CTR2.16b, KEY2.16b stp x21, x22, [OUT00], #16 // AES[2] - store result pmull HASH0.1q, v4.1d, HASH4.1d // GHASH block 4k - low pmull2 v4.1q, v5.2d, HASH3.2d // GHASH block 4k+1 - high ROUND CTR2.16b, KEY3.16b rev64 v7.16b, v7.16b // GHASH[0] pmull v10.1q, v8.1d, v10.1d // GHASH block 4k - mid eor x23, x23, KEND0 // AES[3] - round 14 low pmull v8.1q, v5.1d, HASH3.1d // GHASH block 4k+1 - low eor x24, x24, KEND1 // AES[3] - round 14 high eor v9.16b, v9.16b, v4.16b // GHASH block 4k+1 - high ROUND CTR2.16b, KEY4.16b ROUND CTR3.16b, KEY1.16b mov d4, v5.d[1] // GHASH block 4k+1 - mid ROUND CTR0.16b, KEY4.16b eor HASH0.16b, HASH0.16b, v8.16b // GHASH block 4k+1 - low ROUND CTR2.16b, KEY5.16b add IV_W, IV_W, #1 // CTR[0] ROUND CTR3.16b, KEY2.16b mov d8, v6.d[1] // GHASH[2] - mid ROUND CTR1.16b, KEY4.16b eor v4.8b, v4.8b, v5.8b // GHASH block 4k+1 - mid pmull v5.1q, v6.1d, HASH2.1d // GHASH[2] - low ROUND CTR3.16b, KEY3.16b eor v8.8b, v8.8b, v6.8b // GHASH[2] - mid ROUND CTR1.16b, KEY5.16b ROUND CTR0.16b, KEY5.16b eor HASH0.16b, HASH0.16b, v5.16b // GHASH[2] - low pmull v4.1q, v4.1d, v17.1d // GHASH block 4k+1 - mid rev w9, IV_W // CTR block 4k+8 ROUND CTR1.16b, KEY6.16b ins v8.d[1], v8.d[0] // GHASH[2] - mid ROUND CTR0.16b, KEY6.16b add IV_W, IV_W, #1 // CTR block 4k+8 ROUND CTR3.16b, KEY4.16b ROUND CTR1.16b, KEY7.16b eor v10.16b, v10.16b, v4.16b // GHASH block 4k+1 - mid ROUND CTR0.16b, KEY7.16b pmull2 v4.1q, v6.2d, HASH2.2d // GHASH[2] - high mov d6, v7.d[1] // GHASH[0] - mid ROUND CTR3.16b, KEY5.16b pmull2 v8.1q, v8.2d, v16.2d // GHASH[2] - mid ROUND CTR0.16b, KEY8.16b eor v9.16b, v9.16b, v4.16b // GHASH[2] - high ROUND CTR3.16b, KEY6.16b pmull v4.1q, v7.1d, HASH1.1d // GHASH[0] - low orr x9, x11, x9, lsl #32 // CTR block 4k+8 eor v10.16b, v10.16b, v8.16b // GHASH[2] - mid pmull2 v5.1q, v7.2d, HASH1.2d // GHASH[0] - high ROUND CTR0.16b, KEY9.16b eor v6.8b, v6.8b, v7.8b // GHASH[0] - mid ROUND CTR1.16b, KEY8.16b ROUND CTR2.16b, KEY6.16b eor v9.16b, v9.16b, v5.16b // GHASH[0] - high ROUND CTR0.16b, KEY10.16b pmull v6.1q, v6.1d, v16.1d // GHASH[0] - mid movi v8.8b, #0xc2 ROUND CTR2.16b, KEY7.16b eor HASH0.16b, HASH0.16b, v4.16b // GHASH[0] - low ROUND CTR0.16b, KEY11.16b ROUND CTR3.16b, KEY7.16b shl d8, d8, #56 // mod_constant ROUND CTR2.16b, KEY8.16b eor v10.16b, v10.16b, v6.16b // GHASH[0] - mid ROUND CTR0.16b, KEY12.16b pmull v7.1q, v9.1d, v8.1d // MODULO - top 64b align with mid eor v6.16b, HASH0.16b, v9.16b // MODULO - karatsuba tidy up ROUND CTR1.16b, KEY9.16b ld1 {OUT0.16b}, [INPUT], #16 // AES load[0] ciphertext aese CTR0.16b, KEY13.16b ext v9.16b, v9.16b, v9.16b, #8 // MODULO - other top alignment ROUND CTR1.16b, KEY10.16b eor v10.16b, v10.16b, v6.16b // MODULO - karatsuba tidy up ROUND CTR2.16b, KEY9.16b ld1 {OUT1.16b}, [INPUT], #16 // AES load[1] ciphertext ROUND CTR3.16b, KEY8.16b eor CTR0.16b, OUT0.16b, CTR0.16b // AES[0] block - result ROUND CTR1.16b, KEY11.16b stp x23, x24, [OUT00], #16 // AES[3] block - store result ROUND CTR2.16b, KEY10.16b eor v10.16b, v10.16b, v7.16b // MODULO - fold into mid ROUND CTR3.16b, KEY9.16b ld1 {OUT2.16b}, [INPUT], #16 // AES load[1] ciphertext ROUND CTR1.16b, KEY12.16b ld1 {OUT3.16b}, [INPUT], #16 // AES load[1] ciphertext ROUND CTR2.16b, KEY11.16b mov x7, CTR0.d[1] // AES[0] block - mov high ROUND CTR3.16b, KEY10.16b eor v10.16b, v10.16b, v9.16b // MODULO - fold into mid aese CTR1.16b, KEY13.16b // AES[2] - round 13 mov x6, CTR0.d[0] // AES[0] block - mov low ROUND CTR2.16b, KEY12.16b fmov d0, x10 // CTR[0] ROUND CTR3.16b, KEY11.16b #ifdef HITLS_BIG_ENDIAN rev x6, x6 rev x7, x7 #endif fmov CTR0.d[1], x9 // CTR[0]--OK pmull v8.1q, v10.1d, v8.1d // MODULO - mid 64b align with low eor CTR1.16b, OUT1.16b, CTR1.16b // AES[1] block - result rev w9, IV_W // CTR block 4k+9 aese CTR2.16b, KEY13.16b orr x9, x11, x9, lsl #32 // CTR block 4k+9 subs COUNT, COUNT, #1 // COUNT-- add IV_W, IV_W, #1 // CTR++ eor x6, x6, KEND0 // AES[0] block - round 14 low eor x7, x7, KEND1 // AES[0] block - round 14 high mov x20, v1.d[1] // AES[1] block - mov high eor CTR2.16b, OUT2.16b, CTR2.16b // AES[2] block - result eor HASH0.16b, HASH0.16b, v8.16b // MODULO - fold into low ROUND CTR3.16b, KEY12.16b mov x19, CTR1.d[0] // AES[1] block - mov low fmov d1, x10 // CTR[1] ext v10.16b, v10.16b, v10.16b, #8 // MODULO - other mid alignment #ifdef HITLS_BIG_ENDIAN rev x20, x20 rev x19, x19 #endif fmov CTR1.d[1], x9 // CTR[1]--OK rev w9, IV_W // CTR block 4k+10 add IV_W, IV_W, #1 // CTR++ aese CTR3.16b, KEY13.16b orr x9, x11, x9, lsl #32 // CTR block 4k+10 rev64 v5.16b, v5.16b // GHASH[2] eor x20, x20, KEND1 // AES[1] block - round 14 high stp x6, x7, [OUT00], #16 // AES[0] block - store result eor x19, x19, KEND0 // AES[1] block - round 14 low stp x19, x20, [OUT00], #16 // AES[1] block - store result rev64 OUT0.16b, OUT0.16b // GHASH block[0] eor HASH0.16b, HASH0.16b, v10.16b // MODULO - fold into low .endm #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm/aes256_gcm_aarch64.S
Unix Assembly
unknown
18,230
/* * 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_AES) && defined(HITLS_CRYPTO_CCM) .text .balign 16 g_byteSwapMask: .byte 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08 .byte 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00 .size g_byteSwapMask, .-g_byteSwapMask .balign 16 g_one: .byte 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 .byte 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 .size g_one, .-g_one /* * void AesCcmEncryptAsm(void *key, uint8_t *nonce, const uint8_t *in, uint8_t *out, uint32_t len) * rdi *key * rsi *nonce * rdx *in * rcx *out * r8 len */ .globl AesCcmEncryptAsm .type AesCcmEncryptAsm, @function .balign 16 AesCcmEncryptAsm: .cfi_startproc shr $4, %r8d // loop times jz .Lenc_ret lea g_byteSwapMask(%rip), %r11 mov 0xf0(%rdi), %r9d // key->rounds vmovdqa (%r11), %xmm15 // g_byteSwapMask sub $1, %r9d vmovdqa 0x10(%r11), %xmm14 // g_one vmovdqu (%rsi), %xmm0 // nonce(counter) vmovdqu 0x10(%rsi), %xmm8 // tag vmovdqu 0x20(%rsi), %xmm9 // last .balign 16 .Lenc_outer_loop: mov %r9d, %r10d vpxor (%rdx), %xmm8, %xmm8 // in ^ tag = tag vmovdqu (%rdi), %xmm1 // key0 lea 0x10(%rdi), %r11 // &key + 1 vpxor %xmm0, %xmm1, %xmm2 // first round xor(aes-ctr) vpshufb %xmm15, %xmm0, %xmm0 // reverse byte order of nonce => nonce' vpxor %xmm8, %xmm1, %xmm3 // first round xor(aes-cmac) .balign 16 .Lenc_aes_loop: vmovdqu (%r11), %xmm1 vaesenc %xmm1, %xmm2, %xmm2 vaesenc %xmm1, %xmm3, %xmm3 lea 0x10(%r11), %r11 // to next key ptr dec %r10d jnz .Lenc_aes_loop vmovdqu (%r11), %xmm1 // get the last key vpaddq %xmm14, %xmm0, %xmm0 // nonce' + 1 vaesenclast %xmm1, %xmm2, %xmm9 vaesenclast %xmm1, %xmm3, %xmm8 vpxor (%rdx), %xmm9, %xmm2 // in ^ last = out vpshufb %xmm15, %xmm0, %xmm0 // reverse byte order of nonce' => nonce lea 0x10(%rdx), %rdx // go to next ptr vmovdqu %xmm2, (%rcx) // out out lea 0x10(%rcx), %rcx // go to next ptr dec %r8d jnz .Lenc_outer_loop vpxor %xmm1, %xmm1, %xmm1 vpxor %xmm2, %xmm2, %xmm2 vpxor %xmm3, %xmm3, %xmm3 vmovdqu %xmm0, (%rsi) // out nonce vpxor %xmm0, %xmm0, %xmm0 vmovdqu %xmm8, 0x10(%rsi) // out tag vpxor %xmm8, %xmm8, %xmm8 vmovdqu %xmm9, 0x20(%rsi) // out last vpxor %xmm9, %xmm9, %xmm9 .Lenc_ret: ret .cfi_endproc .size AesCcmEncryptAsm, .-AesCcmEncryptAsm /* * void AesCcmDecryptAsm(void *key, uint8_t *nonce, const uint8_t *in, uint8_t *out, uint32_t len) * rdi *key * rsi *nonce * rdx *in * rcx *out * r8 len */ .globl AesCcmDecryptAsm .type AesCcmDecryptAsm, @function .balign 16 AesCcmDecryptAsm: .cfi_startproc shr $4, %r8d // loop times jz .Ldec_ret lea g_byteSwapMask(%rip), %r11 mov 0xf0(%rdi), %r9d // key->rounds vmovdqa (%r11), %xmm15 // g_byteSwapMask sub $1, %r9d vmovdqa 0x10(%r11), %xmm14 // g_one vmovdqu (%rsi), %xmm0 // nonce(counter) vmovdqu 0x10(%rsi), %xmm8 // tag .balign 16 .Ldec_outer_loop: mov %r9d, %r10d lea 0x10(%rdi), %r11 // &key vmovdqu (%rdi), %xmm1 // key0 vpxor %xmm0, %xmm1, %xmm2 // first round xor(aes-ctr) .Ldec_aes_loop: vmovdqu (%r11), %xmm1 vaesenc %xmm1, %xmm2, %xmm2 lea 0x10(%r11), %r11 dec %r10d jnz .Ldec_aes_loop vmovdqu (%r11), %xmm1 vaesenclast %xmm1, %xmm2, %xmm4 vmovdqu %xmm4, 0x20(%rsi) // out last vpxor (%rdx), %xmm4, %xmm2 // in ^ last = out vpxor %xmm2, %xmm8, %xmm8 // out ^ tag = tag vmovdqu %xmm2, (%rcx) // out out lea 0x10(%rdx), %rdx lea 0x10(%rcx), %rcx vpshufb %xmm15, %xmm0, %xmm0 // reverse byte order of nonce => nonce' vpaddq %xmm14, %xmm0, %xmm0 // nonce' + 1 vpshufb %xmm15, %xmm0, %xmm0 // reverse byte order of nonce' => nonce cmp $2, %r8d jb .Ldec_parallel_out .Ldec_parallel_loop: mov %r9d, %r10d lea 0x10(%rdi), %r11 // &key vmovdqu (%rdi), %xmm1 // key0 vpxor %xmm0, %xmm1, %xmm2 // first round xor(aes-ctr) vpxor %xmm8, %xmm1, %xmm3 // first round xor(aes-cmac) .Ldec_parallel_inner_loop: vmovdqu (%r11), %xmm1 vaesenc %xmm1, %xmm2, %xmm2 lea 0x10(%r11), %r11 vaesenc %xmm1, %xmm3, %xmm3 dec %r10d jnz .Ldec_parallel_inner_loop vmovdqu (%r11), %xmm1 vaesenclast %xmm1, %xmm2, %xmm4 vaesenclast %xmm1, %xmm3, %xmm8 vmovdqu %xmm4, 0x20(%rsi) // out last vpxor (%rdx), %xmm4, %xmm2 // in ^ last = out vpxor %xmm2, %xmm8, %xmm8 // out ^ tag = tag vmovdqu %xmm2, (%rcx) // out out lea 0x10(%rdx), %rdx lea 0x10(%rcx), %rcx vpshufb %xmm15, %xmm0, %xmm0 // reverse byte order of nonce => nonce' vpaddq %xmm14, %xmm0, %xmm0 // nonce' + 1 vpshufb %xmm15, %xmm0, %xmm0 // reverse byte order of nonce' => nonce dec %r8d cmp $2, %r8d jae .Ldec_parallel_loop .Ldec_parallel_out: mov %r9d, %r10d lea 0x10(%rdi), %r11 // &key vmovdqu (%rdi), %xmm1 // key0 vpxor %xmm8, %xmm1, %xmm3 // first round xor(aes-cmac) .Ldec_aes_loop_1: vmovdqu (%r11), %xmm1 vaesenc %xmm1, %xmm3, %xmm3 lea 0x10(%r11), %r11 dec %r10d jnz .Ldec_aes_loop_1 vmovdqu (%r11), %xmm1 vaesenclast %xmm1, %xmm3, %xmm8 dec %r8d jnz .Ldec_outer_loop vmovdqu %xmm0, (%rsi) // out nonce vpxor %xmm0, %xmm0, %xmm0 vpxor %xmm1, %xmm1, %xmm1 vpxor %xmm2, %xmm2, %xmm2 vmovdqu %xmm8, 0x10(%rsi) // out tag vpxor %xmm8, %xmm8, %xmm8 vpxor %xmm3, %xmm3, %xmm3 vpxor %xmm4, %xmm4, %xmm4 .Ldec_ret: ret .cfi_endproc .size AesCcmDecryptAsm, .-AesCcmDecryptAsm #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm/aes_ccm_x86_64.S
Unix Assembly
unknown
6,559
/* * 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_AES) && defined(HITLS_CRYPTO_GCM) #include "crypt_arm.h" #include "aes_gcm_common_aarch64.S" .text .arch armv8-a+crypto .globl AES_GCM_Encrypt16BlockAsm .type AES_GCM_Encrypt16BlockAsm,%function .align 4 AES_GCM_Encrypt16BlockAsm: AARCH64_PACIASP IN_STP // register Protection ldr ROUNDS, [KEY00, #240] // load number of rounds add HTABLE, IVEC0, #16 // obtains the start address of the ghash table lsr COUNT, INLEN, #4 // length divided by 16 LOAD_GHASH_TABLE // load the ghash table cmp ROUNDS, #10 // number of comparison rounds 10 LOAD_KEY // load AES KEY b.eq .LEnc16_128_process // go to the AES128 part cmp ROUNDS, #12 // number of comparison rounds 12 ld1 {KEY10.4s, KEY11.4s}, [KEY00], #32 b.eq .LEnc16_192_process // go to the AES192 part ld1 {KEY12.4s, KEY13.4s}, [KEY00], #32 b .LEnc16_256_process // go to the AES256 part .LEnc16_128_process: BEFORE16_ROUND // data preprocessing .LEnc16_128_loop: FIRST16_ROUND // data preprocessing ldp x6, x7, [INPUT], #16 // load INPUT 0 #ifdef HITLS_BIG_ENDIAN REV_2S x6, x7 #endif aese CTR0.16b, KEY9.16b subs COUNT, COUNT, #1 // COUNT-- ENC16_BLOCK // processes 16-byte data b.le .LEnc16_end b .LEnc16_128_loop .LEnc16_192_process: BEFORE16_ROUND .LEnc16_192_loop: FIRST16_ROUND ldp x6, x7, [INPUT], #16 // load INPUT 0 #ifdef HITLS_BIG_ENDIAN REV_2S x6, x7 #endif ROUND CTR0.16b, KEY9.16b ROUND CTR0.16b, KEY10.16b aese CTR0.16b, KEY11.16b subs COUNT, COUNT, #1 // COUNT-- ENC16_BLOCK b.le .LEnc16_end b .LEnc16_192_loop .LEnc16_256_process: BEFORE16_ROUND .LEnc16_256_loop: FIRST16_ROUND ldp x6, x7, [INPUT], #16 // load INPUT 0 #ifdef HITLS_BIG_ENDIAN REV_2S x6, x7 #endif ROUND CTR0.16b, KEY9.16b ROUND CTR0.16b, KEY10.16b ROUND CTR0.16b, KEY11.16b ROUND CTR0.16b, KEY12.16b aese CTR0.16b, KEY13.16b subs COUNT, COUNT, #1 // COUNT-- ENC16_BLOCK b.le .LEnc16_end b .LEnc16_256_loop .LEnc16_end: ext HASH0.16b, HASH0.16b, HASH0.16b, #8 add x6, IVEC0, #16 rev64 HASH0.16b, HASH0.16b st1 {CTR1.16b }, [IVEC0] // out counter st1 {HASH0.16b }, [x6] // out hash OUT_STP // restore protection register .LEnc_ret: mov w0, #0x0 AARCH64_AUTIASP ret .size AES_GCM_Encrypt16BlockAsm,.-AES_GCM_Encrypt16BlockAsm .globl AES_GCM_Decrypt16BlockAsm .type AES_GCM_Decrypt16BlockAsm,%function .align 4 AES_GCM_Decrypt16BlockAsm: AARCH64_PACIASP IN_STP // stp ldr ROUNDS, [KEY00, #240] // pull rounds mov IVEC0, x0 // ctr0 add HTABLE, IVEC0, #16 // htable lsr COUNT, INLEN, #4 // 2*2 2*2 = 16 LOAD_GHASH_TABLE cmp ROUNDS, #10 LOAD_KEY b.eq .LDec16_128_process cmp ROUNDS, #12 ld1 {KEY10.4s, KEY11.4s}, [KEY00], #32 b.eq .LDec16_192_process ld1 {KEY12.4s, KEY13.4s}, [KEY00], #32 b .LDec16_256_process .LDec16_128_process: BEFORE16_ROUND #ifdef HITLS_BIG_ENDIAN REV_2S KEND0, KEND1 #endif .LDec16_128_loop: FIRST16_ROUND aese CTR0.16b, KEY9.16b DEC16_BLOCK b.le .LDec16_end b .LDec16_128_loop .LDec16_192_process: BEFORE16_ROUND #ifdef HITLS_BIG_ENDIAN REV_2S KEND0, KEND1 #endif .LDec16_192_loop: FIRST16_ROUND ROUND CTR0.16b, KEY9.16b ROUND CTR0.16b, KEY10.16b aese CTR0.16b, KEY11.16b DEC16_BLOCK b.le .LDec16_end b .LDec16_192_loop .LDec16_256_process: BEFORE16_ROUND #ifdef HITLS_BIG_ENDIAN REV_2S KEND0, KEND1 #endif .LDec16_256_loop: FIRST16_ROUND ROUND CTR0.16b, KEY9.16b ROUND CTR0.16b, KEY10.16b ROUND CTR0.16b, KEY11.16b ROUND CTR0.16b, KEY12.16b aese CTR0.16b, KEY13.16b DEC16_BLOCK b.le .LDec16_end b .LDec16_256_loop .LDec16_end: ext HASH0.16b, HASH0.16b, HASH0.16b, #8 add x6, IVEC0, #16 rev64 HASH0.16b, HASH0.16b st1 {CTR1.16b }, [IVEC0] // out counter st1 {HASH0.16b }, [x6] // out hash OUT_STP .LDec_ret: mov w0, #0x0 AARCH64_AUTIASP ret .size AES_GCM_Decrypt16BlockAsm,.-AES_GCM_Decrypt16BlockAsm #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm/aes_gcm_16block_aarch64.S
Unix Assembly
unknown
5,393
/* * 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_AES) && defined(HITLS_CRYPTO_GCM) .text .balign 16 g_byteSwapMask: .byte 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08 .byte 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00 .size g_byteSwapMask, .-g_byteSwapMask .balign 16 g_poly: .byte 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 .byte 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc2 .size g_poly, .-g_poly /* * void AES_GCM_Encrypt16BlockAsm(MODES_GCM_Ctx *ctx, const uint8_t *in, * uint8_t *out, uint32_t len, void *key); * ctx %rdi * in %rsi * out %rdx * len %rcx * key %r8 */ .globl AES_GCM_Encrypt16BlockAsm .type AES_GCM_Encrypt16BlockAsm, @function .align 32 AES_GCM_Encrypt16BlockAsm: .cfi_startproc leaq g_byteSwapMask(%rip), %r11 shrl $4, %ecx // blocks number = loop times mov 240(%r8), %r9d // rounds .Lenc_loop: mov 12(%rdi), %eax // counter eax(32bit) addl $0x1000000, %eax // ctr inc vmovdqu (%rdi), %xmm0 // iv jc .Lenc_ctr_carry jmp .Lenc_aes_cipher .Lenc_ctr_carry: bswap %eax addl $0x100, %eax // add carry bit bswap %eax jmp .Lenc_aes_cipher .Lenc_aes_cipher: mov %eax, 12(%rdi) // out iv vmovdqu (%r8), %xmm1 // key0 vpxor %xmm1, %xmm0, %xmm0 vmovdqu 0x10(%r8), %xmm2 // key1 lea 0xa0(%r8), %r10 // point to the last key in 128-bit encryption vmovdqu 0x20(%r8), %xmm3 // key2 vaesenc %xmm2, %xmm0, %xmm0 vmovdqu 0x30(%r8), %xmm4 // key3 vaesenc %xmm3, %xmm0, %xmm0 vmovdqu 0x40(%r8), %xmm5 // key4 vaesenc %xmm4, %xmm0, %xmm0 vmovdqu 0x50(%r8), %xmm6 // key5 vaesenc %xmm5, %xmm0, %xmm0 vmovdqu 0x60(%r8), %xmm7 // key6 vaesenc %xmm6, %xmm0, %xmm0 vmovdqu 0x70(%r8), %xmm8 // key7 vaesenc %xmm7, %xmm0, %xmm0 vmovdqu 0x80(%r8), %xmm9 // key8 vaesenc %xmm8, %xmm0, %xmm0 vmovdqu 0x90(%r8), %xmm10 // key9 vaesenc %xmm9, %xmm0, %xmm0 vaesenc %xmm10, %xmm0, %xmm0 cmp $12, %r9d // compare the number of rounds to determine // when to jump to the next processing part jb .Lenc_aes_end vmovdqu (%r10), %xmm1 // key10 vaesenc %xmm1, %xmm0, %xmm0 vmovdqu 0x10(%r10), %xmm2 // key11 vaesenc %xmm2, %xmm0, %xmm0 lea 0x20(%r10), %r10 je .Lenc_aes_end vmovdqu (%r10), %xmm1 // key12 vaesenc %xmm1, %xmm0, %xmm0 vmovdqu 0x10(%r10), %xmm2 // key13 vaesenc %xmm2, %xmm0, %xmm0 lea 0x20(%r10), %r10 jmp .Lenc_aes_end .Lenc_aes_end: vmovdqu (%r10), %xmm1 // key last vpxor (%rsi), %xmm1, %xmm1 // Advance ciphertext XOR in vaesenclast %xmm1, %xmm0, %xmm0 vmovdqu %xmm0, (%rdx) // out vmovdqu 16(%rdi), %xmm1 // ghash vmovdqa (%r11), %xmm15 // .LByte_Swap_Mask vpxor %xmm1, %xmm0, %xmm0 // input for ghash operation vmovdqu 32(%rdi), %xmm1 // Hash key H^1 vpshufb %xmm15, %xmm0, %xmm0 // data transform vmovdqu 32+32(%rdi), %xmm2 // Hash key H^1_2 vpalignr $8, %xmm0, %xmm0, %xmm3 // data transform vpclmulqdq $0x11, %xmm1, %xmm0, %xmm5 // Karatsuba Multiply vpxor %xmm0, %xmm3, %xmm3 vpclmulqdq $0x00, %xmm1, %xmm0, %xmm0 vpxor %xmm0, %xmm5, %xmm1 vpclmulqdq $0x00, %xmm2, %xmm3, %xmm3 vpxor %xmm1, %xmm3, %xmm3 vpslldq $8, %xmm3, %xmm4 vpsrldq $8, %xmm3, %xmm3 vpxor %xmm4, %xmm0, %xmm0 vpxor %xmm3, %xmm5, %xmm5 vmovdqa 0x10(%r11), %xmm14 // g_poly vpalignr $8, %xmm0, %xmm0, %xmm2 // 1st phase of reduction vpclmulqdq $0x10, %xmm14, %xmm0, %xmm0 vpxor %xmm2, %xmm0, %xmm0 vpalignr $8, %xmm0, %xmm0, %xmm2 // 2nd phase of reduction vpclmulqdq $0x10, %xmm14, %xmm0, %xmm0 vpxor %xmm5, %xmm2, %xmm2 vpxor %xmm2, %xmm0, %xmm0 vpshufb %xmm15, %xmm0, %xmm0 lea 0x10(%rsi), %rsi vmovdqu %xmm0, 16(%rdi) // out lea 0x10(%rdx), %rdx dec %ecx jnz .Lenc_loop ret .cfi_endproc .size AES_GCM_Encrypt16BlockAsm, .-AES_GCM_Encrypt16BlockAsm /* * void AES_GCM_Decrypt16BlockAsm(MODES_GCM_Ctx *ctx, const uint8_t *in, * uint8_t *out, uint32_t len, void *key); * ctx %rdi * in %rsi * out %rdx * len %rcx * key %r8 */ .globl AES_GCM_Decrypt16BlockAsm .type AES_GCM_Decrypt16BlockAsm, @function .balign 32 AES_GCM_Decrypt16BlockAsm: .cfi_startproc leaq g_byteSwapMask(%rip), %r11 vmovdqu 16(%rdi), %xmm10 // ghash shrl $4, %ecx // blocks number = loop times vmovdqa (%r11), %xmm15 // g_byteSwapMask .Ldec_loop: mov 12(%rdi), %eax // counter eax(32bit) addl $0x1000000, %eax // ctr inc mov 240(%r8), %r9d // rounds vmovdqu (%rdi), %xmm0 // iv jc .Ldec_ctr_carry jmp .Ldec_aes_cipher .Ldec_ctr_carry: bswap %eax addl $0x100, %eax // add carry bit bswap %eax jmp .Ldec_aes_cipher .balign 32 .Ldec_aes_cipher: mov %eax, 12(%rdi) // out iv cmp $12, %r9d // Compare the number of rounds to determine // when to jump to the next processing part vmovdqu (%r8), %xmm1 // key 0 vpxor (%rsi), %xmm10, %xmm10 // input for ghash operation lea 0xa0(%r8), %r10 // Point to the last key in 128-bit encryption vpxor %xmm1, %xmm0, %xmm0 vmovdqu 0x10(%r8), %xmm1 // key 1 vmovdqu 32(%rdi), %xmm11 // Hash key H^1 vmovdqu 32+32(%rdi), %xmm12 // Hash key H^1_2 vaesenc %xmm1, %xmm0, %xmm0 vmovdqu 0x20(%r8), %xmm1 // key 2 vpshufb %xmm15, %xmm10, %xmm10 // data transform vpshufd $0x4e, %xmm10, %xmm13 vaesenc %xmm1, %xmm0, %xmm0 vmovdqu 0x30(%r8), %xmm1 // key 3 vpclmulqdq $0x11, %xmm11, %xmm10, %xmm14// Karatsuba Multiply vpxor %xmm10, %xmm13, %xmm13 vaesenc %xmm1, %xmm0, %xmm0 vmovdqu 0x40(%r8), %xmm1 // key 4 vpclmulqdq $0x00, %xmm11, %xmm10, %xmm10 vpxor %xmm10, %xmm14, %xmm11 vaesenc %xmm1, %xmm0, %xmm0 vmovdqu 0x50(%r8), %xmm1 // key 5 vpclmulqdq $0x00, %xmm12, %xmm13, %xmm13 vpxor %xmm11, %xmm13, %xmm13 vaesenc %xmm1, %xmm0, %xmm0 vmovdqu 0x60(%r8), %xmm1 // key 6 vpslldq $8, %xmm13, %xmm11 vpsrldq $8, %xmm13, %xmm13 vpxor %xmm11, %xmm10, %xmm10 vpxor %xmm13, %xmm14, %xmm14 vaesenc %xmm1, %xmm0, %xmm0 vmovdqu 0x70(%r8), %xmm1 // key 7 vmovdqa 0x10(%r11), %xmm13 // g_poly vpalignr $8, %xmm10, %xmm10, %xmm12 // 1st phase of reduction vaesenc %xmm1, %xmm0, %xmm0 vmovdqu 0x80(%r8), %xmm1 // key 8 vpclmulqdq $0x10, %xmm13, %xmm10, %xmm10 vpxor %xmm12, %xmm10, %xmm10 vaesenc %xmm1, %xmm0, %xmm0 vmovdqu 0x90(%r8), %xmm1 // key 9 vpalignr $8, %xmm10, %xmm10, %xmm12 // 2nd phase of reduction vpclmulqdq $0x10, %xmm13, %xmm10, %xmm10 vaesenc %xmm1, %xmm0, %xmm0 vpxor %xmm14, %xmm12, %xmm12 jb .Ldec_ending vmovdqu (%r10), %xmm1 // key 10 vmovdqu 0x10(%r10), %xmm2 // key 11 lea 0x20(%r10), %r10 vaesenc %xmm1, %xmm0, %xmm0 vaesenc %xmm2, %xmm0, %xmm0 je .Ldec_ending vmovdqu (%r10), %xmm1 // key 12 vmovdqu 0x10(%r10), %xmm2 // key 13 lea 0x20(%r10), %r10 vaesenc %xmm1, %xmm0, %xmm0 vaesenc %xmm2, %xmm0, %xmm0 jmp .Ldec_ending .Ldec_ending: vmovdqu (%r10), %xmm1 // key last vpxor %xmm12, %xmm10, %xmm10 vpxor (%rsi), %xmm1, %xmm1 vaesenclast %xmm1, %xmm0, %xmm0 vpshufb %xmm15, %xmm10, %xmm10 vmovdqu %xmm0, (%rdx) // out lea 0x10(%rsi), %rsi lea 0x10(%rdx), %rdx dec %ecx jnz .Ldec_loop vmovdqu %xmm10, 16(%rdi) // out ret .cfi_endproc .size AES_GCM_Decrypt16BlockAsm, .-AES_GCM_Decrypt16BlockAsm .globl AES_GCM_ClearAsm .type AES_GCM_ClearAsm, @function .balign 32 AES_GCM_ClearAsm: .cfi_startproc vpxor %xmm1, %xmm1, %xmm1 vpxor %xmm2, %xmm2, %xmm2 vpxor %xmm3, %xmm3, %xmm3 vpxor %xmm4, %xmm4, %xmm4 vpxor %xmm5, %xmm5, %xmm5 vpxor %xmm6, %xmm6, %xmm6 vpxor %xmm7, %xmm7, %xmm7 vpxor %xmm8, %xmm8, %xmm8 vpxor %xmm9, %xmm9, %xmm9 vpxor %xmm10, %xmm10, %xmm10 vpxor %xmm11, %xmm11, %xmm11 vpxor %xmm12, %xmm12, %xmm12 ret .cfi_endproc .size AES_GCM_ClearAsm, .-AES_GCM_ClearAsm #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm/aes_gcm_16block_x86_64.S
Unix Assembly
unknown
9,868
/* * 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_AES) && defined(HITLS_CRYPTO_GCM) #include "crypt_arm.h" #include "aes_gcm_common_aarch64.S" #include "aes128_gcm_aarch64.S" #include "aes192_gcm_aarch64.S" #include "aes256_gcm_aarch64.S" .text .arch armv8-a+crypto .globl AES_GCM_ClearAsm .type AES_GCM_ClearAsm,%function .align 4 AES_GCM_ClearAsm: AARCH64_PACIASP eor KEY0.16b, KEY0.16b, KEY0.16b eor KEY1.16b, KEY1.16b, KEY1.16b eor KEY2.16b, KEY2.16b, KEY2.16b eor KEY3.16b, KEY3.16b, KEY3.16b eor KEY4.16b, KEY4.16b, KEY4.16b eor KEY5.16b, KEY5.16b, KEY5.16b eor KEY6.16b, KEY6.16b, KEY6.16b eor KEY7.16b, KEY7.16b, KEY7.16b eor KEY8.16b, KEY8.16b, KEY8.16b eor KEY9.16b, KEY9.16b, KEY9.16b eor KEY10.16b, KEY10.16b, KEY10.16b eor HASH0.16b, HASH0.16b, HASH0.16b eor HASH1.16b, HASH1.16b, HASH1.16b eor HASH2.16b, HASH2.16b, HASH2.16b eor HASH3.16b, HASH3.16b, HASH3.16b eor HASH4.16b, HASH4.16b, HASH4.16b AARCH64_AUTIASP ret .size AES_GCM_ClearAsm,.-AES_GCM_ClearAsm .globl AES_GCM_EncryptBlockAsm .type AES_GCM_EncryptBlockAsm,%function .align 4 AES_GCM_EncryptBlockAsm: AARCH64_PACIASP IN_STP // Register Protection ldr ROUNDS, [KEY00, #240] // Number of loading rounds add HTABLE, IVEC0, #16 // Sets the gHash start address. lsr COUNT, INLEN, #6 // Divided by 64, count the number of times cmp ROUNDS, #10 // Number of comparison rounds 10 LOAD_KEY // load AES KEY b.eq .LEnc_128_process // go to AES128 processing part cmp ROUNDS, #12 // Number of comparison rounds 12 ld1 {KEY10.4s, KEY11.4s}, [KEY00], #32 b.eq .LEnc_192_process // go to AES192 processing part ld1 {KEY12.4s, KEY13.4s}, [KEY00], #32 b .LEnc_256_process // go to AES256 processing part .LEnc_128_process: ldp KEND0, KEND1, [KEY00] // load key-10 ldp IV_H, IV_L, [IVEC0] // load IV #ifdef HITLS_BIG_ENDIAN ror KEND0, KEND0, #32 ror KEND1, KEND1, #32 REV_2S IV_H, IV_L #endif lsr IV_C, IV_L, #32 ld1 {CTR0.16b}, [IVEC0] // CTR bolck 0 lsl IVCTR, COUNTW, #2 // <<16 LOAD_GHASH_TABLE // load gHashTable BEFORE_ROUND FIRST_ROUND // data preprocessing ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY7.16b // round 7 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY8.16b // round 8 rev w9, IV_W // CTR0--Start ROUND4_END CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY9.16b // round 9 orr x9, x11, x9, lsl #32 // CTR0 block 4k+8 add IV_W, IV_W, #1 // CTR0++ eor v17.16b, v17.16b, v9.16b // h4k | h3k eor v16.16b, v16.16b, v8.16b // h2k | h1k STORE_RESULT // data preprocessing b.le .LEnc_end // After the first 64-byte processing is complete, // check the remaining length. b .LEnc_128_loop // Enter the cyclic processing flow. .LEnc_192_process: ldp KEND0, KEND1, [KEY00] // load key-10 ldp IV_H, IV_L, [IVEC0] // load IV #ifdef HITLS_BIG_ENDIAN ror KEND0, KEND0, #32 ror KEND1, KEND1, #32 REV_2S IV_H, IV_L #endif lsr IV_C, IV_L, #32 // IV-l ld1 {CTR0.16b}, [IVEC0] // CTR bolck 0 lsl IVCTR, COUNTW, #2 // <<16 LOAD_GHASH_TABLE // load hash table BEFORE_ROUND FIRST_ROUND // aes round ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY7.16b // round 7 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY8.16b // round 8 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY9.16b // round 9 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY10.16b // round 10 rev w9, IV_W // CTR0--Start ROUND4_END CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY11.16b // round 11 orr x9, x11, x9, lsl #32 // CTR0 block 4k+8 add IV_W, IV_W, #1 // CTR0++ eor v17.16b, v17.16b, v9.16b // h4k | h3k eor v16.16b, v16.16b, v8.16b // h2k | h1k STORE_RESULT b.le .LEnc_end b .LEnc_192_loop .LEnc_256_process: ldp KEND0, KEND1, [KEY00] // load key-10 ldp IV_H, IV_L, [IVEC0] // load IV #ifdef HITLS_BIG_ENDIAN ror KEND0, KEND0, #32 ror KEND1, KEND1, #32 REV_2S IV_H, IV_L #endif lsr IV_C, IV_L, #32 ld1 {CTR0.16b}, [IVEC0] // CTR bolck 0 lsl IVCTR, COUNTW, #2 // <<16 LOAD_GHASH_TABLE BEFORE_ROUND FIRST_ROUND ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY7.16b // round 7 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY8.16b // round 8 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY9.16b // round 9 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY10.16b // round 10 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY11.16b // round 11 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY12.16b // round 12 rev w9, IV_W // CTR0--Start ROUND4_END CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY13.16b // round 13 orr x9, x11, x9, lsl #32 // CTR0 block 4k+8 add IV_W, IV_W, #1 // CTR0++ eor v17.16b, v17.16b, v9.16b // h4k | h3k eor v16.16b, v16.16b, v8.16b // h2k | h1k STORE_RESULT b.le .LEnc_end b .LEnc_256_loop .LEnc_128_loop: GCM_ENC128_LOOP // Processes 64 bytes. b.le .LEnc_end // If the number of remaining blocks is 0, exit the loop. b .LEnc_128_loop // Continue the loop .LEnc_192_loop: GCM_ENC192_LOOP b.le .LEnc_end // <= 0 b .LEnc_192_loop .LEnc_256_loop: GCM_ENC256_LOOP b.le .LEnc_end // <= 0 b .LEnc_256_loop .LEnc_end: rev64 OUT0.16b, OUT0.16b // GHASH block 4k (only t0 is free) rev64 OUT1.16b, OUT1.16b // GHASH block 4k+1 (t0 and t1 free) rev64 OUT2.16b, OUT2.16b // GHASH[2] (t0, t1, and t2 free) rev64 OUT3.16b, OUT3.16b // GHASH[0] (t0, t1, t2 and t3 free) GHASH_BLOCK // Ghash calculation and encryption/decryption processing rev w9, IVCTR // CTR[0] ext HASH0.16b, HASH0.16b, HASH0.16b, #8 add x6, IVEC0, #16 orr x9, x11, x9, lsl #32 // CTR[0] fmov d0, x10 // CTR[0] fmov CTR0.d[1], x9 // CTR[0]--OK st1 {CTR0.16b }, [IVEC0] // out hash rev64 HASH0.16b, HASH0.16b st1 {HASH0.16b }, [x6] // out hash OUT_STP .LEnc_ret: and x0, INLEN, #-64 // length of processed data AARCH64_AUTIASP ret .size AES_GCM_EncryptBlockAsm,.-AES_GCM_EncryptBlockAsm .globl AES_GCM_DecryptBlockAsm .type AES_GCM_DecryptBlockAsm,%function .align 4 AES_GCM_DecryptBlockAsm: AARCH64_PACIASP IN_STP // stp ldr ROUNDS, [KEY00, #240] // pull rounds mov IVEC0, x0 // ctr0 add HTABLE, IVEC0, #16 // htable lsr COUNT, INLEN, #6 // divided by 64 cmp ROUNDS, #10 LOAD_KEY b.eq .LDec_128_process cmp ROUNDS, #12 ld1 {KEY10.4s, KEY11.4s}, [KEY00], #32 b.eq .LDec_192_process ld1 {KEY12.4s, KEY13.4s}, [KEY00], #32 b .LDec_256_process .LDec_128_process: ldp KEND0, KEND1, [KEY00] // load key-10 ldp IV_H, IV_L, [IVEC0] // load IV #ifdef HITLS_BIG_ENDIAN ror KEND0, KEND0, #32 ror KEND1, KEND1, #32 REV_2S IV_H, IV_L #endif lsr IV_C, IV_L, #32 ld1 {CTR0.16b}, [IVEC0] // CTR[0] #ifdef HITLS_BIG_ENDIAN REV_2S KEND0, KEND1 #endif lsl IVCTR, COUNTW, #2 // <<16 LOAD_GHASH_TABLE BEFORE_ROUND ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY0.16b // round 0 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY1.16b // round 1 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY2.16b // round 2 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY3.16b // round 3 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY4.16b // round 4 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY5.16b // round 5 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY6.16b // round 6 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY7.16b // round 7 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY8.16b // round 8 ROUND4_END CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY9.16b // round 9 eor v17.16b, v17.16b, v9.16b // h4k | h3k eor v16.16b, v16.16b, v8.16b // h2k | h1k STORE_DEC_RESULT b.le .LDec_end b .LDec_128_loop .LDec_192_process: ldp KEND0, KEND1, [KEY00] // load key-10 ldp IV_H, IV_L, [IVEC0] // load IV #ifdef HITLS_BIG_ENDIAN ror KEND0, KEND0, #32 ror KEND1, KEND1, #32 REV_2S IV_H, IV_L #endif lsr IV_C, IV_L, #32 ld1 {CTR0.16b}, [IVEC0] // CTR[0] #ifdef HITLS_BIG_ENDIAN REV_2S KEND0, KEND1 #endif lsl IVCTR, COUNTW, #2 // <<16 LOAD_GHASH_TABLE BEFORE_ROUND ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY0.16b // round 0 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY1.16b // round 1 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY2.16b // round 2 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY3.16b // round 3 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY4.16b // round 4 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY5.16b // round 5 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY6.16b // round 6 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY7.16b // round 7 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY8.16b // round 8 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY9.16b // round 9 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY10.16b // round 10 ROUND4_END CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY11.16b // round 11 eor v17.16b, v17.16b, v9.16b // h4k | h3k eor v16.16b, v16.16b, v8.16b // h2k | h1k STORE_DEC_RESULT b.le .LDec_end b .LDec_192_loop .LDec_256_process: ldp KEND0, KEND1, [KEY00] // load key-10 ldp IV_H, IV_L, [IVEC0] // load IV #ifdef HITLS_BIG_ENDIAN ror KEND0, KEND0, #32 ror KEND1, KEND1, #32 REV_2S IV_H, IV_L #endif lsr IV_C, IV_L, #32 ld1 {CTR0.16b}, [IVEC0] // CTR[0] #ifdef HITLS_BIG_ENDIAN REV_2S KEND0, KEND1 #endif lsl IVCTR, COUNTW, #2 // <<16 LOAD_GHASH_TABLE BEFORE_ROUND ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY0.16b // round 0 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY1.16b // round 1 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY2.16b // round 2 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY3.16b // round 3 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY4.16b // round 4 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY5.16b // round 5 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY6.16b // round 6 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY7.16b // round 7 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY8.16b // round 8 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY9.16b // round 9 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY10.16b // round 10 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY11.16b // round 11 ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY12.16b // round 12 ROUND4_END CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY13.16b // round 13 eor v17.16b, v17.16b, v9.16b // h4k | h3k eor v16.16b, v16.16b, v8.16b // h2k | h1k STORE_DEC_RESULT b.le .LDec_end b .LDec_256_loop .LDec_128_loop: GCM_DEC128_LOOP b.le .LDec_end // <=0 b .LDec_128_loop .LDec_192_loop: GCM_DEC192_LOOP b.le .LDec_end // <=0 b .LDec_192_loop .LDec_256_loop: GCM_DEC256_LOOP b.le .LDec_end // <=0 b .LDec_256_loop .LDec_end: GHASH_DEC_BLOCK rev w9, IVCTR // CTR[0] ext HASH0.16b, HASH0.16b, HASH0.16b, #8 add x6, IVEC0, #16 orr x9, x11, x9, lsl #32 // CTR[0] fmov d0, x10 // CTR[0] rev64 HASH0.16b, HASH0.16b fmov CTR0.d[1], x9 // CTR[0]--OK st1 {CTR0.16b }, [IVEC0] // out hash st1 {HASH0.16b }, [x6] // out hash OUT_STP .LDec_ret: and x0, INLEN, #-64 // length of processed data AARCH64_AUTIASP ret .size AES_GCM_DecryptBlockAsm,.-AES_GCM_DecryptBlockAsm #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm/aes_gcm_64block_aarch64.S
Unix Assembly
unknown
15,684
/* * 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_AES) && defined(HITLS_CRYPTO_GCM) #include "aes_gcm_96block_x86_64.S" .text .balign 16 g_byteSwapMask: .byte 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08 .byte 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00 .size g_byteSwapMask, .-g_byteSwapMask .balign 16 g_oneHigh: .byte 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 .byte 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 .size g_oneHigh, .-g_oneHigh .balign 16 g_oneLow: .byte 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 .byte 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 .size g_oneLow, .-g_oneLow .balign 16 g_poly: .byte 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 .byte 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc2 .size g_poly, .-g_poly /* * uint32_t AES_GCM_EncryptBlockAsm(MODES_GCM_Ctx *ctx, const uint8_t *in, * uint8_t *out, uint32_t len, void *key); * ctx %rdi * in %rsi * out %rdx * len %rcx * key %r8 */ .globl AES_GCM_EncryptBlockAsm .type AES_GCM_EncryptBlockAsm, @function .balign 32 AES_GCM_EncryptBlockAsm: .cfi_startproc push %r12 push %r13 leaq g_byteSwapMask(%rip), %r11 mov 240(%r8), %r9d // rounds shrl $4, %ecx movl 12(%rdi), %r12d // counter r12d(32bit) mov %ecx, %eax lea 0x80(%r8), %r8 shl $4, %eax cmp $6, %ecx jb .Lm64_enc_pass // If the number of data blocks is less than six, the data is skipped. call AES_GCM_Encrypt96BlockAsm // Invoke six parallel processing parts. .Lm64_enc_pass: cmp $4, %ecx // If the remaining data is less than four blocks, // the function is returned. jb .Lm64_enc_return vmovdqu (%rdi), %xmm0 // iv and $0b11, %ecx lea -2(%r9d), %r13d addl $0x4000000, %r12d // ctr inc jc .Lm64_enc_ctr_carry mov %r12d, 12(%rdi) // out iv vmovdqa 0x20(%r11), %xmm14 // Lone_low lea -0x70(%r8), %r10 vpaddb %xmm14, %xmm0, %xmm1 vmovdqu -0x80(%r8), %xmm4 // key0 vpaddb %xmm14, %xmm1, %xmm2 vpxor %xmm4, %xmm0, %xmm0 vpxor %xmm4, %xmm1, %xmm1 vpaddb %xmm14, %xmm2, %xmm3 vpxor %xmm4, %xmm2, %xmm2 vpxor %xmm4, %xmm3, %xmm3 jmp .Lm64_enc_aes .Lm64_enc_ctr_carry: vmovdqa 0x10(%r11), %xmm14 // Lone_high bswap %r12d vmovdqa (%r11), %xmm15 addl $0x100, %r12d // add carry bit vpshufb %xmm15, %xmm0, %xmm0 bswap %r12d vpaddd %xmm14, %xmm0, %xmm1 vpshufb %xmm15, %xmm0, %xmm0 mov %r12d, 12(%rdi) // out iv vpaddd %xmm14, %xmm1, %xmm2 lea -0x70(%r8), %r10 vpshufb %xmm15, %xmm1, %xmm1 vmovdqu -0x80(%r8), %xmm4 // key0 vpaddd %xmm14, %xmm2, %xmm3 vpxor %xmm4, %xmm0, %xmm0 vpshufb %xmm15, %xmm2, %xmm2 vpxor %xmm4, %xmm1, %xmm1 vpshufb %xmm15, %xmm3, %xmm3 vpxor %xmm4, %xmm2, %xmm2 vpxor %xmm4, %xmm3, %xmm3 jmp .Lm64_enc_aes .balign 16 .Lm64_enc_aes: vmovdqu (%r10), %xmm4 // key1-8/10/12 vaesenc %xmm4, %xmm0, %xmm0 vaesenc %xmm4, %xmm1, %xmm1 vaesenc %xmm4, %xmm2, %xmm2 vaesenc %xmm4, %xmm3, %xmm3 lea 0x10(%r10), %r10 dec %r13d jnz .Lm64_enc_aes vmovdqu (%r10), %xmm4 // key9/11/13 vmovdqu 0x10(%r10), %xmm5 // key10/12/14 vaesenc %xmm4, %xmm0, %xmm0 vpxor (%rsi), %xmm5, %xmm6 // last key xor plaintext vaesenc %xmm4, %xmm1, %xmm1 vpxor 0x10(%rsi), %xmm5, %xmm7 vaesenc %xmm4, %xmm2, %xmm2 vpxor 0x20(%rsi), %xmm5, %xmm8 vaesenc %xmm4, %xmm3, %xmm3 vpxor 0x30(%rsi), %xmm5, %xmm9 vaesenclast %xmm6, %xmm0, %xmm10 vmovdqu 16(%rdi), %xmm5 // ghash vaesenclast %xmm7, %xmm1, %xmm11 vmovdqu %xmm10, (%rdx) // out ciphertext vaesenclast %xmm8, %xmm2, %xmm12 vmovdqu %xmm11, 0x10(%rdx) vaesenclast %xmm9, %xmm3, %xmm13 vmovdqu %xmm12, 0x20(%rdx) // +++++++++++++++++ ghash process +++++++++++++++++++++++++++++++++ vmovdqu %xmm13, 0x30(%rdx) vpxor %xmm5, %xmm10, %xmm0 // input for ghash operation vmovdqu 0x20+0x40(%rdi), %xmm1 // hash key h^4 vpshufb (%r11), %xmm0, %xmm0 // data transform vmovdqu 0x20+0x50(%rdi), %xmm2 // hash key h^3_4 vpalignr $8, %xmm0, %xmm0, %xmm3 vpclmulqdq $0x11, %xmm1, %xmm0, %xmm9 // Karatsuba Multiply vpxor %xmm0, %xmm3, %xmm3 vpclmulqdq $0x00, %xmm1, %xmm0, %xmm7 vmovdqu 0x20+0x30(%rdi), %xmm1 // hash key h^3 vpclmulqdq $0x11, %xmm2, %xmm3, %xmm8 vpshufb (%r11), %xmm11, %xmm0 // data transform vpalignr $8, %xmm0, %xmm0, %xmm3 vpclmulqdq $0x11, %xmm1, %xmm0, %xmm5 // Karatsuba Multiply vpxor %xmm0, %xmm3, %xmm3 vpclmulqdq $0x00, %xmm1, %xmm0, %xmm0 vpxor %xmm5, %xmm9, %xmm9 vmovdqu 0x20+0x10(%rdi), %xmm1 // hash key h^2 vpclmulqdq $0x00, %xmm2, %xmm3, %xmm3 vpxor %xmm0, %xmm7, %xmm7 vpshufb (%r11), %xmm12, %xmm0 // data transform vpxor %xmm3, %xmm8, %xmm8 vmovdqu 0x20+0x20(%rdi), %xmm2 // hash key h^1_2 vpalignr $8, %xmm0, %xmm0, %xmm3 vpclmulqdq $0x11, %xmm1, %xmm0, %xmm5 // Karatsuba Multiply vpxor %xmm0, %xmm3, %xmm3 vpclmulqdq $0x00, %xmm1, %xmm0, %xmm0 vmovdqu 0x20(%rdi), %xmm1 // hash key h^1 vpxor %xmm5, %xmm9, %xmm9 vpclmulqdq $0x11, %xmm2, %xmm3, %xmm3 vpxor %xmm0, %xmm7, %xmm7 vpshufb (%r11), %xmm13, %xmm0 // data transform vpxor %xmm3, %xmm8, %xmm8 vpalignr $8, %xmm0, %xmm0, %xmm3 vpclmulqdq $0x11, %xmm1, %xmm0, %xmm5 // Karatsuba Multiply vpxor %xmm0, %xmm3, %xmm3 vpclmulqdq $0x00, %xmm1, %xmm0, %xmm0 vpxor %xmm5, %xmm9, %xmm5 vpclmulqdq $0x00, %xmm2, %xmm3, %xmm3 vpxor %xmm0, %xmm7, %xmm0 vpxor %xmm3, %xmm8, %xmm3 vpxor %xmm0, %xmm5, %xmm1 vpxor %xmm1, %xmm3, %xmm3 vpslldq $8, %xmm3, %xmm4 vmovdqa 0x30(%r11), %xmm14 // Lpoly vpxor %xmm4, %xmm0, %xmm0 vpalignr $8, %xmm0, %xmm0, %xmm2 // 1st phase of reduction vpclmulqdq $0x10, %xmm14, %xmm0, %xmm0 vpsrldq $8, %xmm3, %xmm3 vpxor %xmm2, %xmm0, %xmm0 vpalignr $8, %xmm0, %xmm0, %xmm2 // 2nd phase of reduction vpxor %xmm3, %xmm5, %xmm5 vpclmulqdq $0x10, %xmm14, %xmm0, %xmm0 vpxor %xmm5, %xmm2, %xmm2 vpxor %xmm2, %xmm0, %xmm0 vpshufb (%r11), %xmm0, %xmm0 // results for ghash // ------------------- ghash complete --------------------------------- vmovdqu %xmm0, 16(%rdi) // out ghash .Lm64_enc_return: shl $4, %ecx sub %ecx, %eax pop %r13 pop %r12 ret .cfi_endproc .size AES_GCM_EncryptBlockAsm, .-AES_GCM_EncryptBlockAsm /* * uint32_t AES_GCM_DecryptBlockAsm(MODES_GCM_Ctx *ctx, const uint8_t *in, * uint8_t *out, uint32_t len, void *key); * ctx %rdi * in %rsi * out %rdx * len %rcx * key %r8 */ .globl AES_GCM_DecryptBlockAsm .type AES_GCM_DecryptBlockAsm, @function .balign 32 AES_GCM_DecryptBlockAsm: .cfi_startproc leaq g_byteSwapMask(%rip), %r11 shrl $4, %ecx mov %ecx, %eax shll $4, %eax vmovdqa (%r11), %xmm15 // g_byteSwapMask mov 240(%r8), %r9d // rounds cmp $6, %ecx // invoke six parallel processing parts. jb .Lm64_dec_pass // if the number of data blocks is less than six, the data is skipped. call AES_GCM_Decrypt96BlockAsm .Lm64_dec_pass: cmp $4, %ecx // If the remaining data is less than four blocks, // the function is returned. jb .Lm64_dec_return .balign 16 .Lm64_dec_loop: vmovdqu (%rdi), %xmm0 // iv mov 12(%rdi), %r10d // counter r10d(32bit) addl $0x4000000, %r10d // ctr inc jc .Lm64_dec_ctr_carry vmovdqa 0x20(%r11), %xmm14 // Lone_low vpaddb %xmm14, %xmm0, %xmm1 vpaddb %xmm14, %xmm1, %xmm2 vpaddb %xmm14, %xmm2, %xmm3 jmp .Lm64_dec_aes_cipher .Lm64_dec_ctr_carry: vmovdqa (%r11), %xmm15 bswap %r10d vpshufb %xmm15, %xmm0, %xmm0 vmovdqa 0x10(%r11), %xmm14 // Lone_high addl $0x100, %r10d // add carry bit vpaddd %xmm14, %xmm0, %xmm1 vpshufb %xmm15, %xmm0, %xmm0 vpaddd %xmm14, %xmm1, %xmm2 vpshufb %xmm15, %xmm1, %xmm1 vpaddd %xmm14, %xmm2, %xmm3 vpshufb %xmm15, %xmm2, %xmm2 bswap %r10d vpshufb %xmm15, %xmm3, %xmm3 jmp .Lm64_dec_aes_cipher .balign 32 .Lm64_dec_aes_cipher: vmovdqu (%r8), %xmm7 mov %r10d, 12(%rdi) // out iv lea 0x10(%r8), %r10 vmovdqu 0x10(%rsi), %xmm5 vpxor %xmm7, %xmm0, %xmm0 // key 0 vmovdqu 0x20(%rsi), %xmm6 vpxor %xmm7, %xmm1, %xmm1 vmovdqu 0x30(%rsi), %xmm9 vpxor %xmm7, %xmm2, %xmm2 vmovdqu (%r10), %xmm4 vpxor %xmm7, %xmm3, %xmm3 // +++++++++++++++++ ghash process +++++++++++++++++++++++++++++++++ vmovdqu 16(%rdi), %xmm11 // ghash lea 0x10(%r10), %r10 vaesenc %xmm4, %xmm0, %xmm0 // key 1 vpxor (%rsi), %xmm11, %xmm10 // input for ghash operation vmovdqu 0x20+0x40(%rdi), %xmm11 // hash key h^4 vaesenc %xmm4, %xmm1, %xmm1 vmovdqu 0x20+0x50(%rdi), %xmm12 // hash key h^3_4 vpshufb (%r11), %xmm10, %xmm10 // data transform vaesenc %xmm4, %xmm2, %xmm2 vpalignr $8, %xmm10, %xmm10, %xmm13 vaesenc %xmm4, %xmm3, %xmm3 vmovdqu (%r10), %xmm4 vpclmulqdq $0x11, %xmm11, %xmm10, %xmm15 // Karatsuba Multiply lea 0x10(%r10), %r10 vaesenc %xmm4, %xmm0, %xmm0 // key 2 vpxor %xmm10, %xmm13, %xmm13 vpclmulqdq $0x00, %xmm11, %xmm10, %xmm7 vaesenc %xmm4, %xmm1, %xmm1 vmovdqu 0x20+0x30(%rdi), %xmm11 // hash key h^3 vpclmulqdq $0x11, %xmm12, %xmm13, %xmm8 vaesenc %xmm4, %xmm2, %xmm2 vpshufb (%r11), %xmm5, %xmm10 // data transform vaesenc %xmm4, %xmm3, %xmm3 vmovdqu (%r10), %xmm4 vpalignr $8, %xmm10, %xmm10, %xmm13 lea 0x10(%r10), %r10 vaesenc %xmm4, %xmm0, %xmm0 // key 3 vpclmulqdq $0x11, %xmm11, %xmm10, %xmm14 // Karatsuba Multiply vaesenc %xmm4, %xmm1, %xmm1 vpxor %xmm10, %xmm13, %xmm13 vpclmulqdq $0x00, %xmm11, %xmm10, %xmm10 vaesenc %xmm4, %xmm2, %xmm2 vpxor %xmm14, %xmm15, %xmm15 vpclmulqdq $0x00, %xmm12, %xmm13, %xmm13 vaesenc %xmm4, %xmm3, %xmm3 vmovdqu (%r10), %xmm4 vpxor %xmm10, %xmm7, %xmm7 lea 0x10(%r10), %r10 vaesenc %xmm4, %xmm0, %xmm0 // key 4 vpxor %xmm13, %xmm8, %xmm8 vaesenc %xmm4, %xmm1, %xmm1 vmovdqu 0x20+0x10(%rdi), %xmm11 // hash key h^2 vmovdqu 0x20+0x20(%rdi), %xmm12 // hash key h^1_2 vaesenc %xmm4, %xmm2, %xmm2 vpshufb (%r11), %xmm6, %xmm10 // data transform vaesenc %xmm4, %xmm3, %xmm3 vmovdqu (%r10), %xmm4 vpalignr $8, %xmm10, %xmm10, %xmm13 vpclmulqdq $0x11, %xmm11, %xmm10, %xmm14 // Karatsuba Multiply lea 0x10(%r10), %r10 vaesenc %xmm4, %xmm0, %xmm0 // key 5 vpxor %xmm10, %xmm13, %xmm13 vpclmulqdq $0x00, %xmm11, %xmm10, %xmm10 vaesenc %xmm4, %xmm1, %xmm1 vpxor %xmm14, %xmm15, %xmm15 vpclmulqdq $0x11, %xmm12, %xmm13, %xmm13 vaesenc %xmm4, %xmm2, %xmm2 vpxor %xmm10, %xmm7, %xmm7 vaesenc %xmm4, %xmm3, %xmm3 vmovdqu (%r10), %xmm4 vpxor %xmm13, %xmm8, %xmm8 lea 0x10(%r10), %r10 vaesenc %xmm4, %xmm0, %xmm0 // key 6 vmovdqu 0x20(%rdi), %xmm11 // hash key h^1 vpshufb (%r11), %xmm9, %xmm10 // data transform vpalignr $8, %xmm10, %xmm10, %xmm13 vaesenc %xmm4, %xmm1, %xmm1 vpclmulqdq $0x11, %xmm11, %xmm10, %xmm14 // Karatsuba Multiply vpxor %xmm10, %xmm13, %xmm13 vaesenc %xmm4, %xmm2, %xmm2 vpclmulqdq $0x00, %xmm11, %xmm10, %xmm10 vpxor %xmm14, %xmm15, %xmm14 vaesenc %xmm4, %xmm3, %xmm3 vmovdqu (%r10), %xmm4 vpclmulqdq $0x00, %xmm12, %xmm13, %xmm13 vpxor %xmm10, %xmm7, %xmm10 vpxor %xmm13, %xmm8, %xmm13 lea 0x10(%r10), %r10 vaesenc %xmm4, %xmm0, %xmm0 // key 7 vpxor %xmm10, %xmm14, %xmm11 vaesenc %xmm4, %xmm1, %xmm1 vpxor %xmm11, %xmm13, %xmm13 vpslldq $8, %xmm13, %xmm11 vaesenc %xmm4, %xmm2, %xmm2 vpsrldq $8, %xmm13, %xmm13 vpxor %xmm13, %xmm14, %xmm14 vaesenc %xmm4, %xmm3, %xmm3 vmovdqu (%r10), %xmm4 vpxor %xmm11, %xmm10, %xmm10 lea 0x10(%r10), %r10 vaesenc %xmm4, %xmm0, %xmm0 // key 8 vmovdqa 0x30(%r11), %xmm13 // Lpoly vaesenc %xmm4, %xmm1, %xmm1 vpalignr $8, %xmm10, %xmm10, %xmm12 // 1st phase of reduction vpclmulqdq $0x10, %xmm13, %xmm10, %xmm10 vpxor %xmm12, %xmm10, %xmm10 vaesenc %xmm4, %xmm2, %xmm2 vpalignr $8, %xmm10, %xmm10, %xmm12 // 2nd phase of reduction vaesenc %xmm4, %xmm3, %xmm3 vmovdqu (%r10), %xmm4 vpclmulqdq $0x10, %xmm13, %xmm10, %xmm10 vpxor %xmm14, %xmm12, %xmm12 vaesenc %xmm4, %xmm0, %xmm0 // key 9 vpxor %xmm12, %xmm10, %xmm10 vaesenc %xmm4, %xmm1, %xmm1 lea 0x10(%r10), %r10 vaesenc %xmm4, %xmm2, %xmm2 vpshufb (%r11), %xmm10, %xmm10 // ------------------- ghash complete --------------------------------- vaesenc %xmm4, %xmm3, %xmm3 vmovdqu %xmm10, 16(%rdi) // out ghash cmp $12, %r9d jb .Lm64_dec_ending vmovdqu (%r10), %xmm4 vmovdqu 0x10(%r10), %xmm5 vaesenc %xmm4, %xmm0, %xmm0 // key 10 vaesenc %xmm4, %xmm1, %xmm1 vaesenc %xmm4, %xmm2, %xmm2 vaesenc %xmm4, %xmm3, %xmm3 lea 0x20(%r10), %r10 vaesenc %xmm5, %xmm0, %xmm0 // key 11 vaesenc %xmm5, %xmm1, %xmm1 vaesenc %xmm5, %xmm2, %xmm2 vaesenc %xmm5, %xmm3, %xmm3 je .Lm64_dec_ending vmovdqu (%r10), %xmm4 vmovdqu 0x10(%r10), %xmm5 vaesenc %xmm4, %xmm0, %xmm0 // key 12 vaesenc %xmm4, %xmm1, %xmm1 vaesenc %xmm4, %xmm2, %xmm2 vaesenc %xmm4, %xmm3, %xmm3 lea 0x20(%r10), %r10 vaesenc %xmm5, %xmm0, %xmm0 // key 13 vaesenc %xmm5, %xmm1, %xmm1 vaesenc %xmm5, %xmm2, %xmm2 vaesenc %xmm5, %xmm3, %xmm3 jmp .Lm64_dec_ending .Lm64_dec_ending: vmovdqu (%r10), %xmm4 // key10/12/14 vpxor (%rsi), %xmm4, %xmm5 // last key xor plaintext vpxor 0x10(%rsi), %xmm4, %xmm6 vaesenclast %xmm5, %xmm0, %xmm0 vpxor 0x20(%rsi), %xmm4, %xmm7 vaesenclast %xmm6, %xmm1, %xmm1 vpxor 0x30(%rsi), %xmm4, %xmm8 vmovdqu %xmm0, (%rdx) // out ciphertext vaesenclast %xmm7, %xmm2, %xmm2 vmovdqu %xmm1, 0x10(%rdx) vaesenclast %xmm8, %xmm3, %xmm3 vmovdqu %xmm2, 0x20(%rdx) and $0b11, %ecx vmovdqu %xmm3, 0x30(%rdx) .Lm64_dec_return: shl $4, %ecx sub %ecx, %eax ret .cfi_endproc .size AES_GCM_DecryptBlockAsm, .-AES_GCM_DecryptBlockAsm #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm/aes_gcm_64block_x86_64.S
Unix Assembly
unknown
16,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" #if defined(HITLS_CRYPTO_AES) && defined(HITLS_CRYPTO_GCM) .text /* * MODES_GCM_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len, void *key * ctx %rdi * in %rsi * out %rdx * len %rcx * key %r8 * The %r12 register is shared with AES_GCM_EncryptBlockAsm. Pay attention to its use. */ .type AES_GCM_Encrypt96BlockAsm, @function .balign 16 AES_GCM_Encrypt96BlockAsm: .cfi_startproc push %rbp mov %rsp, %rbp vmovdqu (%rdi), %xmm0 // iv lea -2(%r9d), %r13d addl $0x6000000, %r12d // ctr inc vmovdqu -0x80(%r8), %xmm6 // key0 leaq -0x70(%r8), %r10 jc .Lm96_enc_ctr_carry vmovdqa 0x20(%r11), %xmm7 movl %r12d, 12(%rdi) // out iv vpaddb %xmm7, %xmm0, %xmm1 // g_oneLow vpxor %xmm6, %xmm0, %xmm0 vpaddb %xmm7, %xmm1, %xmm2 vpxor %xmm6, %xmm1, %xmm1 vpaddb %xmm7, %xmm2, %xmm3 vpxor %xmm6, %xmm2, %xmm2 vpaddb %xmm7, %xmm3, %xmm4 vpxor %xmm6, %xmm3, %xmm3 vpaddb %xmm7, %xmm4, %xmm5 vpxor %xmm6, %xmm4, %xmm4 vpxor %xmm6, %xmm5, %xmm5 vmovdqu (%r10), %xmm6 // key1 .balign 16 .Lm96_enc_aes: vaesenc %xmm6, %xmm0, %xmm0 vaesenc %xmm6, %xmm1, %xmm1 vaesenc %xmm6, %xmm2, %xmm2 vaesenc %xmm6, %xmm3, %xmm3 vaesenc %xmm6, %xmm4, %xmm4 leaq 0x10(%r10), %r10 vaesenc %xmm6, %xmm5, %xmm5 vmovdqu (%r10), %xmm6 // key2-9/11/13 decl %r13d jnz .Lm96_enc_aes vaesenc %xmm6, %xmm0, %xmm0 vmovdqu 0x10(%r10), %xmm10 // key10/12/14 sub $112, %rsp vaesenc %xmm6, %xmm1, %xmm1 vpxor (%rsi), %xmm10, %xmm8 // last key xor plaintext and $-16, %rsp vaesenc %xmm6, %xmm2, %xmm2 vpxor 0x10(%rsi), %xmm10, %xmm7 vaesenc %xmm6, %xmm3, %xmm3 vpxor 0x20(%rsi), %xmm10, %xmm9 vaesenc %xmm6, %xmm4, %xmm4 vpxor 0x30(%rsi), %xmm10, %xmm11 vaesenc %xmm6, %xmm5, %xmm5 vpxor 0x40(%rsi), %xmm10, %xmm12 vaesenclast %xmm8, %xmm0, %xmm0 vpxor 0x50(%rsi), %xmm10, %xmm13 vmovdqa (%r11), %xmm15 // g_byteSwapMask vaesenclast %xmm7, %xmm1, %xmm1 vmovdqu %xmm0, (%rdx) // out ciphertext vpxor 16(%rdi), %xmm0, %xmm0 // Do it in advance. input for ghash operation vmovdqa 0x20(%r11), %xmm6 vpshufb %xmm15, %xmm0, %xmm8 vmovdqu (%rdi), %xmm0 // iv vaesenclast %xmm9, %xmm2, %xmm2 vmovdqa %xmm8, (%rsp) vmovdqu -0x80(%r8), %xmm7 vmovdqu %xmm1, 0x10(%rdx) vpshufb %xmm15, %xmm1, %xmm9 vpaddb %xmm6, %xmm0, %xmm1 // g_oneLow vpxor %xmm7, %xmm0, %xmm0 // key 0 vaesenclast %xmm11, %xmm3, %xmm3 vmovdqa %xmm9, 0x10(%rsp) vmovdqu %xmm2, 0x20(%rdx) vpshufb %xmm15, %xmm2, %xmm11 vpaddb %xmm6, %xmm1, %xmm2 vpxor %xmm7, %xmm1, %xmm1 vaesenclast %xmm12, %xmm4, %xmm4 vmovdqa %xmm11, 0x20(%rsp) vmovdqu %xmm3, 0x30(%rdx) vpshufb %xmm15, %xmm3, %xmm12 vpaddb %xmm6, %xmm2, %xmm3 vpxor %xmm7, %xmm2, %xmm2 vaesenclast %xmm13, %xmm5, %xmm5 vmovdqa %xmm12, 0x30(%rsp) vmovdqu %xmm4, 0x40(%rdx) vpshufb %xmm15, %xmm4, %xmm13 vpaddb %xmm6, %xmm3, %xmm4 vpxor %xmm7, %xmm3, %xmm3 leaq 0x60(%rsi), %rsi vmovdqu %xmm5, 0x50(%rdx) vpshufb %xmm15, %xmm5, %xmm14 vpaddb %xmm6, %xmm4, %xmm5 vmovdqa %xmm13, 0x40(%rsp) vmovdqa %xmm14, 0x50(%rsp) cmpl $12, %ecx // If the remaining length is less than 12, // the loop is not performed. jb .Lm96_inner_out addl $0x6000000, %r12d jc .Lm96_inner_ctr_carry .balign 16 .Lm96_inner_loop: vmovdqu -0x70(%r8), %xmm6 // rk0 // function stitch second 6x-blocks encryption and ghash of first 6x-blocks. vaesenc %xmm6, %xmm0, %xmm0 // encryption of the 'inout0' of second 6x-blocks. vmovdqu 0x20+0x70(%rdi), %xmm11 // H^6 vmovdqa (%rsp), %xmm10 // xmm10 = inout0, the first encrypted 6x-blocks vaesenc %xmm6, %xmm1, %xmm1 movl %r12d, 12(%rdi) // out iv vmovdqu 0x20+0x80(%rdi), %xmm12 // xmm12 = (H^5.h + H^5.l, H^6.h + H^6.l) vpclmulqdq $0x11, %xmm11, %xmm10, %xmm15 // Karatsuba Multiply. xmm15 = H^6.h·inout0.h, where '·' represent multiply in GF(2^128) of GHASH. vaesenc %xmm6, %xmm2, %xmm2 vpxor %xmm7, %xmm4, %xmm4 vpxor %xmm7, %xmm5, %xmm5 vpclmulqdq $0x00, %xmm11, %xmm10, %xmm14 // xmm14 = H^6.l·inout0.l vaesenc %xmm6, %xmm3, %xmm3 vpunpckhqdq %xmm10, %xmm10, %xmm13 // xmm13= (inout0.h, inout0.h) leaq 0x10(%r8), %r10 vpxor %xmm10, %xmm13, %xmm13 // xmm13 = (inout0.h + inout0.l, inout0.h + inout0.h) vmovdqu 0x20+0x60(%rdi), %xmm11 // H^5 vpclmulqdq $0x10, %xmm12, %xmm13, %xmm13 // xmm13 = (H^6.h + H^6.l)·(inout0.h + inout0.l) vaesenc %xmm6, %xmm4, %xmm4 vmovdqa 0x10(%rsp), %xmm10 // xmm10 = inout1 vpclmulqdq $0x11, %xmm11, %xmm10, %xmm8 // xmm8 = H^5.h·inout1.h vaesenc %xmm6, %xmm5, %xmm5 vmovdqu -0x60(%r8), %xmm7 // rk1 vpxor %xmm8, %xmm15, %xmm15 // xmm15 += xmm8 vpclmulqdq $0x00, %xmm11, %xmm10, %xmm11 // xmm11 = H^5.l·inout1.l vaesenc %xmm7, %xmm0, %xmm0 vpunpckhqdq %xmm10, %xmm10, %xmm8 // xmm8 = (inout1.h, inout1.h) vpxor %xmm11, %xmm14, %xmm14 // xmm14 += xmm11 vpxor %xmm10, %xmm8, %xmm8 // xmm8 = (inout1.h + inout1.l, inout1.h + inout1.h) vmovdqu 0x20+0x40(%rdi), %xmm11 // xmm11 = H^4 vpclmulqdq $0x00, %xmm12, %xmm8, %xmm9 // xmm9 = (H^5.h + H^5.l)·(inout1.h + inout1.l) vaesenc %xmm7, %xmm1, %xmm1 vmovdqa 0x20(%rsp), %xmm10 // xmm10 = inout2 vpxor %xmm9, %xmm13, %xmm13 // xmm13 += xmm9 vpclmulqdq $0x11, %xmm11, %xmm10, %xmm8 // xmm8 = H^4.h·inout2.h vaesenc %xmm7, %xmm2, %xmm2 vmovdqu 0x20+0x50(%rdi), %xmm12 // xmm12 = (H^3.h + H^3.l, H^4.h + H^4.l) vpclmulqdq $0x00, %xmm11, %xmm10, %xmm9 // xmm9 = H^4.l·inout2.l vaesenc %xmm7, %xmm3, %xmm3 vpxor %xmm8, %xmm15, %xmm15 // xmm15 += xmm8 vpxor %xmm9, %xmm14, %xmm14 // xmm14 += xmm9 vpunpckhqdq %xmm10, %xmm10, %xmm6 // xmm6 = (inout2.h, inout2.h) vaesenc %xmm7, %xmm4, %xmm4 vpxor %xmm10, %xmm6, %xmm6 // xmm6 = (inout2.h + inout2.l, inout2.h + inout2.h) vmovdqu 0x20+0x30(%rdi), %xmm11 // xmm11 = H^3 vpclmulqdq $0x10, %xmm12, %xmm6, %xmm8 // xmm8 = (H^4.h + H^4.l)·(inout2.h + inout2.h) vaesenc %xmm7, %xmm5, %xmm5 vmovdqa 0x30(%rsp), %xmm10 // xmm10 = inout3 vmovdqu -0x50(%r8), %xmm6 // rk2 vpclmulqdq $0x11, %xmm11, %xmm10, %xmm9 // xmm9 = H^3.h·inout3.h vaesenc %xmm6, %xmm0, %xmm0 vpxor %xmm8, %xmm13, %xmm13 // xmm13 += xmm8 vpclmulqdq $0x00, %xmm11, %xmm10, %xmm7 // xmm7 = H^3.l·inout3.l vaesenc %xmm6, %xmm1, %xmm1 vpxor %xmm9, %xmm15, %xmm15 // xmm15 += xmm9 vpunpckhqdq %xmm10, %xmm10, %xmm8 // xmm8 = (inout3.h, inout3,h) vaesenc %xmm6, %xmm2, %xmm2 vpxor %xmm10, %xmm8, %xmm8 // xmm8 = (inout3.h + inout3.l, inout3.h + inout3.h) vpxor %xmm7, %xmm14, %xmm14 // xmm14 += xmm7 vpclmulqdq $0x00, %xmm12, %xmm8, %xmm9 // xmm9 = (H^3.h + H^3.l)·(inout3.h + inout3.l) vaesenc %xmm6, %xmm3, %xmm3 vmovdqa 0x40(%rsp), %xmm10 // xmm10 = inout4 vmovdqu 0x20+0x10(%rdi), %xmm11 // xmm11 = H^2 vaesenc %xmm6, %xmm4, %xmm4 vpxor %xmm9, %xmm13, %xmm13 // xmm13 += xmm9 vaesenc %xmm6, %xmm5, %xmm5 vmovdqu -0x40(%r8), %xmm7 // rk3 vpclmulqdq $0x11, %xmm11, %xmm10, %xmm8 // xmm8 = H^2.h·inout4.h vaesenc %xmm7, %xmm0, %xmm0 vmovdqu 0x20+0x20(%rdi), %xmm12 // xmm12 = (H^1.h + H^1.l, H^2.h + H^2.l) vpclmulqdq $0x00, %xmm11, %xmm10, %xmm9 // xmm9 = H^2.h·inout4.h vaesenc %xmm7, %xmm1, %xmm1 vpunpckhqdq %xmm10, %xmm10, %xmm6 // xmm6 = (inout4.h, inout4.h) vpxor %xmm8, %xmm15, %xmm15 // xmm15 += xmm8 vaesenc %xmm7, %xmm2, %xmm2 vpxor %xmm10, %xmm6, %xmm6 // xmm6 = (inout4.h + inout4.l, inout4.h + inout4.h) vpxor %xmm9, %xmm14, %xmm14 // xmm14 += xmm9 vpclmulqdq $0x10, %xmm12, %xmm6, %xmm8 // xmm8 = (H^2.h + H^2.l)·(inout4.h + inout4.l) vaesenc %xmm7, %xmm3, %xmm3 vmovdqa 0x50(%rsp), %xmm10 // xmm10 = inout5 vmovdqu 0x20(%rdi), %xmm11 // xmm11 = H^1 vaesenc %xmm7, %xmm4, %xmm4 vpxor %xmm8, %xmm13, %xmm13 // xmm13 += xmm8 vmovdqu -0x30(%r8), %xmm6 // rk4 vaesenc %xmm7, %xmm5, %xmm5 vpclmulqdq $0x11, %xmm11, %xmm10, %xmm9 // xmm9 = H^1.h·inout5.h vaesenc %xmm6, %xmm0, %xmm0 vpunpckhqdq %xmm10, %xmm10, %xmm7 // xmm7 = (inout5.h, inout5.h) vpclmulqdq $0x00, %xmm11, %xmm10, %xmm8 // xmm8 = H^1.l·inout5.l vaesenc %xmm6, %xmm1, %xmm1 vpxor %xmm10, %xmm7, %xmm7 // xmm7 = (inout5.h + inout5.l, inout5.h + inout5.h) vpxor %xmm9, %xmm15, %xmm15 // xmm15 += xmm9 vpclmulqdq $0x00, %xmm12, %xmm7, %xmm12 // xmm12 = (H^1.h + H^1.l)·(inout5.h + inout5.l), that's all the (l+h)·(l+h) vaesenc %xmm6, %xmm2, %xmm2 vpxor %xmm12, %xmm13, %xmm13 // xmm13 += xmm12 vpxor %xmm8, %xmm14, %xmm14 // xmm14 += xmm8 vaesenc %xmm6, %xmm3, %xmm3 vpxor %xmm15, %xmm13, %xmm13 // Karatsuba, middle coefficient + higher coefficient vpxor %xmm14, %xmm13, %xmm13 // Karatsuba, middle coefficient + lower coefficient vpslldq $8, %xmm13, %xmm9 // xmm9 = (0, xmm13.l) vaesenc %xmm6, %xmm4, %xmm4 vpxor %xmm9, %xmm14, %xmm14 // xmm14 is the lower 128-bits of ghash of first 6x-blocks vaesenc %xmm6, %xmm5, %xmm5 // montgomery reduction method from https://link.springer.com/chapter/10.1007/978-3-031-34671-2_30 // T = [D:C:B:A]. here, xmm14 = [B:A], xmm15 = [D:C] // WA = W·A, U = C + A + WA.h, V = B + WA.l vmovdqu -0x20(%r8), %xmm7 // rk5 vpalignr $8, %xmm14, %xmm14, %xmm9 // xmm9 = [A:B] vaesenc %xmm7, %xmm0, %xmm0 vmovdqu 0x30(%r11), %xmm12 // poly vaesenc %xmm7, %xmm1, %xmm1 vpsrldq $8, %xmm13, %xmm8 // xmm8 = (xmm13.h, 0) vpxor %xmm8, %xmm15, %xmm15 // xmm15 is the higher 128-bits of ghash of first 6x-blocks vaesenc %xmm7, %xmm2, %xmm2 vpclmulqdq $0x10, %xmm12, %xmm14, %xmm14 // xmm14 = W·A, where W = 0xC200000000000000. vaesenc %xmm7, %xmm3, %xmm3 vmovdqu -0x10(%r8), %xmm6 // rk6 vpxor %xmm9, %xmm14, %xmm14 // xmm14 = W·A + [A:B] = [A+WA.h:B+WA.l] = [U':V], where U' = A + WA.h vaesenc %xmm7, %xmm4, %xmm4 vpalignr $8, %xmm14, %xmm14, %xmm8 // xmm8 = [V:U'] vpclmulqdq $0x10, %xmm12, %xmm14, %xmm14 // xmm14 = W·V vaesenc %xmm7, %xmm5, %xmm5 vpxor %xmm8, %xmm15, %xmm15 // xmm15 = [D+V:C+U'] vpxor %xmm14, %xmm15, %xmm15 // xmm15 = [D+V:C+U'] + W·V = [D+V+WV.h:C+U'+WV.l] = [D+V+WV.h:U+WV.l] = [D+V:U+WV] // reduction finished. vaesenc %xmm6, %xmm0, %xmm0 vaesenc %xmm6, %xmm1, %xmm1 vaesenc %xmm6, %xmm2, %xmm2 vaesenc %xmm6, %xmm3, %xmm3 vaesenc %xmm6, %xmm4, %xmm4 vaesenc %xmm6, %xmm5, %xmm5 vmovdqu 0x00(%r8), %xmm7 // rk7 vaesenc %xmm7, %xmm0, %xmm0 vaesenc %xmm7, %xmm1, %xmm1 vmovdqa %xmm15, %xmm10 vaesenc %xmm7, %xmm2, %xmm2 vaesenc %xmm7, %xmm3, %xmm3 vaesenc %xmm7, %xmm4, %xmm4 cmpl $12, %r9d vaesenc %xmm7, %xmm5, %xmm5 vmovdqu (%r10), %xmm6 vmovdqu 0x10(%r10), %xmm11 jb .Lm96_inner_ending vaesenc %xmm6, %xmm0, %xmm0 // key 10 vaesenc %xmm6, %xmm1, %xmm1 vaesenc %xmm6, %xmm2, %xmm2 vaesenc %xmm6, %xmm3, %xmm3 vaesenc %xmm6, %xmm4, %xmm4 vaesenc %xmm6, %xmm5, %xmm5 vaesenc %xmm11, %xmm0, %xmm0 // key 11 vaesenc %xmm11, %xmm1, %xmm1 vaesenc %xmm11, %xmm2, %xmm2 vaesenc %xmm11, %xmm3, %xmm3 leaq 0x20(%r10), %r10 vaesenc %xmm11, %xmm4, %xmm4 vmovdqu (%r10), %xmm6 vaesenc %xmm11, %xmm5, %xmm5 vmovdqu 0x10(%r10), %xmm11 je .Lm96_inner_ending vaesenc %xmm6, %xmm0, %xmm0 // key 12 vaesenc %xmm6, %xmm1, %xmm1 vaesenc %xmm6, %xmm2, %xmm2 vaesenc %xmm6, %xmm3, %xmm3 vaesenc %xmm6, %xmm4, %xmm4 vaesenc %xmm6, %xmm5, %xmm5 vaesenc %xmm11, %xmm0, %xmm0 // key 13 vaesenc %xmm11, %xmm1, %xmm1 vaesenc %xmm11, %xmm2, %xmm2 vaesenc %xmm11, %xmm3, %xmm3 leaq 0x20(%r10), %r10 vaesenc %xmm11, %xmm4, %xmm4 vmovdqu (%r10), %xmm6 vaesenc %xmm11, %xmm5, %xmm5 vmovdqu 0x10(%r10), %xmm11 jmp .Lm96_inner_ending .balign 16 .Lm96_inner_ctr_carry: vmovdqu (%rdi), %xmm0 // iv bswap %r12d vmovdqa (%r11), %xmm15 addl $0x100, %r12d // add carry bit vmovdqa 0x10(%r11), %xmm14 // lone_high vpshufb %xmm15, %xmm0, %xmm0 vmovdqu -0x80(%r8), %xmm7 vpaddd %xmm14, %xmm0, %xmm1 vpshufb %xmm15, %xmm0, %xmm0 vpaddd %xmm14, %xmm1, %xmm2 vpxor %xmm7, %xmm0, %xmm0 // key 0 vpshufb %xmm15, %xmm1, %xmm1 vpaddd %xmm14, %xmm2, %xmm3 vpxor %xmm7, %xmm1, %xmm1 vpshufb %xmm15, %xmm2, %xmm2 vpaddd %xmm14, %xmm3, %xmm4 vpxor %xmm7, %xmm2, %xmm2 vpshufb %xmm15, %xmm3, %xmm3 vpaddd %xmm14, %xmm4, %xmm5 vpxor %xmm7, %xmm3, %xmm3 vpshufb %xmm15, %xmm4, %xmm4 bswap %r12d vpshufb %xmm15, %xmm5, %xmm5 jmp .Lm96_inner_loop .balign 16 .Lm96_inner_ending: vaesenc %xmm6, %xmm0, %xmm0 // key 9 vpxor (%rsi), %xmm11, %xmm13 // last key xor plaintext vpxor %xmm14, %xmm12, %xmm12 vaesenc %xmm6, %xmm1, %xmm1 vpxor 0x10(%rsi), %xmm11, %xmm8 vaesenclast %xmm13, %xmm0, %xmm0 // key 10/12/14 vmovdqa (%r11), %xmm15 leaq 0x60(%rdx), %rdx vaesenc %xmm6, %xmm2, %xmm2 vpxor 0x20(%rsi), %xmm11, %xmm9 sub $6, %ecx vaesenclast %xmm8, %xmm1, %xmm1 vmovdqu %xmm0, (%rdx) // out result text vaesenc %xmm6, %xmm3, %xmm3 vpshufb %xmm15, %xmm0, %xmm0 vmovdqa 0x20(%r11), %xmm12 vpxor %xmm10, %xmm0, %xmm0 // Do it in advance. input for ghash operation vpxor 0x30(%rsi), %xmm11, %xmm8 vmovdqa %xmm0, (%rsp) vaesenclast %xmm9, %xmm2, %xmm2 vmovdqu -0x80(%r8), %xmm7 vmovdqu %xmm1, 0x10(%rdx) vmovdqu (%rdi), %xmm0 // iv vpshufb %xmm15, %xmm1, %xmm1 vaesenc %xmm6, %xmm4, %xmm4 vmovdqa %xmm1, 0x10(%rsp) vpaddb %xmm12, %xmm0, %xmm1 // g_oneLow vaesenc %xmm6, %xmm5, %xmm5 vpxor %xmm7, %xmm0, %xmm0 // key 0 vmovdqu %xmm2, 0x20(%rdx) vpxor 0x40(%rsi), %xmm11, %xmm9 vpshufb %xmm15, %xmm2, %xmm2 vaesenclast %xmm8, %xmm3, %xmm3 vmovdqa %xmm2, 0x20(%rsp) vpaddb %xmm12, %xmm1, %xmm2 vpxor %xmm7, %xmm1, %xmm1 vpxor 0x50(%rsi), %xmm11, %xmm8 vmovdqu %xmm3, 0x30(%rdx) vpshufb %xmm15, %xmm3, %xmm3 vaesenclast %xmm9, %xmm4, %xmm4 vmovdqa %xmm3, 0x30(%rsp) vpaddb %xmm12, %xmm2, %xmm3 vpxor %xmm7, %xmm2, %xmm2 leaq 0x60(%rsi), %rsi vmovdqu %xmm4, 0x40(%rdx) vpshufb %xmm15, %xmm4, %xmm4 vaesenclast %xmm8, %xmm5, %xmm5 vmovdqa %xmm4, 0x40(%rsp) vpaddb %xmm12, %xmm3, %xmm4 vpxor %xmm7, %xmm3, %xmm3 vmovdqu %xmm5, 0x50(%rdx) vpshufb %xmm15, %xmm5, %xmm5 cmpl $12, %ecx // If the remaining length is greater than or equal to 12, // the loop continues. vmovdqa %xmm5, 0x50(%rsp) vpaddb %xmm12, %xmm4, %xmm5 jb .Lm96_inner_out addl $0x6000000, %r12d jc .Lm96_inner_ctr_carry jmp .Lm96_inner_loop .balign 16 .Lm96_enc_ctr_carry: vmovdqa (%r11), %xmm15 bswap %r12d vmovdqa 0x10(%r11), %xmm14 vpshufb %xmm15, %xmm0, %xmm0 addl $0x100, %r12d // add carry bit vpaddd %xmm14, %xmm0, %xmm1 // g_oneHigh vpshufb %xmm15, %xmm0, %xmm0 vpaddd %xmm14, %xmm1, %xmm2 vpxor %xmm6, %xmm0, %xmm0 vpshufb %xmm15, %xmm1, %xmm1 vpaddd %xmm14, %xmm2, %xmm3 vpxor %xmm6, %xmm1, %xmm1 vpshufb %xmm15, %xmm2, %xmm2 vpaddd %xmm14, %xmm3, %xmm4 vpxor %xmm6, %xmm2, %xmm2 vpshufb %xmm15, %xmm3, %xmm3 vpaddd %xmm14, %xmm4, %xmm5 vpxor %xmm6, %xmm3, %xmm3 vpshufb %xmm15, %xmm4, %xmm4 bswap %r12d vpshufb %xmm15, %xmm5, %xmm5 vpxor %xmm6, %xmm4, %xmm4 movl %r12d, 12(%rdi) // out iv vpxor %xmm6, %xmm5, %xmm5 vmovdqu (%r10), %xmm6 // key1 jmp .Lm96_enc_aes .balign 16 .Lm96_inner_out: // +++++++++++++++++ ghash process +++++++++++++++++++++++++++++++++ vmovdqu 0x20+0x70(%rdi), %xmm11 // hash key h^6 vmovdqa (%rsp), %xmm10 vpclmulqdq $0x11, %xmm11, %xmm10, %xmm9 // Karatsuba Multiply vmovdqu 0x20+0x80(%rdi), %xmm12 // hash key h^5_6 vpxor 0x08(%rsp), %xmm10, %xmm13 vpclmulqdq $0x00, %xmm11, %xmm10, %xmm7 vmovdqu 0x20+0x60(%rdi), %xmm11 // hash key h^5 vmovdqa 0x10(%rsp), %xmm10 vpclmulqdq $0x10, %xmm12, %xmm13, %xmm8 vpclmulqdq $0x11, %xmm11, %xmm10, %xmm14 // Karatsuba Multiply vmovdqu 0x20+0x50(%rdi), %xmm6 // hash key h^3_4 vpxor 0x18(%rsp), %xmm10, %xmm13 vpclmulqdq $0x00, %xmm11, %xmm10, %xmm10 vmovdqu 0x20+0x40(%rdi), %xmm11 // hash key h^4 vpxor %xmm14, %xmm9, %xmm9 vpclmulqdq $0x00, %xmm12, %xmm13, %xmm13 vpxor %xmm10, %xmm7, %xmm7 vmovdqa 0x20(%rsp), %xmm10 vpxor %xmm13, %xmm8, %xmm8 vpclmulqdq $0x11, %xmm11, %xmm10, %xmm14 // Karatsuba Multiply vpxor 0x28(%rsp), %xmm10, %xmm13 vpclmulqdq $0x00, %xmm11, %xmm10, %xmm10 vmovdqu 0x20+0x30(%rdi), %xmm11 // hash key h^3 vpxor %xmm14, %xmm9, %xmm9 vpclmulqdq $0x10, %xmm6, %xmm13, %xmm13 vpxor %xmm10, %xmm7, %xmm7 vmovdqa 0x30(%rsp), %xmm10 vpxor %xmm13, %xmm8, %xmm8 vpclmulqdq $0x11, %xmm11, %xmm10, %xmm14 // Karatsuba Multiply vmovdqu 0x20+0x20(%rdi), %xmm12 // hash key h^1_2 vpxor 0x38(%rsp), %xmm10, %xmm13 vpclmulqdq $0x00, %xmm11, %xmm10, %xmm10 vmovdqu 0x20+0x10(%rdi), %xmm11 // hash key h^2 vpxor %xmm14, %xmm9, %xmm9 vpclmulqdq $0x00, %xmm6, %xmm13, %xmm13 vpxor %xmm10, %xmm7, %xmm7 vmovdqa 0x40(%rsp), %xmm10 vpxor %xmm13, %xmm8, %xmm8 vpclmulqdq $0x11, %xmm11, %xmm10, %xmm14 // Karatsuba Multiply vpxor 0x48(%rsp), %xmm10, %xmm13 vpclmulqdq $0x00, %xmm11, %xmm10, %xmm10 vmovdqu 0x20(%rdi), %xmm11 // hash key h^1 vpxor %xmm14, %xmm9, %xmm9 vpclmulqdq $0x10, %xmm12, %xmm13, %xmm13 vpxor %xmm10, %xmm7, %xmm7 vmovdqa 0x50(%rsp), %xmm10 vpxor %xmm13, %xmm8, %xmm8 vpclmulqdq $0x11, %xmm11, %xmm10, %xmm14 // Karatsuba Multiply vpxor 0x58(%rsp), %xmm10, %xmm13 vpclmulqdq $0x00, %xmm11, %xmm10, %xmm10 vpxor %xmm14, %xmm9, %xmm14 vpclmulqdq $0x00, %xmm12, %xmm13, %xmm13 vpxor %xmm10, %xmm7, %xmm10 vpxor %xmm13, %xmm8, %xmm13 vpxor %xmm10, %xmm14, %xmm11 vpxor %xmm11, %xmm13, %xmm13 vpslldq $8, %xmm13, %xmm11 vmovdqa 0x30(%r11), %xmm15 // g_poly vpsrldq $8, %xmm13, %xmm13 vpxor %xmm11, %xmm10, %xmm10 vpxor %xmm13, %xmm14, %xmm14 vpalignr $8, %xmm10, %xmm10, %xmm12 // 1st phase of reduction vpclmulqdq $0x10, %xmm15, %xmm10, %xmm10 sub $6, %ecx vpxor %xmm12, %xmm10, %xmm10 vpalignr $8, %xmm10, %xmm10, %xmm12 // 2nd phase of reduction vpclmulqdq $0x10, %xmm15, %xmm10, %xmm10 vpxor %xmm14, %xmm12, %xmm12 leaq 0x60(%rdx), %rdx vpxor %xmm12, %xmm10, %xmm10 vpxor %xmm0, %xmm0, %xmm0 vpshufb (%r11), %xmm10, %xmm10 // ------------------- ghash complete --------------------------------- vmovdqa %xmm0, (%rsp) vmovdqu %xmm10, 16(%rdi) // out ghash vmovdqa %xmm0, 0x10(%rsp) vmovdqa %xmm0, 0x20(%rsp) vmovdqa %xmm0, 0x30(%rsp) vmovdqa %xmm0, 0x40(%rsp) vmovdqa %xmm0, 0x50(%rsp) mov %rbp, %rsp pop %rbp ret .cfi_endproc .size AES_GCM_Encrypt96BlockAsm, .-AES_GCM_Encrypt96BlockAsm /* * MODES_GCM_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len, void *key * ctx %rdi * in %rsi * out %rdx * len %rcx * key %r8 */ .type AES_GCM_Decrypt96BlockAsm, @function .balign 32 AES_GCM_Decrypt96BlockAsm: .cfi_startproc push %rbp push %r12 push %r13 push %r14 mov %rsp, %rbp sub $112, %rsp vmovdqu (%rsi), %xmm0 // in0 vmovdqa (%r11), %xmm6 and $-16, %rsp vpshufb %xmm6, %xmm0, %xmm0 vmovdqu 0x10(%rsi), %xmm1 // in1 vmovdqa %xmm0, (%rsp) vpshufb %xmm6, %xmm1, %xmm1 vmovdqu 0x20(%rsi), %xmm2 // in2 vmovdqa %xmm1, 0x10(%rsp) vpshufb %xmm6, %xmm2, %xmm2 vmovdqu 0x30(%rsi), %xmm3 // in3 vmovdqa %xmm2, 0x20(%rsp) vpshufb %xmm6, %xmm3, %xmm3 vmovdqu 0x40(%rsi), %xmm4 // in4 vmovdqa %xmm3, 0x30(%rsp) vpshufb %xmm6, %xmm4, %xmm4 vmovdqu 0x50(%rsi), %xmm5 // in5 vmovdqa %xmm4, 0x40(%rsp) vpshufb %xmm6, %xmm5, %xmm5 vmovdqu 16(%rdi), %xmm10 // ghash vmovdqa %xmm5, 0x50(%rsp) vpshufb %xmm6, %xmm10, %xmm10 .balign 16 .Lm96_dec_loop: mov 12(%rdi), %r10d // counter r10d(32bit) vmovdqu (%rdi), %xmm0 // iv addl $0x6000000, %r10d // ctr inc jc .Lm96_dec_ctr_carry vmovdqa 0x20(%r11), %xmm6 vmovdqu (%r8), %xmm7 vpaddb %xmm6, %xmm0, %xmm1 // g_oneLow vpxor %xmm7, %xmm0, %xmm0 // key 0 vpaddb %xmm6, %xmm1, %xmm2 vpxor %xmm7, %xmm1, %xmm1 vpaddb %xmm6, %xmm2, %xmm3 vpxor %xmm7, %xmm2, %xmm2 vpaddb %xmm6, %xmm3, %xmm4 vpxor %xmm7, %xmm3, %xmm3 vpaddb %xmm6, %xmm4, %xmm5 vmovdqu 0x10(%r8), %xmm6 .Lm96_dec_aes_cipher: vaesenc %xmm6, %xmm0, %xmm0 // key 1 xor %r14, %r14 cmp $12, %ecx mov %r10d, 12(%rdi) // out iv setae %r14b vaesenc %xmm6, %xmm1, %xmm1 vpxor %xmm7, %xmm4, %xmm4 neg %r14 lea 0x90(%r8), %r10 // +++++++++++++++++ ghash process +++++++++++++++++++++++++++++++++ vmovdqu 0x20+0x70(%rdi), %xmm11 // hash key h^6 and $0x60, %r14 vpxor %xmm7, %xmm5, %xmm5 vmovdqu 0x20+0x80(%rdi), %xmm12 // hash key h^5_6 lea (%rsi, %r14), %r14 vaesenc %xmm6, %xmm2, %xmm2 vpxor (%rsp), %xmm10, %xmm10 // xor ghash vaesenc %xmm6, %xmm3, %xmm3 vpalignr $8, %xmm10, %xmm10, %xmm13 vpclmulqdq $0x11, %xmm11, %xmm10, %xmm15 // Karatsuba Multiply vpxor %xmm10, %xmm13, %xmm13 vaesenc %xmm6, %xmm4, %xmm4 movbe (%r14), %r12 vpclmulqdq $0x00, %xmm11, %xmm10, %xmm7 movbe 0x08(%r14), %r13 vaesenc %xmm6, %xmm5, %xmm5 vmovdqu 0x20(%r8), %xmm6 mov %r13, (%rsp) vpclmulqdq $0x10, %xmm12, %xmm13, %xmm8 vmovdqu 0x20+0x60(%rdi), %xmm11 // hash key h^5 mov %r12, 0x08(%rsp) vaesenc %xmm6, %xmm0, %xmm0 // key 2 vmovdqa 0x10(%rsp), %xmm10 vaesenc %xmm6, %xmm1, %xmm1 vpxor 0x18(%rsp), %xmm10, %xmm13 vpclmulqdq $0x11, %xmm11, %xmm10, %xmm14 // Karatsuba Multiply movbe 0x10(%r14), %r12 vaesenc %xmm6, %xmm2, %xmm2 vpxor %xmm14, %xmm15, %xmm15 vpclmulqdq $0x00, %xmm11, %xmm10, %xmm10 movbe 0x18(%r14), %r13 vaesenc %xmm6, %xmm3, %xmm3 mov %r13, 0x10(%rsp) vmovdqu 0x20+0x40(%rdi), %xmm11 // hash key h^4 vpclmulqdq $0x00, %xmm12, %xmm13, %xmm13 mov %r12, 0x18(%rsp) vpxor %xmm10, %xmm7, %xmm7 vaesenc %xmm6, %xmm4, %xmm4 vpxor %xmm13, %xmm8, %xmm8 vmovdqu 0x20+0x50(%rdi), %xmm12 // hash key h^3_4 vaesenc %xmm6, %xmm5, %xmm5 vmovdqu 0x30(%r8), %xmm6 vmovdqa 0x20(%rsp), %xmm10 vaesenc %xmm6, %xmm0, %xmm0 // key 3 vpxor 0x28(%rsp), %xmm10, %xmm13 movbe 0x20(%r14), %r12 vaesenc %xmm6, %xmm1, %xmm1 movbe 0x28(%r14), %r13 vpclmulqdq $0x11, %xmm11, %xmm10, %xmm14 // Karatsuba Multiply mov %r13, 0x20(%rsp) vaesenc %xmm6, %xmm2, %xmm2 vpxor %xmm14, %xmm15, %xmm15 vpclmulqdq $0x00, %xmm11, %xmm10, %xmm10 mov %r12, 0x28(%rsp) vmovdqu 0x20+0x30(%rdi), %xmm11 // hash key h^3 vaesenc %xmm6, %xmm3, %xmm3 vpxor %xmm10, %xmm7, %xmm7 vpclmulqdq $0x10, %xmm12, %xmm13, %xmm13 vmovdqa 0x30(%rsp), %xmm10 vaesenc %xmm6, %xmm4, %xmm4 vpxor %xmm13, %xmm8, %xmm8 vaesenc %xmm6, %xmm5, %xmm5 vmovdqu 0x40(%r8), %xmm6 vpclmulqdq $0x11, %xmm11, %xmm10, %xmm14 // Karatsuba Multiply vpxor 0x38(%rsp), %xmm10, %xmm13 vaesenc %xmm6, %xmm0, %xmm0 // key 4 movbe 0x30(%r14), %r12 vpclmulqdq $0x00, %xmm11, %xmm10, %xmm10 vpxor %xmm14, %xmm15, %xmm15 vaesenc %xmm6, %xmm1, %xmm1 movbe 0x38(%r14), %r13 vpxor %xmm10, %xmm7, %xmm7 vpclmulqdq $0x00, %xmm12, %xmm13, %xmm13 mov %r13, 0x30(%rsp) vpxor %xmm13, %xmm8, %xmm8 vaesenc %xmm6, %xmm2, %xmm2 mov %r12, 0x38(%rsp) vaesenc %xmm6, %xmm3, %xmm3 vmovdqu 0x20+0x10(%rdi), %xmm11 // hash key h^2 vaesenc %xmm6, %xmm4, %xmm4 vmovdqu 0x20+0x20(%rdi), %xmm12 // hash key h^1_2 vaesenc %xmm6, %xmm5, %xmm5 vmovdqu 0x50(%r8), %xmm6 vmovdqa 0x40(%rsp), %xmm10 vaesenc %xmm6, %xmm0, %xmm0 // key 5 vpxor 0x48(%rsp), %xmm10, %xmm13 vpclmulqdq $0x11, %xmm11, %xmm10, %xmm14 // Karatsuba Multiply movbe 0x40(%r14), %r12 vaesenc %xmm6, %xmm1, %xmm1 movbe 0x48(%r14), %r13 vpxor %xmm14, %xmm15, %xmm15 vpclmulqdq $0x00, %xmm11, %xmm10, %xmm10 mov %r13, 0x40(%rsp) vaesenc %xmm6, %xmm2, %xmm2 vpxor %xmm10, %xmm7, %xmm7 vpclmulqdq $0x10, %xmm12, %xmm13, %xmm13 mov %r12, 0x48(%rsp) vpxor %xmm13, %xmm8, %xmm8 vaesenc %xmm6, %xmm3, %xmm3 vmovdqu 0x20(%rdi), %xmm11 // hash key h^1 vaesenc %xmm6, %xmm4, %xmm4 vmovdqa 0x50(%rsp), %xmm10 vaesenc %xmm6, %xmm5, %xmm5 vmovdqu 0x60(%r8), %xmm6 vaesenc %xmm6, %xmm0, %xmm0 // key 6 vpxor 0x58(%rsp), %xmm10, %xmm13 vpclmulqdq $0x11, %xmm11, %xmm10, %xmm14 // Karatsuba Multiply movbe 0x50(%r14), %r12 vaesenc %xmm6, %xmm1, %xmm1 vpxor %xmm14, %xmm15, %xmm14 vpclmulqdq $0x00, %xmm11, %xmm10, %xmm10 movbe 0x58(%r14), %r13 vaesenc %xmm6, %xmm2, %xmm2 mov %r13, 0x50(%rsp) vpclmulqdq $0x00, %xmm12, %xmm13, %xmm13 mov %r12, 0x58(%rsp) vpxor %xmm10, %xmm7, %xmm10 vaesenc %xmm6, %xmm3, %xmm3 vpxor %xmm13, %xmm8, %xmm13 vaesenc %xmm6, %xmm4, %xmm4 vpxor %xmm10, %xmm14, %xmm11 vaesenc %xmm6, %xmm5, %xmm5 vmovdqu 0x70(%r8), %xmm6 vpxor %xmm11, %xmm13, %xmm13 vaesenc %xmm6, %xmm0, %xmm0 // key 7 vpslldq $8, %xmm13, %xmm11 vaesenc %xmm6, %xmm1, %xmm1 vpsrldq $8, %xmm13, %xmm13 vaesenc %xmm6, %xmm2, %xmm2 vpxor %xmm13, %xmm14, %xmm14 vaesenc %xmm6, %xmm3, %xmm3 vpxor %xmm11, %xmm10, %xmm10 vaesenc %xmm6, %xmm4, %xmm4 vmovdqa 0x30(%r11), %xmm13 // g_poly vaesenc %xmm6, %xmm5, %xmm5 vmovdqu 0x80(%r8), %xmm6 vpalignr $8, %xmm10, %xmm10, %xmm12 // 1st phase of reduction vaesenc %xmm6, %xmm0, %xmm0 // key 8 vpclmulqdq $0x10, %xmm13, %xmm10, %xmm10 vaesenc %xmm6, %xmm1, %xmm1 vpxor %xmm12, %xmm10, %xmm10 vaesenc %xmm6, %xmm2, %xmm2 vpalignr $8, %xmm10, %xmm10, %xmm12 // 2nd phase of reduction vaesenc %xmm6, %xmm3, %xmm3 vpclmulqdq $0x10, %xmm13, %xmm10, %xmm10 vpxor %xmm14, %xmm12, %xmm12 vaesenc %xmm6, %xmm4, %xmm4 vpxor %xmm12, %xmm10, %xmm10 vmovdqu 0x10(%r10), %xmm7 vaesenc %xmm6, %xmm5, %xmm5 vmovdqu (%r10), %xmm6 // ------------------- ghash complete --------------------------------- cmp $12, %r9d jb .Lm96_dec_ending vaesenc %xmm6, %xmm0, %xmm0 // key 9 vaesenc %xmm6, %xmm1, %xmm1 vaesenc %xmm6, %xmm2, %xmm2 vaesenc %xmm6, %xmm3, %xmm3 vaesenc %xmm6, %xmm4, %xmm4 vaesenc %xmm6, %xmm5, %xmm5 vaesenc %xmm7, %xmm0, %xmm0 // key 10 vaesenc %xmm7, %xmm1, %xmm1 vaesenc %xmm7, %xmm2, %xmm2 vaesenc %xmm7, %xmm3, %xmm3 lea 0x20(%r10), %r10 vaesenc %xmm7, %xmm4, %xmm4 vmovdqu (%r10), %xmm6 vaesenc %xmm7, %xmm5, %xmm5 vmovdqu 0x10(%r10), %xmm7 je .Lm96_dec_ending vaesenc %xmm6, %xmm0, %xmm0 // key 11 vaesenc %xmm6, %xmm1, %xmm1 vaesenc %xmm6, %xmm2, %xmm2 vaesenc %xmm6, %xmm3, %xmm3 vaesenc %xmm6, %xmm4, %xmm4 vaesenc %xmm6, %xmm5, %xmm5 vaesenc %xmm7, %xmm0, %xmm0 // key 12 vaesenc %xmm7, %xmm1, %xmm1 vaesenc %xmm7, %xmm2, %xmm2 vaesenc %xmm7, %xmm3, %xmm3 lea 0x20(%r10), %r10 vaesenc %xmm7, %xmm4, %xmm4 vmovdqu (%r10), %xmm6 vaesenc %xmm7, %xmm5, %xmm5 vmovdqu 0x10(%r10), %xmm7 jmp .Lm96_dec_ending .balign 16 .Lm96_dec_ctr_carry: vmovdqa (%r11), %xmm8 vmovdqu (%r8), %xmm7 bswap %r10d vpshufb %xmm8, %xmm0, %xmm0 vmovdqa 0x10(%r11), %xmm6 addl $0x100, %r10d // add carry bit vpaddd %xmm6, %xmm0, %xmm1 vpshufb %xmm8, %xmm0, %xmm0 vpaddd %xmm6, %xmm1, %xmm2 vpxor %xmm7, %xmm0, %xmm0 // key 0 vpshufb %xmm8, %xmm1, %xmm1 vpaddd %xmm6, %xmm2, %xmm3 vpxor %xmm7, %xmm1, %xmm1 vpshufb %xmm8, %xmm2, %xmm2 vpaddd %xmm6, %xmm3, %xmm4 vpxor %xmm7, %xmm2, %xmm2 vpshufb %xmm8, %xmm3, %xmm3 vpaddd %xmm6, %xmm4, %xmm5 vpxor %xmm7, %xmm3, %xmm3 vpshufb %xmm8, %xmm4, %xmm4 bswap %r10d vpshufb %xmm8, %xmm5, %xmm5 vmovdqu 0x10(%r8), %xmm6 jmp .Lm96_dec_aes_cipher .balign 16 .Lm96_dec_ending: vaesenc %xmm6, %xmm0, %xmm0 sub $6, %ecx vpxor (%rsi), %xmm7, %xmm8 // last key xor plaintext vaesenc %xmm6, %xmm1, %xmm1 vpxor 0x10(%rsi), %xmm7, %xmm9 // last key xor plaintext vaesenc %xmm6, %xmm2, %xmm2 vpxor 0x20(%rsi), %xmm7, %xmm11 // last key xor plaintext vaesenc %xmm6, %xmm3, %xmm3 vpxor 0x30(%rsi), %xmm7, %xmm12 // last key xor plaintext vaesenc %xmm6, %xmm4, %xmm4 vpxor 0x40(%rsi), %xmm7, %xmm13 // last key xor plaintext vaesenc %xmm6, %xmm5, %xmm5 vpxor 0x50(%rsi), %xmm7, %xmm14 // last key xor plaintext vaesenclast %xmm8, %xmm0, %xmm0 // last key lea 0x60(%rsi), %rsi vaesenclast %xmm9, %xmm1, %xmm1 vmovdqu %xmm0, (%rdx) // out result text vaesenclast %xmm11, %xmm2, %xmm2 vmovdqu %xmm1, 0x10(%rdx) vaesenclast %xmm12, %xmm3, %xmm3 vmovdqu %xmm2, 0x20(%rdx) vaesenclast %xmm13, %xmm4, %xmm4 vmovdqu %xmm3, 0x30(%rdx) vaesenclast %xmm14, %xmm5, %xmm5 vmovdqu %xmm4, 0x40(%rdx) cmp $6, %ecx vmovdqu %xmm5, 0x50(%rdx) lea 0x60(%rdx), %rdx jae .Lm96_dec_loop vpxor %xmm0, %xmm0, %xmm0 vpshufb (%r11), %xmm10, %xmm10 vmovdqa %xmm0, (%rsp) vmovdqa %xmm0, 0x10(%rsp) vmovdqa %xmm0, 0x20(%rsp) vmovdqa %xmm0, 0x30(%rsp) vmovdqa %xmm0, 0x40(%rsp) vmovdqa %xmm0, 0x50(%rsp) mov %rbp, %rsp vmovdqu %xmm10, 16(%rdi) // out ghash pop %r14 pop %r13 pop %r12 pop %rbp ret .cfi_endproc .size AES_GCM_Decrypt96BlockAsm, .-AES_GCM_Decrypt96BlockAsm #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm/aes_gcm_96block_x86_64.S
Unix Assembly
unknown
33,413
/* * 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_AES) && defined(HITLS_CRYPTO_GCM) .text INPUT .req x1 OUT00 .req x2 INLEN .req x3 KEY00 .req x4 IVCTR .req w4 HTABLE .req x5 IVEC0 .req x0 ROUNDS .req w8 COUNT .req x15 COUNTW .req w15 IV_H .req x10 // high 64 bits IV_L .req x11 // lower 64 bits IV_C .req x12 IV_W .req w12 IV_CW .req w9 IV_CX .req x9 CTR0 .req v0 CTR1 .req v1 CTR2 .req v2 CTR3 .req v3 OUT0 .req v4 OUT1 .req v5 OUT2 .req v6 OUT3 .req v7 KEY0 .req v18 KEY1 .req v19 KEY2 .req v20 KEY3 .req v21 KEY4 .req v22 KEY5 .req v23 KEY6 .req v24 KEY7 .req v25 KEY8 .req v26 KEY9 .req v27 KEY10 .req v28 KEY11 .req v29 KEY12 .req v30 KEY13 .req v31 KEND0 .req x13 KEND1 .req x14 HASH0 .req v11 HASH1 .req v12 HASH2 .req v13 HASH3 .req v14 HASH4 .req v15 MULL_C2 .req v13 HASH1_2 .req v12 .macro IN_STP stp x19, x20, [sp, #-112]! stp x21, x22, [sp, #16] stp x23, x24, [sp, #32] stp d8, d9, [sp, #48] stp d10, d11, [sp, #64] stp d12, d13, [sp, #80] stp d14, d15, [sp, #96] .endm .macro OUT_STP ldp x21, x22, [sp, #16] ldp x23, x24, [sp, #32] ldp d8, d9, [sp, #48] ldp d10, d11, [sp, #64] ldp d12, d13, [sp, #80] ldp d14, d15, [sp, #96] ldp x19, x20, [sp], #112 .endm .macro REV_2S REG0, REG1 rev \REG0, \REG0 rev \REG1, \REG1 .endm .macro LOAD_KEY ld1 {KEY0.4s, KEY1.4s}, [KEY00], #32 // load key-0-1 ld1 {KEY2.4s, KEY3.4s}, [KEY00], #32 // load key-2-3 ld1 {KEY4.4s, KEY5.4s}, [KEY00], #32 // load key-4-5 ld1 {KEY6.4s, KEY7.4s}, [KEY00], #32 // load key-6-7 ld1 {KEY8.4s, KEY9.4s}, [KEY00], #32 // load key-8-9 .endm .macro LOAD_GHASH_TABLE ld1 {HASH0.16b}, [HTABLE], #16 // load ghash ld1 {HASH1.2d}, [HTABLE], #16 // load h^1 add HTABLE, HTABLE, #16 ld1 {HASH2.2d}, [HTABLE], #16 // load h^2 ld1 {HASH3.2d}, [HTABLE], #16 // load h^3 add HTABLE, HTABLE, #16 ld1 {HASH4.2d}, [HTABLE] // load h^4 .endm .macro ROUND4 BLOCK0, BLOCK1, BLOCK2, BLOCK3, KEY aese \BLOCK0, \KEY aesmc \BLOCK0, \BLOCK0 aese \BLOCK1, \KEY aesmc \BLOCK1, \BLOCK1 aese \BLOCK2, \KEY aesmc \BLOCK2, \BLOCK2 aese \BLOCK3, \KEY aesmc \BLOCK3, \BLOCK3 .endm .macro ROUND4_END BLOCK0, BLOCK1, BLOCK2, BLOCK3, KEY aese \BLOCK0, \KEY aese \BLOCK1, \KEY aese \BLOCK2, \KEY aese \BLOCK3, \KEY .endm .macro ROUND BLOCK, KEY aese \BLOCK, \KEY aesmc \BLOCK, \BLOCK .endm .macro LOAD_CTR DI, VI rev IV_CW, IV_W fmov \DI, IV_H // set h64 orr IV_CX, IV_L, IV_CX, lsl #32 add IV_W, IV_W, #1 // CTR++ fmov \VI, IV_CX // set l64 .endm .macro BEFORE_ROUND ext HASH0.16b, HASH0.16b, HASH0.16b, #8 // xi ext HASH1.16b, HASH1.16b, HASH1.16b, #8 // h^1 rev IV_W, IV_W // rev_ctr32 ext HASH2.16b, HASH2.16b, HASH2.16b, #8 // h^2 ext HASH3.16b, HASH3.16b, HASH3.16b, #8 // h^3 add IVCTR, IV_W, IVCTR ext HASH4.16b, HASH4.16b, HASH4.16b, #8 // h^4 add IV_W, IV_W, #1 // ctr++ rev64 HASH0.16b, HASH0.16b // orr w11, w11, w11 // trn2 v17.2d, HASH3.2d, HASH4.2d // h4l | h3l LOAD_CTR d1, CTR1.d[1] // CTR bolck 1 trn1 v9.2d, HASH3.2d, HASH4.2d // h4h | h3h LOAD_CTR d2, CTR2.d[1] // CTR bolck 2 trn2 v16.2d, HASH1.2d, HASH2.2d // h2l | h1l LOAD_CTR d3, CTR3.d[1] // CTR bolck 3 trn1 v8.2d, HASH1.2d, HASH2.2d // h2h | h1h .endm .macro FIRST_ROUND ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY0.16b // round 0 ldp x6, x7, [INPUT, #0] // load INPUT 0 #ifdef HITLS_BIG_ENDIAN REV_2S x6, x7 #endif ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY1.16b // round 1 ldp x19, x20, [INPUT, #16] // AES[1] - load plaintext #ifdef HITLS_BIG_ENDIAN REV_2S x19, x20 #endif eor x6, x6, KEND0 // round 10 low eor x7, x7, KEND1 // round 10 high ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY2.16b // round 2 ldp x21, x22, [INPUT, #32] // AES[2] - load plaintext #ifdef HITLS_BIG_ENDIAN REV_2S x21, x22 #endif eor x19, x19, KEND0 // AES[1] - round 10 low eor x20, x20, KEND1 // AES[1] - round 10 high ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY3.16b // round 3 ldp x23, x24, [INPUT, #48] // AES[3] - load plaintext #ifdef HITLS_BIG_ENDIAN REV_2S x23, x24 #endif eor x21, x21, KEND0 // AES[2] - round 10 low eor x22, x22, KEND1 // AES[2] - round 10 high ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY4.16b // round 4 eor x23, x23, KEND0 // AES[3] - round 10 low eor x24, x24, KEND1 // AES[3] - round 10 high ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY5.16b // round 5 fmov d4, x6 // INPUT 0 - mov low fmov d5, x19 // AES[1] - mov low fmov d6, x21 // AES[2] - mov low fmov d7, x23 // AES[3] - mov low ROUND4 CTR2.16b, CTR1.16b, CTR3.16b, CTR0.16b, KEY6.16b // round 6 fmov OUT0.d[1], x7 // AES[0] - mov high fmov OUT1.d[1], x20 // AES[1] - mov high fmov OUT2.d[1], x22 // AES[2] - mov high fmov OUT3.d[1], x24 // AES[3] - mov high .endm .macro STORE_RESULT add INPUT, INPUT, #64 // AES input_ptr update eor OUT0.16b, OUT0.16b, CTR0.16b // AES[0] - result eor OUT1.16b, OUT1.16b, CTR1.16b // AES[1] - result eor OUT2.16b, OUT2.16b, CTR2.16b // AES[2] - result fmov d0, x10 // CTR[0] eor OUT3.16b, OUT3.16b, CTR3.16b // AES[3] - result subs COUNT, COUNT, #1 // count-- fmov CTR0.d[1], x9 // CTR[0]--OK rev w9, IV_W // CTR[1]--Start st1 {OUT0.16b}, [OUT00], #16 // AES[0] - store result orr x9, x11, x9, lsl #32 // CTR[1] st1 {OUT1.16b}, [OUT00], #16 // AES[1] - store result add IV_W, IV_W, #1 // CTR++ fmov d1, x10 // CTR[1] st1 {OUT2.16b}, [OUT00], #16 // AES[2] - store result fmov v1.d[1], x9 // CTR[1]--OK rev w9, IV_W // CTR[2]--Start st1 {OUT3.16b}, [OUT00], #16 // AES[3] - store result orr x9, x11, x9, lsl #32 // CTR[2] add IV_W, IV_W, #1 // CTR++ fmov d2, x10 // CTR2-0 fmov v2.d[1], x9 // CTR[2]--OK rev w9, IV_W // CTR[3]--Start orr x9, x11, x9, lsl #32 // CTR[3] // <= 0 .endm .macro STORE_DEC_RESULT ld1 {OUT0.16b}, [INPUT], #16 ld1 {OUT1.16b}, [INPUT], #16 ld1 {OUT2.16b}, [INPUT], #16 eor CTR0.16b, CTR0.16b, OUT0.16b ld1 {OUT3.16b}, [INPUT], #16 eor CTR1.16b, CTR1.16b, OUT1.16b eor CTR2.16b, CTR2.16b, OUT2.16b mov x6, CTR0.d[0] mov x7, CTR0.d[1] mov x19, CTR1.d[0] mov x20, CTR1.d[1] #ifdef HITLS_BIG_ENDIAN REV_2S x6, x7 REV_2S x19, x20 #endif rev w9, IV_W // CTR[0] eor x6, x6, KEND0 orr x9, x11, x9, lsl #32 // CTR[0] eor x7, x7, KEND1 add IV_W, IV_W, #1 // CTR++ fmov d0, x10 // CTR[0] eor x19, x19, KEND0 fmov CTR0.d[1], x9 // CTR[0]--OK rev w9, IV_W // CTR[1] eor x20, x20, KEND1 orr x9, x11, x9, lsl #32 // CTR[1] subs COUNT, COUNT, #1 // count-- add IV_W, IV_W, #1 // CTR++ fmov d1, x10 // CTR[1] stp x6, x7, [OUT00], #16 fmov v1.d[1], x9 // CTR[1]--OK stp x19, x20, [OUT00], #16 rev w9, IV_W // CTR[2] rev64 OUT0.16b, OUT0.16b add IV_W, IV_W, #1 // CTR++ rev64 OUT1.16b, OUT1.16b orr x9, x11, x9, lsl #32 // CTR[2] .endm .macro GHASH_BLOCK ext HASH0.16b, HASH0.16b, HASH0.16b, #8 // PRE 0 mov d30, OUT1.d[1] // GHASH block 4k+1 - mid mov d31, OUT2.d[1] // GHASH[2] - mid eor OUT0.16b, OUT0.16b, HASH0.16b // PRE 1 tag ^ out pmull2 v28.1q, OUT1.2d, HASH3.2d // GHASH block 4k+1 - high eor v30.8b, v30.8b, OUT1.8b // GHASH block 4k+1 - mid eor v31.8b, v31.8b, OUT2.8b // GHASH[2] - mid mov d8, OUT0.d[1] // GHASH block 4k - mid mov d10, v17.d[1] // GHASH block 4k - mid pmull2 v9.1q, OUT0.2d, HASH4.2d // GHASH block 4k - high pmull HASH0.1q, OUT0.1d, HASH4.1d // GHASH block 4k - low eor v8.8b, v8.8b, OUT0.8b // GHASH block 4k - mid eor v9.16b, v9.16b, v28.16b // GHASH block 4k+1 - high pmull v29.1q, OUT1.1d, HASH3.1d // GHASH block 4k+1 - low pmull v28.1q, OUT2.1d, HASH2.1d // GHASH[2] - low pmull v10.1q, v8.1d, v10.1d // GHASH block 4k - mid pmull v30.1q, v30.1d, v17.1d // GHASH block 4k+1 - mid ins v31.d[1], v31.d[0] // GHASH[2] - mid pmull2 v8.1q, OUT2.2d, HASH2.2d // GHASH[2] - high eor v10.16b, v10.16b, v30.16b // GHASH block 4k+1 - mid mov d30, OUT3.d[1] // GHASH[0] - mid eor HASH0.16b, HASH0.16b, v29.16b // GHASH block 4k+1 - low eor v30.8b, v30.8b, OUT3.8b // GHASH[0] - mid pmull2 OUT0.1q, OUT3.2d, HASH1.2d // GHASH[0] - high eor v9.16b, v9.16b, v8.16b // GHASH[2] - high pmull2 v31.1q, v31.2d, v16.2d // GHASH[2] - mid pmull v29.1q, OUT3.1d, HASH1.1d // GHASH[0] - low movi v8.8b, #0xc2 pmull v30.1q, v30.1d, v16.1d // GHASH[0] - mid eor HASH0.16b, HASH0.16b, v28.16b // GHASH[2] - low shl d8, d8, #56 // mod_constant eor v9.16b, v9.16b, OUT0.16b // GHASH[0] - high eor v10.16b, v10.16b, v31.16b // GHASH[2] - mid pmull v31.1q, v9.1d, v8.1d // MODULO - top 64b align with mid eor HASH0.16b, HASH0.16b, v29.16b // GHASH[0] - low eor v10.16b, v10.16b, v30.16b // GHASH[0] - mid eor v30.16b, HASH0.16b, v9.16b // MODULO - karatsuba tidy up ext v9.16b, v9.16b, v9.16b, #8 // MODULO - other top alignment eor v10.16b, v10.16b, v30.16b // MODULO - karatsuba tidy up eor v10.16b, v10.16b, v31.16b // MODULO - fold into mid eor v10.16b, v10.16b, v9.16b // MODULO - fold into mid pmull v9.1q, v10.1d, v8.1d // MODULO - mid 64b align with low ext v10.16b, v10.16b, v10.16b, #8 // MODULO - other mid alignment eor HASH0.16b, HASH0.16b, v9.16b // MODULO - fold into low eor HASH0.16b, HASH0.16b, v10.16b // MODULO - fold into low .endm .macro GHASH_DEC_BLOCK ext HASH0.16b, HASH0.16b, HASH0.16b, #8 // PRE 0 mov x21, v2.d[0] // AES[2] block - mov low mov x22, v2.d[1] // AES[2] block - mov high rev64 v6.16b, v6.16b // GHASH[2] #ifdef HITLS_BIG_ENDIAN REV_2S x21, x22 #endif eor v4.16b, v4.16b, HASH0.16b // PRE 1 eor CTR3.16b, OUT3.16b, CTR3.16b // AES[3] block - result eor x21, x21, KEND0 // AES[2] - round 14 low eor x22, x22, KEND1 // AES[2] - round 14 high pmull2 v9.1q, v4.2d, HASH4.2d // GHASH block 4k - high mov d8, v4.d[1] // GHASH block 4k - mid mov d10, v17.d[1] // GHASH block 4k - mid mov x24, CTR3.d[1] // AES[3] block - mov high pmull HASH0.1q, v4.1d, HASH4.1d // GHASH block 4k - low eor v8.8b, v8.8b, v4.8b // GHASH block 4k - mid pmull2 v4.1q, v5.2d, HASH3.2d // GHASH block 4k+1 - high mov x23, CTR3.d[0] // AES[3] block - mov low rev64 v7.16b, v7.16b // GHASH[0] #ifdef HITLS_BIG_ENDIAN REV_2S x24, x23 #endif pmull v10.1q, v8.1d, v10.1d // GHASH block 4k - mid eor x23, x23, KEND0 // AES[3] block - round 14 low pmull v8.1q, v5.1d, HASH3.1d // GHASH block 4k+1 - low eor x24, x24, KEND1 // AES[3] block - round 14 high eor v9.16b, v9.16b, v4.16b // GHASH block 4k+1 - high mov d4, v5.d[1] // GHASH block 4k+1 - mid eor HASH0.16b, HASH0.16b, v8.16b // GHASH block 4k+1 - low mov d8, v6.d[1] // GHASH[2] - mid eor v4.8b, v4.8b, v5.8b // GHASH block 4k+1 - mid pmull v5.1q, v6.1d, HASH2.1d // GHASH[2] - low eor v8.8b, v8.8b, v6.8b // GHASH[2] - mid eor HASH0.16b, HASH0.16b, v5.16b // GHASH[2] - low pmull v4.1q, v4.1d, v17.1d // GHASH block 4k+1 - mid ins v8.d[1], v8.d[0] // GHASH[2] - mid eor v10.16b, v10.16b, v4.16b // GHASH block 4k+1 - mid pmull2 v4.1q, v6.2d, HASH2.2d // GHASH[2] - high mov d6, v7.d[1] // GHASH[0] - mid pmull2 v8.1q, v8.2d, v16.2d // GHASH[2] - mid eor v9.16b, v9.16b, v4.16b // GHASH[2] - high pmull v4.1q, v7.1d, HASH1.1d // GHASH[0] - low eor v10.16b, v10.16b, v8.16b // GHASH[2] - mid pmull2 v5.1q, v7.2d, HASH1.2d // GHASH[0] - high eor v6.8b, v6.8b, v7.8b // GHASH[0] - mid eor v9.16b, v9.16b, v5.16b // GHASH[0] - high pmull v6.1q, v6.1d, v16.1d // GHASH[0] - mid movi v8.8b, #0xc2 eor HASH0.16b, HASH0.16b, v4.16b // GHASH[0] - low shl d8, d8, #56 // mod_constant eor v10.16b, v10.16b, v6.16b // GHASH[0] - mid pmull v7.1q, v9.1d, v8.1d // MODULO - top 64b align with mid eor v6.16b, HASH0.16b, v9.16b // MODULO - karatsuba tidy up ext v9.16b, v9.16b, v9.16b, #8 // MODULO - other top alignment eor v10.16b, v10.16b, v6.16b // MODULO - karatsuba tidy up eor v10.16b, v10.16b, v7.16b // MODULO - fold into mid eor v10.16b, v10.16b, v9.16b // MODULO - fold into mid pmull v8.1q, v10.1d, v8.1d // MODULO - mid 64b align with low eor HASH0.16b, HASH0.16b, v8.16b // MODULO - fold into low stp x21, x22, [OUT00], #16 // AES[2] block - store result ext v10.16b, v10.16b, v10.16b, #8 // MODULO - other mid alignment stp x23, x24, [OUT00], #16 // AES[3] block - store result eor HASH0.16b, HASH0.16b, v10.16b // MODULO - fold into low .endm .macro FIRST16_ROUND ROUND CTR0.16b, KEY0.16b ROUND CTR0.16b, KEY1.16b ROUND CTR0.16b, KEY2.16b ROUND CTR0.16b, KEY3.16b ROUND CTR0.16b, KEY4.16b ROUND CTR0.16b, KEY5.16b ROUND CTR0.16b, KEY6.16b ROUND CTR0.16b, KEY7.16b ROUND CTR0.16b, KEY8.16b .endm .macro DEC16_BLOCK ld1 {OUT0.16b}, [INPUT], #16 eor CTR0.16b, CTR0.16b, OUT0.16b // data->out[i] = data->in[i] ^ data->ctr[i]; subs COUNT, COUNT, #1 // COUNT-- mov x6, CTR0.d[0] mov x7, CTR0.d[1] #ifdef HITLS_BIG_ENDIAN REV_2S x6, x7 #endif rev w9, IV_W // CTR[0] eor x6, x6, KEND0 orr x9, x11, x9, lsl #32 // CTR[0] eor x7, x7, KEND1 stp x6, x7, [OUT00], #16 // OUT OK add IV_W, IV_W, #1 // CTR++ fmov d0, x10 // CTR[0] fmov CTR0.d[1], x9 // CTR[0]--OK ext v8.16b, HASH0.16b, HASH0.16b, #8 // prepare final partial tag movi v11.8b, #0 movi v9.8b, #0 movi v10.8b, #0 rev64 v4.16b, OUT0.16b // GHASH final block mov CTR1.16b, CTR0.16b eor v4.16b, v4.16b, v8.16b // feed in partial tag mov d8, v4.d[1] // GHASH final block - mid pmull v6.1q, v4.1d, HASH1_2.1d // GHASH final block - low eor v8.8b, v8.8b, v4.8b // GHASH final block - mid pmull2 v5.1q, v4.2d, HASH1_2.2d // GHASH final block - high pmull v8.1q, v8.1d, v16.1d // GHASH final block - mid eor HASH0.16b, HASH0.16b, v6.16b // GHASH final block - low eor v9.16b, v9.16b, v5.16b // GHASH final block - high eor v10.16b, v10.16b, v8.16b // GHASH final block - mid movi v8.8b, #0xc2 eor v7.16b, HASH0.16b, v9.16b // MODULO - karatsuba tidy up shl d8, d8, #56 // mod_constant eor v10.16b, v10.16b, v7.16b // MODULO - karatsuba tidy up pmull v5.1q, v9.1d, v8.1d // MODULO - top 64b align with mid ext v9.16b, v9.16b, v9.16b, #8 // MODULO - other top alignment eor v10.16b, v10.16b, v5.16b // MODULO - fold into mid eor v10.16b, v10.16b, v9.16b // MODULO - fold into mid pmull v9.1q, v10.1d, v8.1d // MODULO - mid 64b align with low ext v10.16b, v10.16b, v10.16b, #8 // MODULO - other mid alignment eor HASH0.16b, HASH0.16b, v9.16b // MODULO - fold into low eor HASH0.16b, HASH0.16b, v10.16b // MODULO - fold into low .endm .macro ENC16_BLOCK eor x6, x6, KEND0 // round 10 low eor x7, x7, KEND1 // round 10 high rev w9, IV_W // CTR[0] fmov d4, x6 // INPUT 0 - mov low fmov OUT0.d[1], x7 // AES[0] - mov high orr x9, x11, x9, lsl #32 // CTR[0] add IV_W, IV_W, #1 // CTR++ eor OUT0.16b, OUT0.16b, CTR0.16b // AES[0] - result st1 {OUT0.16b}, [OUT00], #16 // AES[0] - store result fmov d0, x10 // CTR[0] fmov CTR0.d[1], x9 // CTR[0]--OK ext v8.16b, HASH0.16b, HASH0.16b, #8 // prepare final partial tag movi v11.8b, #0 movi v9.8b, #0 movi v10.8b, #0 rev64 v4.16b, OUT0.16b // GHASH final block mov CTR1.16b, CTR0.16b eor v4.16b, v4.16b, v8.16b // feed in partial tag mov d8, v4.d[1] // GHASH final block - mid pmull v6.1q, v4.1d, HASH1_2.1d // GHASH final block - low eor v8.8b, v8.8b, v4.8b // GHASH final block - mid pmull2 v5.1q, v4.2d, HASH1_2.2d // GHASH final block - high pmull v8.1q, v8.1d, v16.1d // GHASH final block - mid eor HASH0.16b, HASH0.16b, v6.16b // GHASH final block - low eor v9.16b, v9.16b, v5.16b // GHASH final block - high eor v10.16b, v10.16b, v8.16b // GHASH final block - mid movi v8.8b, #0xc2 eor v7.16b, HASH0.16b, v9.16b // MODULO - karatsuba tidy up shl d8, d8, #56 // mod_constant eor v10.16b, v10.16b, v7.16b // MODULO - karatsuba tidy up pmull v5.1q, v9.1d, v8.1d // MODULO - top 64b align with mid ext v9.16b, v9.16b, v9.16b, #8 // MODULO - other top alignment eor v10.16b, v10.16b, v5.16b // MODULO - fold into mid eor v10.16b, v10.16b, v9.16b // MODULO - fold into mid pmull v9.1q, v10.1d, v8.1d // MODULO - mid 64b align with low ext v10.16b, v10.16b, v10.16b, #8 // MODULO - other mid alignment eor HASH0.16b, HASH0.16b, v9.16b // MODULO - fold into low eor HASH0.16b, HASH0.16b, v10.16b // MODULO - fold into low .endm .macro BEFORE16_ROUND ext HASH0.16b, HASH0.16b, HASH0.16b, #8 // xi ext HASH1.16b, HASH1.16b, HASH1.16b, #8 // h^1 // rev_ctr32 ext HASH2.16b, HASH2.16b, HASH2.16b, #8 // h^2 ldp KEND0, KEND1, [KEY00] // load key-10 #ifdef HITLS_BIG_ENDIAN ror KEND0, KEND0, #32 ror KEND1, KEND1, #32 #endif ldp IV_H, IV_L, [IVEC0] // load IV #ifdef HITLS_BIG_ENDIAN rev IV_H, IV_H rev IV_L, IV_L #endif lsr IV_C, IV_L, #32 ld1 {CTR0.16b}, [IVEC0] // CTR[0] rev IV_W, IV_W // rev_ctr32 trn1 v8.2d, HASH1.2d, HASH2.2d // h2h | h1h trn2 v16.2d, HASH1.2d, HASH2.2d // h2l | h1l orr w11, w11, w11 // rev64 HASH0.16b, HASH0.16b // add IV_W, IV_W, #1 // ctr++ eor v16.16b, v16.16b, v8.16b //h2k | h1k .endm #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm/aes_gcm_common_aarch64.S
Unix Assembly
unknown
25,230
/* * 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_GCM #include "crypt_arm.h" .arch armv8-a+crypto .text INPUT_H .req x0 OUT_TB .req x1 MULL_C2 .req v31 MULL_H .req v24 OUT_H0 .req v25 OUT_H1_2 .req v26 OUT_H2 .req v27 OUT_H3 .req v28 OUT_H3_4 .req v29 OUT_H4 .req v30 INPUT_X .req v0 OUT_X .req v23 .macro GEN_H ext v1.16b, MULL_H.16b, MULL_H.16b, #8 // ushr v2.2d, MULL_C2.2d, #63 dup MULL_H.4s, MULL_H.s[1] ext v3.16b, v2.16b, MULL_C2.16b, #8 // t0 = 0xc2....01 ushr v2.2d, v1.2d, #63 sshr MULL_H.4s, MULL_H.4s, #31 // broadcast carry bit and v2.16b, v2.16b, v3.16b shl v1.2d, v1.2d, #1 ext v2.16b, v2.16b, v2.16b, #8 and v3.16b, v3.16b, MULL_H.16b orr v1.16b, v1.16b, v2.16b // H<<<=1 eor OUT_H0.16b, v1.16b, v3.16b // twisted H st1 {OUT_H0.2d}, [OUT_TB], #16 // store H0 .endm .macro GEN_H2 //(ah + al) * (ah + al) = ah * ah + 2 * ah * al + al * al ext v10.16b, OUT_H0.16b, OUT_H0.16b, #8 // A pmull v12.1q, OUT_H0.1d, OUT_H0.1d // aL * aL eor v10.16b, v10.16b, OUT_H0.16b // A + h pmull2 v11.1q, OUT_H0.2d, OUT_H0.2d // ah * ah pmull v13.1q, v10.1d, v10.1d // (A + h) * (A + h) ext v14.16b, v12.16b, v11.16b, #8 // B eor v15.16b, v12.16b, v11.16b // aL * aL + ah * ah eor v13.16b, v13.16b, v14.16b // ah * al + B eor v13.16b, v13.16b, v15.16b // pmull v15.1q, v12.1d, MULL_C2.1d // 1st phase ins v11.d[0], v13.d[1] ins v13.d[1], v12.d[0] eor v12.16b, v13.16b, v15.16b ext v15.16b, v12.16b, v12.16b, #8 pmull v12.1q, v12.1d, MULL_C2.1d eor v15.16b, v15.16b, v11.16b eor OUT_H2.16b, v12.16b, v15.16b // H^2 ext v16.16b, OUT_H2.16b, OUT_H2.16b, #8 eor v16.16b, v16.16b, OUT_H2.16b ext OUT_H1_2.16b, v10.16b, v16.16b, #8 st1 {OUT_H1_2.2d, OUT_H2.2d}, [OUT_TB], #32 // store H^2h H^2 .endm .macro GEN_H3_4 //calculate H^3 and H^4 pmull v0.1q, OUT_H0.1d, OUT_H2.1d pmull v1.1q, OUT_H2.1d, OUT_H2.1d pmull2 v2.1q, OUT_H0.2d, OUT_H2.2d pmull2 v3.1q, OUT_H2.2d, OUT_H2.2d pmull v4.1q, v10.1d, v16.1d pmull v5.1q, v16.1d, v16.1d ext v6.16b, v0.16b, v2.16b, #8 // Karatsuba post-processing ext v7.16b, v1.16b, v3.16b, #8 eor v8.16b, v0.16b, v2.16b eor v4.16b, v4.16b, v6.16b eor v9.16b, v1.16b, v3.16b eor v5.16b, v5.16b, v7.16b eor v4.16b, v4.16b, v8.16b pmull v8.1q, v0.1d, MULL_C2.1d // 1st phase eor v5.16b, v5.16b, v9.16b pmull v9.1q, v1.1d, MULL_C2.1d ins v2.d[0], v4.d[1] ins v3.d[0], v5.d[1] ins v4.d[1], v0.d[0] ins v5.d[1], v1.d[0] eor v0.16b, v4.16b, v8.16b eor v1.16b, v5.16b, v9.16b ext v8.16b, v0.16b, v0.16b,#8 // 2nd phase ext v9.16b, v1.16b, v1.16b,#8 pmull v0.1q, v0.1d, MULL_C2.1d pmull v1.1q, v1.1d, MULL_C2.1d eor v8.16b, v8.16b, v2.16b eor v9.16b, v9.16b, v3.16b eor OUT_H3.16b, v0.16b, v8.16b // H^3 eor OUT_H4.16b, v1.16b, v9.16b // H^4 ext v20.16b, OUT_H3.16b, OUT_H3.16b, #8 // Karatsuba pre-processing ext v21.16b, OUT_H4.16b, OUT_H4.16b, #8 eor v20.16b, v20.16b, OUT_H4.16b eor v21.16b, v21.16b, OUT_H4.16b ext OUT_H3_4.16b, v20.16b, v21.16b, #8 // h st1 {OUT_H3.2d, OUT_H3_4.2d, OUT_H4.2d}, [OUT_TB] // store h^3 h^3+h^4 h^4 .endm .globl GcmTableGen4bit .type GcmTableGen4bit, %function .align 4 GcmTableGen4bit: AARCH64_PACIASP stp x29, x30, [sp, #-0x50]! add x29, sp, #0 stp d8, d9, [sp, #0x10] stp d10, d11, [sp, #0x20] stp d12, d13, [sp, #0x30] stp d14, d15, [sp, #0x40] movi MULL_C2.16b, #0xe1 // set 0xc2 ld1 {MULL_H.16b}, [INPUT_H] // load input H shl MULL_C2.2d, MULL_C2.2d, #57 // 0xc20000000000000 rev64 MULL_H.16b, MULL_H.16b GEN_H GEN_H2 GEN_H3_4 ldp d8, d9, [sp, #0x10] ldp d10, d11, [sp, #0x20] ldp d12, d13, [sp, #0x30] ldp d14, d15, [sp, #0x40] ldp x29, x30, [sp], #0x50 AARCH64_AUTIASP ret .size GcmTableGen4bit,.-GcmTableGen4bit // void GcmHashMultiBlock(uint8_t t[GCM_BLOCKSIZE], const MODES_GCM_GF128 hTable[16], const uint8_t *in, uint32_t inLen) .globl GcmHashMultiBlock .type GcmHashMultiBlock, %function .align 4 GcmHashMultiBlock: AARCH64_PACIASP lsr x3, x3, #4 // Divided by 64 16*2*2 ld1 {INPUT_X.16b}, [INPUT_H] // load Xi movi MULL_C2.16b, #0xe1 // set 0xc2 ld1 {OUT_H0.2d, OUT_H1_2.2d}, [OUT_TB] // load twisted H, ... shl MULL_C2.2d, MULL_C2.2d, #57 // 0xc20000000000000 .LGcmLoop: subs x3, x3, #1 ld1 {v20.16b}, [x2], #16 // load in eor INPUT_X.16b, INPUT_X.16b, v20.16b // t ^ in rev64 INPUT_X.16b, INPUT_X.16b // Vectors are reversed in doublewords ext v3.16b, INPUT_X.16b, INPUT_X.16b, #8 // {Xi.hi, Xi.lo} => {Xi.lo, Xi.hi} pmull OUT_X.1q, OUT_H0.1d, v3.1d // (H.lo * Xi.hi) eor INPUT_X.16b, INPUT_X.16b, v3.16b // (Xi.lo + Xi.hi) pmull2 v2.1q, OUT_H0.2d, v3.2d // (H.hi * Xi.lo) pmull v1.1q, OUT_H1_2.1d, INPUT_X.1d // (H.lo + H.hi) * (Xi.lo + Xi.hi) ext v7.16b, OUT_X.16b, v2.16b, #8 // M eor v6.16b, OUT_X.16b, v2.16b // (H.lo * Xi.hi) + (H.hi * Xi.lo) eor v1.16b, v1.16b, v7.16b // (H.lo + H.hi) * (Xi.lo + Xi.hi) + M eor v1.16b, v1.16b, v6.16b // (H.lo * Xi.hi) + (H.hi * Xi.lo) + (H.lo + H.hi) * (Xi.lo + Xi.hi) + M pmull v18.1q, OUT_X.1d, MULL_C2.1d // 1st phase of reduction ins v2.d[0], v1.d[1] ins v1.d[1], OUT_X.d[0] eor OUT_X.16b, v1.16b, v18.16b ext v18.16b, OUT_X.16b, OUT_X.16b, #8 // 2nd phase of reduction pmull OUT_X.1q, OUT_X.1d, MULL_C2.1d eor v18.16b, v18.16b, v2.16b eor OUT_X.16b, OUT_X.16b, v18.16b rev64 OUT_X.16b, OUT_X.16b ext INPUT_X.16b, OUT_X.16b, OUT_X.16b, #8 b.gt .LGcmLoop // > 0 st1 {INPUT_X.16b}, [INPUT_H] // write out Xi .LhashEnd: AARCH64_AUTIASP ret .size GcmHashMultiBlock,.-GcmHashMultiBlock #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm/ghash_armv8.S
Unix Assembly
unknown
7,061
/* * 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_GCM .file "ghash_x86_64.S" .text .set INL, %xmm11 .set INH, %xmm12 .set INM, %xmm13 .set HKEY3, %xmm14 .set HKEY4, %xmm15 .set INPUT_XI, %rdi .set HTABLE, %rsi .set INPUT_IN, %rdx .set LEN, %rcx .set XI_L, %xmm0 .set XI_H, %xmm1 .set HKEY, %xmm2 .set IN_L, %xmm3 .set IN_H, %xmm4 .set IN_M, %xmm5 .set HKEY2, %xmm6 .set HKEY1_2, %xmm7 .set TEMP1, %xmm8 .set TEMP2, %xmm9 .set MASK, %xmm10 .balign 16 g_bswapMask: .byte 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 .size g_bswapMask, .-g_bswapMask .balign 16 g_polynomial: .byte 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xc2 .size g_polynomial, .-g_polynomial .balign 16 g_64swapMask: .byte 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8 .size g_64swapMask, .-g_64swapMask .balign 16 g_poly: .byte 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 .byte 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc2 .size g_poly, .-g_poly /** * Macro description: one block * H (128bit * 128bit) * Input registers: xl, hKey, hKey12 * Change registers: temp1 and temp2 * Result register: xh, xl */ .macro GHASH_MUL128X128 xh, xl, hKey, hKey12, temp1, temp2 vpshufd $0x4e, \xl, \temp1 vpclmulqdq $0x11, \hKey, \xl, \xh vpxor \xl, \temp1, \temp1 vpclmulqdq $0x00, \hKey, \xl, \xl vpxor \xl, \xh, \temp2 vpclmulqdq $0x00, \hKey12, \temp1, \temp1 vpxor \temp2, \temp1, \temp1 vpslldq $8, \temp1, \temp2 vpsrldq $8, \temp1, \temp1 vpxor \temp1, \xh, \xh vpxor \temp2, \xl, \xl .endm /** * Macro description: 256-bit large number reduction modulo g(x) * Input register: xh, xl * Change registers: temp1 and temp2 * Result register: xl */ .macro REDUCTION_256BIT xh, xl, temp1, temp2, reducMask vmovdqa \reducMask(%rip), \temp1 // g_poly vpalignr $8, \xl, \xl, \temp2 // 1st phase of reduction vpclmulqdq $0x10, \temp1, \xl, \xl vpxor \temp2, \xl, \xl vpalignr $8, \xl, \xl, \temp2 // 2nd phase of reduction vpclmulqdq $0x10, \temp1, \xl, \xl vpxor \xh, \temp2, \temp2 vpxor \temp2, \xl, \xl .endm /** * Function description: x86_64 hTable pre-computation table implementation (H has been transformed) * Function prototype: void GcmTableGen4bit(uint8_t key[GCM_BLOCKSIZE], MODES_GCM_GF128 hTable[16]); * Input register: * rdi: uint8_t key[GCM_BLOCKSIZE] * rsi: MODES_GCM_GF128 hTable[16] * Change register: xmm0-xmm15 * Function/Macro Call: * GHASH_MUL128X128 * REDUCTION_256BIT */ .align 32 .globl GcmTableGen4bit .type GcmTableGen4bit, %function GcmTableGen4bit: .cfi_startproc vmovdqu (INPUT_XI), HKEY vpshufb g_64swapMask(%rip), HKEY, HKEY vpshufd $0x4e, HKEY, IN_L vpshufd $0x55, HKEY, HKEY // broadcast carry bit vmovdqa g_polynomial(%rip), IN_H vpsrlq $63, IN_L, IN_M vpxor MASK, MASK, MASK vpcmpgtd HKEY, MASK, HKEY vpand IN_H, IN_M, IN_M vpsllq $1, IN_L, IN_L vpshufd $0x4e, IN_M, IN_M vpand HKEY, IN_H, IN_H vpor IN_M, IN_L, IN_L // H<<<=1 vpxor IN_L, IN_H, HKEY // twisted H vmovdqu HKEY, (HTABLE) // store in H[0] vpshufd $0x4e, HKEY, HKEY1_2 vpxor HKEY, HKEY1_2, HKEY1_2 vmovdqa HKEY, XI_L /* xh, xl, hKey, hKey12, temp1, temp2 */ GHASH_MUL128X128 XI_H, XI_L, HKEY, HKEY1_2, TEMP1, TEMP2 // calculate H^2 /* xh, xl, temp1, temp2, reducMask */ REDUCTION_256BIT XI_H, XI_L, TEMP1, TEMP2, g_poly vmovdqa XI_L, HKEY2 GHASH_MUL128X128 XI_H, XI_L, HKEY, HKEY1_2, TEMP1, TEMP2 // calculate H^3 REDUCTION_256BIT XI_H, XI_L, TEMP1, TEMP2, g_poly vmovdqa XI_L, HKEY3 GHASH_MUL128X128 XI_H, XI_L, HKEY, HKEY1_2, TEMP1, TEMP2 // calculate H^4 REDUCTION_256BIT XI_H, XI_L, TEMP1, TEMP2, g_poly vmovdqa XI_L, HKEY4 vmovdqu HKEY2, 0x10(HTABLE) // store H^2 in H[1] vmovdqu HKEY3, 0x30(HTABLE) // store H^3 in H[3] vmovdqu HKEY4, 0x40(HTABLE) // store H^4 in H[4] vpshufd $0x4e, HKEY2, TEMP1 vpxor HKEY2, TEMP1, TEMP1 vshufps $0x44, TEMP1, HKEY1_2, HKEY1_2 vmovdqu HKEY1_2, 0x20(HTABLE) // store [H^2.h + H^2.l, H.h + H.l] in H[2] vpshufd $0x4e, HKEY3, TEMP1 vpshufd $0x4e, HKEY4, TEMP2 vpxor HKEY3, TEMP1, TEMP1 vpxor HKEY4, TEMP2, TEMP2 vshufps $0x44, TEMP2, TEMP1, HKEY1_2 vmovdqu HKEY1_2, 0x50(HTABLE) // store [H^4.h + H^4.l, H^3.h + H^3.l] in H[5] vmovdqu 0x20(HTABLE), HKEY1_2 // reload [H^2.h + H^2.l, H.h + H.l] GHASH_MUL128X128 XI_H, XI_L, HKEY, HKEY1_2, TEMP1, TEMP2 // calculate H^5, for aes-gcm REDUCTION_256BIT XI_H, XI_L, TEMP1, TEMP2, g_poly vmovdqa XI_L, HKEY3 GHASH_MUL128X128 XI_H, XI_L, HKEY, HKEY1_2, TEMP1, TEMP2 // calculate H^6, for aes-gcm REDUCTION_256BIT XI_H, XI_L, TEMP1, TEMP2, g_poly vmovdqa XI_L, HKEY4 vmovdqu HKEY3, 0x60(HTABLE) // store H^5 in H[6] vmovdqu HKEY4, 0x70(HTABLE) // store H^6 in H[7] vpshufd $0x4e, HKEY3, TEMP1 vpshufd $0x4e, HKEY4, TEMP2 vpxor HKEY3, TEMP1, TEMP1 vpxor HKEY4, TEMP2, TEMP2 vshufps $0x44, TEMP2, TEMP1, HKEY1_2 vmovdqu HKEY1_2, 0x80(HTABLE) // store [H^6.h + H^6.l, H^5.h + H^5.l] in H[8] vpxor HKEY, HKEY, HKEY // clear hTable vpxor HKEY1_2, HKEY1_2, HKEY1_2 vpxor HKEY2, HKEY2, HKEY2 vpxor HKEY3, HKEY3, HKEY3 vpxor HKEY4, HKEY4, HKEY4 ret .cfi_endproc .size GcmTableGen4bit, .-GcmTableGen4bit /** * Function description: x86_64 ghash assembly acceleration implementation * Function prototype: void GcmHashMultiBlock(uint8_t t[GCM_BLOCKSIZE], const MODES_GCM_GF128 hTable[16], * const uint8_t *in, uint32_t inLen); * Input register: * rdi: uint8_t t[GCM_BLOCKSIZE] * rsi: const MODES_GCM_GF128 hTable[16] * rdx: const uint8_t *in * rcx: uint32_t inLen * Change register: xmm0-xmm15 * Function/Macro Call: * GHASH_MUL128X128 * REDUCTION_256BIT // reduction modulo g(x) */ .align 32 .globl GcmHashMultiBlock .type GcmHashMultiBlock, %function GcmHashMultiBlock: .cfi_startproc vmovdqa g_bswapMask(%rip), MASK vmovdqu (INPUT_XI), XI_L vmovdqu (HTABLE), HKEY vmovdqu 0x20(HTABLE), HKEY1_2 vpshufb MASK, XI_L, XI_L cmp $0x10, LEN je .Lremain_1block vmovdqu 0x10(HTABLE), HKEY2 cmp $0x40, LEN jae .Lmul_4blocks jmp .Lremain_Least_2blocks .align 32 .Lmul_4blocks: subq $0x40, LEN vmovdqu 0x30(INPUT_IN), IN_L // load In_3, In_2 vmovdqu 0x20(INPUT_IN), INL vpshufb MASK, IN_L, IN_L vpshufb MASK, INL, INL vmovdqa IN_L, IN_H // H * In_3 vpshufd $0x4e, IN_L, IN_M vpxor IN_L, IN_M, IN_M vpclmulqdq $0x00, HKEY, IN_L, IN_L vpclmulqdq $0x11, HKEY, IN_H, IN_H vpclmulqdq $0x00, HKEY1_2, IN_M, IN_M vmovdqa INL, INH // H^2 * In_2 vpshufd $0x4e, INL, INM vpxor INL, INM, INM vpclmulqdq $0x00, HKEY2, INL, INL vpclmulqdq $0x11, HKEY2, INH, INH vpclmulqdq $0x10, HKEY1_2, INM, INM vxorps INL, IN_L, IN_L // H * In_3 + H^2 * In_2 vxorps INH, IN_H, IN_H vxorps INM, IN_M, IN_M vmovdqu 0x30(HTABLE), HKEY3 vmovdqu 0x40(HTABLE), HKEY4 vmovdqu 0x50(HTABLE), HKEY1_2 vmovdqu 0x10(INPUT_IN), INL // load In_1, In_0 vmovdqu (INPUT_IN), TEMP1 vpshufb MASK, INL, INL vpshufb MASK, TEMP1, TEMP1 vmovdqa INL, INH // H^3 * In_1 vpshufd $0x4e, INL, INM vpxor INL, INM, INM vpclmulqdq $0x00, HKEY3, INL, INL vpclmulqdq $0x11, HKEY3, INH, INH vpclmulqdq $0x00, HKEY1_2, INM, INM vxorps INL, IN_L, IN_L // H * In_3 + H^2 * In_2 + H^3 * In_1 vxorps INH, IN_H, IN_H vxorps INM, IN_M, IN_M vpxor TEMP1, XI_L, XI_L // (In_1 + Xi) vmovdqa XI_L, XI_H vpshufd $0x4e, XI_L, TEMP1 vpxor XI_L, TEMP1, TEMP1 vpclmulqdq $0x00, HKEY4, XI_L, XI_L // H^4 * (In_1 + Xi) vpclmulqdq $0x11, HKEY4, XI_H, XI_H vpclmulqdq $0x10, HKEY1_2, TEMP1, TEMP1 vxorps IN_L, XI_L, XI_L // H * In_3 + H^2 * In_2 + H^3 * In_1 + H^4 * (In_1 + Xi) vxorps IN_H, XI_H, XI_H vxorps IN_M, TEMP1, TEMP1 vpxor XI_L, TEMP1, TEMP1 vpxor XI_H, TEMP1, TEMP1 vmovdqa TEMP1, TEMP2 vpslldq $8, TEMP1, TEMP1 vpsrldq $8, TEMP2, TEMP2 vpxor TEMP1, XI_L, XI_L vpxor TEMP2, XI_H, XI_H REDUCTION_256BIT XI_H, XI_L, TEMP1, TEMP2, g_poly cmp $0x00, LEN jz .Lend // finshed all blocks leaq 0x40(INPUT_IN), INPUT_IN vmovdqu 0x20(HTABLE), HKEY1_2 cmp $0x40, LEN jae .Lmul_4blocks cmp $0x20, LEN jae .Lremain_Least_2blocks jmp .Lremain_1block .align 32 .Lremain_Least_2blocks: subq $0x20, LEN vmovdqu 0x10(INPUT_IN), IN_L // loda (4 * i) + 1 or 2 block vmovdqu (INPUT_IN), TEMP1 vpshufb MASK, IN_L, IN_L vpshufb MASK, TEMP1, TEMP1 vpxor TEMP1, XI_L, XI_L vmovdqa IN_L, IN_H vpshufd $0x4e, IN_L, IN_M vpxor IN_L, IN_M, IN_M vpclmulqdq $0x00, HKEY, IN_L, IN_L vpclmulqdq $0x11, HKEY, IN_H, IN_H vpclmulqdq $0x00, HKEY1_2, IN_M, IN_M vmovdqa XI_L, XI_H vpshufd $0x4e, XI_L, TEMP1 vpxor XI_L, TEMP1, TEMP1 vpclmulqdq $0x00, HKEY2, XI_L, XI_L vpclmulqdq $0x11, HKEY2, XI_H, XI_H vpclmulqdq $0x10, HKEY1_2, TEMP1, TEMP1 vxorps IN_L, XI_L, XI_L vxorps IN_H, XI_H, XI_H vxorps IN_M, TEMP1, TEMP1 vpxor XI_L, TEMP1, TEMP1 vpxor XI_H, TEMP1, TEMP1 vmovdqa TEMP1, TEMP2 vpslldq $8, TEMP1, TEMP1 vpsrldq $8, TEMP2, TEMP2 vpxor TEMP1, XI_L, XI_L vpxor TEMP2, XI_H, XI_H REDUCTION_256BIT XI_H, XI_L, TEMP1, TEMP2, g_poly cmp $0x00, LEN jz .Lend leaq 0x20(INPUT_IN), INPUT_IN .align 32 .Lremain_1block: subq $0x10, LEN vmovdqu (INPUT_IN), TEMP1 vpshufb MASK, TEMP1, TEMP1 vpxor TEMP1, XI_L, XI_L GHASH_MUL128X128 XI_H, XI_L, HKEY, HKEY1_2, TEMP1, TEMP2 REDUCTION_256BIT XI_H, XI_L, TEMP1, TEMP2, g_poly .Lend: vpshufb MASK, XI_L, XI_L vmovdqu XI_L, (INPUT_XI) vpxor HKEY, HKEY, HKEY // clear hTable vpxor HKEY1_2, HKEY1_2, HKEY1_2 vpxor HKEY2, HKEY2, HKEY2 vpxor HKEY3, HKEY3, HKEY3 vpxor HKEY4, HKEY4, HKEY4 ret .cfi_endproc .size GcmHashMultiBlock, .-GcmHashMultiBlock #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm/ghash_x86_64.S
Unix Assembly
unknown
11,593
/* * 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_CHACHA20) && defined(HITLS_CRYPTO_CHACHA20POLY1305) #include "crypt_arm.h" .arch armv8-a /** * c structure:Poly1305Ctx */ .set CTX_acc, 0 .set CTX_r, 24 .set CTX_s, 40 .set CTX_table, 56 .set CTX_data, 200 .set CTX_lastLen, 216 .set CTX_flag, 220 .set CTX_size, 224 .equ FLAG_BASE2_26, 1 /* 104 78 52 26 0 * out4 out3 out2 out1 out0 * in0[63:52] in0[51:26] in0[25:0] * in1[63:40] in1[39:14] in1[13:0]<<12 * in2[39:0]<<24 */ /** * Macro description: converts the large number format. Three pieces of base 2^64 data are transferred, * and five pieces of base 2^26 data are transferred. * Input register: * in0: digits 0 to 63 of the large number in the original format * in1:64 to 127 characters in the original format * in2:128 or more digits of the large number in the original format * Modified register: None * Output register: * out0: 0 to 25 bits of the converted large number * out1:26 to 51 digits of the converted large number * out2:52 to 77 bits of the converted large number * out3:78 to 103 bits of the converted large number * out4:104 or more digits of the converted large number * Function/Macro Call: None * Restriction: Note that the valid bits of in2 cannot exceed 40 bits. * Otherwise, data will be lost. */ .macro CONVERT_64TO26 out0 out1 out2 out3 out4 in0 in1 in2 and \out0, \in0, #0x03ffffff ubfx \out1, \in0, #26, #26 extr \out2, \in1, \in0, #52 and \out2, \out2, #0x03ffffff ubfx \out3, \in1, #14, #26 extr \out4, \in2, \in1, #40 .endm /* 128 64 0 * out2 out1 out0 * in0 * (in1>>38) in1<<26 * in2>>12 in2<<52 * (in3>>50) in3<<14 * in4>>24 in4<<40 */ /** * Macro description: converts the large number format. Five pieces of base2^26 data are transferred, * and three pieces of base2^64 data are transferred. * Input register: * in0: large data block 0 in the original format * in1: large data block 1 in the original format * in2: large data block 2 in the original format * in3: large data block 3 in the original format * in4: large data block 4 in the original format * Modified register: None * Output register: * out0: bits 0 to 63 of the converted large number * out1: 64-127 bits of the converted large number * out2: 128 or more digits of the converted large number * Function/Macro Call: None * Restriction: Ensure that the valid bits in0-in4 of the input data do not exceed 38 bits. Otherwise, * data will be lost. */ .macro CONVERT_26TO64 out0 out1 out2 in0 in1 in2 in3 in4 add \out0, \in0, \in1, lsl#26 adds \out0, \out0, \in2, lsl#52 lsr \out1, \in2, #12 add \out1, \out1, \in3, lsl#14 adc \out1, \out1, xzr adds \out1, \out1, \in4, lsl#40 lsr \out2, \in4, #24 adc \out2, \out2, xzr .endm /* register | t_0 t_1 | t_2 | * bits | 128 bits | 64 bits | * 1 | r0*a0(lo) r0*a1(lo) | r0*a2(lo) | * 2 | r0*a0(hi) | r0*a1(hi) | * 3 | s1*a1(lo) r1*a0(lo) | | * 4 | s1*a1(hi) | r1*a0(hi) | * 5 | s1*a2(lo) | | */ /** * Macro description: Multiply large numbers and perform modulo * (a0|a1|a2) = (a0|a1|a2) * (r0|r1) mod P * Input register: * a_0: digits 0 to 63 of the large number a * a_1: 64 to 127 digits of the major number a * a_2: 128 or more digits of the major number a * r_0: bits 0 to 63 of the large number r * r_1: 64-127 bits of the large number r * s_1: 5/4 times the large number r_1 * Change register: x11-x15 * Output register: * a_0: bits 0 to 63 of the multiplication result * a_1: 64-127 bits of the multiplication result * a_2: 128 or more bits of the multiplication result * Function/Macro Call: None * Restriction: The relationship between s1 and r1 is s1 = r1 + r1 >> 2. */ .macro POLY1305_MOD_MUL a_0, a_1, a_2, r_0, r_1, s_1 /* 1 */ mul x11, \r_0, \a_0 mul x12, \r_0, \a_1 mul x13, \r_0, \a_2 /* 2 */ umulh x14, \r_0, \a_0 umulh x15, \r_0, \a_1 adds x12, x12, x14 adc x13, x13, x15 /* 3 */ mul x14, \s_1, \a_1 mul x15, \r_1, \a_0 adds x11, x11, x14 adcs x12, x12, x15 adc x13, x13, xzr /* 4 */ umulh x14, \s_1, \a_1 umulh x15, \r_1, \a_0 adds x12, x12, x14 adc x13, x13, x15 /* 5 */ mul x15, \s_1, \a_2 adds x12, x12, x15 adc x13, x13, xzr /* Split x13 and add 5/4 of the high-order part to x11. */ bic x15, x13, #3 and x13, x13, #3 add x15, x15, x15, lsr#2 adds \a_0, x11, x15 adcs \a_1, x12, xzr adc \a_2, x13, xzr .endm /** * Macro description: Convert the content of a large number (r_0|r_1|r_2) into the format of 2 ^ 26, * and then fill the memory pointed to by ptr at intervals. * Input register: * r_0: digits 0 to 63 of a large number * r_1: indicates the 64th to 127th digits of the large number. * r_2: 128th to 191th digits of a large number * ptr: start address of the memory to be filled * Change register: x11-x15 * Output register: None * Function/Macro call: TRANSFER_64TO26 * */ .macro Fill_TABLE r_0, r_1, r_2, ptr /* base 2^64 -> base 2^26 */ /* r_0 r_1 r_2 --> x11 x12 x13 x14 x15 */ CONVERT_64TO26 x11, x12, x13, x14, x15, \r_0, \r_1, \r_2 /* Stores the converted value. */ str w11, [\ptr, #16*0] str w12, [\ptr, #16*1] str w13, [\ptr, #16*2] str w14, [\ptr, #16*3] str w15, [\ptr, #16*4] /* Multiply 5 times and continue to store */ add w12, w12, w12, lsl#2 add w13, w13, w13, lsl#2 add w14, w14, w14, lsl#2 add w15, w15, w15, lsl#2 str w12, [\ptr, #16*5] str w13, [\ptr, #16*6] str w14, [\ptr, #16*7] str w15, [\ptr, #16*8] .endm /** * Function description: This function is used to initialize the pre-computation table. * Function prototype: void Poly1305InitForAsm(Poly1305Ctx *ctx); * Input register: * x0: address of the context structure * Change register x0 and x5-x15. * Output register: None * Function/Macro Call: Poly1305_MOD_MUL Fill_TABLE */ .text .balign 64 .global Poly1305InitForAsm .type Poly1305InitForAsm, %function Poly1305InitForAsm: AARCH64_PACIASP stp x29, x30, [sp, #-16]! add x29, sp, #0 /* Clearing the member flag */ str wzr, [x0, #CTX_flag] /* Initialize the r table. */ ldp x8, x9, [x0, #CTX_r] #ifdef HITLS_BIG_ENDIAN /* The r value needs to be reversed in the big-endian case. */ ror x8, x8, #32 ror x9, x9, #32 #endif add x10, x9, x9, lsr#2 /* padding r^1 */ add x0, x0, #CTX_table + 12 mov x5, x8 mov x6, x9 mov x7, xzr Fill_TABLE x5, x6, x7, x0 /* Calculate and populate r^2 */ sub x0, x0, #4 POLY1305_MOD_MUL x5, x6, x7, x8, x9, x10 Fill_TABLE x5, x6, x7, x0 /* Calculate and populate r^3 */ sub x0, x0, #4 POLY1305_MOD_MUL x5, x6, x7, x8, x9, x10 Fill_TABLE x5, x6, x7, x0 /* Calculate and populate r^4 */ sub x0, x0, #4 POLY1305_MOD_MUL x5, x6, x7, x8, x9, x10 Fill_TABLE x5, x6, x7, x0 eor x5, x5, x5 eor x6, x6, x6 eor x7, x7, x7 eor x8, x8, x8 eor x9, x9, x9 eor x10, x10, x10 ldp x29, x30, [sp], #16 AARCH64_AUTIASP ret .size Poly1305InitForAsm, .-Poly1305InitForAsm /** * Function description: Outputs the final result value to the specified memory. * Function prototype: void Poly1305Last(Poly1305Ctx *ctx, uint8_t mac[POLY1305_TAGSIZE]); * Input register: * x0: address of the context structure * x1: pointer to the output buffer * Change register: x3-x15 * Output register: None * Function/Macro Call: Poly1305LastNeon */ .text .balign 64 .global Poly1305Last .type Poly1305Last, %function Poly1305Last: AARCH64_PACIASP ldr w15, [x0, #CTX_flag] and w15, w15, #FLAG_BASE2_26 cbnz w15, Poly1305LastNeon ldp x3, x4, [x0, #CTX_acc] ldr x5, [x0, #CTX_acc + 16] ldp x12, x13, [x0, #CTX_s] adds x9, x3, #5 // Compute acc + 5 adcs x10, x4, xzr adc x11, x5, xzr /* Test for more than 2 ^ 130 */ cmp x11, #3 /* If yes, use the value after adding 5 (equal to the value after modulo operation). If no, use the original value. */ csel x3, x3, x9, le csel x4, x4, x10, le /* Plus the s value */ #ifdef HITLS_BIG_ENDIAN /* In the big-endian scenario, the s value needs to be reversed. */ ror x12, x12, #32 ror x13, x13, #32 #endif adds x3, x3, x12 adc x4, x4, x13 mov x12, xzr // zero out. mov x13, xzr #ifdef HITLS_BIG_ENDIAN /* In big-endian mode, the data is converted to little-endian and then output to the memory. */ rev x3, x3 rev x4, x4 #endif stp x3, x4, [x1] AARCH64_AUTIASP ret .size Poly1305Last, .-Poly1305Last /** * Function description: Outputs the final result value to the specified memory. * Function prototype: void Poly1305LastNeon(Poly1305Ctx *ctx, uint8_t mac[POLY1305_TAGSIZE]); * Input register: * x0: address of the context structure * x1: pointer to the output buffer * Change register: x2-x15 * Output register: None * Function/Macro Call: None */ .text .balign 64 .type Poly1305LastNeon, %function Poly1305LastNeon: AARCH64_PACIASP /* Load the value of base 2^26. */ ldp w11, w12, [x0, #CTX_acc] ldp w13, w14, [x0, #CTX_acc + 8] ldr w15, [x0, #CTX_acc + 16] /* Converted to base 2^64, x11 to x15 are within 30 bits. */ CONVERT_26TO64 x5, x6, x7, x11, x12, x13, x14, x15 /* Load the s value. */ ldp x2, x3, [x0, #CTX_s] /* Add more than 130 bits by 5 to the lower bits. */ bic x15, x7, #3 and x7, x7, #3 add x15, x15, x15, lsr#2 adds x5, x5, x15 adcs x6, x6, xzr adc x7, x7, xzr /* Modulo P, subtract directly */ /* subtraction:acc - (2^130 - 5) = acc + 5 - 2^130 */ adds x11, x5, #5 adcs x12, x6, xzr adc x13, x7, xzr /* Test for more than 2 ^ 130 */ cmp x13, #4 /* If P is greater than or equal to P, the new value is used. */ csel x5, x11, x5, ge csel x6, x12, x6, ge /* Value of s plus acc */ #ifdef HITLS_BIG_ENDIAN /* In the big-endian scenario, the s value needs to be reversed. */ ror x2, x2, #32 ror x3, x3, #32 #endif adds x2, x2, x5 adc x3, x3, x6 #ifdef HITLS_BIG_ENDIAN /* In big-endian mode, the data is converted to little-endian and then output to the memory. */ rev x2, x2 rev x3, x3 #endif stp x2, x3, [x1] AARCH64_AUTIASP ret .size Poly1305LastNeon, .-Poly1305LastNeon /** * Function description: Compresses the input data and stores it in the context structure. * Function prototype: uint32_t Poly1305Block(Poly1305Ctx *ctx, const uint8_t *data, * uint32_t dataLen, uint32_t padbit); * Input register: * x0: address of the context structure * x1: pointer to the input data * x2: length of the input data * x3: padded bits, 0 or 1. * Change register: x4-x15 * Output register: * x0: length of the remaining data to be processed * Function/Macro Call: CONVERT_26TO64 POLY1305_MOD_MUL Poly1305BlockNeon */ .text .balign 64 .global Poly1305Block .type Poly1305Block, %function Poly1305Block: AARCH64_PACIASP /* x4 indicates the length of the basic instruction set to be processed, and x2 indicates the remaining length of the instruction set to be processed. */ /* If the value is less than 16, no processing is required. If NEON is supported, the part that is greater than or equal to 256 is reserved for NEON. */ and x4, x2, #0xF0 // x4 is the processing length of the basic instruction set. bic x2, x2, #0xF0 // x2 is the remaining length after the basic instruction set is processed. cbz x4, .Lskip_process /* Load the ACC value. */ ldr w15, [x0, #CTX_flag] and w14, w15, #FLAG_BASE2_26 cbz w14, .Lload_acc_64 bic w15, w15, #FLAG_BASE2_26 str w15, [x0, #CTX_flag] ldp w10, w11, [x0, #CTX_acc] ldp w12, w13, [x0, #CTX_acc + 8] ldr w14, [x0, #CTX_acc + 16] CONVERT_26TO64 x5, x6, x7, x10, x11, x12, x13, x14 b .Lend_load_acc_64 .Lload_acc_64: ldp x5, x6, [x0, #CTX_acc] ldr x7, [x0, #CTX_acc + 16] .Lend_load_acc_64: /* Load the r value. */ ldp x8, x9, [x0, #CTX_r] #ifdef HITLS_BIG_ENDIAN /* The r value needs to be reversed in the big-endian case. */ ror x8, x8, #32 ror x9, x9, #32 #endif add x10, x9, x9, lsr#2 .Lloop_64: /* Accumulator acc plus plaintext block with padding x3 */ ldp x11, x12, [x1], #16 #ifdef HITLS_BIG_ENDIAN rev x11, x11 rev x12, x12 #endif adds x5, x5, x11 adcs x6, x6, x12 adc x7, x7, x3 /* Multiply large numbers and take modulo (x5|x6|x7) = (x5|x6|x7) * (x8|x9) mod P */ /* x10 = x9 + x9 >> 2 */ POLY1305_MOD_MUL x5, x6, x7, x8, x9, x10 /* End of loop, update iteration information */ sub x4, x4, #16 cbnz x4, .Lloop_64 stp x5, x6, [x0, #CTX_acc] str x7, [x0, #CTX_acc + 16] .Lskip_process: /* If the remaining length is 256 bytes or more, the NEON processes the remaining length. */ bic x4, x2, #0xFF cbnz x4, Poly1305BlockNeon /* function returns */ and x0, x2, #15 // The return value is the unprocessed length. eor x8, x8, x8 eor x9, x9, x9 AARCH64_AUTIASP ret .size Poly1305Block, .-Poly1305Block /** * Function description: Compresses the input data, stores the data in the context structure, and uses the NEON register. * Function prototype: uint32_t Poly1305BlockNeon(Poly1305Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint32_t padbit); * Input register: * x0: context structure address * x1: pointer to the input data * x2: length of the input data * x3: padding bit, 0 or 1. * Modify the register x0-x15,v0-v7,v16-v31. * Output register: * x0: length of the remaining data to be processed * Function/Macro call: CONVERT_64TO26 */ .text .balign 64 .type Poly1305BlockNeon, %function Poly1305BlockNeon: stp x29, x30, [sp, #-16]! stp d8, d9, [sp, #-16]! stp d10, d11, [sp, #-16]! stp d12, d13, [sp, #-16]! stp d14, d15, [sp, #-16]! /* Load the acc value, which is stored in v24-v28. */ ldr w15, [x0, #CTX_flag] and w14, w15, #FLAG_BASE2_26 cbnz w14, .Lload_acc_26 orr w15, w15, #FLAG_BASE2_26 str w15, [x0, #CTX_flag] ldp x5, x6, [x0, #CTX_acc] ldr x7, [x0, #CTX_acc + 16] CONVERT_64TO26 x11, x12, x13, x14, x15, x5, x6, x7 fmov s24, w11 fmov s25, w12 fmov s26, w13 fmov s27, w14 fmov s28, w15 b .Lend_load_acc_26 .Lload_acc_26: ldp s24, s25, [x0, #CTX_acc] ldp s26, s27, [x0, #CTX_acc + 8] ldr s28, [x0, #CTX_acc + 16] .Lend_load_acc_26: /* Load r-value table */ add x15, x0, #CTX_table ld1 {v0.4s}, [x15], #16 // r^n[0] mod P, n = 1, 2, 3, 4 ld1 {v1.4s, v2.4s, v3.4s, v4.4s}, [x15], #64 // r^n[1:4] mod P ld1 {v5.4s, v6.4s, v7.4s, v8.4s}, [x15], #64 // 5 * r^n[1:4] mod P /* Pre-treatment before start of cycle */ add x1, x1, #64 sub x4, x4, #64 /* v31.2d is {0x3ffffff, 0x3ffffff} */ movi v31.16b, #0xFF ushr v31.2d, v31.2d, #38 /* Load (m[2], m[3]), convert the format, and save it to v14-v18. */ ldp x9, x10, [x1, #-32] ldp x14, x15, [x1, #-16] #ifdef HITLS_BIG_ENDIAN rev x9, x9 rev x10, x10 rev x14, x14 rev x15, x15 #endif and x6, x9, #0x03ffffff ubfx x7, x9, #26, #26 extr x8, x10, x9, #52 and x8, x8, #0x03ffffff ubfx x9, x10, #14, #26 extr x10, x3, x10, #40 and x11, x14, #0x03ffffff ubfx x12, x14, #26, #26 extr x13, x15, x14, #52 and x13, x13, #0x03ffffff ubfx x14, x15, #14, #26 extr x15, x3, x15, #40 add x6, x6, x11, lsl#32 add x7, x7, x12, lsl#32 add x8, x8, x13, lsl#32 add x9, x9, x14, lsl#32 add x10, x10, x15, lsl#32 fmov d14, x6 fmov d15, x7 fmov d16, x8 fmov d17, x9 fmov d18, x10 /* Load (m[0], m[1]) and save the converted format in v9-v13. */ ldp x9, x10, [x1, #-64] ldp x14, x15, [x1, #-48] #ifdef HITLS_BIG_ENDIAN rev x9, x9 rev x10, x10 rev x14, x14 rev x15, x15 #endif and x6, x9, #0x03ffffff ubfx x7, x9, #26, #26 extr x8, x10, x9, #52 and x8, x8, #0x03ffffff ubfx x9, x10, #14, #26 extr x10, x3, x10, #40 and x11, x14, #0x03ffffff ubfx x12, x14, #26, #26 extr x13, x15, x14, #52 and x13, x13, #0x03ffffff ubfx x14, x15, #14, #26 extr x15, x3, x15, #40 add x6, x6, x11, lsl#32 add x7, x7, x12, lsl#32 add x8, x8, x13, lsl#32 add x9, x9, x14, lsl#32 add x10, x10, x15, lsl#32 fmov d9, x6 fmov d10, x7 fmov d11, x8 fmov d12, x9 fmov d13, x10 /* See NEON Crypto by Daniel J. Bernstein and Peter Schwabe Use base 2^26 to represent a large number: f = f[0] + f[1]<<26 + f[2]<<52 + f[3]<<78 + f[4]<<104 Calculate h = (f * g) mod (2^130 - 5), using the NEON register h[0] = f[0]g[0] + 5f[1]g[4] + 5f[2]g[3] + 5f[3]g[2] + 5f[4]g[1] h[1] = f[0]g[1] + f[1]g[0] + 5f[2]g[4] + 5f[3]g[3] + 5f[4]g[2] h[2] = f[0]g[2] + f[1]g[1] + f[2]g[0] + 5f[3]g[4] + 5f[4]g[3] h[3] = f[0]g[3] + f[1]g[2] + f[2]g[1] + f[3]g[0] + 5f[4]g[4] h[4] = f[0]g[4] + f[1]g[3] + f[2]g[2] + f[3]g[1] + f[4]g[0] NEON Polynomial Calculation Process: ((m[0]r^4 + m[2]r^2 + m[4])*r^4 + m[6]r^2 + m[8])*r^4 + m[10]r^2 + ((m[1]r^4 + m[3]r^2 + m[5])*r^4 + m[7]r^2 + m[9])*r^3 + m[11]r^1 Calculated inside the loop: (x[0],y[0]) = (acc, 0) (x[1],y[1]) = (m[2],m[3])*(r^2,r^2) + ((m[0],m[1]) + (x[0],y[0]))*(r^4,r^4) (x[2],y[2]) = (m[6],m[7])*(r^2,r^2) + ((m[4],m[5]) + (x[1],y[1]))*(r^4,r^4) */ /* Start loop, vector register has used v0-v8 to hold r value precalculated table, v24-v28 to hold ACC value */ .Lloop_neon: add x1, x1, #64 sub x4, x4, #64 /* Compute (m[2 + 4i], m[3 + 4i])*(r^2, r^2), stored in v19-v23 */ /* Load the (m[6 + 4i], m[7 + 4i]) file and save it in v14-v18. */ ldp x9, x10, [x1, #-32] umull v19.2d, v14.2s, v0.s[2] umull v20.2d, v14.2s, v1.s[2] umull v21.2d, v14.2s, v2.s[2] umull v22.2d, v14.2s, v3.s[2] umull v23.2d, v14.2s, v4.s[2] ldp x14, x15, [x1, #-16] umlal v19.2d, v15.2s, v8.s[2] umlal v20.2d, v15.2s, v0.s[2] umlal v21.2d, v15.2s, v1.s[2] umlal v22.2d, v15.2s, v2.s[2] umlal v23.2d, v15.2s, v3.s[2] #ifdef HITLS_BIG_ENDIAN rev x9, x9 rev x10, x10 rev x14, x14 rev x15, x15 #endif and x6, x9, #0x03ffffff and x11, x14, #0x03ffffff ubfx x7, x9, #26, #26 ubfx x12, x14, #26, #26 extr x8, x10, x9, #52 extr x13, x15, x14, #52 umlal v19.2d, v16.2s, v7.s[2] umlal v20.2d, v16.2s, v8.s[2] umlal v21.2d, v16.2s, v0.s[2] umlal v22.2d, v16.2s, v1.s[2] umlal v23.2d, v16.2s, v2.s[2] and x8, x8, #0x03ffffff and x13, x13, #0x03ffffff ubfx x9, x10, #14, #26 ubfx x14, x15, #14, #26 extr x10, x3, x10, #40 extr x15, x3, x15, #40 umlal v19.2d, v17.2s, v6.s[2] umlal v20.2d, v17.2s, v7.s[2] umlal v21.2d, v17.2s, v8.s[2] umlal v22.2d, v17.2s, v0.s[2] umlal v23.2d, v17.2s, v1.s[2] add x6, x6, x11, lsl#32 add x7, x7, x12, lsl#32 add x8, x8, x13, lsl#32 add x9, x9, x14, lsl#32 add x10, x10, x15, lsl#32 umlal v19.2d, v18.2s, v5.s[2] umlal v20.2d, v18.2s, v6.s[2] umlal v21.2d, v18.2s, v7.s[2] umlal v22.2d, v18.2s, v8.s[2] umlal v23.2d, v18.2s, v0.s[2] fmov d14, x6 fmov d15, x7 fmov d16, x8 fmov d17, x9 fmov d18, x10 /* It is not placed at the beginning of the loop because it depends on v24 to v28. */ /* Compute ((m[0 + 4i], m[1 + 4i]) + (x[i], y[i]))*(r^4, r^4), stored in v19-v23 */ /* Load the (m[4 + 4i], m[5 + 4i]) file and save it in v9-v13. */ add v9.2s, v9.2s, v24.2s add v10.2s, v10.2s, v25.2s add v11.2s, v11.2s, v26.2s add v12.2s, v12.2s, v27.2s add v13.2s, v13.2s, v28.2s ldp x9, x10, [x1, #-64] umlal v19.2d, v9.2s, v0.s[0] umlal v20.2d, v9.2s, v1.s[0] umlal v21.2d, v9.2s, v2.s[0] umlal v22.2d, v9.2s, v3.s[0] umlal v23.2d, v9.2s, v4.s[0] ldp x14, x15, [x1, #-48] umlal v19.2d, v10.2s, v8.s[0] umlal v20.2d, v10.2s, v0.s[0] umlal v21.2d, v10.2s, v1.s[0] umlal v22.2d, v10.2s, v2.s[0] umlal v23.2d, v10.2s, v3.s[0] #ifdef HITLS_BIG_ENDIAN rev x9, x9 rev x10, x10 rev x14, x14 rev x15, x15 #endif and x6, x9, #0x03ffffff and x11, x14, #0x03ffffff ubfx x7, x9, #26, #26 ubfx x12, x14, #26, #26 extr x8, x10, x9, #52 extr x13, x15, x14, #52 umlal v19.2d, v11.2s, v7.s[0] umlal v20.2d, v11.2s, v8.s[0] umlal v21.2d, v11.2s, v0.s[0] umlal v22.2d, v11.2s, v1.s[0] umlal v23.2d, v11.2s, v2.s[0] and x8, x8, #0x03ffffff and x13, x13, #0x03ffffff ubfx x9, x10, #14, #26 ubfx x14, x15, #14, #26 extr x10, x3, x10, #40 extr x15, x3, x15, #40 umlal v19.2d, v12.2s, v6.s[0] umlal v20.2d, v12.2s, v7.s[0] umlal v21.2d, v12.2s, v8.s[0] umlal v22.2d, v12.2s, v0.s[0] umlal v23.2d, v12.2s, v1.s[0] add x6, x6, x11, lsl#32 add x7, x7, x12, lsl#32 add x8, x8, x13, lsl#32 add x9, x9, x14, lsl#32 add x10, x10, x15, lsl#32 umlal v19.2d, v13.2s, v5.s[0] umlal v20.2d, v13.2s, v6.s[0] umlal v21.2d, v13.2s, v7.s[0] umlal v22.2d, v13.2s, v8.s[0] umlal v23.2d, v13.2s, v0.s[0] fmov d9, x6 fmov d10, x7 fmov d11, x8 fmov d12, x9 fmov d13, x10 /* Because v19-v23 significant bits may exceed 56 bits, to ensure that subsequent multiplication does not overflow, two carry is processed. */ ushr v24.2d, v19.2d, #26 ushr v25.2d, v20.2d, #26 ushr v26.2d, v21.2d, #26 ushr v27.2d, v22.2d, #26 ushr v28.2d, v23.2d, #26 /* More than 130 digits multiplied by 5 to the lower bits */ shl v29.2d, v28.2d, #2 add v28.2d, v28.2d, v29.2d /* Use the AND operation to truncate the lower 26 bits. */ and v19.16b, v19.16b, v31.16b and v20.16b, v20.16b, v31.16b and v21.16b, v21.16b, v31.16b and v22.16b, v22.16b, v31.16b and v23.16b, v23.16b, v31.16b /* Add the part of the low carry */ add v19.2d, v19.2d, v28.2d add v20.2d, v20.2d, v24.2d add v21.2d, v21.2d, v25.2d add v22.2d, v22.2d, v26.2d add v23.2d, v23.2d, v27.2d /* Continue carry processing */ ushr v24.2d, v19.2d, #26 ushr v25.2d, v20.2d, #26 ushr v26.2d, v21.2d, #26 ushr v27.2d, v22.2d, #26 ushr v28.2d, v23.2d, #26 shl v29.2d, v28.2d, #2 add v28.2d, v28.2d, v29.2d and v19.16b, v19.16b, v31.16b and v20.16b, v20.16b, v31.16b and v21.16b, v21.16b, v31.16b and v22.16b, v22.16b, v31.16b and v23.16b, v23.16b, v31.16b add v19.2d, v19.2d, v28.2d add v20.2d, v20.2d, v24.2d add v21.2d, v21.2d, v25.2d add v22.2d, v22.2d, v26.2d add v23.2d, v23.2d, v27.2d /* The calculated (x[i + 1], y[i + 1]) is stored in v24-v28 and is reserved for the next cycle. */ xtn v24.2s, v19.2d xtn v25.2s, v20.2d xtn v26.2s, v21.2d xtn v27.2s, v22.2d xtn v28.2s, v23.2d /* End of loop, skip */ cbnz x4, .Lloop_neon /* Dealing with the tail */ /* Compute (m[6 + 4i], m[7 + 4i])*(r^2, r^1), stored in v19-v23 */ dup v14.2d, v14.d[0] dup v15.2d, v15.d[0] dup v16.2d, v16.d[0] dup v17.2d, v17.d[0] dup v18.2d, v18.d[0] umull2 v19.2d, v14.4s, v0.4s umull2 v20.2d, v14.4s, v1.4s umull2 v21.2d, v14.4s, v2.4s umull2 v22.2d, v14.4s, v3.4s umull2 v23.2d, v14.4s, v4.4s umlal2 v19.2d, v15.4s, v8.4s umlal2 v20.2d, v15.4s, v0.4s umlal2 v21.2d, v15.4s, v1.4s umlal2 v22.2d, v15.4s, v2.4s umlal2 v23.2d, v15.4s, v3.4s umlal2 v19.2d, v16.4s, v7.4s umlal2 v20.2d, v16.4s, v8.4s umlal2 v21.2d, v16.4s, v0.4s umlal2 v22.2d, v16.4s, v1.4s umlal2 v23.2d, v16.4s, v2.4s umlal2 v19.2d, v17.4s, v6.4s umlal2 v20.2d, v17.4s, v7.4s umlal2 v21.2d, v17.4s, v8.4s umlal2 v22.2d, v17.4s, v0.4s umlal2 v23.2d, v17.4s, v1.4s umlal2 v19.2d, v18.4s, v5.4s umlal2 v20.2d, v18.4s, v6.4s umlal2 v21.2d, v18.4s, v7.4s umlal2 v22.2d, v18.4s, v8.4s umlal2 v23.2d, v18.4s, v0.4s /* Compute (m[4 + 4i], m[5 + 4i])*(r^4, r^3), stored in v19-v23 */ add v9.2s, v9.2s, v24.2s add v10.2s, v10.2s, v25.2s add v11.2s, v11.2s, v26.2s add v12.2s, v12.2s, v27.2s add v13.2s, v13.2s, v28.2s umlal v19.2d, v9.2s, v0.2s umlal v20.2d, v9.2s, v1.2s umlal v21.2d, v9.2s, v2.2s umlal v22.2d, v9.2s, v3.2s umlal v23.2d, v9.2s, v4.2s umlal v19.2d, v10.2s, v8.2s umlal v20.2d, v10.2s, v0.2s umlal v21.2d, v10.2s, v1.2s umlal v22.2d, v10.2s, v2.2s umlal v23.2d, v10.2s, v3.2s umlal v19.2d, v11.2s, v7.2s umlal v20.2d, v11.2s, v8.2s umlal v21.2d, v11.2s, v0.2s umlal v22.2d, v11.2s, v1.2s umlal v23.2d, v11.2s, v2.2s umlal v19.2d, v12.2s, v6.2s umlal v20.2d, v12.2s, v7.2s umlal v21.2d, v12.2s, v8.2s umlal v22.2d, v12.2s, v0.2s umlal v23.2d, v12.2s, v1.2s umlal v19.2d, v13.2s, v5.2s umlal v20.2d, v13.2s, v6.2s umlal v21.2d, v13.2s, v7.2s umlal v22.2d, v13.2s, v8.2s umlal v23.2d, v13.2s, v0.2s /* The results are added, stored in v24-v28, and base 2^26 carry. */ ushr v24.2d, v19.2d, #26 ushr v25.2d, v20.2d, #26 ushr v26.2d, v21.2d, #26 ushr v27.2d, v22.2d, #26 ushr v28.2d, v23.2d, #26 shl v29.2d, v28.2d, #2 add v28.2d, v28.2d, v29.2d and v19.16b, v19.16b, v31.16b and v20.16b, v20.16b, v31.16b and v21.16b, v21.16b, v31.16b and v22.16b, v22.16b, v31.16b and v23.16b, v23.16b, v31.16b add v19.2d, v19.2d, v28.2d add v20.2d, v20.2d, v24.2d add v21.2d, v21.2d, v25.2d add v22.2d, v22.2d, v26.2d add v23.2d, v23.2d, v27.2d /* Continue carry processing */ ushr v24.2d, v19.2d, #26 ushr v25.2d, v20.2d, #26 ushr v26.2d, v21.2d, #26 ushr v27.2d, v22.2d, #26 ushr v28.2d, v23.2d, #26 shl v29.2d, v28.2d, #2 add v28.2d, v28.2d, v29.2d and v19.16b, v19.16b, v31.16b and v20.16b, v20.16b, v31.16b and v21.16b, v21.16b, v31.16b and v22.16b, v22.16b, v31.16b and v23.16b, v23.16b, v31.16b add v19.2d, v19.2d, v28.2d add v20.2d, v20.2d, v24.2d add v21.2d, v21.2d, v25.2d add v22.2d, v22.2d, v26.2d add v23.2d, v23.2d, v27.2d addp v24.2d, v19.2d, v19.2d addp v25.2d, v20.2d, v20.2d addp v26.2d, v21.2d, v21.2d addp v27.2d, v22.2d, v22.2d addp v28.2d, v23.2d, v23.2d /* After the processing is complete, save the data. Note that the carry may not be completely processed. */ stp s24, s25, [x0, #CTX_acc] stp s26, s27, [x0, #CTX_acc + 8] str s28, [x0, #CTX_acc + 16] /* return */ mov x5, xzr ldp d14, d15, [sp], #16 ldp d12, d13, [sp], #16 ldp d10, d11, [sp], #16 ldp d8, d9, [sp], #16 ldp x29, x30, [sp], #16 and x0, x2, #15 // The return value is the unprocessed length. AARCH64_AUTIASP ret .size Poly1305BlockNeon, .-Poly1305BlockNeon /** * Function description: This function is used to clear residual sensitive information in registers. * Function prototype: void Poly1305CleanRegister(); * Input register: None * Modify the registers v0-v7, v16-v31. * Output register: None * Function/Macro Call: None */ .text .balign 64 .global Poly1305CleanRegister .type Poly1305CleanRegister, %function Poly1305CleanRegister: AARCH64_PACIASP movi v0.16b, #0 and v1.16b, v1.16b, v0.16b and v2.16b, v2.16b, v0.16b and v3.16b, v3.16b, v0.16b and v4.16b, v4.16b, v0.16b and v5.16b, v5.16b, v0.16b and v6.16b, v6.16b, v0.16b and v7.16b, v7.16b, v0.16b /* V8 to V15 are overwritten during register recovery and do not need to be cleared. */ and v16.16b, v16.16b, v0.16b and v17.16b, v17.16b, v0.16b and v18.16b, v18.16b, v0.16b and v19.16b, v19.16b, v0.16b and v20.16b, v20.16b, v0.16b and v21.16b, v21.16b, v0.16b and v22.16b, v22.16b, v0.16b and v23.16b, v23.16b, v0.16b and v24.16b, v24.16b, v0.16b and v25.16b, v25.16b, v0.16b and v26.16b, v26.16b, v0.16b and v27.16b, v27.16b, v0.16b and v28.16b, v28.16b, v0.16b and v29.16b, v29.16b, v0.16b and v30.16b, v30.16b, v0.16b and v31.16b, v31.16b, v0.16b AARCH64_AUTIASP ret .size Poly1305CleanRegister, .-Poly1305CleanRegister #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm/poly1305_armv8.S
Unix Assembly
unknown
31,825
/* * 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_CHACHA20) && defined(HITLS_CRYPTO_CHACHA20POLY1305) #include "poly1305_x86_64_macro.s" .file "poly1305_x86_64.S" .text /** * Function description: Initializes the pre-computation table and clears the flag. * Function prototype: void Poly1305InitForAsm(Poly1305_Ctx *ctx); * Input register: * CTX: address of the Poly305_Ctx structure * Modify the register: rax, rdx, rbx, rbp, r8, r9, r11-r14. * Output register: None * Function/Macro Call: Poly1305_MOD_MUL */ .globl Poly1305InitForAsm .type Poly1305InitForAsm, @function .align 32 Poly1305InitForAsm: .cfi_startproc push %rbx push %rbp push %r12 push %r13 push %r14 movl $0, 220(CTX) // flag bit Clear movq 24(CTX), R0 movq 32(CTX), R1 movq R1, R2 shrq $2, R2 addq R1, R2 lea 56(CTX), CTX movq R0, ACC1 movq R1, ACC2 xorq ACC3, ACC3 movq R1, %rax POLY1305_MOD_MUL ACC1, ACC2, ACC3, R0, R1, R2 // r^2 movl $0x3ffffff, %eax movl $0x3ffffff, %edx movq ACC1, D1 andl %r14d, %eax movq R0, D2 andl %r11d, %edx movl %eax, (CTX) // r0^2 shrq $26, D1 movl %edx, 4(CTX) // r0 shrq $26, D2 movl $0x3ffffff, %eax movl $0x3ffffff, %edx andl %r8d, %eax andl %r9d, %edx movl %eax, 16(CTX) // r1^2 lea (%rax, %rax, 4), %eax movl %edx, 20(CTX) // r1 lea (%rdx, %rdx, 4), %edx movl %eax, 32(CTX) // s1^2 shrq $26, D1 movl %edx, 36(CTX) // s1 shrq $26, D2 movq ACC2, %rax movq R1, %rdx shlq $12, %rax shlq $12, %rdx orq D1, %rax orq D2, %rdx andl $0x3ffffff, %eax andl $0x3ffffff, %edx movl %eax, 48(CTX) // r2^2 lea (%rax, %rax, 4), %eax movl %edx, 52(CTX) // r2 lea (%rdx, %rdx, 4), %edx movl %eax, 64(CTX) // s2^2 movq ACC2, D1 movl %edx, 68(CTX) // s2 movq R1, D2 shrq $14, D1 movl $0x3ffffff, %eax shrq $14, D2 movl $0x3ffffff, %edx andl %r8d, %eax andl %r9d, %edx movl %eax, 80(CTX) // r3^2 lea (%rax, %rax, 4), %eax movl %edx, 84(CTX) // r3 lea (%rdx, %rdx, 4), %edx movl %eax, 96(CTX) // s3^2 shrq $26, D1 movl %edx, 100(CTX) // s3 shrq $26, D2 movq ACC3, %rax shlq $24, %rax orq %rax, D1 movl %r8d, 112(CTX) // r4^2 lea (D1, D1, 4), D1 movl %r9d, 116(CTX) // r4 lea (D2, D2, 4), D2 movl %r8d, 128(CTX) // s4^2 movl %r9d, 132(CTX) // s4 movq R1, %rax POLY1305_MOD_MUL ACC1, ACC2, ACC3, R0, R1, R2 // r^3 movq ACC1, D1 movl $0x3ffffff, %edx andl %r8d, %edx movl %edx, 12(CTX) // r0^3 shrq $26, D1 movl $0x3ffffff, %edx andl %r8d, %edx movl %edx, 28(CTX) // r1^3 lea (%rdx, %rdx, 4), %edx shrq $26, D1 movl %edx, 44(CTX) // s1^3 movq ACC2, %rax shlq $12, %rax orq D1, %rax andl $0x3ffffff, %eax movl %eax, 60(CTX) // r2^3 lea (%rax, %rax, 4), %eax movq ACC2, D1 movl %eax, 76(CTX) // s2^3 shrq $14, D1 movl $0x3ffffff, %eax andl %r8d, %eax movl %eax, 92(CTX) // r3^3 lea (%rax, %rax, 4), %eax shrq $26, D1 movl %eax, 108(CTX) // s3^3 movq ACC3, %rdx shlq $24, %rdx orq %rdx, D1 movl %r8d, 124(CTX) // r4^3 lea (D1, D1, 4), D1 movl %r8d, 140(CTX) // s4^3 movq R1, %rax POLY1305_MOD_MUL ACC1, ACC2, ACC3, R0, R1, R2 // r^4 movq ACC1, D1 movl $0x3ffffff, %edx andl %r8d, %edx movl %edx, 8(CTX) // r0^4 shrq $26, D1 movl $0x3ffffff, %edx andl %r8d, %edx movl %edx, 24(CTX) // r1^4 lea (%rdx, %rdx, 4), %edx shrq $26, D1 movl %edx, 40(CTX) // s1^4 movq ACC2, %rax shlq $12, %rax orq D1, %rax andl $0x3ffffff, %eax movl %eax, 56(CTX) // r2^4 lea (%rax, %rax, 4), %eax movq ACC2, D1 movl %eax, 72(CTX) // s2^4 shrq $14, D1 movl $0x3ffffff, %eax andl %r8d, %eax movl %eax, 88(CTX) // r3^4 lea (%rax, %rax, 4), %eax shrq $26, D1 movl %eax, 104(CTX) // s3^4 movq ACC3, %rdx shlq $24, %rdx orq %rdx, D1 movl %r8d, 120(CTX) // r4^4 lea (D1, D1, 4), D1 movl %r8d, 136(CTX) // s4^4 lea -56(CTX), CTX pop %r14 pop %r13 pop %r12 pop %rbp pop %rbx ret .cfi_endproc .size Poly1305InitForAsm, .-Poly1305InitForAsm /** * Function description: x86_64 poly1305 64-bit basic instruction implementation * Input register: * CTX: address of the Poly305_Ctx structure * INP: data pointer * LEN: data length * PADBIT: padding data * Change register: r8-r15, rax, rbx, rdx, rbp * Output register: * rax: length of the remaining data to be processed * Macro invoking:Poly1305_MOD_MUL */ .globl Poly1305Block64Bit .type Poly1305Block64Bit, @function Poly1305Block64Bit: .cfi_startproc .align 32 .Lblock_start: push %rbx push %rbp push %r12 push %r13 push %r14 push %r15 movq LEN, %r15 LOAD_ACC_R CTX, R0, R1, R2, ACC1, ACC2, ACC3, %r8d, %rax test %r8d, %r8d jz .Lblock64_loop CONVERT_26TO64_PRE ACC1, ACC2, D1, D2, D3 CONVERT_26TO64 ACC1, D1, ACC2, D2, D3, ACC3 movl $0, 220(CTX) .align 32 .Lblock64_loop: addq (INP), ACC1 adcq 8(INP), ACC2 adcq PADBIT, ACC3 lea 16(INP), INP POLY1305_MOD_MUL ACC1, ACC2, ACC3, R0, R1, R2 subq $16, %r15 movq R1, %rax jnz .Lblock64_loop movq ACC1, (CTX) movq ACC2, 8(CTX) movq ACC3, 16(CTX) movq %r15, %rax pop %r15 pop %r14 pop %r13 pop %r12 pop %rbp pop %rbx ret .cfi_endproc .size Poly1305Block64Bit, .-Poly1305Block64Bit /** * Function description: Calculates (acc + s) mod 2^128 and outputs the final result to the specified memory. * Function prototype: void Poly1305Last(Poly1305_Ctx *ctx, uint8_t mac[POLY1305_TAGSIZE]); * Input register: * rdi: address of the Poly305_Ctx structure * rsi: pointer to the output buffer * Modify the register: rax, rcx, r14, rbx, rbp, r8-r10. * Output register: None * Function/Macro Call: * CONVERT_26TO64 */ .globl Poly1305Last .type Poly1305Last, @function .align 32 Poly1305Last: .cfi_startproc push %rbx push %rbp push %r14 movl 220(CTX), %r8d movq (CTX), ACC1 movq 8(CTX), ACC2 movq 16(CTX), ACC3 test %r8d, %r8d jz .Lblock_last_body CONVERT_26TO64_PRE ACC1, ACC2, D1, D2, D3 CONVERT_26TO64 ACC1, D1, ACC2, D2, D3, ACC3 movl $0, 220(CTX) .Lblock_last_body: movq ACC1, %rax addq $5, ACC1 movq ACC2, %rcx adcq $0, ACC2 adcq $0, ACC3 shrq $2, ACC3 cmovnz ACC1, %rax cmovnz ACC2, %rcx addq 40(CTX), %rax adcq 48(CTX), %rcx movq %rax, (%rsi) movq %rcx, 8(%rsi) pop %r14 pop %rbp pop %rbx ret .cfi_endproc .size Poly1305Last, .-Poly1305Last #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm/poly1305_x86_64.S
Unix Assembly
unknown
8,997
/* * 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_CHACHA20) && defined(HITLS_CRYPTO_CHACHA20POLY1305) #include "poly1305_x86_64.S" .file "poly1305_x86_64_avx2.S" .text /** * Function description: This function is implemented by x86_64 poly1305. The result is stored in ctx->acc. * Function prototype: uint32_t Poly1305Block(Poly1305_Ctx *ctx, const uint8_t *data, * uint32_t dataLen, uint32_t padbit); * Input register: * CTX: address of the Poly305_Ctx structure * INP: pointer to the input data * LEN: length of the input data * PADBIT: padding bit, 0 or 1. * Change registers: r8-r14, rbx, rbp * Output register: * %rax: length of the remaining data to be processed * Function/Macro Call:Poly1305_MOD_MUL */ .globl Poly1305Block .type Poly1305Block,@function Poly1305Block: .cfi_startproc .align 32 cmp $256, LEN jae .Lblock_avx_pre jmp Poly1305Block64Bit .Lblock_avx_pre: andq $-16, LEN test $63, LEN jz Poly1305BlockAVX2 .Lbase2_64_avx_body: push %rbx push %rbp push %r12 push %r13 push %r14 push %r15 movq LEN, %r15 LOAD_ACC_R CTX, R0, R1, R2, ACC1, ACC2, ACC3, %r8d, %rax test %r8d, %r8d jz .Lbase2_64_avx_loop CONVERT_26TO64_PRE ACC1, ACC2, D1, D2, D3 CONVERT_26TO64 ACC1, D1, ACC2, D2, D3, ACC3 movl $0, 220(CTX) .align 32 .Lbase2_64_avx_loop: addq (INP), ACC1 adcq 8(INP), ACC2 adcq PADBIT, ACC3 lea 16(INP), INP POLY1305_MOD_MUL ACC1, ACC2, ACC3, R0, R1, R2 subq $16, %r15 movq R1, %rax test $63, %r15 jnz .Lbase2_64_avx_loop movq ACC1, (CTX) movq ACC2, 8(CTX) movq ACC3, 16(CTX) movq %r15, LEN pop %r15 pop %r14 pop %r13 pop %r12 pop %rbp pop %rbx jmp Poly1305BlockAVX2 ret .cfi_endproc .size Poly1305Block, .-Poly1305Block /** * Function description: x86_64 poly1305 AVX2 implementation * Input register: * CTX: address of the Poly305_Ctx structure * INP: pointer to the input data * LEN: length of the input data * PADBIT: padding bit, 0 or 1. * Change register: ymm0-15, r8, r9, r14, r15, rax, rbx, rdx, rbp * Output register: * rax: length of the remaining data to be processed * Function/Macro Call: * CONVERT_64TO26 */ .globl Poly1305BlockAVX2 .type Poly1305BlockAVX2, @function .align 32 Poly1305BlockAVX2: .cfi_startproc push %rbx push %rbp push %r14 push %r15 vzeroupper movq (CTX), ACC1 // load acc movq 8(CTX), ACC2 movq 16(CTX), ACC3 movl 220(CTX), %r8d test %r8d, %r8d jnz .Lblock_avx2_pre movq LEN, %r15 CONVERT_64TO26 ACC1, ACC2, ACC3, %rax, %rdx // base2_64 --> base2_26 movq %r15, LEN jmp .Lblock_avx2_body .Lblock_avx2_pre: movd %r14, %xmm0 movd %rbx, %xmm2 movd %rbp, %xmm4 shrq $32, %r14 shrq $32, %rbx movd %r14, %xmm1 movd %rbx, %xmm3 .align 32 .Lblock_avx2_body: leaq 56(CTX), CTX // 56(CTX) vmovdqu g_permd_avx2(%rip), YT0 // g_permd_avx2 leaq -8(%rsp), %r11 /* Transform the content in the precomputation table into a computable form and put it into the stack. */ vmovdqu (CTX), %xmm7 vmovdqu 16(CTX), %xmm8 subq $0x128, %rsp vmovdqu 32(CTX), %xmm9 vmovdqu 48(CTX), %xmm11 andq $-512, %rsp vmovdqu 64(CTX), %xmm12 vmovdqu 80(CTX), %xmm13 vpermd YT2, YT0, YT2 // 00 00 34 12 --> 14 24 34 44 vmovdqu 96(CTX), %xmm14 vpermd YT3, YT0, YT3 vmovdqu 112(CTX), %xmm15 vpermd YT4, YT0, YT4 vmovdqu 128(CTX), %xmm10 vpermd YB0, YT0, YB0 vmovdqa YT2, (%rsp) // r0 vpermd YB1, YT0, YB1 vmovdqa YT3, 0x20(%rsp) // r1 vpermd YB2, YT0, YB2 vmovdqa YT4, 0x40(%rsp) // s1 vpermd YB3, YT0, YB3 vmovdqa YB0, 0x60(%rsp) // r2 vpermd YB4, YT0, YB4 vmovdqa YB1, 0x80(%rsp) // s2 vpermd YMASK, YT0, YMASK vmovdqa YB2, 0xa0(%rsp) // r3 vmovdqa YB3, 0xc0(%rsp) // s3 vmovdqa YB4, 0xe0(%rsp) // r4 vmovdqa YMASK, 0x100(%rsp) // s4 /* Load 4 blocks of data and convert them to base2_26 */ vmovdqu g_mask26(%rip), YMASK // g_mask26 vmovdqu (INP), %xmm5 vmovdqu 16(INP), %xmm6 vinserti128 $1, 32(INP), YT0, YT0 vinserti128 $1, 48(INP), YT1, YT1 leaq 64(INP), INP vpsrldq $6, YT0, YT2 vpsrldq $6, YT1, YT3 vpunpckhqdq YT1, YT0, YT4 vpunpcklqdq YT1, YT0, YT0 vpunpcklqdq YT3, YT2, YT2 vpsrlq $26, YT0, YT1 vpsrlq $30, YT2, YT3 vpsrlq $4, YT2, YT2 vpsrlq $40, YT4, YT4 // 4 vpand YMASK, YT3, YT3 // 3 vpand YMASK, YT2, YT2 // 2 vpor g_129(%rip), YT4, YT4 // padbit vpand YMASK, YT1, YT1 // 1 vpand YMASK, YT0, YT0 // 0 vpaddq YH2, YT2, YH2 sub $64, LEN jz .Lblock_avx2_tail jmp .Lblock_avx2_loop .align 32 .Lblock_avx2_loop: // ((inp[0]*r^4 + inp[4])*r^4 + inp[ 8])*r^4 // ((inp[1]*r^4 + inp[5])*r^4 + inp[ 9])*r^3 // ((inp[2]*r^4 + inp[6])*r^4 + inp[10])*r^2 // ((inp[3]*r^4 + inp[7])*r^4 + inp[11])*r^1 vpaddq YH0, YT0, YH0 vpaddq YH1, YT1, YH1 vpaddq YH3, YT3, YH3 vpaddq YH4, YT4, YH4 vmovdqa (%rsp), YT0 // r0^4 vmovdqa 0x20(%rsp), YT1 // r1^4 vmovdqa 0x60(%rsp), YT2 // r2^4 vmovdqa 0xc0(%rsp), YT3 // s3^4 vmovdqa 0x100(%rsp), YMASK // s4^4 // b4 = h4*r0^4 + h3*r1^4 + h2*r2^4 + h1*r3^4 + h0*r4^4 // b3 = h3*r0^4 + h2*r1^4 + h1*r2^4 + h0*r3^4 + h4*s4^4 // b2 = h2*r0^4 + h1*r1^4 + h0*r2^4 + h4*s3^4 + h3*s4^4 // b1 = h1*r0^4 + h0*r1^4 + h4*s2^4 + h3*s3^4 + h2*s4^4 // b0 = h0*r0^4 + h4*s1^4 + h3*s2^4 + h2*s3^4 + h1*s4^4 // // First calculate h2, the above formula can be deformed as // // b4 = h2*r2^4 + h4*r0^4 + h3*r1^4 + + h1*r3^4 + h0*r4^4 // b3 = h2*r1^4 + h3*r0^4 + + h1*r2^4 + h0*r3^4 + h4*s4^4 // b2 = h2*r0^4 + + h1*r1^4 + h0*r2^4 + h4*s3^4 + h3*s4^4 // b1 = h2*s4^4 + h1*r0^4 + h0*r1^4 + h4*s2^4 + h3*s3^4 + // b0 = h2*s3^4 + h0*r0^4 + h4*s1^4 + h3*s2^4 + + h1*s4^4 vpmuludq YH2, YT0, YB2 // b2 = h2 * r0^4 vpmuludq YH2, YT1, YB3 // b3 = h2 * r1^4 vpmuludq YH2, YT2, YB4 // b4 = h2 * r2^4 vpmuludq YH2, YT3, YB0 // b0 = h2 * s3^4 vpmuludq YH2, YMASK, YB1 // b1 = h2 * s4^4 vpmuludq YH1, YT1, YT4 // h1 * r1^4 (Available Scratch Registers:T4、H2) vpmuludq YH0, YT1, YH2 // h0 * r1^4 vpaddq YT4, YB2, YB2 // b2 += h1 * r1^4 vpaddq YH2, YB1, YB1 // b1 += h0 * r1^4 vpmuludq YH3, YT1, YT4 // h3 * r1^4 vpmuludq 0x40(%rsp), YH4, YH2 // h4 * s1^4 vpaddq YT4 ,YB4, YB4 // b4 += h3 * r1^4 vpaddq YH2, YB0, YB0 // b0 += h4 * s1^4 vmovdqa 0x80(%rsp), YT1 // load s2^4 vpmuludq YH4, YT0, YT4 // h4 * r0^4 (Available Scratch Registers:T4、H2) vpmuludq YH3, YT0, YH2 // h3 * r0^4 vpaddq YT4, YB4, YB4 // b4 += h4 * r0^4 vpaddq YH2, YB3, YB3 // b3 += h3 * r0^4 vpmuludq YH0, YT0, YT4 // h0 * r0^4 vpmuludq YH1, YT0, YH2 // h1 * r0^4 vpaddq YT4, YB0, YB0 // b0 += h0 * r0^4 vpaddq YH2, YB1, YB1 // b1 += h1 * r0^4 vmovdqu (INP), %xmm5 // load input (YT0) vpmuludq YH4, YT1, YT4 // h4 * s2^4 vpmuludq YH3, YT1, YH2 // h3 * s2^4 vinserti128 $1, 32(INP), YT0, YT0 vpaddq YT4, YB1, YB1 // b1 += h4 * s2^4 vpaddq YH2, YB0, YB0 // b0 += h3 * s2^4 vpmuludq YH1, YT2, YT4 // h1 * r2^4 (Available Scratch Registers:T4、H2) vpmuludq YH0, YT2, YH2 // h0 * r2^4 vmovdqu 16(INP), %xmm6 // load input (YT1) vpaddq YT4, YB3, YB3 // b3 += h1 * r2^4 vpaddq YH2, YB2, YB2 // b2 += h0 * r2^4 vinserti128 $1, 48(INP), YT1, YT1 vmovdqa 0xa0(%rsp), YH2 // load r3^4 leaq 64(INP), INP vpmuludq YH1, YH2, YT4 // h1 * r3^4 (Available Scratch Registers:T4、H2) vpmuludq YH0, YH2, YH2 // h0 * r3^4 vpsrldq $6, YT0, YT2 vpaddq YT4, YB4, YB4 // b4 += h1 * r3^4 vpaddq YH2, YB3, YB3 // b3 += h0 * r3^4 vpmuludq YH4, YT3, YT4 // h4 * s3^4 vpmuludq YH3, YT3, YH2 // h3 * s3^4 vpsrldq $6, YT1, YT3 vpaddq YT4, YB2, YB2 // b2 += h4 * s3^4 vpaddq YH2, YB1, YB1 // b1 += h3 * s3^4 (finish) vpunpckhqdq YT1, YT0, YT4 vpmuludq YH3, YMASK, YH3 // h3 * s4^4 vpmuludq YH4, YMASK, YH4 // h4 * s4^4 vpunpcklqdq YT1, YT0, YT0 vpaddq YB2, YH3, YH2 // h2 += h3 * s4^4 (finish) vpaddq YB3, YH4, YH3 // h3 += h4 * s4^4 (finish) vpunpcklqdq YT3, YT2, YT3 vpmuludq 0xe0(%rsp), YH0, YH4 // h0 * r4^4 vpmuludq YH1, YMASK, YH0 // h1 * s4^4 vmovdqu g_mask26(%rip), YMASK vpaddq YH4, YB4, YH4 // h4 += h0 * r4^4 (finish) vpaddq YH0, YB0, YH0 // h0 += h1 * s4^4 (finish) // reduction vpsrlq $26, YH3, YB3 vpand YMASK, YH3, YH3 vpaddq YB3, YH4, YH4 // h3 -> h4 vpsrlq $26, YH0, YB0 vpand YMASK, YH0, YH0 vpaddq YB0, YB1, YH1 // h0 -> h1 vpsrlq $26, YH4, YB4 vpand YMASK, YH4, YH4 vpsrlq $4, YT3, YT2 vpsrlq $26, YH1, YB1 vpand YMASK, YH1, YH1 vpaddq YB1, YH2, YH2 // h1 -> h2 vpaddq YB4, YH0, YH0 vpsllq $2, YB4, YB4 vpaddq YB4, YH0, YH0 // h4 -> h0 vpand YMASK, YT2, YT2 vpsrlq $26, YT0, YT1 vpsrlq $26, YH2, YB2 vpand YMASK, YH2, YH2 vpaddq YB2, YH3, YH3 // h2 -> h3 vpaddq YT2, YH2, YH2 // prepare next 4 block vpsrlq $30, YT3, YT3 vpsrlq $26, YH0, YB0 vpand YMASK, YH0, YH0 vpaddq YB0, YH1, YH1 // h0 -> h1 vpsrlq $40, YT4, YT4 vpsrlq $26, YH3, YB3 vpand YMASK, YH3, YH3 vpaddq YB3, YH4, YH4 // h3 -> h4 vpand YMASK, YT0, YT0 // new input 0 vpand YMASK, YT1, YT1 // new input 1 vpand YMASK, YT3, YT3 // new input 3 vpor g_129(%rip), YT4, YT4 // new input 4, padbit subq $64, LEN jnz .Lblock_avx2_loop .Lblock_avx2_tail: BLOCK4_AVX2_TAIL YT0, YT1, YT2, YT3, YT4, YH0, YH1, YH2, YH3, YH4, YB0, YB1, YB2, YB3, YB4, YMASK, %rsp vmovd %xmm0, -56(CTX) vmovd %xmm1, -52(CTX) vmovd %xmm2, -48(CTX) vmovd %xmm3, -44(CTX) vmovd %xmm4, -40(CTX) vzeroupper leaq 8(%r11), %rsp pop %r15 pop %r14 pop %rbp pop %rbx movq LEN, %rax ret .cfi_endproc .size Poly1305BlockAVX2, .-Poly1305BlockAVX2 /** * Function description: This function is used to clear residual sensitive information in a register. * Function prototype: void Poly1305CleanRegister(); */ .globl Poly1305CleanRegister .type Poly1305CleanRegister, @function Poly1305CleanRegister: .cfi_startproc vzeroall ret .cfi_endproc .size Poly1305CleanRegister, .-Poly1305CleanRegister #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm/poly1305_x86_64_avx2.S
Unix Assembly
unknown
13,801
/* * 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_CHACHA20) && defined(HITLS_CRYPTO_CHACHA20POLY1305) #include "poly1305_x86_64.S" .file "poly1305_x86_64_avx512.S" .text .set ZH0, %zmm0 .set ZH1, %zmm1 .set ZH2, %zmm2 .set ZH3, %zmm3 .set ZH4, %zmm4 .set ZT0, %zmm5 .set ZT1, %zmm6 .set ZT2, %zmm7 .set ZT3, %zmm8 .set ZT4, %zmm9 .set ZMASK, %zmm10 .set ZB0, %zmm11 .set ZB1, %zmm12 .set ZB2, %zmm13 .set ZB3, %zmm14 .set ZB4, %zmm15 .set ZR0, %zmm16 .set ZR1, %zmm17 .set ZR2, %zmm18 .set ZR3, %zmm19 .set ZR4, %zmm20 .set ZS1, %zmm21 .set ZS2, %zmm22 .set ZS3, %zmm23 .set ZS4, %zmm24 .set ZM0, %zmm25 .set ZM1, %zmm26 .set ZM2, %zmm27 .set ZM3, %zmm28 .set ZM4, %zmm29 .set PADBIT_ZMM, %zmm30 .align 64 g_permd_avx512: .long 0, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7 .size g_permd_avx512, .-g_permd_avx512 /** * Function description: This function is implemented by x86_64 poly1305. The result is stored in ctx->acc. * Function prototype: uint32_t Poly1305Block(Poly1305_Ctx *ctx, const uint8_t *data, uint32_t dataLen, uint32_t padbit); * Input register: * CTX: address of the Poly305_Ctx structure * INP: pointer to the input data * LEN: length of the input data * PADBIT: padding bit, 0 or 1. * Change register: r8-r15, rbx, rbp, rdx, rax * Output register: * %rax: length of the remaining data to be processed * Function/Macro Call: Poly1305_MOD_MUL */ .globl Poly1305Block .type Poly1305Block, @function Poly1305Block: .cfi_startproc .align 32 cmp $256, LEN jae .Lblock_avx_pre call Poly1305Block64Bit ret .Lblock_avx_pre: andq $-16, LEN test $63, LEN jz Poly1305BlockAVX512 .Lbase2_64_avx_body: push %rbx push %rbp push %r12 push %r13 push %r14 push %r15 movq LEN, %r15 movq (CTX), ACC1 // load acc LOAD_ACC_R CTX, R0, R1, R2, ACC1, ACC2, ACC3, %r8d, %rax test %r8d, %r8d jz .Lbase2_64_avx_loop CONVERT_26TO64_PRE ACC1, ACC2, D1, D2, D3 CONVERT_26TO64 ACC1 D1, ACC2, D2, D3, ACC3 movl $0, 220(CTX) .align 32 .Lbase2_64_avx_loop: addq (INP), ACC1 adcq 8(INP), ACC2 adcq PADBIT, ACC3 lea 16(INP), INP POLY1305_MOD_MUL ACC1, ACC2, ACC3, R0, R1, R2 subq $16, %r15 test $63, %r15 movq R1, %rax jnz .Lbase2_64_avx_loop movq ACC1, (CTX) movq ACC2, 8(CTX) movq ACC3, 16(CTX) movq %r15, LEN pop %r15 pop %r14 pop %r13 pop %r12 pop %rbp pop %rbx jmp Poly1305BlockAVX512 ret .cfi_endproc .size Poly1305Block, .-Poly1305Block /** * Function description: x86_64 poly1305 AVX512 assembly acceleration implementation * Input register: * CTX: address of the Poly305_Ctx structure * INP: pointer to the input data * LEN: length of the input data * PADBIT: padding bit, 0 or 1. * Change register: zmm0-31, rax, rsp, r11, rcx, rdi, k1-k3 * Output register: * rax: length of the remaining data to be processed * Function/Macro Call: * CONVERT_64TO26 */ .globl Poly1305BlockAVX512 .type Poly1305BlockAVX512, @function .align 32 Poly1305BlockAVX512: .cfi_startproc push %rbx push %rbp push %r12 push %r13 push %r14 push %r15 vzeroupper movq (CTX), ACC1 movq 8(CTX), ACC2 movq 16(CTX), ACC3 movl 220(CTX), %r8d test %r8d, %r8d jnz .Lblock_avx512_pre movq LEN, %r15 CONVERT_64TO26 ACC1, ACC2, ACC3, %rax, %rdx movq %r15, LEN jmp .Lblock_avx512_body .Lblock_avx512_pre: movd %r14, %xmm0 movd %rbx, %xmm2 shrq $32, %r14 shrq $32, %rbx movd %r14, %xmm1 movd %rbx, %xmm3 movd %rbp, %xmm4 .Lblock_avx512_body: movl $15, %eax kmovw %eax, %k2 leaq -8(%rsp), %r11 subq $0x128, %rsp leaq 56(CTX), CTX vmovdqa g_permd_avx2(%rip), YT2 // g_permd_avx2 // Extend the precomputation table to the power of 8 andq $-512, %rsp movq $0x20, %rax vmovdqu (CTX), %xmm11 vmovdqu 16(CTX), %xmm12 vmovdqu 32(CTX), %xmm5 vmovdqu 48(CTX), %xmm13 vmovdqu 64(CTX), %xmm6 vmovdqu 80(CTX), %xmm14 vpermd ZB0, ZT2, ZR0 // 00 00 34 12 -> 14 24 34 44 vmovdqu 96(CTX), %xmm8 vpbroadcastq g_mask26(%rip), ZMASK // g_mask26 vmovdqu 112(CTX), %xmm15 vpermd ZB1, ZT2, ZR1 vmovdqu 128(CTX), %xmm9 vpermd ZT0, ZT2, ZS1 vpermd ZB2, ZT2, ZR2 vmovdqa64 ZR0, (%rsp){%k2} vpsrlq $32, ZR0, ZT0 // 14 24 34 44 -> 01 02 03 04 vpermd ZT1, ZT2, ZS2 vmovdqu64 ZR1, (%rsp, %rax){%k2} vpsrlq $32, ZR1, ZT1 vpermd ZB3, ZT2, ZR3 vmovdqa64 ZS1, 0x40(%rsp){%k2} vpermd ZT3, ZT2, ZS3 vmovdqu64 ZR2, 0x40(%rsp, %rax){%k2} vpermd ZB4, ZT2, ZR4 vmovdqa64 ZS2, 0x80(%rsp){%k2} vpermd ZT4, ZT2, ZS4 vmovdqu64 ZR3, 0x80(%rsp, %rax){%k2} vmovdqa64 ZS3, 0xc0(%rsp){%k2} vmovdqu64 ZR4, 0xc0(%rsp, %rax){%k2} vmovdqa64 ZS4, 0x100(%rsp){%k2} vpmuludq ZT0, ZR0, ZB0 vpmuludq ZT0, ZR1, ZB1 vpmuludq ZT0, ZR2, ZB2 vpmuludq ZT0, ZR3, ZB3 vpmuludq ZT0, ZR4, ZB4 vpsrlq $32, ZR2, ZT2 vpmuludq ZT1, ZS4, ZM0 vpmuludq ZT1, ZR0, ZM1 vpmuludq ZT1, ZR1, ZM2 vpmuludq ZT1, ZR2, ZM3 vpmuludq ZT1, ZR3, ZM4 vpsrlq $32, ZR3, ZT3 vpaddq ZM0, ZB0, ZB0 vpaddq ZM1, ZB1, ZB1 vpaddq ZM2, ZB2, ZB2 vpaddq ZM3, ZB3, ZB3 vpaddq ZM4, ZB4, ZB4 vpmuludq ZT2, ZS3, ZM0 vpmuludq ZT2, ZS4, ZM1 vpmuludq ZT2, ZR0, ZM2 vpmuludq ZT2, ZR1, ZM3 vpmuludq ZT2, ZR2, ZM4 vpsrlq $32, ZR4, ZT4 vpaddq ZM0, ZB0, ZB0 vpaddq ZM1, ZB1, ZB1 vpaddq ZM2, ZB2, ZB2 vpaddq ZM3, ZB3, ZB3 vpaddq ZM4, ZB4, ZB4 vpmuludq ZT3, ZS2, ZM0 vpmuludq ZT3, ZS3, ZM1 vpmuludq ZT3, ZS4, ZM2 vpmuludq ZT3, ZR0, ZM3 vpmuludq ZT3, ZR1, ZM4 vpaddq ZM0, ZB0, ZB0 vpaddq ZM1, ZB1, ZB1 vpaddq ZM2, ZB2, ZB2 vpaddq ZM3, ZB3, ZB3 vpaddq ZM4, ZB4, ZB4 vpmuludq ZT4, ZS1, ZM0 vpmuludq ZT4, ZS2, ZM1 vpmuludq ZT4, ZS3, ZM2 vpmuludq ZT4, ZS4, ZM3 vpmuludq ZT4, ZR0, ZM4 vpaddq ZM0, ZB0, ZB0 vpaddq ZM1, ZB1, ZB1 vpaddq ZM2, ZB2, ZB2 vpaddq ZM3, ZB3, ZB3 vpaddq ZM4, ZB4, ZB4 // reduction vpsrlq $26, ZB3, ZM3 vpandq ZMASK, ZB3, ZB3 vpaddq ZM3, ZB4, ZB4 // d3 -> d4 vpsrlq $26, ZB0, ZM0 vpandq ZMASK, ZB0, ZB0 vpaddq ZM0, ZB1, ZB1 // d0 -> d1 vpsrlq $26, ZB4, ZM4 vpandq ZMASK, ZB4, ZB4 vmovdqu64 (INP), ZT3 vmovdqu64 64(INP), ZT4 leaq 128(INP), INP vpsrlq $26, ZB1, ZM1 vpandq ZMASK, ZB1, ZB1 vpaddq ZM1, ZB2, ZB2 // d1 -> d2 vpaddq ZM4, ZB0, ZB0 vpsllq $2, ZM4, ZM4 vpaddq ZM4, ZB0, ZB0 // d4 -> d0 vpsrlq $26, ZB2, ZM2 vpandq ZMASK, ZB2, ZB2 vpaddq ZM2, ZB3, ZB3 // d2 -> d3 vpsrlq $26, ZB0, ZM0 vpandq ZMASK, ZB0, ZB0 vpaddq ZM0, ZB1, ZB1 // d0 -> d1 vpsrlq $26, ZB3, ZM3 vpandq ZMASK, ZB3, ZB3 vpaddq ZM3, ZB4, ZB4 // d3 -> d4 vpunpcklqdq ZT4, ZT3, ZT0 vpunpckhqdq ZT4, ZT3, ZT4 // Construct R and S to make them in operable form. vmovdqu32 g_permd_avx512(%rip), ZM0 // g_permd_avx512 movl $0x7777, %eax kmovw %eax, %k1 vpermd ZR0, ZM0, ZR0 // 14 24 34 44 -> 1444 2444 3444 4444 vpermd ZR1, ZM0, ZR1 vpermd ZR2, ZM0, ZR2 vpermd ZR3, ZM0, ZR3 vpermd ZR4, ZM0, ZR4 vpermd ZB0, ZM0, ZR0{%k1} // 05 06 07 08 and 1444 2444 3444 4444 -> 1858 2868 3878 4888 vpermd ZB1, ZM0, ZR1{%k1} vpermd ZB2, ZM0, ZR2{%k1} vpermd ZB3, ZM0, ZR3{%k1} vpermd ZB4, ZM0, ZR4{%k1} vpslld $2, ZR1, ZS1 vpslld $2, ZR2, ZS2 vpslld $2, ZR3, ZS3 vpslld $2, ZR4, ZS4 vpaddd ZR1, ZS1, ZS1 vpaddd ZR2, ZS2, ZS2 vpaddd ZR3, ZS3, ZS3 vpaddd ZR4, ZS4, ZS4 // Processes the input message block and constructs the operation form. vpbroadcastq g_129(%rip), PADBIT_ZMM // g_129 vpsrlq $52, ZT0, ZT2 vpsllq $12, ZT4, ZT3 vporq ZT3, ZT2, ZT2 vpsrlq $26, ZT0, ZT1 vpsrlq $14, ZT4, ZT3 vpsrlq $40, ZT4, ZT4 // 4 vpandq ZMASK, ZT0, ZT0 // 0 vpandq ZMASK, ZT2, ZT2 // 2 vpaddq ZH2, ZT2, ZH2 subq $192, LEN jbe .Lblock_avx512_tail jmp .Lblock_avx512_loop .align 32 .Lblock_avx512_loop: // ((inp[0] * r^8 + inp[ 8]) * r^8 + inp[16]) * r^8 // ((inp[1] * r^8 + inp[ 9]) * r^8 + inp[17]) * r^7 // ((inp[2] * r^8 + inp[10]) * r^8 + inp[18]) * r^6 // ((inp[3] * r^8 + inp[11]) * r^8 + inp[19]) * r^5 // ((inp[4] * r^8 + inp[12]) * r^8 + inp[20]) * r^4 // ((inp[5] * r^8 + inp[13]) * r^8 + inp[21]) * r^3 // ((inp[6] * r^8 + inp[14]) * r^8 + inp[22]) * r^2 // ((inp[7] * r^8 + inp[15]) * r^8 + inp[23]) * r^1 // b3 = h2*r1 + h0*r3 + h1*r2 + h3*r0 + h4*5*r4 // b4 = h2*r2 + h0*r4 + h1*r3 + h3*r1 + h4*r0 // b0 = h2*5*r3 + h0*r0 + h1*5*r4 + h3*5*r2 + h4*5*r1 // b1 = h2*5*r4 + h0*r1 + h1*r0 + h3*5*r3 + h4*5*r2 // b2 = h2*r0 + h0*r2 + h1*r1 + h3*5*r4 + h4*5*r3 vpmuludq ZH2, ZR1, ZB3 vpandq ZMASK, ZT1, ZT1 // 1 vpmuludq ZH2, ZR2, ZB4 vpandq ZMASK, ZT3, ZT3 // 3 vpmuludq ZH2, ZS3, ZB0 vporq PADBIT_ZMM, ZT4, ZT4 vpmuludq ZH2, ZS4, ZB1 vpaddq ZH0, ZT0, ZH0 vpmuludq ZH2, ZR0, ZB2 vpaddq ZH1, ZT1, ZH1 vpaddq ZH3, ZT3, ZH3 vpaddq ZH4, ZT4, ZH4 vmovdqu64 (INP), ZT3 vmovdqu64 64(INP), ZT4 lea 128(INP), INP vpmuludq ZH0, ZR3, ZM3 vpmuludq ZH0, ZR4, ZM4 vpmuludq ZH0, ZR0, ZM0 vpmuludq ZH0, ZR1, ZM1 vpaddq ZM3, ZB3, ZB3 vpaddq ZM4, ZB4, ZB4 vpaddq ZM0, ZB0, ZB0 vpaddq ZM1, ZB1, ZB1 vpmuludq ZH1, ZR2, ZM3 vpmuludq ZH1, ZR3, ZM4 vpmuludq ZH1, ZS4, ZM0 vpmuludq ZH0, ZR2, ZM2 vpaddq ZM3, ZB3, ZB3 vpaddq ZM4, ZB4, ZB4 vpaddq ZM0, ZB0, ZB0 vpaddq ZM2, ZB2, ZB2 vpunpcklqdq ZT4, ZT3, ZT0 vpunpckhqdq ZT4, ZT3, ZT4 vpmuludq ZH3, ZR0, ZM3 vpmuludq ZH3, ZR1, ZM4 vpmuludq ZH1, ZR0, ZM1 vpmuludq ZH1, ZR1, ZM2 vpaddq ZM3, ZB3, ZB3 vpaddq ZM4, ZB4, ZB4 vpaddq ZM1, ZB1, ZB1 vpaddq ZM2, ZB2, ZB2 vpmuludq ZH4, ZS4, ZM3 vpmuludq ZH4, ZR0, ZM4 vpmuludq ZH3, ZS2, ZM0 vpmuludq ZH3, ZS3, ZM1 vpmuludq ZH3, ZS4, ZM2 vpaddq ZM3, ZB3, ZB3 vpaddq ZM4, ZB4, ZB4 vpaddq ZM0, ZB0, ZB0 vpaddq ZM1, ZB1, ZB1 vpaddq ZM2, ZB2, ZB2 vpmuludq ZH4, ZS1, ZM0 vpmuludq ZH4, ZS2, ZM1 vpmuludq ZH4, ZS3, ZM2 vpaddq ZM0, ZB0, ZH0 vpaddq ZM1, ZB1, ZH1 vpaddq ZM2, ZB2, ZH2 vpsrlq $52, ZT0, ZT2 vpsllq $12, ZT4, ZT3 // reduction vpsrlq $26, ZB3, ZH3 vpandq ZMASK, ZB3, ZB3 vpaddq ZH3, ZB4, ZH4 vporq ZT3, ZT2, ZT2 vpsrlq $26, ZH0, ZB0 vpandq ZMASK, ZH0, ZH0 vpaddq ZB0, ZH1, ZH1 vpandq ZMASK, ZT2, ZT2 vpsrlq $26, ZH4, ZB4 vpandq ZMASK, ZH4, ZH4 vpsrlq $26, ZH1, ZB1 vpandq ZMASK, ZH1, ZH1 vpaddq ZB1, ZH2, ZH2 vpaddq ZB4, ZH0, ZH0 vpsllq $2, ZB4, ZB4 vpaddq ZB4, ZH0, ZH0 vpaddq ZT2, ZH2, ZH2 vpsrlq $26, ZT0, ZT1 vpsrlq $26, ZH2, ZB2 vpandq ZMASK, ZH2, ZH2 vpaddq ZB2, ZB3, ZH3 vpsrlq $14, ZT4, ZT3 vpsrlq $40, ZT4, ZT4 vpandq ZMASK, ZT0, ZT0 vpsrlq $26, ZH0, ZB0 vpandq ZMASK, ZH0, ZH0 vpaddq ZB0, ZH1, ZH1 vpsrlq $26, ZH3, ZB3 vpandq ZMASK, ZH3, ZH3 vpaddq ZB3, ZH4, ZH4 subq $128, LEN ja .Lblock_avx512_loop .align 32 .Lblock_avx512_tail: vpsrlq $32, ZR0, ZR0 // 1858286838784888 -> 0105020603070408 vpsrlq $32, ZR1, ZR1 vpsrlq $32, ZS1, ZS1 vpsrlq $32, ZR2, ZR2 vpsrlq $32, ZS2, ZS2 vpsrlq $32, ZR3, ZR3 vpsrlq $32, ZS3, ZS3 vpsrlq $32, ZR4, ZR4 vpsrlq $32, ZS4, ZS4 lea (INP, LEN), INP vpaddq ZH0, ZT0, ZH0 vpmuludq ZH2, ZR1, ZB3 vpandq ZMASK, ZT1, ZT1 vpmuludq ZH2, ZR2, ZB4 vpandq ZMASK, ZT3, ZT3 vpmuludq ZH2, ZS3, ZB0 vporq PADBIT_ZMM, ZT4, ZT4 vpmuludq ZH2, ZS4, ZB1 vpaddq ZH1, ZT1, ZH1 vpmuludq ZH2, ZR0, ZB2 vpaddq ZH3, ZT3, ZH3 vpaddq ZH4, ZT4, ZH4 vmovdqu (INP), %xmm5 vmovdqu 16(INP), %xmm6 vpmuludq ZH0, ZR3, ZM3 vpmuludq ZH0, ZR4, ZM4 vpmuludq ZH0, ZR0, ZM0 vpmuludq ZH0, ZR1, ZM1 vpaddq ZM3, ZB3, ZB3 vpaddq ZM4, ZB4, ZB4 vpaddq ZM0, ZB0, ZB0 vpaddq ZM1, ZB1, ZB1 vinserti128 $1, 32(INP), YT0, YT0 vinserti128 $1, 48(INP), YT1, YT1 vpmuludq ZH1, ZR2, ZM3 vpmuludq ZH1, ZR3, ZM4 vpmuludq ZH1, ZS4, ZM0 vpmuludq ZH0, ZR2, ZM2 vpaddq ZM3, ZB3, ZB3 vpaddq ZM4, ZB4, ZB4 vpaddq ZM0, ZB0, ZB0 vpaddq ZM2, ZB2, ZB2 vpmuludq ZH3, ZR0, ZM3 vpmuludq ZH3, ZR1, ZM4 vpmuludq ZH1, ZR0, ZM1 vpmuludq ZH1, ZR1, ZM2 vpaddq ZM3, ZB3, ZB3 vpaddq ZM4, ZB4, ZB4 vpaddq ZM1, ZB1, ZB1 vpaddq ZM2, ZB2, ZB2 vpmuludq ZH4, ZS4, ZM3 vpmuludq ZH4, ZR0, ZM4 vpmuludq ZH3, ZS2, ZM0 vpmuludq ZH3, ZS3, ZM1 vpmuludq ZH3, ZS4, ZM2 vpaddq ZM3, ZB3, ZH3 vpaddq ZM4, ZB4, ZB4 vpaddq ZM0, ZB0, ZB0 vpaddq ZM1, ZB1, ZB1 vpaddq ZM2, ZB2, ZB2 vpmuludq ZH4, ZS1, ZM0 vpmuludq ZH4, ZS2, ZM1 vpmuludq ZH4, ZS3, ZM2 vpaddq ZM0, ZB0, ZH0 vpaddq ZM1, ZB1, ZH1 vpaddq ZM2, ZB2, ZH2 // Summary of calculation results of different blocks movl $1, %eax kmovw %eax, %k3 vpermq $0xb1, ZH0, ZB0 vpermq $0xb1, ZH1, ZB1 vpermq $0xb1, ZH2, ZB2 vpermq $0xb1, ZH3, ZB3 vpermq $0xb1, ZB4, ZH4 vpaddq ZB0, ZH0, ZH0 vpaddq ZB1, ZH1, ZH1 vpaddq ZB2, ZH2, ZH2 vpaddq ZB3, ZH3, ZH3 vpaddq ZB4, ZH4, ZH4 vpermq $0x2, ZH0, ZB0 vpermq $0x2, ZH1, ZB1 vpermq $0x2, ZH2, ZB2 vpermq $0x2, ZH3, ZB3 vpermq $0x2, ZH4, ZB4 vpaddq ZB0, ZH0, ZH0 vpaddq ZB1, ZH1, ZH1 vpaddq ZB2, ZH2, ZH2 vpaddq ZB3, ZH3, ZH3 vpaddq ZB4, ZH4, ZH4 vextracti64x4 $0x1, ZH0, YB0 vextracti64x4 $0x1, ZH1, YB1 vextracti64x4 $0x1, ZH2, YB2 vextracti64x4 $0x1, ZH3, YB3 vextracti64x4 $0x1, ZH4, YB4 vpaddq ZB0, ZH0, ZH0{%k3}{z} vpaddq ZB1, ZH1, ZH1{%k3}{z} vpaddq ZB2, ZH2, ZH2{%k3}{z} vpaddq ZB3, ZH3, ZH3{%k3}{z} vpaddq ZB4, ZH4, ZH4{%k3}{z} // reduction vpsrlq $26, YH3, YB3 vpandq YMASK, YH3, YH3 vpaddq YB3, YH4, YH4 vpsrldq $6, YT0, YT2 vpsrldq $6, YT1, YT3 vpsrlq $26, YH0, YB0 vpandq YMASK, YH0, YH0 vpaddq YB0, YH1, YH1 vpunpckhqdq YT1, YT0, YT4 vpunpcklqdq YT1, YT0, YT0 vpunpcklqdq YT3, YT2, YT2 vpsrlq $26, YH4, YB4 vpandq YMASK, YH4, YH4 vpsrlq $26, YH1, YB1 vpandq YMASK, YH1, YH1 vpaddq YB1, YH2, YH2 vpsrlq $30, YT2, YT3 vpsrlq $4, YT2, YT2 vpaddq YB4, YH0, YH0 vpsllq $2, YB4, YB4 vpaddq YB4, YH0, YH0 vpsrlq $26, YT0, YT1 vpsrlq $40, YT4, YT4 vpsrlq $26, YH2, YB2 vpandq YMASK, YH2, YH2 vpaddq YB2, YH3, YH3 vpand YMASK, YT2, YT2 vpand YMASK, YT3, YT3 vpsrlq $26, YH0, YB0 vpandq YMASK, YH0, YH0 vpaddq YB0, YH1, YH1 vpaddq YH2, YT2, YH2 vpand YMASK, YT1, YT1 vpsrlq $26, YH3, YB3 vpand YMASK, YH3, YH3 vpaddq YB3, YH4, YH4 vpand YMASK, YT0, YT0 vpor g_129(%rip), YT4, YT4 addq $64, LEN jnz .Lblock_4_tail vpsubq YT2, YH2, YH2 jmp .Lblock_avx512_end .align 32 .Lblock_4_tail: BLOCK4_AVX2_TAIL YT0, YT1, YT2, YT3, YT4, YH0, YH1, YH2, YH3, YH4, YB0, YB1, YB2, YB3, YB4, YMASK, %rsp .Lblock_avx512_end: vmovd %xmm0, -56(CTX) vmovd %xmm1, -52(CTX) vmovd %xmm2, -48(CTX) vmovd %xmm3, -44(CTX) vmovd %xmm4, -40(CTX) vzeroall lea 8(%r11),%rsp pop %r15 pop %r14 pop %r13 pop %r12 pop %rbp pop %rbx movq LEN, %rax ret .cfi_endproc .size Poly1305BlockAVX512, .-Poly1305BlockAVX512 /** * Function description: This function is used to clear residual sensitive information in a register. * Function prototype: void Poly1305CleanRegister(); * Input register: None * Modify the register: * Output register: None * Function/Macro Call: None */ .globl Poly1305CleanRegister .type Poly1305CleanRegister,@function Poly1305CleanRegister: .cfi_startproc vzeroall vpxorq ZR0, ZR0, ZR0 vpxorq ZR1, ZR1, ZR1 vpxorq ZR2, ZR2, ZR2 vpxorq ZR3, ZR3, ZR3 vpxorq ZR4, ZR4, ZR4 vpxorq ZS1, ZS1, ZS1 vpxorq ZS2, ZS2, ZS2 vpxorq ZS3, ZS3, ZS3 vpxorq ZS4, ZS4, ZS4 vpxorq ZM0, ZM0, ZM0 vpxorq ZM1, ZM1, ZM1 vpxorq ZM2, ZM2, ZM2 vpxorq ZM3, ZM3, ZM3 vpxorq ZM4, ZM4, ZM4 ret .cfi_endproc .size Poly1305CleanRegister, .-Poly1305CleanRegister #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm/poly1305_x86_64_avx512.S
Unix Assembly
unknown
19,352
/* * 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_CHACHA20) && defined(HITLS_CRYPTO_CHACHA20POLY1305) .file "poly1305_x86_64_macro.s" .text .align 32 g_129: .long 1<<24, 0, 1<<24, 0, 1<<24, 0, 1<<24, 0 .size g_129, .-g_129 .align 32 g_mask26: .long 0x3ffffff, 0, 0x3ffffff, 0, 0x3ffffff, 0, 0x3ffffff, 0 .size g_mask26, .-g_mask26 .align 32 g_permd_avx2: .long 2, 2, 2, 3, 2, 0, 2, 1 .size g_permd_avx2, .-g_permd_avx2 .set CTX, %rdi .set INP, %rsi .set LEN, %rdx .set PADBIT, %rcx .set ACC1, %r14 .set ACC2, %rbx .set ACC3, %rbp .set D1, %r8 .set D2, %r9 .set D3, %r10 .set R0, %r11 .set R1, %r12 .set R2, %r13 .set YH0, %ymm0 .set YH1, %ymm1 .set YH2, %ymm2 .set YH3, %ymm3 .set YH4, %ymm4 .set YT0, %ymm5 .set YT1, %ymm6 .set YT2, %ymm7 .set YT3, %ymm8 .set YT4, %ymm9 .set YMASK, %ymm10 .set YB0, %ymm11 .set YB1, %ymm12 .set YB2, %ymm13 .set YB3, %ymm14 .set YB4, %ymm15 /** * Macro description: x86_64 poly1305 big number multiplication modulo basic instruction implementation (acc1|acc2|acc3) = (acc1|acc2|acc3) * (r0|r1) mod P * Input register: * acc1-3: accumulator * r0-1: key r * r2: r1 + (r1 >> 2) * Change register: r8-r14, rbx, rbp, rax * Output register: * acc1-3: result of the one block operation */ .macro POLY1305_MOD_MUL acc1 acc2 acc3 r0 r1 r2 mulq \acc1 // acc1 * r1 movq %rax, D2 movq \r0, %rax movq %rdx, D3 mulq \acc1 // acc1 * r0 movq %rax, \acc1 movq \r0, %rax movq %rdx, D1 mulq \acc2 // acc2 * r0 addq %rax, D2 movq \r2, %rax adcq %rdx, D3 mulq \acc2 // acc2 * (r1 + (r1 >> 2)) movq \acc3, \acc2 addq %rax, \acc1 adcq %rdx, D1 imulq \r2, \acc2 // acc3 * (r1 + (r1 >> 2)) addq \acc2, D2 movq D1, \acc2 adcq $0, D3 imulq \r0, \acc3 // acc3 * r0 mov $-4, %rax addq D2, \acc2 adcq \acc3, D3 andq D3, %rax // reduction movq D3, \acc3 shrq $2, D3 andq $3, \acc3 addq D3, %rax addq %rax, \acc1 adcq $0, \acc2 adcq $0, \acc3 .endm /** * Macro description: converts 130-bit base2^26 data into base 2^64 data. * Input register: * a1: large data block 0 in the original format * d1: large data block 1 in the original format * a2: large data block 2 in the original format * d2: large data block 3 in the original format * r2: big number of data blocks 2 and 3 in the original format * a3: large data block 4 in the original format * Modify the register r8, r9, r13, r14, rbx, rbp. * Output register: * a1: bits 0 to 63 of the converted big number * a2: 64-127 bits of the converted big number * a3: 128-130 bits of the converted big number * Function/Macro Call: None */ .macro CONVERT_26TO64 a1 d1 a2 d2 r2 a3 shrq $6, \d1 shlq $52, \r2 shrq $12, \a2 addq \d1, \a1 shrq $18, \d2 addq \r2, \a1 // 1st 64bit adcq \d2, \a2 movq \a3, \d1 shlq $40, \d1 shrq $24, \a3 addq \d1, \a2 // 2nd 64bit adcq $0, \a3 // 3rd 64bit .endm /** * Macro description: converts 130-bit base2^64 data to base 2^26 data. * Input register: * a1: large data block 0 in the original format * a2: large data block 1 in the original format * a3: large data block 2 in the original format * Modify the register: r8, r9, r14, rax, rdx, rbp, rbx. * Output register: * a4: 0 to 25 digits of the converted big number * a5: 26 to 51 digits of the converted big number * a1: 52 to 77 digits of the converted big number * a2: 78 to 103 bits of the converted big number * a3: 104-130 bits of the converted big number * Function/Macro Call: None */ .macro CONVERT_64TO26 a1 a2 a3 a4 a5 movq \a1, \a4 movq \a1, \a5 andq $0x3ffffff, \a4 // 1st 26bit shrq $26, \a5 movd \a4, %xmm0 andq $0x3ffffff, \a5 // 2nd 26bit shrq $52, \a1 movd \a5, %xmm1 movq \a2, D1 movq \a2, D2 shlq $12, D1 orq D1, \a1 andq $0x3ffffff, \a1 // 3rd 26bit shrq $14, \a2 movd \a1, %xmm2 shlq $24, \a3 andq $0x3ffffff, \a2 // 4th 26bit shrq $40, D2 movd \a2, %xmm3 orq D2, \a3 // 5th 26bit movl $1, 220(CTX) movd \a3, %xmm4 .endm /** * Macro description: preprocessing of converting base2^26 data to base 2^64 * Input register: 128 bits of acc1 and acc2 data * Change register: r8-r10, r14, and rbx. * Output register: acc1, acc2, d1, d2, d3 */ .macro CONVERT_26TO64_PRE acc1 acc2 d1 d2 d3 movq $0xffffffff, \d3 // base2_26 --> base2_64 movq \acc1, \d1 movq \acc2, \d2 andq \d3, \acc1 andq \d3, \acc2 andq $-1*(1<<31), \d1 movq \d2, \d3 andq $-1*(1<<31), \d2 .endm /** * Macro description: load accumulator data and key r * Input register: in_ctx context * Modify the register: r8, r11-r14, rax, rbp, rbx. * Output register: * r0 - r2: key r * acc1 - acc3: accumulator data * flag: indicates the data organization flag of the current accumulator. * mul: r1 */ .macro LOAD_ACC_R inctx r0 r1 r2 acc1 acc2 acc3 flag mul movq 24(\inctx), \r0 // load r movq 32(\inctx), \r1 movl 220(\inctx), \flag // judge the ACC organization form. movq \r1, \r2 movq (\inctx), \acc1 // load acc shrq $2, \r2 movq 8(\inctx), \acc2 addq \r1, \r2 // R2 = R1 + (R1 >> 2) movq 16(\inctx), \acc3 movq \r1, \mul .endm /** * Macro description: The avx2 instruction set implements parallel operation of the last four blocks. * Input register: * yh0 - yh4: stores messages. * yt0 - yt4: stores keys. * yb0 - yb4: temporary storage of intermediate results * addr: stack address * Output register: * yh0 - yh4: store operation results. */ .macro BLOCK4_AVX2_TAIL yt0 yt1 yt2 yt3 yt4 yh0 yh1 yh2 yh3 yh4 yb0 yb1 yb2 yb3 yb4 ymask addr vpaddq \yt0, \yh0, \yh0 vpaddq \yt1, \yh1, \yh1 vpaddq \yt3, \yh3, \yh3 vpaddq \yt4, \yh4, \yh4 vmovdqu 0x4(\addr), \yt0 // r0^i vmovdqu 0x24(\addr), \yt1 // r1^i vmovdqu 0x64(\addr), \yt2 // r2^i vmovdqu 0xc4(\addr), \yt3 // s3^i vmovdqu 0x104(\addr), \ymask // s4^i vpmuludq \yh2, \yt0, \yb2 // b2 = h2 * r0^i vpmuludq \yh2, \yt1, \yb3 // b3 = h2 * r1^i vpmuludq \yh2, \yt2, \yb4 // b4 = h2 * r2^i vpmuludq \yh2, \yt3, \yb0 // b0 = h2 * s3^i vpmuludq \yh2, \ymask, \yb1 // b1 = h2 * s4^i vpmuludq \yh1, \yt1, \yt4 // h1 * r1^i vpmuludq \yh0, \yt1, \yh2 // h0 * r1^i vpaddq \yt4, \yb2, \yb2 // b2 += h1 * r1^i vpaddq \yh2, \yb1, \yb1 // b1 += h0 * r1^i vpmuludq \yh3, \yt1, \yt4 // h3 * r1^i vpmuludq 0x44(\addr), \yh4, \yh2 // h4 * s1^i vpaddq \yt4, \yb4, \yb4 // b4 += h3 * r1^i vpaddq \yh2, \yb0, \yb0 // b0 += h4 * s1^i vmovdqu 0x84(\addr), \yt1 // load s2^i vpmuludq \yh4, \yt0, \yt4 // h4 * r0^i vpmuludq \yh3, \yt0, \yh2 // h3 * r0^i vpaddq \yt4, \yb4, \yb4 // b4 += h4 * r0^i vpaddq \yh2, \yb3, \yb3 // b3 += h3 * r0^i vpmuludq \yh0, \yt0, \yt4 // h0 * r0^i vpmuludq \yh1, \yt0, \yh2 // h1 * r0^i vpaddq \yt4, \yb0, \yb0 // b0 += h0 * r0^i vpaddq \yh2, \yb1, \yb1 // b1 += h1 * r0^i vpmuludq \yh1, \yt2, \yt4 // h1 * r2^i vpmuludq \yh0, \yt2, \yh2 // h0 * r2^i vpaddq \yt4, \yb3, \yb3 // b3 += h1 * r2^i vpaddq \yh2, \yb2, \yb2 // b2 += h0 * r2^i vpmuludq \yh4, \yt1, \yt4 // h4 * s2^i vpmuludq \yh3, \yt1, \yh2 // h3 * s2^i vpaddq \yt4, \yb1, \yb1 // b1 += h4 * s2^i vpaddq \yh2, \yb0, \yb0 // b0 += h3 * s2^i vmovdqu 0xa4(\addr), \yh2 // load r3^i vpmuludq \yh1, \yh2, \yt4 // h1 * r3^i vpmuludq \yh0, \yh2, \yh2 // h0 * r3^i vpaddq \yt4, \yb4, \yb4 // b4 += h1 * r3^i vpaddq \yh2, \yb3, \yb3 // b3 += h0 * r3^i vpmuludq \yh4, \yt3, \yt4 // h4 * s3^i vpmuludq \yh3, \yt3, \yh2 // h3 * s3^i vpaddq \yt4, \yb2, \yb2 // b2 += h4 * s3^i vpaddq \yh2, \yb1, \yb1 // b1 += h3 * s3^i (finish) vpmuludq \yh3, \ymask, \yh3 // h3 * s4^i vpmuludq \yh4, \ymask, \yh4 // h4 * s4^i vpaddq \yb2, \yh3, \yh2 // h2 += h3 * s4^i (finish) vpaddq \yb3, \yh4, \yh3 // h3 += h4 * s4^i (finish) vpmuludq 0xe4(\addr), \yh0, \yh4 // h0 * r4^i vpmuludq \yh1, \ymask, \yh0 // h1 * s4^i vmovdqu g_mask26(%rip), \ymask vpaddq \yh4, \yb4, \yh4 // h4 += h0 * r4^i (finish) vpaddq \yh0, \yb0, \yh0 // h0 += h1 * s4^i (finish) // Summary of calculation results of different blocks vpsrldq $8, \yh0, \yt0 vpsrldq $8, \yb1, \yt1 vpaddq \yt0, \yh0, \yh0 vpsrldq $8, \yh2, \yt2 vpaddq \yt1, \yb1, \yb1 vpsrldq $8, \yh3, \yt3 vpaddq \yt2, \yh2, \yh2 vpsrldq $8, \yh4, \yt4 vpaddq \yt3, \yh3, \yh3 vpaddq \yt4, \yh4, \yh4 vpermq $0x2, \yh0, \yt0 vpermq $0x2, \yb1, \yt1 vpaddq \yt0, \yh0, \yh0 vpermq $0x2, \yh2, \yt2 vpaddq \yt1, \yb1, \yb1 vpermq $0x2, \yh3, \yt3 vpaddq \yt2, \yh2, \yh2 vpermq $0x2, \yh4, \yt4 vpaddq \yt3, \yh3, \yh3 vpaddq \yt4, \yh4, \yh4 // reduction vpsrlq $26, \yh3, \yb3 vpand \ymask, \yh3, \yh3 vpaddq \yb3, \yh4, \yh4 // h3 -> h4 vpsrlq $26, \yh0, \yb0 vpand \ymask, \yh0, \yh0 vpaddq \yb0, \yb1, \yh1 // h0 -> h1 vpsrlq $26, \yh4, \yb4 vpand \ymask, \yh4, \yh4 vpsrlq $26, \yh1, \yb1 vpand \ymask, \yh1, \yh1 vpaddq \yb1, \yh2, \yh2 // h1 -> h2 vpaddq \yb4, \yh0, \yh0 vpsllq $2, \yb4, \yb4 vpaddq \yb4, \yh0, \yh0 // h4 -> h0 vpsrlq $26, \yh2, \yb2 vpand \ymask, \yh2, \yh2 vpaddq \yb2, \yh3, \yh3 // h2 -> h3 vpsrlq $26, \yh0, \yb0 vpand \ymask, \yh0, \yh0 vpaddq \yb0, \yh1, \yh1 // h0 -> h1 vpsrlq $26, \yh3, \yb3 vpand \ymask, \yh3, \yh3 vpaddq \yb3, \yh4, \yh4 // h3 -> h4 .endm #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm/poly1305_x86_64_macro.s
Unix Assembly
unknown
12,863
/* * 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_AES) && defined(HITLS_CRYPTO_CBC) #include "bsl_err_internal.h" #include "crypt_aes.h" #include "modes_local.h" #include "crypt_errno.h" #include "crypt_modes_cbc.h" int32_t AES_CBC_EncryptBlock(MODES_CipherCommonCtx *ctx, const uint8_t *in, uint8_t *out, uint32_t len) { if (ctx->ciphCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if ((len & 0x0f) != 0) { BSL_ERR_PUSH_ERROR(CRYPT_MODE_ERR_INPUT_LEN); return CRYPT_MODE_ERR_INPUT_LEN; } (void)CRYPT_AES_CBC_Encrypt(ctx->ciphCtx, in, out, len, ctx->iv); return CRYPT_SUCCESS; } int32_t AES_CBC_DecryptBlock(MODES_CipherCommonCtx *ctx, const uint8_t *in, uint8_t *out, uint32_t len) { if (ctx->ciphCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if ((len & 0x0f) != 0) { BSL_ERR_PUSH_ERROR(CRYPT_MODE_ERR_INPUT_LEN); return CRYPT_MODE_ERR_INPUT_LEN; } (void)CRYPT_AES_CBC_Decrypt(ctx->ciphCtx, in, out, len, ctx->iv); return CRYPT_SUCCESS; } int32_t AES_CBC_Update(MODES_CipherCtx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { return MODES_CipherUpdate(modeCtx, modeCtx->enc ? AES_CBC_EncryptBlock : AES_CBC_DecryptBlock, in, inLen, out, outLen); } int32_t AES_CBC_Final(MODES_CipherCtx *modeCtx, uint8_t *out, uint32_t *outLen) { return MODES_CipherFinal(modeCtx, modeCtx->enc ? AES_CBC_EncryptBlock : AES_CBC_DecryptBlock, out, outLen); } #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm_aes_cbc.c
C
unknown
2,185
/* * 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_AES) && defined(HITLS_CRYPTO_CCM) #include "bsl_err_internal.h" #include "crypt_errno.h" #include "asm_aes_ccm.h" #include "ccm_core.h" #include "crypt_modes_ccm.h" #include "modes_local.h" static int32_t AesCcmBlocks(MODES_CipherCCMCtx *ctx, const uint8_t *in, uint8_t *out, uint32_t len, bool enc) { if (ctx->ciphCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } XorCryptData data; data.in = in; data.out = out; data.ctr = ctx->last; data.tag = ctx->tag; uint8_t countLen = (ctx->nonce[0] & 0x07) + 1; uint32_t dataLen = len; void (*xor)(XorCryptData *data, uint32_t len) = enc ? XorInEncrypt : XorInDecrypt; void (*crypt_asm)(void *key, uint8_t *nonce, const uint8_t *in, uint8_t *out, uint32_t len) = enc ? AesCcmEncryptAsm : AesCcmDecryptAsm; crypt_asm(ctx->ciphCtx, ctx->nonce, data.in, data.out, dataLen); uint32_t tmpOffset = dataLen & 0xfffffff0; dataLen &= 0x0fU; data.in += tmpOffset; data.out += tmpOffset; if (dataLen > 0) { // data processing with less than 16 bytes (void)ctx->ciphMeth->encryptBlock(ctx->ciphCtx, ctx->nonce, ctx->last, CCM_BLOCKSIZE); xor(&data, dataLen); MODE_IncCounter(ctx->nonce + CCM_BLOCKSIZE - countLen, countLen); // counter +1 } return CRYPT_SUCCESS; } int32_t MODES_AES_CCM_Encrypt(MODES_CipherCCMCtx *ctx, const uint8_t *in, uint8_t *out, uint32_t len) { return CcmCrypt(ctx, in, out, len, true, AesCcmBlocks); } int32_t MODES_AES_CCM_Decrypt(MODES_CipherCCMCtx *ctx, const uint8_t *in, uint8_t *out, uint32_t len) { return CcmCrypt(ctx, in, out, len, false, AesCcmBlocks); } int32_t AES_CCM_Update(MODES_CCM_Ctx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { return MODES_CipherStreamProcess(modeCtx->enc ? MODES_AES_CCM_Encrypt : MODES_AES_CCM_Decrypt, &modeCtx->ccmCtx, in, inLen, out, outLen); } #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm_aes_ccm.c
C
unknown
2,558
/* * 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 ASM_AES_CCM_H #define ASM_AES_CCM_H #include "hitls_build.h" #if defined(HITLS_CRYPTO_AES) && defined(HITLS_CRYPTO_CCM) #include "crypt_utils.h" #include "modes_local.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus void AesCcmEncryptAsm(void *key, uint8_t *nonce, const uint8_t *in, uint8_t *out, uint32_t len); void AesCcmDecryptAsm(void *key, uint8_t *nonce, const uint8_t *in, uint8_t *out, uint32_t len); void XorInDecrypt(XorCryptData *data, uint32_t len); void XorInEncrypt(XorCryptData *data, uint32_t len); void XorInEncryptBlock(XorCryptData *data); void XorInDecryptBlock(XorCryptData *data); #ifdef __cplusplus } #endif // __cplusplus #endif #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm_aes_ccm.h
C
unknown
1,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" #if defined(HITLS_CRYPTO_AES) && defined(HITLS_CRYPTO_CFB) #include "bsl_err_internal.h" #include "crypt_aes.h" #include "crypt_errno.h" #include "crypt_modes_cfb.h" #include "modes_local.h" /* Decrypt the 128-bit CFB. Here, len indicates the number of bytes to be processed. */ static int32_t CRYPT_AES_CFB16_Decrypt(MODES_CipherCFBCtx *ctx, const uint8_t *in, uint8_t *out, uint32_t len) { if (ctx->modeCtx.ciphCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } const uint8_t *input = in; uint8_t *output = out; uint8_t *tmp = ctx->modeCtx.buf; uint32_t blockSize = ctx->modeCtx.blockSize; uint32_t left = len; uint32_t i, k; // If the remaining encryption iv is not used up last time, use the part to perform exclusive OR. while (left > 0 && ctx->modeCtx.offset > 0) { uint8_t tmpInput = *input; // To support the same address in and out *(output++) = ctx->modeCtx.iv[ctx->modeCtx.offset] ^ *(input++); // Write the iv to ciphertext to prepare for the next round of encryption. ctx->modeCtx.iv[ctx->modeCtx.offset] = tmpInput; ctx->modeCtx.offset = (ctx->modeCtx.offset + 1) % blockSize; left--; } if (left >= blockSize) { uint32_t processedLen = left - (left % blockSize); (void)CRYPT_AES_CFB_Decrypt(ctx->modeCtx.ciphCtx, input, output, processedLen, ctx->modeCtx.iv); UPDATE_VALUES(left, input, output, processedLen); } if (left > 0) { // encrypt the IV int32_t ret = ctx->modeCtx.ciphMeth->encryptBlock(ctx->modeCtx.ciphCtx, ctx->modeCtx.iv, tmp, blockSize); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } for (i = 0, k = 0; k < left; k++, i++) { // Write the iv to ciphertext to prepare for the next round of encryption. ctx->modeCtx.iv[i] = input[k]; output[k] = input[k] ^ tmp[k]; } while (i < blockSize) { ctx->modeCtx.iv[i++] = tmp[k++]; } ctx->modeCtx.offset = (uint8_t)left; } return CRYPT_SUCCESS; } int32_t MODE_AES_CFB_Decrypt(MODES_CipherCFBCtx *ctx, const uint8_t *in, uint8_t *out, uint32_t len) { if (ctx == NULL || in == NULL || out == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->feedbackBits == 128) { // feedbackBits 128 has assembly optimization return CRYPT_AES_CFB16_Decrypt(ctx, in, out, len); } else { // no optimization return MODES_CFB_Decrypt(ctx, in, out, len); } } int32_t AES_CFB_Update(MODES_CFB_Ctx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { return MODES_CipherStreamProcess(modeCtx->enc ? MODES_CFB_Encrypt : MODE_AES_CFB_Decrypt, &modeCtx->cfbCtx, in, inLen, out, outLen); } #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm_aes_cfb.c
C
unknown
3,485
/* * 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_AES) && defined(HITLS_CRYPTO_CTR) #include "bsl_err_internal.h" #include "crypt_aes.h" #include "crypt_errno.h" #include "crypt_utils.h" #include "crypt_modes_ctr.h" #include "modes_local.h" int32_t AES_CTR_EncryptBlock(MODES_CipherCommonCtx *ctx, const uint8_t *in, uint8_t *out, uint32_t len) { // The ctx, in, and out pointers have been determined at the EAL layer and are not determined again. if (ctx->ciphCtx == NULL || len == 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } uint32_t left = len; const uint8_t *tmpIn = in; uint8_t *tmpOut = out; while ((ctx->offset != 0) && (left > 0)) { *(tmpOut++) = ((*(tmpIn++)) ^ (ctx->buf[ctx->offset++])); --left; ctx->offset &= (uint8_t)(ctx->blockSize - 1); } uint32_t blockSize = ctx->blockSize; // ctr supports only 16-byte block size uint32_t blocks, beCtr32; while (left >= blockSize) { blocks = left >> 4; // Shift rightwards by 4 bytes to obtain the number of blocks. beCtr32 = GET_UINT32_BE(ctx->iv, 12); // offset of 12 bytes, it is used to obtain the lower 32 bits of IV beCtr32 += blocks; if (beCtr32 < blocks) { blocks -= beCtr32; beCtr32 = 0; } // Shift leftwards by 4 bytes to obtain the length of the data involved in the calculation. uint32_t calLen = blocks << 4; (void)CRYPT_AES_CTR_Encrypt(ctx->ciphCtx, tmpIn, tmpOut, calLen, ctx->iv); left -= calLen; tmpIn += calLen; tmpOut += calLen; if (beCtr32 == 0) { // 16 - 4, the lower 32 bits are carried, and the upper 12 bytes are increased by 1. MODE_IncCounter(ctx->iv, blockSize - 4); } } if (left > 0) { (void)ctx->ciphMeth->encryptBlock(ctx->ciphCtx, ctx->iv, ctx->buf, blockSize); MODE_IncCounter(ctx->iv, ctx->blockSize); ctx->offset = 0; while ((left) > 0) { tmpOut[ctx->offset] = (tmpIn[ctx->offset]) ^ (ctx->buf[ctx->offset]); --left; ++ctx->offset; } } return CRYPT_SUCCESS; } int32_t AES_CTR_Update(MODES_CipherCtx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { return MODES_CipherStreamProcess(AES_CTR_EncryptBlock, &modeCtx->commonCtx, in, inLen, out, outLen); } #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm_aes_ctr.c
C
unknown
3,061
/* * 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_AES) && defined(HITLS_CRYPTO_ECB) #include "bsl_err_internal.h" #include "crypt_aes.h" #include "crypt_errno.h" #include "crypt_modes_ecb.h" #include "modes_local.h" int32_t AES_ECB_EncryptBlock(MODES_CipherCommonCtx *ctx, const uint8_t *in, uint8_t *out, uint32_t len) { if (ctx->ciphCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if ((len & 0x0f) != 0) { BSL_ERR_PUSH_ERROR(CRYPT_MODE_ERR_INPUT_LEN); return CRYPT_MODE_ERR_INPUT_LEN; } (void)CRYPT_AES_ECB_Encrypt(ctx->ciphCtx, in, out, len); return CRYPT_SUCCESS; } int32_t AES_ECB_DecryptBlock(MODES_CipherCommonCtx *ctx, const uint8_t *in, uint8_t *out, uint32_t len) { if (ctx->ciphCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if ((len & 0x0f) != 0) { BSL_ERR_PUSH_ERROR(CRYPT_MODE_ERR_INPUT_LEN); return CRYPT_MODE_ERR_INPUT_LEN; } (void)CRYPT_AES_ECB_Decrypt(ctx->ciphCtx, in, out, len); return CRYPT_SUCCESS; } int32_t AES_ECB_Update(MODES_CipherCtx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { return MODES_CipherUpdate(modeCtx, modeCtx->enc ? AES_ECB_EncryptBlock : AES_ECB_DecryptBlock, in, inLen, out, outLen); } int32_t AES_ECB_Final(MODES_CipherCtx *modeCtx, uint8_t *out, uint32_t *outLen) { return MODES_CipherFinal(modeCtx, modeCtx->enc ? AES_ECB_EncryptBlock : AES_ECB_DecryptBlock, out, outLen); } #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm_aes_ecb.c
C
unknown
2,167
/* * 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_AES) && defined(HITLS_CRYPTO_GCM) #include "crypt_aes.h" #include "asm_aes_gcm.h" #include "modes_local.h" #include "crypt_utils.h" #include "crypt_errno.h" #include "crypt_modes_gcm.h" int32_t AES_GCM_EncryptBlock(MODES_CipherGCMCtx *ctx, const uint8_t *in, uint8_t *out, uint32_t len) { if (ctx->ciphCtx == NULL) { return CRYPT_NULL_INPUT; } int32_t ret = CryptLenCheckAndRefresh(ctx, len); if (ret != CRYPT_SUCCESS) { return ret; } uint32_t lastLen = MODES_GCM_LastHandle(ctx, in, out, len, true); // Data processing is complete. Exit. if (lastLen == len) { return CRYPT_SUCCESS; } uint32_t clen = len - lastLen; if (clen >= 64) { // If the value is greater than 64, the logic for processing large blocks is used. // invoke the assembly API uint32_t finishedLen = AES_GCM_EncryptBlockAsm(ctx, in + lastLen, out + lastLen, clen, ctx->ciphCtx); lastLen += finishedLen; // add the processed length clen -= finishedLen; // subtract the processed length } if (clen >= 16) { // Remaining 16, use small block processing logic AES_GCM_Encrypt16BlockAsm(ctx, in + lastLen, out + lastLen, clen, ctx->ciphCtx); // call the assembly API lastLen += clen & 0xfffffff0; clen = clen & 0x0f; // take the remainder of 16 } AES_GCM_ClearAsm(); // clear the Neon register if (clen > 0) { // tail processing uint32_t ctr = GET_UINT32_BE(ctx->iv, 12); ret = ctx->ciphMeth->encryptBlock(ctx->ciphCtx, ctx->iv, ctx->last, GCM_BLOCKSIZE); if (ret != CRYPT_SUCCESS) { return ret; } uint32_t i; // encryption const uint8_t *cin = (const uint8_t *)(in + lastLen); uint8_t *cout = out + lastLen; for (i = 0; i < clen; i++) { cout[i] = cin[i] ^ ctx->last[i]; ctx->remCt[i] = cout[i]; } ctr++; PUT_UINT32_BE(ctr, ctx->iv, 12); // offset of 12 bytes, the last four bytes are used ctx->lastLen = GCM_BLOCKSIZE - clen; } return CRYPT_SUCCESS; } int32_t AES_GCM_DecryptBlock(MODES_CipherGCMCtx *ctx, const uint8_t *in, uint8_t *out, uint32_t len) { if (ctx->ciphCtx == NULL) { return CRYPT_NULL_INPUT; } int32_t ret = CryptLenCheckAndRefresh(ctx, len); if (ret != CRYPT_SUCCESS) { return ret; } uint32_t lastLen = MODES_GCM_LastHandle(ctx, in, out, len, false); // Data processing is complete. Exit. if (lastLen == len) { return CRYPT_SUCCESS; } uint32_t clen = len - lastLen; if (clen >= 64) { // If the value is greater than 64, the logic for processing large blocks is used. // invoke the assembly API uint32_t finishedLen = AES_GCM_DecryptBlockAsm(ctx, in + lastLen, out + lastLen, clen, ctx->ciphCtx); lastLen += finishedLen; // add the processed length clen -= finishedLen; // subtract the processed length } if (clen >= 16) { // Remaining 16, use small block processing logic AES_GCM_Decrypt16BlockAsm(ctx, in + lastLen, out + lastLen, clen, ctx->ciphCtx); // call the assembly API lastLen += clen & 0xfffffff0; clen = clen & 0x0f; // take the remainder of 16 } AES_GCM_ClearAsm(); // clear the Neon register if (clen > 0) { // tail processing uint32_t ctr = GET_UINT32_BE(ctx->iv, 12); ret = ctx->ciphMeth->encryptBlock(ctx->ciphCtx, ctx->iv, ctx->last, GCM_BLOCKSIZE); if (ret != CRYPT_SUCCESS) { return ret; } uint32_t i; // encryption const uint8_t *cin = (const uint8_t *)(in + lastLen); uint8_t *cout = out + lastLen; for (i = 0; i < clen; i++) { ctx->remCt[i] = cin[i]; cout[i] = cin[i] ^ ctx->last[i]; } ctr++; PUT_UINT32_BE(ctr, ctx->iv, 12); // offset of 12 bytes, the last four bytes are used ctx->lastLen = GCM_BLOCKSIZE - clen; } return CRYPT_SUCCESS; } int32_t AES_GCM_Update(MODES_GCM_Ctx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { return MODES_CipherStreamProcess(modeCtx->enc ? AES_GCM_EncryptBlock : AES_GCM_DecryptBlock, &modeCtx->gcmCtx, in, inLen, out, outLen); } #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm_aes_gcm.c
C
unknown
4,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. */ #ifndef ASM_AES_GCM_H #define ASM_AES_GCM_H #include "hitls_build.h" #if defined(HITLS_CRYPTO_AES) && defined(HITLS_CRYPTO_GCM) #include "crypt_modes_gcm.h" #include "modes_local.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus uint32_t AES_GCM_EncryptBlockAsm(MODES_CipherGCMCtx *ctx, const uint8_t *in, uint8_t *out, uint32_t len, void *key); uint32_t AES_GCM_DecryptBlockAsm(MODES_CipherGCMCtx *ctx, const uint8_t *in, uint8_t *out, uint32_t len, void *key); void AES_GCM_Encrypt16BlockAsm(MODES_CipherGCMCtx *ctx, const uint8_t *in, uint8_t *out, uint32_t len, void *key); void AES_GCM_Decrypt16BlockAsm(MODES_CipherGCMCtx *ctx, const uint8_t *in, uint8_t *out, uint32_t len, void *key); void AES_GCM_ClearAsm(void); #ifdef __cplusplus } #endif // __cplusplus #endif #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm_aes_gcm.h
C
unknown
1,334
/* * 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_AES) && defined(HITLS_CRYPTO_XTS) #include "securec.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "crypt_utils.h" #include "crypt_errno.h" #include "crypt_aes.h" #include "crypt_modes_xts.h" #include "modes_local.h" int32_t MODES_AES_XTS_Encrypt(MODES_CipherXTSCtx *xtsCtx, const uint8_t *in, uint8_t *out, uint32_t len) { if (xtsCtx == NULL || in == NULL || out == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (len < xtsCtx->blockSize) { BSL_ERR_PUSH_ERROR(CRYPT_MODE_ERR_INPUT_LEN); return CRYPT_MODE_ERR_INPUT_LEN; } (void)CRYPT_AES_XTS_Encrypt(xtsCtx->ciphCtx, in, out, len, xtsCtx->tweak); return CRYPT_SUCCESS; } int32_t MODES_AES_XTS_Decrypt(MODES_CipherXTSCtx *xtsCtx, const uint8_t *in, uint8_t *out, uint32_t len) { if (xtsCtx == NULL || in == NULL || out == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (len < xtsCtx->blockSize) { BSL_ERR_PUSH_ERROR(CRYPT_MODE_BUFF_LEN_NOT_ENOUGH); return CRYPT_MODE_BUFF_LEN_NOT_ENOUGH; } (void)CRYPT_AES_XTS_Decrypt(xtsCtx->ciphCtx, in, out, len, xtsCtx->tweak); return CRYPT_SUCCESS; } int32_t AES_XTS_Update(MODES_XTS_Ctx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { return MODES_CipherStreamProcess(modeCtx->enc ? MODES_AES_XTS_Encrypt : MODES_AES_XTS_Decrypt, &modeCtx->xtsCtx, in, inLen, out, outLen); } #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm_aes_xts.c
C
unknown
2,099
/* * 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_SM4) && defined(HITLS_CRYPTO_CBC) #include "bsl_err_internal.h" #include "crypt_sm4.h" #include "crypt_errno.h" #include "crypt_modes_cbc.h" #include "modes_local.h" int32_t MODE_SM4_CBC_Encrypt(MODES_CipherCommonCtx *ctx, const uint8_t *in, uint8_t *out, uint32_t len) { if (ctx == NULL || in == NULL || out == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } return CRYPT_SM4_CBC_Encrypt(ctx->ciphCtx, in, out, len, ctx->iv); } int32_t MODE_SM4_CBC_Decrypt(MODES_CipherCommonCtx *ctx, const uint8_t *in, uint8_t *out, uint32_t len) { if (ctx == NULL || in == NULL || out == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } return CRYPT_SM4_CBC_Decrypt(ctx->ciphCtx, in, out, len, ctx->iv); } int32_t SM4_CBC_Update(MODES_CipherCtx *modeCtx, const uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen) { return MODES_CipherUpdate(modeCtx, modeCtx->enc ? MODE_SM4_CBC_Encrypt : MODE_SM4_CBC_Decrypt, in, inLen, out, outLen); } int32_t SM4_CBC_Final(MODES_CipherCtx *modeCtx, uint8_t *out, uint32_t *outLen) { return MODES_CipherFinal(modeCtx, modeCtx->enc ? MODE_SM4_CBC_Encrypt : MODE_SM4_CBC_Decrypt, out, outLen); } int32_t SM4_CBC_InitCtx(MODES_CipherCtx *modeCtx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv, uint32_t ivLen, bool enc) { void *setKey = enc ? MODES_SM4_SetEncryptKey : MODES_SM4_SetDecryptKey; return MODES_CipherInitCtx(modeCtx, setKey, &modeCtx->commonCtx, key, keyLen, iv, ivLen, enc); } #endif
2302_82127028/openHiTLS-examples_1508
crypto/modes/src/asm_sm4_cbc.c
C
unknown
2,168