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.
*/
#ifndef CRYPT_BN_H
#define CRYPT_BN_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_BN
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
#if defined(HITLS_SIXTY_FOUR_BITS)
#define BN_UINT uint64_t
#define BN_MASK (0xffffffffffffffffL)
#define BN_DEC_VAL (10000000000000000000ULL)
#define BN_DEC_LEN 19
#define BN_UNIT_BITS 64
#elif defined(HITLS_THIRTY_TWO_BITS)
#define BN_UINT uint32_t
#define BN_MASK (0xffffffffL)
#define BN_DEC_VAL (1000000000L)
#define BN_DEC_LEN 9
#define BN_UNIT_BITS 32
#else
#error BN_UINT MUST be defined first.
#endif
#define BN_MAX_BITS (1u << 29) /* @note: BN_BigNum bits limitation 2^29 bits */
#define BN_BITS_TO_BYTES(n) (((n) + 7) >> 3) /* @note: Calcute bytes form bits, bytes = (bits + 7) >> 3 */
#define BN_BYTES_TO_BITS(n) ((n) << 3) /* bits = bytes * 8 = bytes << 3 */
#define BN_UINT_BITS ((uint32_t)sizeof(BN_UINT) << 3)
#define BITS_TO_BN_UNIT(bits) (((bits) + BN_UINT_BITS - 1) / BN_UINT_BITS)
/* Flag of BigNum. If a new number is added, the value increases by 0x01 0x02 0x04... */
typedef enum {
CRYPT_BN_FLAG_OPTIMIZER = 0x01, /**< Flag of BigNum, indicating the BigNum obtained from the optimizer */
CRYPT_BN_FLAG_STATIC = 0x02, /**< Flag of BigNum, indicating the BN memory management belongs to the user. */
CRYPT_BN_FLAG_CONSTTIME = 0x04, /**< Flag of BigNum, indicating the constant time execution. */
} CRYPT_BN_FLAG;
typedef struct BigNum {
bool sign; /* *< bignum sign: negtive(true) or not(false) */
uint32_t size; /* *< bignum size (count of BN_UINT) */
uint32_t room; /* *< bignum max size (count of BN_UINT) */
uint32_t flag; /* *< bignum flag */
BN_UINT *data; /* *< bignum data chunk(most significant limb at the largest) */
} BN_BigNum;
typedef struct BnMont BN_Mont;
typedef struct BnOptimizer BN_Optimizer;
typedef struct BnCbCtx BN_CbCtx;
typedef int32_t (*BN_CallBack)(BN_CbCtx *, int32_t, int32_t);
/* If a is 0, all Fs are returned. If a is not 0, 0 is returned. */
static inline BN_UINT BN_IsZeroUintConsttime(BN_UINT a)
{
BN_UINT t = ~a & (a - 1); // The most significant bit of t is 1 only when a == 0.
// Shifting 3 bits to the left is equivalent to multiplying 8, convert the number of bytes into the number of bits.
return (BN_UINT)0 - (t >> (((uint32_t)sizeof(BN_UINT) << 3) - 1));
}
#ifdef HITLS_CRYPTO_EAL_BN
/* Check whether the BN entered externally is valid. */
bool BnVaild(const BN_BigNum *a);
#endif
/**
* @ingroup bn
* @brief BigNum creation
*
* @param bits [IN] Number of bits
*
* @retval not-NULL Success
* @retval NULL fail
*/
BN_BigNum *BN_Create(uint32_t bits);
/**
* @ingroup bn
* @brief BigNum Destruction
*
* @param a [IN] BigNum
*
* @retval none
*/
void BN_Destroy(BN_BigNum *a);
/**
* @ingroup bn
* @brief BN initialization
* @attention This interface is used to create the BN structure between modules. The BN does not manage the memory of
the external BN structure and internal data space. the interface only the fixed attributes such as data,
room, and flag. The size attribute is defined by the caller.
*
* @param bn [IN/OUT] BN, which is created by users and is not managed by the BN.
* @param data [IN] BN data, the memory is allocated by the user and is not managed by the BN.
* @param number [IN] number of BN that need to be initialized.
*
* @retval void
*/
void BN_Init(BN_BigNum *bn, BN_UINT *data, uint32_t room, int32_t number);
#ifdef HITLS_CRYPTO_BN_CB
/**
* @ingroup bn
* @brief BigNum callback creation
*
* @param none
*
* @retval not-NULL Success
* @retval NULL fail
*/
BN_CbCtx *BN_CbCtxCreate(void);
/**
* @ingroup bn
* @brief BigNum callback configuration
*
* @param gencb [out] Callback
* @param callBack [in] Callback API
* @param arg [in] Callback parameters
*
* @retval none
*/
void BN_CbCtxSet(BN_CbCtx *gencb, BN_CallBack callBack, void *arg);
/**
* @ingroup bn
* @brief Invoke the callback.
*
* @param callBack [out] Callback
* @param process [in] Parameter
* @param target [in] Parameter
* @retval CRYPT_SUCCESS succeeded
* @retval other determined by the callback function
*/
int32_t BN_CbCtxCall(BN_CbCtx *callBack, int32_t process, int32_t target);
/**
* @ingroup bn
* @brief Obtain the arg parameter in the callback.
*
* @param callBack [in] Callback
* @retval void* NULL or callback parameter.
*/
void *BN_CbCtxGetArg(BN_CbCtx *callBack);
/**
* @ingroup bn
* @brief Callback release
*
* @param cb [in] Callback
*
* @retval none
*/
void BN_CbCtxDestroy(BN_CbCtx *cb);
#endif
/**
* @ingroup bn
* @brief Set the symbol.
*
* @param a [IN] BigNum
* @param sign [IN] symbol. The value true indicates a negative number and the value false indicates a positive number.
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_BN_NO_NEGATOR_ZERO 0 cannot be set to a negative sign.
*/
int32_t BN_SetSign(BN_BigNum *a, bool sign);
/**
* @ingroup bn
* @brief Set the flag.
*
* @param a [IN] BigNum
* @param flag [IN] flag, for example, BN_MARK_CONSTTIME indicates that the constant interface is used.
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_BN_FLAG_INVALID Invalid BigNum flag.
*/
int32_t BN_SetFlag(BN_BigNum *a, uint32_t flag);
/**
* @ingroup bn
* @brief BigNum copy
*
* @param r [OUT] BigNum
* @param a [IN] BigNum
*
* @retval CRYPT_SUCCESS succeeded.
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
*/
int32_t BN_Copy(BN_BigNum *r, const BN_BigNum *a);
/**
* @ingroup bn
* @brief Generate a BigNum with the same content.
*
* @param a [IN] BigNum
*
* @retval Not NULL Success
* @retval NULL failure
*/
BN_BigNum *BN_Dup(const BN_BigNum *a);
/**
* @ingroup bn
* @brief Check whether the value of a BigNum is 0.
*
* @attention The input parameter cannot be null.
* @param a [IN] BigNum
*
* @retval true. The value of a BigNum is 0.
* @retval false. The value of a BigNum is not 0.
* @retval other: indicates that the input parameter is abnormal.
*
*/
bool BN_IsZero(const BN_BigNum *a);
/**
* @ingroup bn
* @brief Check whether the value of a BigNum is 1.
*
* @attention The input parameter cannot be null.
* @param a [IN] BigNum
*
* @retval true. The value of a BigNum is 1.
* @retval false. The value of a BigNum is not 1.
* @retval other: indicates that the input parameter is abnormal.
*
*/
bool BN_IsOne(const BN_BigNum *a);
/**
* @ingroup bn
* @brief Check whether a BigNum is a negative number.
*
* @attention The input parameter cannot be null.
* @param a [IN] BigNum
*
* @retval true. The value of a BigNum is a negative number.
* @retval false. The value of a BigNum is not a negative number.
*
*/
bool BN_IsNegative(const BN_BigNum *a);
/**
* @ingroup bn
* @brief Check whether the value of a BigNum is an odd number.
*
* @attention The input parameter cannot be null.
* @param a [IN] BigNum
*
* @retval true. The value of a BigNum is an odd number.
* @retval false. The value of a BigNum is not an odd number.
* @retval other: indicates that the input parameter is abnormal.
*
*/
bool BN_IsOdd(const BN_BigNum *a);
/**
* @ingroup bn
* @brief Check whether the flag of a BigNum meets the expected flag.
*
* @param a [IN] BigNum
* @param flag [IN] Flag. For example, BN_MARK_CONSTTIME indicates that the constant interface is used.
*
* @retval true, invalid null pointer
* @retval false, 0 cannot be set to a negative number.
* @retval other: indicates that the input parameter is abnormal.
*/
bool BN_IsFlag(const BN_BigNum *a, uint32_t flag);
/**
* @ingroup bn
* @brief Set the value of a BigNum to 0.
*
* @param a [IN] BigNum
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval other: indicates that the input parameter is abnormal.
*/
int32_t BN_Zeroize(BN_BigNum *a);
/**
* @ingroup bn
* @brief Compare whether the value of BigNum a is the target limb w.
*
* @attention The input parameter cannot be null.
* @param a [IN] BigNum
* @param w [IN] Limb
*
* @retval true: equal
* @retval false, not equal
* @retval other: indicates that the input parameter is abnormal.
*/
bool BN_IsLimb(const BN_BigNum *a, const BN_UINT w);
/**
* @ingroup bn
* @brief Set a limb to the BigNum.
*
* @param a [IN] BigNum
* @param w [IN] Limb
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
*/
int32_t BN_SetLimb(BN_BigNum *r, BN_UINT w);
/**
* @ingroup bn
* @brief Obtain the limb from the BigNum.
*
* @param a [IN] BigNum
*
* @retval 0 Get 0
* @retval BN_MASK Obtain the mask.
* @retval others The limb is obtained successfully.
*/
BN_UINT BN_GetLimb(const BN_BigNum *a);
/**
* @ingroup bn
* @brief Obtain the value of the bit corresponding to a BigNum. The value is 1 or 0.
*
* @attention The input parameter of a BigNum cannot be null.
* @param a [IN] BigNum
* @param n [IN] Number of bits
*
* @retval true. The corresponding bit is 1.
* @retval false. The corresponding bit is 0.
*
*/
bool BN_GetBit(const BN_BigNum *a, uint32_t n);
/**
* @ingroup bn
* @brief Set the bit corresponding to the BigNum to 1.
*
* @param a [IN] BigNum
* @param n [IN] Number of bits
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_BN_SPACE_NOT_ENOUGH The space is insufficient.
*/
int32_t BN_SetBit(BN_BigNum *a, uint32_t n);
/**
* @ingroup bn
* @brief Clear the bit corresponding to the BigNum to 0.
*
* @param a [IN] BigNum
* @param n [IN] Number of bits
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_BN_SPACE_NOT_ENOUGH The space is insufficient.
*/
int32_t BN_ClrBit(BN_BigNum *a, uint32_t n);
/**
* @ingroup bn
* @brief Truncate a BigNum from the corresponding bit.
*
* @param a [IN] BigNum
* @param n [IN] Number of bits
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_BN_SPACE_NOT_ENOUGH The space is insufficient.
*/
int32_t BN_MaskBit(BN_BigNum *a, uint32_t n);
/**
* @ingroup bn
* @brief Obtain the valid bit length of a BigNum.
*
* @attention The input parameter of a BigNum cannot be null.
* @param a [IN] BigNum
*
* @retval uint32_t, valid bit length
*/
uint32_t BN_Bits(const BN_BigNum *a);
/**
* @ingroup bn
* @brief Obtain the valid byte length of a BigNum.
*
* @attention The large input parameter cannot be a null pointer.
* @param a [IN] BigNum
*
* @retval uint32_t, valid byte length of a BigNum
*/
uint32_t BN_Bytes(const BN_BigNum *a);
/**
* @ingroup bn
* @brief BigNum Calculate the greatest common divisor
* @par Description: gcd(a, b) (a, b!=0)
*
* @param r [OUT] greatest common divisor
* @param a [IN] BigNum
* @param b [IN] BigNum
* @param opt [IN] Optimizer
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer.
* @retval CRYPT_BN_ERR_GCD_NO_ZERO The greatest common divisor cannot be 0.
*/
int32_t BN_Gcd(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, BN_Optimizer *opt);
/**
* @ingroup bn
* @brief BigNum modulo inverse
*
* @param r [OUT] Result
* @param x [IN] BigNum
* @param m [IN] mod
* @param opt [IN] Optimizer
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer.
* @retval CRYPT_BN_ERR_NO_INVERSE Cannot calculate the module inverse.
*/
int32_t BN_ModInv(BN_BigNum *r, const BN_BigNum *x, const BN_BigNum *m, BN_Optimizer *opt);
/**
* @ingroup bn
* @brief BigNum comparison
*
* @attention The input parameter of a BigNum cannot be null.
* @param a [IN] BigNum
* @param b [IN] BigNum
*
* @retval 0,a == b
* @retval 1,a > b
* @retval -1,a < b
*/
int32_t BN_Cmp(const BN_BigNum *a, const BN_BigNum *b);
/**
* @ingroup bn
* @brief BigNum Addition
*
* @param r [OUT] and
* @param a [IN] Addendum
* @param b [IN] Addendum
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
*/
int32_t BN_Add(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b);
/**
* @ingroup bn
* @brief BigNum plus limb
*
* @param r [OUT] and
* @param a [IN] Addendum
* @param w [IN] Addendum
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
*/
int32_t BN_AddLimb(BN_BigNum *r, const BN_BigNum *a, BN_UINT w);
/**
* @ingroup bn
* @brief subtraction of large numbers
*
* @param r [OUT] difference
* @param a [IN] minuend
* @param b [IN] subtrahend
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
*/
int32_t BN_Sub(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b);
/**
* @ingroup bn
* @brief BigNum minus limb
*
* @param r [OUT] difference
* @param a [IN] minuend
* @param w [IN] subtrahend
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
*/
int32_t BN_SubLimb(BN_BigNum *r, const BN_BigNum *a, BN_UINT w);
/**
* @ingroup bn
* @brief BigNum Multiplication
*
* @param r [OUT] product
* @param a [IN] multiplier
* @param b [IN] multiplier
* @param opt [IN] Optimizer
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer.
*/
int32_t BN_Mul(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, BN_Optimizer *opt);
/**
* @ingroup bn
* @brief Multiplication of BigNum by Limb
*
* @param r [OUT] product
* @param a [IN] multiplicand
* @param w [IN] multiplier (limb)
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
*/
int32_t BN_MulLimb(BN_BigNum *r, const BN_BigNum *a, const BN_UINT w);
/**
* @ingroup bn
* @brief BigNum square. r must not be a.
*
* @param r [OUT] product
* @param a [IN] multiplier
* @param opt [IN] Optimizer
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer.
*/
int32_t BN_Sqr(BN_BigNum *r, const BN_BigNum *a, BN_Optimizer *opt);
/**
* @ingroup bn
* @brief BigNum Division
*
* @param q [OUT] quotient
* @param r [OUT] remainder
* @param x [IN] dividend
* @param y [IN] divisor
* @param opt [IN] optimizer
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_INVALID_ARG The addresses of q, r are identical, or both of them are null.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer.
* @retval CRYPT_BN_ERR_DIVISOR_ZERO divisor cannot be 0.
*/
int32_t BN_Div(BN_BigNum *q, BN_BigNum *r, const BN_BigNum *x, const BN_BigNum *y, BN_Optimizer *opt);
/**
* @ingroup bn
* @brief BigNum divided by limb
*
* @param q [OUT] quotient
* @param r [OUT] remainder
* @param x [IN] dividend
* @param y [IN] Divisor (limb)
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_BN_ERR_DIVISOR_ZERO divisor cannot be 0.
*/
int32_t BN_DivLimb(BN_BigNum *q, BN_UINT *r, const BN_BigNum *x, const BN_UINT y);
/**
* @ingroup bn
* @brief BigNum Modular addition
* @par Description: r = (a + b) mod (mod)
*
* @param r [OUT] Modulus result
* @param a [IN] BigNum
* @param b [IN] BigNum
* @param mod [IN] mod
* @param opt [IN] Optimizer
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer.
* @retval CRYPT_BN_ERR_DIVISOR_ZERO module cannot be 0.
*/
int32_t BN_ModAdd(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b,
const BN_BigNum *mod, BN_Optimizer *opt);
/**
* @ingroup bn
* @brief BigNum Modular subtraction
* @par Description: r = (a - b) mod (mod)
*
* @param r [OUT] Modulo result
* @param a [IN] minuend
* @param b [IN] subtrahend
* @param mod [IN] mod
* @param opt [IN] Optimizer
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer.
* @retval CRYPT_BN_ERR_DIVISOR_ZERO module cannot be 0.
*/
int32_t BN_ModSub(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b,
const BN_BigNum *mod, BN_Optimizer *opt);
/**
* @ingroup bn
* @brief BigNum Modular multiplication
* @par Description: r = (a * b) mod (mod)
*
* @param r [OUT] Modulus result
* @param a [IN] BigNum
* @param b [IN] BigNum
* @param mod [IN] mod
* @param opt [IN] Optimizer
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer.
* @retval CRYPT_BN_ERR_DIVISOR_ZERO module cannot be 0.
*/
int32_t BN_ModMul(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b,
const BN_BigNum *mod, BN_Optimizer *opt);
/**
* @ingroup bn
* @brief BigNum Modular squared
* @par Description: r = (a ^ 2) mod (mod)
*
* @param r [OUT] Modulus result
* @param a [IN] BigNum
* @param mod [IN] mod
* @param opt [IN] Optimizer
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer.
* @retval CRYPT_BN_ERR_DIVISOR_ZERO module cannot be 0.
*/
int32_t BN_ModSqr(
BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *mod, BN_Optimizer *opt);
/**
* @ingroup bn
* @brief BigNum Modular power
* @par Description: r = (a ^ e) mod (mod)
*
* @param r [OUT] Modulus result
* @param a [IN] BigNum
* @param mod [IN] mod
* @param opt [IN] Optimizer
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer.
* @retval CRYPT_BN_ERR_DIVISOR_ZERO module cannot be 0.
* @retval CRYPT_BN_ERR_EXP_NO_NEGATIVE exponent cannot be a negative number
*/
int32_t BN_ModExp(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e,
const BN_BigNum *m, BN_Optimizer *opt);
/**
* @ingroup bn
* @brief BigNum modulo
* @par Description: r = a mod m
*
* @param r [OUT] Modulus result
* @param a [IN] BigNum
* @param m [IN] mod
* @param opt [IN] Optimizer
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer.
* @retval CRYPT_BN_ERR_DIVISOR_ZERO module cannot be 0.
*/
int32_t BN_Mod(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt);
/**
* @ingroup bn
* @brief BigNum modulo limb
* @par Description: r = a mod m
*
* @param r [OUT] Modulus result
* @param a [IN] BigNum
* @param m [IN] Modulus (limb)
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_BN_ERR_DIVISOR_ZERO module cannot be 0.
*/
int32_t BN_ModLimb(BN_UINT *r, const BN_BigNum *a, const BN_UINT m);
#ifdef HITLS_CRYPTO_BN_PRIME
/**
* @ingroup bn
* @brief generate BN prime
*
* @param r [OUT] Generate a prime number.
* @param e [OUT] A helper prime to reduce the number of Miller-Rabin primes check.
* @param bits [IN] Length of the generated prime number
* @param half [IN] Whether to generate a prime number greater than the maximum value of this prime number by 1/2:
* Yes: True, No: false
* @param opt [IN] Optimizer
* @param cb [IN] BigNum callback
* @retval CRYPT_SUCCESS The prime number is successfully generated.
* @retval CRYPT_NULL_INPUT Invalid null pointer.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_BN_OPTIMIZER_STACK_FULL The optimizer stack is full.
* @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer.
* @retval CRYPT_BN_NOR_GEN_PRIME Failed to generate prime numbers.
* @retval CRYPT_NO_REGIST_RAND No random number is registered.
* @retval CRYPT_BN_RAND_GEN_FAIL Failed to generate a random number.
*/
int32_t BN_GenPrime(BN_BigNum *r, BN_BigNum *e, uint32_t bits, bool half, BN_Optimizer *opt, BN_CbCtx *cb);
/**
* @ingroup bn
* @brief check prime number
*
* @param bn [IN] Prime number to be checked
* @param checkTimes [IN] the user can set the check times of miller-rabin testing.
* if checkTimes == 0, it will use the default detection times of miller-rabin.
* @param opt [IN] Optimizer
*
* @retval CRYPT_SUCCESS The check result is a prime number.
* @retval CRYPT_BN_NOR_CHECK_PRIME The check result is a non-prime number.
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_BN_OPTIMIZER_STACK_FULL The optimizer stack is full.
* @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer.
* @retval CRYPT_NO_REGIST_RAND No random number is registered.
* @retval CRYPT_BN_RAND_GEN_FAIL Failed to generate a random number.
*/
int32_t BN_PrimeCheck(const BN_BigNum *bn, uint32_t checkTimes, BN_Optimizer *opt, BN_CbCtx *cb);
#endif // HITLS_CRYPTO_BN_PRIME
#ifdef HITLS_CRYPTO_BN_RAND
#define BN_RAND_TOP_NOBIT 0 /* Not set bits */
#define BN_RAND_TOP_ONEBIT 1 /* Set the most significant bit to 1. */
#define BN_RAND_TOP_TWOBIT 2 /* Set the highest two bits to 1 */
#define BN_RAND_BOTTOM_NOBIT 0 /* Not set bits */
#define BN_RAND_BOTTOM_ONEBIT 1 /* Set the least significant bit to 1. */
#define BN_RAND_BOTTOM_TWOBIT 2 /* Set the least significant two bits to 1. */
/**
* @ingroup bn
* @brief generate random BigNum
*
* @param r [OUT] Generate a random number.
* @param bits [IN] Length of the generated prime number
* @param top [IN] Generating the flag indicating whether to set the most significant bit of a random number
* @param bottom [IN] Generate the flag indicating whether to set the least significant bit of the random number.
*
* @retval CRYPT_SUCCESS A random number is generated successfully.
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_BN_ERR_RAND_TOP_BOTTOM The top or bottom is invalid during random number generation.
* @retval CRYPT_NO_REGIST_RAND No random number is registered.
* @retval CRYPT_BN_RAND_GEN_FAIL Failed to generate a random number.
* @retval CRYPT_BN_ERR_RAND_BITS_NOT_ENOUGH The bit is too small during random number generation.
*/
int32_t BN_Rand(BN_BigNum *r, uint32_t bits, uint32_t top, uint32_t bottom);
/**
* @ingroup bn
* @brief generate random BigNum
*
* @param libCtx [IN] provider libCtx
* @param r [OUT] Generate a random number.
* @param bits [IN] Length of the generated prime number
* @param top [IN] Generating the flag indicating whether to set the most significant bit of a random number
* @param bottom [IN] Generate the flag indicating whether to set the least significant bit of the random number.
*
* @retval CRYPT_SUCCESS A random number is generated successfully.
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_BN_ERR_RAND_TOP_BOTTOM The top or bottom is invalid during random number generation.
* @retval CRYPT_BN_RAND_GEN_FAIL Failed to generate a random number.
* @retval CRYPT_BN_ERR_RAND_BITS_NOT_ENOUGH The bit is too small during random number generation.
*/
int32_t BN_RandEx(void *libCtx, BN_BigNum *r, uint32_t bits, uint32_t top, uint32_t bottom);
/**
* @ingroup bn
* @brief generate random BigNum
*
* @param r [OUT] Generate a random number.
* @param p [IN] Compare data so that the generated r < p
*
* @retval CRYPT_SUCCESS A random number is successfully generated.
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_NO_REGIST_RAND No random number is registered.
* @retval CRYPT_BN_RAND_GEN_FAIL Failed to generate a random number.
* @retval CRYPT_BN_ERR_RAND_ZERO Generate a random number smaller than 0.
* @retval CRYPT_BN_ERR_RAND_NEGATE Generate a negative random number.
*/
int32_t BN_RandRange(BN_BigNum *r, const BN_BigNum *p);
/**
* @ingroup bn
* @brief generate random BigNum
*
* @param libCtx [IN] provider libCtx
* @param r [OUT] Generate a random number.
* @param p [IN] Compare data so that the generated r < p
*
* @retval CRYPT_SUCCESS A random number is successfully generated.
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_BN_RAND_GEN_FAIL Failed to generate a random number.
* @retval CRYPT_BN_ERR_RAND_ZERO Generate a random number smaller than 0.
* @retval CRYPT_BN_ERR_RAND_NEGATE Generate a negative random number.
*/
int32_t BN_RandRangeEx(void *libCtx, BN_BigNum *r, const BN_BigNum *p);
#endif
/**
* @ingroup bn
* @brief Binary to BigNum
*
* @param r [OUT] BigNum
* @param bin [IN] Data stream to be converted
* @param binLen [IN] Data stream length
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
*/
int32_t BN_Bin2Bn(BN_BigNum *r, const uint8_t *bin, uint32_t binLen);
/**
* @ingroup bn
* @brief Convert BigNum to a big-endian binary
*
* @param a [IN] BigNum
* @param bin [IN/OUT] Data stream to be converted -- The input pointer cannot be null.
* @param binLen [IN/OUT] Data stream length -- When input, binLen is also the length of the bin buffer.
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_SECUREC_FAIL An error occurred during the copy.
*/
int32_t BN_Bn2Bin(const BN_BigNum *a, uint8_t *bin, uint32_t *binLen);
/**
* @ingroup bn
* @brief fix size of BigNum
*
* @param a [IN] BigNum
*
* @retval void
*/
void BN_FixSize(BN_BigNum *a);
/**
* @ingroup bn
* @brief
*
* @param a [IN/OUT] BigNum
* @param words [IN] the bn room that the caller wanted.
*
* @retval CRYPT_SUCCESS
* @retval others, see crypt_errno.h
*/
int32_t BN_Extend(BN_BigNum *a, uint32_t words);
/**
* @ingroup bn
* @brief Convert BigNum to binary to obtain big-endian data with the length of binLen.
* The most significant bits are filled with 0.
*
* @param a [IN] BigNum
* @param bin [OUT] Data stream to be converted -- The input pointer cannot be null.
* @param binLen [IN] Data stream length -- When input, binLen is also the length of the bin buffer.
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_BN_BUFF_LEN_NOT_ENOUGH The space is insufficient.
*/
int32_t BN_Bn2BinFixZero(const BN_BigNum *a, uint8_t *bin, uint32_t binLen);
#ifdef HITLS_CRYPTO_BN_STR_CONV
/**
* @ingroup bn
* @brief Hexadecimal to a BigNum
*
* @param r [OUT] BigNum
* @param r [IN] Data stream to be converted
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_BN_CONVERT_INPUT_INVALID Invalid string
*/
int32_t BN_Hex2Bn(BN_BigNum **r, const char *str);
/**
* @ingroup bn
* @brief Convert BigNum to hexadecimal number
*
* @param a [IN] BigNum
* @param char [OUT] Converts a hexadecimal string.
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
*/
char *BN_Bn2Hex(const BN_BigNum *a);
/**
* @ingroup bn
* @brief Decimal to BigNum
*
* @param r [OUT] BigNum
* @param str [IN] A decimal string to be converted
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_BN_CONVERT_INPUT_INVALID Invalid string
*/
int32_t BN_Dec2Bn(BN_BigNum **r, const char *str);
/**
* @ingroup bn
* @brief Convert BigNum to decimal number
*
* @param r [IN] BigNum
*
* @retval A decimal string after conversion or push error.
*/
char *BN_Bn2Dec(const BN_BigNum *a);
#endif
#if defined(HITLS_CRYPTO_CURVE_SM2_ASM) || \
((defined(HITLS_CRYPTO_CURVE_NISTP521) || defined(HITLS_CRYPTO_CURVE_NISTP384_ASM)) && \
defined(HITLS_CRYPTO_NIST_USE_ACCEL))
/**
* @ingroup bn
* @brief Converting a 64-bit unsigned number array to a BigNum
*
* @param r [OUT] BigNum
* @param array [IN] Array to be converted
* @param len [IN] Number of elements in the array
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
*/
int32_t BN_U64Array2Bn(BN_BigNum *r, const uint64_t *array, uint32_t len);
/**
* @ingroup bn
* @brief BigNum to 64-bit unsigned number array
*
* @param a [IN] BigNum
* @param array [IN/OUT] Array for storing results -- The input pointer cannot be null.
* @param len [IN/OUT] Length of the written array -- Number of writable elements when input
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_SECUREC_FAIL A copy error occurs.
*/
int32_t BN_Bn2U64Array(const BN_BigNum *a, uint64_t *array, uint32_t *len);
#endif
/**
* @ingroup bn
* @brief BigNum optimizer creation
*
* @param None
*
* @retval Not NULL Success
* @retval NULL failure
*/
BN_Optimizer *BN_OptimizerCreate(void);
/**
* @ingroup bn
* @brief Destroy the BigNum optimizer.
*
* @param opt [IN] BigNum optimizer
*
* @retval none
*/
void BN_OptimizerDestroy(BN_Optimizer *opt);
/**
* @ingroup bn
* @brief set library context
*
* @param libCtx [IN] Library context
* @param opt [OUT] BigNum optimizer
*
* @retval none
*/
void BN_OptimizerSetLibCtx(void *libCtx, BN_Optimizer *opt);
/**
* @ingroup bn
* @brief get library context
*
* @param opt [In] BigNum optimizer
*
* @retval library context
*/
void *BN_OptimizerGetLibCtx(BN_Optimizer *opt);
/**
* @ingroup bn
* @brief BigNum Montgomery context creation and setting
*
* @param m [IN] Modulus m, which must be positive and odd
*
* @retval Not NULL Success
* @retval NULL failure
*/
BN_Mont *BN_MontCreate(const BN_BigNum *m);
/**
* @ingroup bn
* @brief BigNum Montgomery modular exponentiation.
* Whether to use the constant API depends on the property of the BigNum.
*
* @param r [OUT] Modular exponentiation result
* @param a [IN] base
* @param e [IN] Index
* @param mont [IN] Montgomery context
* @param opt [IN] Optimizer
*
* @retval CRYPT_SUCCESS calculated successfully.
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer.
* @retval CRYPT_BN_MONT_BASE_TOO_MAX Montgomery modulus exponentiation base is too large
* @retval CRYPT_BN_OPTIMIZER_STACK_FULL The optimizer stack is full.
* @retval CRYPT_BN_ERR_EXP_NO_NEGATE exponent cannot be a negative number
*/
int32_t BN_MontExp(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e, BN_Mont *mont,
BN_Optimizer *opt);
/**
* @ingroup bn
* @brief Constant time BigNum Montgomery modular exponentiation
*
* @param r [OUT] Modular exponentiation result
* @param a [IN] base
* @param e [IN] exponent
* @param mont [IN] Montgomery context
* @param opt [IN] Optimizer
*
* @retval CRYPT_SUCCESS calculated successfully.
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer.
* @retval CRYPT_BN_MONT_BASE_TOO_MAX Montgomery Modular exponentiation base is too large
* @retval CRYPT_BN_OPTIMIZER_STACK_FULL The optimizer stack is full.
* @retval CRYPT_BN_ERR_EXP_NO_NEGATE exponent cannot be a negative number
*/
int32_t BN_MontExpConsttime(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e,
BN_Mont *mont, BN_Optimizer *opt);
/**
* @ingroup mont
* @brief BigNum Montgomery Context Destruction
*
* @param mont [IN] BigNum Montgomery context
*
* @retval none
*/
void BN_MontDestroy(BN_Mont *mont);
/**
* @ingroup bn
* @brief shift a BigNum to the right
*
* @param r [OUT] Shift result
* @param a [IN] Source data
* @param n [IN] Shift bit num
*
* @retval CRYPT_SUCCESS succeeded.
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_SECUREC_FAIL The security function returns an error.
*/
int32_t BN_Rshift(BN_BigNum *r, const BN_BigNum *a, uint32_t n);
/**
* @ingroup bn
* @brief shift a BigNum to the left
*
* @param r [OUT] Shift result
* @param a [IN] Source data
* @param n [IN] Shift bit num
*
* @retval CRYPT_SUCCESS succeeded.
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
*/
int32_t BN_Lshift(BN_BigNum *r, const BN_BigNum *a, uint32_t n);
#ifdef HITLS_CRYPTO_DSA
int32_t BN_MontExpMul(BN_BigNum *r, const BN_BigNum *a1, const BN_BigNum *e1,
const BN_BigNum *a2, const BN_BigNum *e2, BN_Mont *mont, BN_Optimizer *opt);
#endif
#ifdef HITLS_CRYPTO_ECC
/**
* @ingroup bn
* @brief Mould opening root
* @par Description: r^2 = a mod p; p-1=q*2^s.
* In the current implementation s=1 will take a special branch, and the calculation speed is faster.
* The fast calculation branch with s=2 is not implemented currently.
* Currently, the s corresponding to the mod p of the EC nist224, 256, 384, and 521 is 96, 1, 1, and 1 respectively
* The branch with s=2 is not used.
* The root number is provided for the EC.
* @param r [OUT] Modular root result
* @param a [IN] Source data, 0 <= a <= p-1
* @param p [IN] module, odd prime number
* @param opt [IN] Optimizer
*
* @retval CRYPT_SUCCESS calculated successfully.
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_BN_ERR_SQRT_PARA The input parameter is incorrect.
* @retval CRYPT_BN_ERR_LEGENDE_DATA:
* Failed to find the specific number of the Legendre sign (z|p) of z to p equal to -1 when calculating the square root.
* @retval CRYPT_BN_ERR_NO_SQUARE_ROOT The square root cannot be found.
*/
int32_t BN_ModSqrt(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *p, BN_Optimizer *opt);
#endif
#if defined(HITLS_CRYPTO_CURVE_SM2_ASM) || (defined(HITLS_CRYPTO_CURVE_NISTP256_ASM) && \
defined(HITLS_CRYPTO_NIST_USE_ACCEL))
/**
* @ingroup bn
* @brief BigNum to BN_UINT array
*
* @param src [IN] BigNum
* @param dst [OUT] BN_UINT array for receiving the conversion result
* @param size [IN] Length of the dst buffer
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_SECUREC_FAIL The security function returns an error.
*/
int32_t BN_BN2Array(const BN_BigNum *src, BN_UINT *dst, uint32_t size);
/**
* @ingroup bn
* @brief BN_UINT array to BigNum
*
* @param dst [OUT] BigNum
* @param src [IN] BN_UINT array to be converted
* @param size [IN] Length of the src buffer
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
*/
int32_t BN_Array2BN(BN_BigNum *dst, const BN_UINT *src, const uint32_t size);
#endif
#ifdef HITLS_CRYPTO_ECC
/**
* @ingroup bn
* @brief Copy with the mask. When the mask is set to (0), r = a; when the mask is set to (-1), r = b.
*
* @attention Data r, a, and b must have the same room.
*
* @param r [OUT] Output result
* @param a [IN] Source data
* @param b [IN] Source data
* @param mask [IN] Mask data
*
* @retval CRYPT_SUCCESS succeeded.
* @retval For details about other errors, see crypt_errno.h.
*/
int32_t BN_CopyWithMask(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, BN_UINT mask);
/**
* @ingroup bn
* @brief Calculate r = (a - b) % mod
*
* @attention This API is invoked in the area where ECC point computing is intensive and is performance-sensitive.
* The user must ensure that a < mod, b < mod
* In addition, a->room and b->room are not less than mod->size.
* All data are non-negative
* The mod information cannot be 0.
* Otherwise, the interface may not be functional.
*
* @param r [OUT] Output result
* @param a [IN] Source data
* @param b [IN] Source data
* @param mod [IN] Modular data
* @param opt [IN] Optimizer
*
* @retval CRYPT_SUCCESS succeeded.
* @retval For details about other errors, see crypt_errno.h.
*/
int32_t BN_ModSubQuick(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b,
const BN_BigNum *mod, const BN_Optimizer *opt);
/**
* @ingroup bn
* @brief Calculate r = (a + b) % mod
*
* @attention This API is invoked in the area where ECC point computing is intensive and is performance-sensitive.
* The user must ensure that a < mod, b < mod
* In addition, a->room and b->room are not less than mod->size.
* All data are non-negative
* The mod information cannot be 0.
* Otherwise, the interface may not be functional.
*
* @param r [OUT] Output result
* @param a [IN] Source data
* @param b [IN] Source data
* @param mod [IN] Modular data
* @param opt [IN] Optimizer
*
* @retval CRYPT_SUCCESS succeeded.
* @retval For details about other errors, see crypt_errno.h.
*/
int32_t BN_ModAddQuick(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b,
const BN_BigNum *mod, const BN_Optimizer *opt);
/**
* @ingroup bn
* @brief Calculate r = (a * b) % mod
*
* @attention This API is invoked in the area where ECC point computing is intensive and is performance sensitive.
* The user must ensure that a < mod, b < mod
* In addition, a->room and b->room are not less than mod->size.
* All data are non-negative
* The mod information can only be the parameter p of the curve of nistP224, nistP256, nistP384, and nistP521.
* Otherwise, the interface may not be functional.
*
* @param r [OUT] Output result
* @param a [IN] Source data
* @param b [IN] Source data
* @param mod [IN] Modular data
* @param opt [IN] Optimizer
*
* @retval CRYPT_SUCCESS succeeded.
* @retval For other errors, see crypt_errno.h.
*/
int32_t BN_ModNistEccMul(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b,
void *mod, BN_Optimizer *opt);
/**
* @ingroup bn
* @brief Calculate r = (a ^ 2) % mod
*
* @attention This API is invoked in the area where ECC point computing is intensive and is performance sensitive.
* The user must guarantee a < mod
* In addition, a->room are not less than mod->size.
* All data are non-negative
* The mod information can only be the parameter p of the curve of nistP224, nistP256, nistP384, and nistP521.
* Otherwise, the interface may not be functional.
*
* @param r [OUT] Output result
* @param a [IN] Source data
* @param mod [IN] Modular data
* @param opt [IN] Optimizer
*
* @retval CRYPT_SUCCESS succeeded.
* @retval For details about other errors, see crypt_errno.h.
*/
int32_t BN_ModNistEccSqr(BN_BigNum *r, const BN_BigNum *a, void *mod, BN_Optimizer *opt);
#endif
#ifdef HITLS_CRYPTO_CURVE_SM2
/**
* @ingroup ecc
* @brief sm2 curve: calculate r = (a*b)% mod
*
* @attention This API is invoked in the area where ECC point computing is intensive and is performance sensitive.
* The user must guarantee a < mod、b < mod
* In addition, a->room and b->room are not less than mod->size.
* All data are non-negative
* The mod information can only be the parameter p of the curve of sm2.
* Otherwise, the interface may not be functional.
*
* @param r [OUT] Output result
* @param a [IN] Source data
* @param b [IN] Source data
* @param mod [IN] Modular data
* @param opt [IN] Optimizer
*
* @retval CRYPT_SUCCESS succeeded.
* @retval For details about other errors, see crypt_errno.h.
*/
int32_t BN_ModSm2EccMul(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, void *data, BN_Optimizer *opt);
/**
* @ingroup ecc
* @brief sm2 curve: calculate r = (a ^ 2) % mod
*
* @attention This API is invoked in the area where ECC point computing is intensive and is performance sensitive.
* The user must guarantee a < mod
* In addition, a->room are not less than mod->size.
* All data are non-negative
* The mod information can only be the parameter p of the curve of sm2.
* Otherwise, the interface may not be functional.
*
* @param r [OUT] Output result
* @param a [IN] Source data
* @param mod [IN] Modular data
* @param opt [IN] Optimizer
*
* @retval CRYPT_SUCCESS succeeded.
* @retval For details about other errors, see crypt_errno.h.
*/
int32_t BN_ModSm2EccSqr(BN_BigNum *r, const BN_BigNum *a, void *data, BN_Optimizer *opt);
#endif
#ifdef HITLS_CRYPTO_BN_PRIME_RFC3526
/**
* @ingroup bn
* @brief Return the corresponding length of modulo exponent of the BigNum.
*
* @param r [OUT] Output result
* @param len [IN] Length
*
* @retval Not NULL Success
* @retval NULL failure
*/
BN_BigNum *BN_GetRfc3526Prime(BN_BigNum *r, uint32_t len);
#endif
/**
* @ingroup bn
* @brief Return the number of security bits provided by a specific algorithm and specific key size.
*
* @param [OUT] Output the result.
* @param pubLen [IN] Size of the public key
* @param prvLen [IN] Size of the private key.
*
* @retval Number of security bits
*/
int32_t BN_SecBits(int32_t pubLen, int32_t prvLen);
#if defined(HITLS_CRYPTO_RSA)
/**
* @ingroup bn
* @brief Montgomery modulus calculation process, need a < m, b < m, All is positive numbers, The large number
optimizer must be enabled before this function is used.
*
* @param r [OUT] Output results
* @param a [IN] Input data
* @param b [IN] Input data
* @param mont [IN] Montgomery context
* @param opt [IN] Large number optimizer
*
* @retval CRYPT_SUCCESS
* @retval For details about other errors, see crypt_errno.h.
*/
int32_t MontMulCore(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, BN_Mont *mont, BN_Optimizer *opt);
#endif // HITLS_CRYPTO_RSA
#if defined(HITLS_CRYPTO_BN_PRIME)
/**
* @ingroup bn
* @brief Montgomery modulus calculation process, need a < m, unlimited symbols.
*
* @param r [OUT] Output results
* @param a [IN] Input data
* @param mont [IN] Montgomery context
* @param opt [IN] Large number optimizer
*
* @retval CRYPT_SUCCESS
* @retval For details about other errors, see crypt_errno.h.
*/
int32_t MontSqrCore(BN_BigNum *r, const BN_BigNum *a, BN_Mont *mont, BN_Optimizer *opt);
#endif // HITLS_CRYPTO_BN_PRIME
/**
* @ingroup bn
* @brief Enabling the big data optimizer
*
* @param opt [IN] Large number optimizer
*
* @retval CRYPT_SUCCESS
* @retval For details about other errors, see crypt_errno.h.
*/
int32_t OptimizerStart(BN_Optimizer *opt);
/**
* @ingroup bn
* @brief Disabling the Large Number Optimizer
*
* @param opt [IN] Large number optimizer
*
* @retval CRYPT_SUCCESS
* @retval For details about other errors, see crypt_errno.h.
*/
void OptimizerEnd(BN_Optimizer *opt);
/**
* @ingroup bn
* @brief Get Bn from the large number optimizer.
*
* @param opt [IN] Large number optimizer
* @param room [IN] Length of the big number.
*
* @retval BN_BigNum if success
* @retval NULL if failed
*/
BN_BigNum *OptimizerGetBn(BN_Optimizer *opt, uint32_t room);
#if defined(HITLS_CRYPTO_PAILLIER) || defined(HITLS_CRYPTO_RSA_CHECK)
/**
* @ingroup bn
* @brief BigNum Calculate the least common multiple
* @par Description: lcm(a, b) (a, b!=0)
*
* @param r [OUT] least common multiple
* @param a [IN] BigNum
* @param b [IN] BigNum
* @param opt [IN] Optimizer
*
* @retval CRYPT_SUCCESS
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
*/
int32_t BN_Lcm(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, BN_Optimizer *opt);
#endif // HITLS_CRYPTO_PAILLIER || HITLS_CRYPTO_RSA_CHECK
/**
* @ingroup bn
* @brief Enabling the big data optimizer
*
* @param opt [IN] Large number optimizer
*
* @retval CRYPT_SUCCESS
* @retval For details about other errors, see crypt_errno.h.
*/
int32_t OptimizerStart(BN_Optimizer *opt);
/**
* @ingroup bn
* @brief Disabling the Large Number Optimizer
*
* @param opt [IN] Large number optimizer
*
* @retval CRYPT_SUCCESS
* @retval For details about other errors, see crypt_errno.h.
*/
void OptimizerEnd(BN_Optimizer *opt);
/**
* @ingroup bn
* @brief Get Bn from the large number optimizer.
*
* @param opt [IN] Large number optimizer
* @param room [IN] Length of the big number.
*
* @retval BN_BigNum if success
* @retval NULL if failed
*/
BN_BigNum *OptimizerGetBn(BN_Optimizer *opt, uint32_t room);
#ifdef HITLS_CRYPTO_CURVE_MONT
/**
* a, b is mont form.
* r = a * b
*/
int32_t BN_EcPrimeMontMul(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, void *data, BN_Optimizer *opt);
/**
* a is mont form.
* r = a ^ 2
*/
int32_t BN_EcPrimeMontSqr(BN_BigNum *r, const BN_BigNum *a, void *mont, BN_Optimizer *opt);
/**
* r = Reduce(r * RR)
*/
int32_t BnMontEnc(BN_BigNum *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime);
/**
* r = Reduce(r)
*/
void BnMontDec(BN_BigNum *r, BN_Mont *mont);
/**
* This interface is a constant time.
* if mask = BN_MASK. swap a and b.
* if mask = 0, a and b remain as they are.
*/
int32_t BN_SwapWithMask(BN_BigNum *a, BN_BigNum *b, BN_UINT mask);
#endif // HITLS_CRYPTO_CURVE_MONT
#ifdef __cplusplus
}
#endif
#endif /* HITLS_CRYPTO_BN */
#endif
|
2301_79861745/bench_create
|
crypto/bn/include/crypt_bn.h
|
C
|
unknown
| 48,680
|
/*
* 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_BN
#include <stdint.h>
#include "bn_bincal.h"
#ifndef HITLS_SIXTY_FOUR_BITS
#error Bn binical x8664 optimizer must open BN-64.
#endif
// r = a + b, len = n, return carry
BN_UINT BinAdd(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t n)
{
if (n == 0) {
return 0;
}
BN_UINT ret = 0;
BN_UINT times = n >> 2;
BN_UINT rem = n & 3;
asm volatile(
".align 3 \n"
" mov %0, #1 \n"
" adcs %0, xzr, %0 \n" // clear C flags
" mov %0, #0 \n"
" cbz %1, 3f \n"
"4: add x4, %3, %0 \n"
" add x5, %4, %0 \n"
" add x6, %5, %0 \n"
" ldp x7, x8, [x5] \n"
" ldp x9, x10, [x5,#16] \n"
" ldp x11, x12, [x6] \n"
" ldp x13, x14, [x6,#16] \n"
" adcs x7, x7, x11 \n"
" adcs x8, x8, x12 \n"
" adcs x9, x9, x13 \n"
" adcs x10, x10, x14 \n"
" stp x7, x8, [x4] \n"
" stp x9, x10, [x4, #16] \n"
" sub %1, %1, #0x1 \n"
" add %0, %0, #0x20 \n"
" cbnz %1, 4b \n"
"3: cbz %2, 2f \n" // times <= 0, jump to single cycle
"1: ldr x7, [%4, %0] \n"
" ldr x8, [%5, %0] \n"
" adcs x7, x7, x8 \n"
" str x7, [%3, %0] \n"
" sub %2, %2, #0x1 \n"
" add %0, %0, #0x8 \n"
" cbnz %2, 1b \n"
"2: mov %0, #0 \n"
" adcs %0, xzr, %0 \n"
:"+&r" (ret), "+r"(times), "+r"(rem)
:"r"(r), "r"(a), "r"(b)
:"x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", "x14", "cc", "memory");
return ret & 1;
}
// r = a - b, len = n, return carry
BN_UINT BinSub(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t n)
{
if (n == 0) {
return 0;
}
BN_UINT ret = 0;
BN_UINT rem = n & 3;
BN_UINT times = n >> 2;
asm volatile(
".align 3 \n"
" mov %0, #1 \n"
" sbcs %0, %0, xzr \n" // clear C flags
" mov %0, #0 \n"
" cbz %1, 2f \n"
"4: add x4, %3, %0 \n"
" add x5, %4, %0 \n"
" add x6, %5, %0 \n"
" ldp x7, x8, [x5] \n"
" ldp x9, x10, [x5,#16] \n"
" ldp x11, x12, [x6] \n"
" ldp x13, x14, [x6,#16] \n"
" sbcs x7, x7, x11 \n"
" sbcs x8, x8, x12 \n"
" sbcs x9, x9, x13 \n"
" sbcs x10, x10, x14 \n"
" stp x7, x8, [x4] \n"
" stp x9, x10, [x4, #16] \n"
" sub %1, %1, #0x1 \n"
" add %0, %0, #0x20 \n"
" cbnz %1, 4b \n"
"2: cbz %2, 3f \n" // times <= 0, jump to single cycle
"1: ldr x7, [%4, %0] \n"
" ldr x8, [%5, %0] \n"
" sbcs x7, x7, x8 \n"
" str x7, [%3, %0] \n"
" sub %2, %2, #0x1 \n"
" add %0, %0, #0x8 \n"
" cbnz %2, 1b \n"
"3: mov %0,#0 \n"
" sbcs %0,xzr,%0 \n"
:"+&r" (ret), "+r"(times), "+r"(rem)
:"r"(r), "r"(a), "r"(b)
:"x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", "x14", "cc", "memory");
return ret & 1;
}
// r = r - a * m, return the carry;
BN_UINT BinSubMul(BN_UINT *r, const BN_UINT *a, BN_UINT aSize, BN_UINT m)
{
BN_UINT borrow = 0;
BN_UINT i = 0;
asm volatile(
".align 3 \n"
"2: ldr x4, [%3, %1] \n" // x4 = r[i]
" ldr x5, [%4, %1] \n" // x5 = r[i]
" mul x7, x5, %5 \n" // x7 = al
" umulh x6, x5, %5 \n" // x6 = ah
" adds x7, %0, x7 \n" // x7 = borrow + al
" adcs %0, x6, xzr \n" // borrow = ah + H(borrow + al)
" cmp x7, x4 \n" // if r[i] > borrow + al, dont needs carry
" beq 1f \n"
" adc %0, %0, xzr \n"
"1: sub x4, x4, x7 \n"
" str x4, [%3, %1] \n"
" sub %2, %2, #0x1 \n"
" add %1, %1, #0x8 \n"
" cbnz %2, 2b \n"
:"+&r" (borrow), "+r"(i), "+r"(aSize)
:"r"(r), "r"(a), "r"(m)
:"x4", "x5", "x6", "x7", "cc", "memory");
return borrow;
}
/* Obtains the number of 0s in the first x most significant bits of data. */
uint32_t GetZeroBitsUint(BN_UINT x)
{
BN_UINT count;
asm ("clz %0, %1" : "=r" (count) : "r" (x));
return (uint32_t)count;
}
#endif /* HITLS_CRYPTO_BN */
|
2301_79861745/bench_create
|
crypto/bn/src/armv8_bn_bincal.c
|
C
|
unknown
| 7,049
|
/*
* 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.
*/
/*
* Description: Big number Montgomery modular multiplication in armv8 implementation, MontMul_Asm
* Ref: Montgomery Multiplication
* Process: To cal A * B mod n, we can convert to mont form, and cal A*B*R^(-1).
* Detail:
* intput:A = (An-1,...,A1,A0)b, B = (Bn-1,...,B1,B0)b, n, n'
* output:A*B*R^(-1)
* tmp = (tn,tn-1,...,t1,t0)b, initialize to 0
* for i: 0 -> (n-1)
* ui = (t0 + Ai*B0)m' mod b
* t = (t + Ai*B + ui * m) / b
* if t >= m
* t -= m
* return t;
*
* Deal process:
* i. size % 8 == 0 & a == b --> Sqr8x --> complete multiplication
* --> size == 8, goto single reduce step
* --> size >= 8, goto loop reduce process
* ii. size % 4 == 0 --> Mul4x
* --> size == 4, goto single step
* --> size >= 4, goto loop process
* iii. Ordinary --> Mul1x
* --> size == 2, goto single step
* --> size >= 2, goto loop process
*
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_BN
#include "crypt_arm.h"
.arch armv8-a+crypto
.file "bn_mont_armv8.S"
.text
.global MontMul_Asm
.type MontMul_Asm, %function
.align 5
MontMul_Asm:
AARCH64_PACIASP
tst x5, #7
b.eq MontSqr8
tst x5, #3
b.eq MontMul4
stp x29, x30, [sp, #-64]!
mov x29, sp
stp x23, x24, [sp, #16]
stp x21, x22, [sp, #32]
stp x19, x20, [sp, #48]
sub x21, x5 , #2 // j = size-2
cbnz x21,.LMul1xBegin
// if size == 2, goto single step
ldp x15, x16, [x1] // a[0], a[1]
ldp x19, x20, [x2] // b[0], b[1]
ldp x9, x10, [x3] // n[0], n[1]
mul x23 , x15 , x19 // x23 = lo(a[0] * b[0])
umulh x24 , x15 , x19 // x24 = hi(a[0] * b[0])
mul x6, x16 , x19 // x6 = lo(a[1] * b[0])
umulh x7, x16 , x19 // x7 = hi(a[1] * b[0])
mul x11, x23 , x4 // x11 = lo(t[0] * k0)
umulh x19, x9, x11 // x19 = hi(n[0] * t[0]*k0)
mul x12, x10, x11 // x12 = lo(n[1] * t[0]*k0)
umulh x13, x10, x11 // x13 = hi(n[1] * t[0]*k0)
// we knowns a*b + n'n = 0 (mod R)
// so lo(a[0] * b[0]) + lo(n[0] * t[0]*k0) = 0 (mod R)
// if lo(a[0] * b[0]) > 0, then 'lo(a[0] * b[0]) + lo(n[0] * t[0]*k0)' would overflow,
// else if lo(a[0] * b[0]) == 0, then lo(n[0] * t[0]*k0) == 0
cmp x23, #1
adc x19, x19, xzr
adds x23 , x6, x24 // x23 = lo(a[1] * b[0]) + hi(a[0] * b[0])
adc x24 , x7, xzr // x24 = hi(a[1] * b[0]) + CF
adds x8, x12, x19 // x8 = lo(n[1] * t[0]*k0) + hi(n[0] * t[0]*k0)
adc x19, x13, xzr // x19 = hi(n[1] * t[0]*k0) + CF
adds x21, x8, x23 // x21 = lo(n[1] * t[0]*k0) + hi(n[0] * t[0]*k0)
adcs x22, x19, x24
adc x23, xzr, xzr // x23 = CF
mul x14 , x15 , x20 // a[0] * b[1]
umulh x15 , x15 , x20
mul x6, x16 , x20 // a[1] * b[1]
umulh x7, x16 , x20
adds x14 , x14 , x21
adc x15 , x15 , xzr
mul x11, x14 , x4 // t[0] * k0
umulh x20, x9, x11
mul x12, x10, x11 // n[1] * t[0]*k0
umulh x13, x10, x11
cmp x14 , #1 // Check whether the low location is carried.
adc x20, x20, xzr
adds x14 , x6, x15
adc x15 , x7, xzr
adds x21, x12, x20
adcs x20, x13, x23
adc x23, xzr, xzr
adds x14 , x14 , x22
adc x15 , x15 , xzr
adds x21, x21, x14
adcs x20, x20, x15
adc x23, x23, xzr // x23 += CF
subs x12 , x21, x9
sbcs x13, x20, x10
sbcs x23, x23, xzr // update CF
csel x10, x21, x12, lo
csel x11, x20, x13, lo
stp x10, x11, [x0]
b .LMul1xEnd
.LMul1xBegin:
mov x24, x5 // the outermost pointers of our loop
lsl x5 , x5 , #3
sub x22, sp , x5 // The space size needs to be applied for.
and x22, x22, #-16 // For 4-byte alignment
mov sp , x22 // Apply for Space.
mov x6, x5
mov x23, xzr
.LMul1xInitstack:
sub x6, x6, #8
str xzr, [x22], #8
cbnz x6, .LMul1xInitstack
mov x22, sp
.LMul1xLoopProces:
sub x24, x24, #1
sub x21, x5 , #16 // j = size-2
// Begin mulx
ldr x17, [x2], #8 // b[i]
ldp x15, x16, [x1], #16 // a[0], a[1]
ldp x9, x10, [x3], #16 // n[0], n[1]
ldr x19, [x22] // The sp val is 0 during initialization.
mul x14 , x15 , x17 // a[0] * b[i]
umulh x15 , x15 , x17
mul x6, x16 , x17 // a[1] * b[i]
umulh x7, x16 , x17
adds x14 , x14 , x19
adc x15 , x15 , xzr
mul x11, x14 , x4
umulh x9, x9, x11
mul x12, x10, x11 // n[1] * t[0]*k0
cmp x14, #1
umulh x13, x10, x11
.LMul1xPrepare:
sub x21, x21, #8 // index -= 1
ldr x16, [x1], #8 // a[i]
ldr x10, [x3], #8 // n[i]
ldr x19, [x22, #8] // t[j]
adc x9, x9, xzr
adds x14 , x6, x15
adc x15 , x7, xzr
adds x8, x12, x9
adc x9, x13, xzr
mul x6, x16, x17 // a[j] * b[i]
adds x14, x14 , x19
umulh x7, x16 , x17
adc x15, x15 , xzr
mul x12, x10, x11 // n[j] * t[0]*k0
adds x8, x8, x14
umulh x13, x10, x11
str x8, [x22], #8 // t[j-1]
cbnz x21, .LMul1xPrepare
.LMul1xReduce:
ldr x19, [x22, #8]
adc x9, x9, xzr
adds x14 , x6, x15
adc x15 , x7, xzr
adds x8, x12, x9
adcs x9, x13, x23
adc x23, xzr, xzr
adds x14 , x14 , x19
adc x15 , x15 , xzr
adds x8, x8, x14
adcs x9, x9, x15
adc x23, x23, xzr // x23 += CF, carry of the most significant bit.
stp x8, x9, [x22], #8
mov x22, sp
sub x1 , x1 , x5
subs x3 , x3 , x5 // x3 = &n[0]
cbnz x24, .LMul1xLoopProces
mov x1, x0
mov x21, x5 // get index
.LMul1xSubMod:
ldr x19, [x22], #8
ldr x10, [x3], #8
sub x21, x21, #8 // j--
sbcs x16, x19, x10 // t[j] - n[j]
str x16, [x1], #8 // r[j] = t[j] - n[j]
cbnz x21,.LMul1xSubMod
sbcs x23, x23, xzr // x23 -= CF
mov x22, sp
.LMul1xCopy:
ldr x19, [x22], #8
ldr x16, [x0]
sub x5, x5, #8 // size--
csel x10, x19, x16, lo
str x10, [x0], #8
cbnz x5 , .LMul1xCopy
.LMul1xEnd:
ldp x23, x24, [x29, #16]
mov sp , x29
ldp x21, x22, [x29, #32]
ldp x19, x20, [x29, #48]
ldr x29, [sp], #64
AARCH64_AUTIASP
ret
.size MontMul_Asm, .-MontMul_Asm
.type MontSqr8, %function
MontSqr8:
AARCH64_PACIASP
cmp x1, x2
b.ne MontMul4
stp x29, x30, [sp, #-128]! // sp = sp - 128(Modify the SP and then save the SP.), [sp] = x29, [sp + 8] = x30,
// !Indicates modification sp
mov x29, sp // x29 = sp, The sp here has been reduced by 128.
stp x27, x28, [sp, #16]
stp x25, x26, [sp, #32]
stp x23, x24, [sp, #48]
stp x21, x22, [sp, #64]
stp x19, x20, [sp, #80]
stp x0 , x3 , [sp, #96] // offload r and n, Push the pointers of r and n into the stack.
str x4 , [sp, #112] // store n0
lsl x5, x5, #3 // x5 = x5 * 8, Converts size to bytes.
sub x2, sp, x5, lsl#1 // x2 = sp - 2*x5*8, x5 = size, x2 points to the start address of a 2*size memory. *8 is to convert to bytes
mov sp, x2 // Alloca, Apply for Space.
mov x19, x5 // The lowest eight data blocks do not need to be cleared.
eor v0.16b,v0.16b,v0.16b
eor v1.16b,v1.16b,v1.16b
.LSqr8xStackInit:
sub x19, x19, #8*8 // Offset 64, cyclic increment.
st1 {v0.2d, v1.2d}, [x2], #32
st1 {v0.2d, v1.2d}, [x2], #32
st1 {v0.2d, v1.2d}, [x2], #32
st1 {v0.2d, v1.2d}, [x2], #32
cbnz x19, .LSqr8xStackInit // When x19 = 0, the loop exits.
mov x2 , sp // After clear to zero, assign sp back to x2.
ldp x27, x28, [x2]
ldp x25, x26, [x2]
ldp x23, x24, [x2]
ldp x21, x22, [x2]
add x3 , x1 , x5 // x3 = x1 + bytes(size * 8)
ldp x14 , x15 , [x1], #16 // x14 = a[0], x15 = a[1]
ldp x16 , x17 , [x1], #16 // x16 = a[2], x17 = a[3]
ldp x6, x7, [x1], #16 // x6 = a[4], x7 = a[5]
ldp x8, x9, [x1], #16 // x8 = a[6], x9 = a[7]
.LSqr8xLoopMul:
mul x10, x14, x15 // a[0] * a[1~4]
mul x11, x14, x16 // keep cache hit ratio of x6
mul x12, x14, x17
mul x13, x14, x6
adds x28, x28, x10 // x27~x22 = t[0~7], x28 = t[1] = lo(a[0]*a[1]), adds is used to set CF to 0.
adcs x25, x25, x11 // x10~x17 Used to save subsequent calculation results
mul x10, x14 , x7 // lo(a[0] * a[5~7]), keep cache hit ratio of x14, the same below
mul x11, x14 , x8
adcs x26, x26, x12
adcs x23, x23, x13 // t[4] = lo(a[0] * a[4])
adcs x24, x24, x10 // x24~x22 = t[5~7]
mul x12, x14 , x9 // lo(a[0] * a[7])
stp x27, x28, [x2], #8*2 // t[0] = a[0]^2, Because the square term is not calculated temporarily,
// so t[0] = 0, t[1] = a[0] * a[1] + carry
adcs x21, x21, x11
adcs x22, x22, x12 // t[7] += lo(a[0] * a[7]), Carrying has to be given t[8]
adc x27, xzr, xzr // x27 = CF ( Set by t[7] += lo(a[0] * a[7]) ),
umulh x13, x14 , x15 // hi(a[0] * a[1~4]), Use x17 to keep the cache hit
umulh x10, x14 , x16
umulh x11, x14 , x17
umulh x12, x14 , x6
// In the new round, the first calculation does not need to be carried, but the CF bit needs to be modified.
adds x25, x25, x13 // t[2] += hi(a[0] * a[1])
adcs x26, x26, x10
adcs x23, x23, x11
adcs x24, x24, x12 // t[5] += hi(a[0] * a[4])
umulh x13, x14 , x7 // hi(a[0] * a[5~7])
umulh x10, x14 , x8
umulh x11, x14 , x9
//----- lo(a[1] * a[2~4]) ------
adcs x21, x21, x13 // t[6] += hi(a[0] * a[5])
adcs x22, x22, x10 // t[7] += hi(a[0] * a[6])
adc x27, x27, x11 // t[8] += hi(a[0] * a[7])
mul x12, x15, x16 // lo(a[1] * a[2])
mul x13, x15, x17
mul x10, x15, x6
//----- lo(a[1] * a[5~7]) ------
adds x26, x26, x12 // t[3] += lo(a[1] * a[2]), The first calculation of this round
// does not take into account the previous carry, and the CF is not modified in line 118.
adcs x23, x23, x13 // t[4] += lo(a[1] * a[3])
adcs x24, x24, x10 // t[5] += lo(a[1] * a[4])
mul x11, x15 , x7
mul x12, x15 , x8
mul x13, x15 , x9
//----- hi(a[1] * a[2~5]) ------
adcs x21, x21, x11 // t[6] += lo(a[1] * a[5])
adcs x22, x22, x12 // t[7] += lo(a[1] * a[6])
adcs x27, x27, x13 // t[8] += lo(a[1] * a[7])
umulh x10, x15, x16 // hi(a[1] * a[2])
umulh x11, x15, x17
umulh x12, x15, x6
umulh x13, x15, x7
stp x25, x26, [x2], #8*2 // t[2] and t[3] are calculated and stored in the memory.
// x25 and x22 are used to store t[10] and t[11].
adc x28, xzr, xzr // t[9] = CF ( Set by t[8] += lo(a[1] * a[7]) )
//In the new round, the first calculation does not need to be carried, but the CF bit needs to be modified.
//----- hi(a[1] * a[6~7]) ------
adds x23, x23, x10 // t[4] += hi(a[1] * a[2])
adcs x24, x24, x11 // t[5] += hi(a[1] * a[3])
adcs x21, x21, x12 // t[6] += hi(a[1] * a[4])
umulh x10, x15 , x8 // hi(a[1] * a[6])
umulh x11, x15 , x9 // hi(a[1] * a[7])
//----- lo(a[2] * a[3~7]) ------
adcs x22, x22, x13 // t[7] += hi(a[1] * a[5])
adcs x27, x27, x10 // t[8] += hi(a[1] * a[6])
adc x28, x28, x11 // t[9] += hi(a[1] * a[7]), Here, only the carry of the previous round
mul x12, x16, x17 // lo(a[2] * a[3])
mul x13, x16, x6
mul x10, x16, x7
// of calculation is retained before x20 calculation. Add x15 to the carry.
mul x11, x16 , x8
adds x24, x24, x12 // t[5] += lo(a[2] * a[3]), For the first calculation of this round,
// the previous carry is not considered.
mul x12, x16 , x9
adcs x21, x21, x13 // t[6] += lo(a[2] * a[4])
//----- hi(a[2] * a[3~7]) ------
adcs x22, x22, x10 // t[7] += lo(a[2] * a[5])
umulh x13, x16, x17 // hi(a[2] * a[3])
umulh x10, x16, x6
adcs x27, x27, x11 // t[8] += lo(a[2] * a[6])
adcs x28, x28, x12 // t[9] += lo(a[2] * a[7])
umulh x11, x16, x7
umulh x12, x16, x8
stp x23, x24, [x2], #8*2 // After t[4] and t[5] are calculated, they are stored in the memory.
// x23 and x24 are used to store t[12] and t[13].
adc x25, xzr, xzr // t[10] = CF ( Set by t[9] += lo(a[2] * a[7]) )
// In the new round, the first calculation does not need to be carried, but the CF bit needs to be modified.
adds x21, x21, x13 // t[6] += hi(a[2] * a[3])
adcs x22, x22, x10 // t[7] += hi(a[2] * a[4])
umulh x13, x16, x9
//----- lo(a[3] * a[4~7]) ------
adcs x27, x27, x11 // t[8] += hi(a[2] * a[5])
adcs x28, x28, x12 // t[9] += hi(a[2] * a[6])
adc x25, x25, x13 // t[10] += hi(a[2] * a[7])
mul x10, x17, x6
mul x11, x17, x7
mul x12, x17, x8
mul x13, x17, x9
//----- hi(a[3] * a[4~7]) ------
adds x22, x22, x10 // t[7] += lo(a[3] * a[4])
adcs x27, x27, x11 // t[8] += lo(a[3] * a[5])
adcs x28, x28, x12 // t[9] += lo(a[3] * a[6])
adcs x25, x25, x13 // t[10] += lo(a[3] * a[7])
umulh x10, x17, x6
umulh x11, x17, x7
umulh x12, x17, x8
umulh x13, x17, x9
stp x21, x22, [x2], #8*2 // t[6] and t[7] are calculated and stored in the memory.
// x21 and x26 are used to store t[14] and t[15].
adc x26, xzr, xzr // t[11] = CF ( Set by t[10] += lo(a[3] * a[7]) )
// In the new round, the first calculation does not need to be carried, but the CF bit needs to be modified.
adds x27, x27, x10 // t[8] += hi(a[3] * a[4])
//----- lo(a[4] * a[5~7]) ------
adcs x28, x28, x11 // t[9] += hi(a[3] * a[5])
adcs x25, x25, x12 // t[10] += hi(a[3] * a[6])
adc x26, x26, x13 // t[11] += hi(a[3] * a[7])
mul x10, x6, x7
mul x11, x6, x8
mul x12, x6, x9
//----- hi(a[4] * a[5~7]) ------
adds x28, x28, x10 // t[9] += lo(a[4] * a[5])
adcs x25, x25, x11 // t[10] += lo(a[4] * a[6])
adcs x26, x26, x12 // t[11] += lo(a[4] * a[7])
umulh x13, x6, x7
umulh x10, x6, x8
umulh x11, x6, x9
//----- lo(a[5] * a[6~7]) ------
mul x12, x7, x8
// This is actually a new round, but only t[0-7] can be calculated in each cycle,
// and t[8-15] retains the intermediate calculation result.
adc x23, xzr, xzr // t[12] = CF( Set by t[11] += lo(a[4] * a[7]) )
adds x25, x25, x13 // t[10] += hi(a[4] * a[5])
adcs x26, x26, x10 // t[11] += hi(a[4] * a[6])
mul x13, x7, x9
//----- hi(a[5] * a[6~7]) ------
adc x23, x23, x11 // t[12] += hi(a[4] * a[7])
umulh x10, x7, x8
umulh x11, x7, x9
adds x26, x26, x12 // t[11] += lo(a[5] * a[6])
//----- lo(a[6] * a[7]) ------
adcs x23, x23, x13 // t[12] += lo(a[5] * a[7])
mul x12, x8, x9
//----- hi(a[6] * a[7]) ------
adc x24, xzr, xzr // t[13] = CF ( Set by t[12] += lo(a[5] * a[7]) ),
umulh x13, x8, x9
// This operation is required when a new umulh is added.
adds x23, x23, x10 // t[12] += hi(a[5] * a[6])
adc x24, x24, x11 // t[13] += hi(a[5] * a[7])
sub x19, x3, x1 // x3 = &a[size], x1 = &a[8], x19 = (size - 8) * 8
adds x24, x24, x12 // t[13] += lo(a[6] * a[7])
adc x21, xzr, xzr // t[14] = CF ( set by t[13] += lo(a[6] * a[7]) )
add x21, x21, x13 // t[14] += hi(a[6] * a[7]), There must be no carry in the last step.
cbz x19, .LSqr8xLoopMulEnd
mov x0, x1 // x0 = &a[8]
mov x22, xzr
//########################################
//# a[0~7] * a[8~15] #
//########################################
.LSqr8xHighMulBegian:
mov x19, #-8*8 // Loop range. x0 can retrieve a[0–7] based on this offset.
ldp x14 , x15 , [x2, #8*0] // x14 = t[8] , x15 = t[9]
adds x27, x27, x14 // t[8](t[8] reserved in the previous round of calculation) + = t[8]
// (t[8] taken from memory, initially 0)
adcs x28, x28, x15 // t[9] += t[9], be the same as the above
ldp x16 , x17 , [x2, #8*2] // x16 = t[10], x17 = t[11]
ldp x14 , x15 , [x1], #16 // x14 = a[8], x15 = a[9]
adcs x25, x25, x16
adcs x26, x26, x17
ldp x6, x7, [x2, #8*4] // x6 = t[12], x7 = t[13]
ldp x16 , x17 , [x1], #16 // x16 = a[10], x17 = a[11]
adcs x23, x23, x6
adcs x24, x24, x7
ldp x8, x9, [x2, #8*6] // x8 = t[14], x9 = t[15]
ldp x6, x7, [x1], #16 // x6 = a[12], x7 = a[13]
adcs x21, x21, x8
adcs x22, x22, x9 // t[15] = t[15] + CF, Because a[7]*a[7] is not calculated previously, t[15]=0
ldp x8, x9, [x1], #16 // x8 = a[14], x9 = a[15]
.LSqr8xHighMulProces:
ldr x4 , [x0, x19] // x4 = [x0 + x19] = [x0 - 56] = [&a[8] - 56] = a[8 - 7] = a[1]
//-----lo(a[0] * a[8~11])-----
adc x20, xzr, xzr // x20 += CF, Save the carry of t[15]. The same operation is performed below.
add x19, x19, #8 // x19 += 8, Loop step size
mul x10, x4 , x14 // x4 = a[0], x14 = a[8], x10 = lo(a[0] * a[8])
mul x11, x4 , x15 // x11 = lo(a[0] * a[9])
mul x12, x4 , x16 // x12 = lo(a[0] * a[10])
mul x13, x4 , x17 // x13 = lo(a[0] * a[11])
//-----lo(a[0] * a[12~15])-----
adds x27, x27, x10 // CF does not need to be added for the first calculation,
// t[8] += lo(a[0] * a[8])
adcs x28, x28, x11 // t[9] += lo(a[0] * a[9])
adcs x25, x25, x12 // t[10] += lo(a[0] * a[10])
adcs x26, x26, x13 // t[11] += lo(a[0] * a[11])
mul x10, x4 , x6
mul x11, x4 , x7
mul x12, x4 , x8
mul x13, x4 , x9
//-----hi(a[0] * a[8~11])-----
adcs x23, x23, x10 // t[12] += lo(a[0] * a[12])
adcs x24, x24, x11 // t[13] += lo(a[0] * a[13])
adcs x21, x21, x12 // t[14] += lo(a[0] * a[14])
adcs x22, x22, x13 // t[15] += lo(a[0] * a[15])
umulh x10, x4 , x14
umulh x11, x4 , x15
umulh x12, x4 , x16
umulh x13, x4 , x17
adc x20, x20, xzr // x20 += CF, Save the carry of t[15]
str x27, [x2], #8 // [x2] = t[8], x2 += 8, x27~x22 = t[9~16],
// Update the mapping relationship to facilitate cycling.
// x27~x26 always correspond to t[m~m+7], and x19 is always the LSB of the window
//-----hi(a[0] * a[12~15])-----
adds x27, x28, x10 // t[9] += hi(a[0] * a[8]), The last calculation was to calculate t[15],
// so carry cannot be added to t[9], so adds is used
adcs x28, x25, x11 // t[10] += hi(a[0] * a[9])
adcs x25, x26, x12 // t[11] += hi(a[0] * a[10])
adcs x26, x23, x13 // t[12] += hi(a[0] * a[11])
umulh x10, x4 , x6
umulh x11, x4 , x7
umulh x12, x4 , x8
umulh x13, x4 , x9 // x13 = hi(a[0] * a[15])
adcs x23, x24, x10 // t[13] += hi(a[0] * a[12])
adcs x24, x21, x11 // t[14] += hi(a[0] * a[13])
adcs x21, x22, x12 // t[15] += hi(a[0] * a[14])
adcs x22, x20, x13 // t[16] = hi(a[0] * a[15]) + CF
cbnz x19, .LSqr8xHighMulProces // When exiting the loop, x0 = &a[8], x2 = &t[16]
sub x16, x1, x3 // x3 = x1 + x5 * 8(Converted to bytes), When x1 = x3, the loop ends.
cbnz x16, .LSqr8xHighMulBegian // x0 is the outer loop, x1 is the inner loop, and the inner loop ends.
// In this case, x2 = &a[size], out-of-bounds position.
mov x1, x0 // Outer Loop Increment, x1 = &a[16]
ldp x14 , x15 , [x1], #16 // x14 = a[8] , x15 = a[9]
ldp x16 , x17 , [x1], #16 // x16 = a[10], x17 = a[11]
ldp x6, x7, [x1], #16 // x6 = a[12], x7 = a[13]
ldp x8, x9, [x1], #16 // x8 = a[14], x9 = a[15]
sub x10, x3 , x1 // Check whether the outer loop ends, x3 = &a[size], x10 = (size - 16)*8
cbz x10, .LSqr8xLoopMul
sub x11, x2 , x10 // x2 = &t[24], x11 = &t[16]
stp x27, x28, [x2 , #8*0] // t[24] = x27, t[25] = x28
ldp x27, x28, [x11, #8*0] // x27 = t[16], x28 = t[17]
stp x25, x26, [x2 , #8*2] // t[26] = x25, t[27] = x26
ldp x25, x26, [x11, #8*2] // x25 = t[18], x26 = t[19]
stp x23, x24, [x2 , #8*4] // t[28] = x23, t[29] = x24
ldp x23, x24, [x11, #8*4] // x23 = t[20], x24 = t[21]
stp x21, x22, [x2 , #8*6] // t[30] = x21, t[31] = x22
ldp x21, x22, [x11, #8*6] // x21 = t[22], x22 = t[23]
mov x2 , x11 // x2 = &t[16]
b .LSqr8xLoopMul
.align 4
.LSqr8xLoopMulEnd:
//===== Calculate the squared term =====
//----- sp = &t[0] , x2 = &t[24]-----
sub x10, x3, x5 // x10 = a[0]
stp x27, x28, [x2, #8*0] // t[24] = x27, t[25] = x28
stp x25, x26, [x2, #8*2] // When this step is performed, the calculation results reserved for x27–x26
// are not pushed to the stack.
stp x23, x24, [x2, #8*4]
stp x21, x22, [x2, #8*6]
ldp x11, x12, [sp, #8*1] // x11 = t[1], x12 = t[2]
ldp x15, x17, [x10], #16 // x15 = a[0], x17 = a[1]
ldp x7, x9, [x10], #16 // x7 = a[2], x9 = a[3]
mov x1, x10
ldp x13, x10, [sp, #8*3] // x13 = t[3], x10 = t[4]
mul x27, x15, x15 // x27 = lo(a[0] * a[0])
umulh x15, x15, x15 // x15 = hi(a[0] * a[0])
mov x2 , sp // x2 = sp = &t[0]
mul x16, x17, x17 // x16 = lo(a[1] * a[1])
adds x28, x15, x11, lsl#1 // x28 = x15 + (x11 * 2) = hi(a[0] * a[0]) + 2 * t[1]
umulh x17, x17, x17 // x17 = hi(a[1] * a[1])
extr x11, x12, x11, #63 // Lower 63 bits of x11 = x16 | most significant bit of x15
// Cyclic right shift by 63 bits to obtain the lower bit,
// which is equivalent to cyclic left shift by 1 bit to obtain the upper bit.
// The purpose is to *2.
// x11 = 2*t[2](Ignore the overflowed part) + carry of (2*t[1])
mov x19, x5 // x19 = size*8
.LSqr8xDealSquare:
adcs x25, x16 , x11 // x25 = lo(a[1] * a[1]) + 2*t[2]
extr x12, x13, x12, #63 // x12 = 2*t[3](Ignore the overflowed part) + carry of (2*t[2])
adcs x26, x17 , x12 // x26 = hi(a[1] * a[1]) + 2*t[3]
sub x19, x19, #8*4 // x19 = (size - 8)*8
stp x27, x28, [x2], #16 // t[0~3]Re-push stack
stp x25, x26, [x2], #16
mul x6, x7, x7 // x6 = lo(a[2] * a[2])
umulh x7, x7, x7 // x7 = hi(a[2] * a[2])
mul x8, x9, x9 // x6 = lo(a[3] * a[3])
umulh x9, x9, x9 // x7 = hi(a[3] * a[3])
ldp x11, x12, [x2, #8] // x11 = t[5], x12 = t[6]
extr x13, x10, x13, #63 // x13 = 2*t[4](Ignore the overflowed part) + carry of(2*t[3])
extr x10, x11, x10, #63 // x10 = 2*t[5](Ignore the overflowed part) + carry of(2*t[4])
adcs x23, x6, x13 // x23 = lo(a[2] * a[2]) + 2*t[4]
adcs x24, x7, x10 // x24 = hi(a[2] * a[2]) + 2*t[5]
cbz x19, .LSqr8xReduceStart
ldp x13, x10, [x2, #24] // x13 = t[7], x10 = t[8]
extr x11, x12, x11, #63 // x11 = 2*t[6](Ignore the overflowed part) + carry of(2*t[5])
extr x12, x13, x12, #63 // x12 = 2*t[7](Ignore the overflowed part) + carry of(2*t[6])
adcs x21, x8, x11 // x21 = lo(a[3] * a[3]) + 2*t[6]
adcs x22, x9, x12 // x22 = hi(a[3] * a[3]) + 2*t[7]
stp x23, x24, [x2], #16 // t[4~7]re-push stack
stp x21, x22, [x2], #16
ldp x15, x17, [x1], #8*2 // x15 = a[4], x17 = a[5], x1 += 16 = &a[6]
ldp x11, x12, [x2, #8] // x11 = t[9], x12 = t[10]
mul x14 , x15 , x15 // x14 = lo(a[4] * a[4])
umulh x15 , x15 , x15 // x15 = hi(a[4] * a[4])
mul x16 , x17 , x17 // x16 = lo(a[5] * a[5])
umulh x17 , x17 , x17 // x17 = hi(a[5] * a[5])
extr x13, x10, x13, #63 // x13 = 2*t[8](Ignore the overflowed part) + carry of(2*t[7])
adcs x27, x14 , x13 // x27 = lo(a[4] * a[4]) + 2*t[8]
extr x10, x11, x10, #63 // x10 = 2*t[9](Ignore the overflowed part) + carry of(2*t[8])
adcs x28, x15 , x10 // x28 = hi(a[4] * a[4]) + 2*t[9]
extr x11, x12, x11, #63 // x11 = 2*t[10](Ignore the overflowed part) + carry of(2*t[9])
ldp x13, x10, [x2, #8*3] // Line 438 has obtained t[9] and t[10], x13 = &t[11], x10 = &t[12]
ldp x7, x9, [x1], #8*2 // x7 = a[6], x9 = a[7], x1 += 16 = &a[8]
b .LSqr8xDealSquare
.LSqr8xReduceStart:
extr x11, x12, x11, #63 // x11 = 2*t[2*size-2](Ignore the overflowed part) + carry of (2*t[2*size-3])
adcs x21, x8, x11 // x21 = lo(a[size-1] * a[size-1]) + 2*t[2*size-2]
extr x12, xzr, x12, #63 // x12 = 2*t[2*size-1](Ignore the overflowed part) + carry of (2*t[2*size-2])
adc x22, x9, x12 // x22 = hi(a[size-1] * a[size-1]) + 2*t[2*size-1]
ldp x1, x4, [x29, #104] // Pop n and k0 out of the stack, x1 = &n[0], x4 = k0
stp x23, x24, [x2] // t[2*size-4 ~ 2*size-1]re-push stack
stp x21, x22, [x2,#8*2]
cmp x5, #64 // if size == 8, we can goto Single step reduce
b.ne .LSqr8xReduceLoop
ldp x14 , x15 , [x1], #16 // x14~x9 = n[0~7]
ldp x16 , x17 , [x1], #16
ldp x6, x7, [x1], #16
ldp x8, x9, [x1], #16
ldp x27, x28, [sp] // x14~x9 = t[0~7]
ldp x25, x26, [sp,#8*2]
ldp x23, x24, [sp,#8*4]
ldp x21, x22, [sp,#8*6]
mov x19, #8
mov x2 , sp
// if size == 8, goto single reduce step
.LSqr8xSingleReduce:
mul x20, x4, x27
sub x19, x19, #1
//----- lo(n[1~7] * lo(t[0]*k0)) -----
mul x11, x15 , x20
mul x12, x16 , x20
mul x13, x17 , x20
mul x10, x6, x20
cmp x27, #1
adcs x27, x28, x11
adcs x28, x25, x12
adcs x25, x26, x13
adcs x26, x23, x10
mul x11, x7, x20
mul x12, x8, x20
mul x13, x9, x20
//----- hi(n[0~7] * lo(t[0]*k0)) -----
adcs x23, x24, x11
adcs x24, x21, x12
adcs x21, x22, x13
adc x22, xzr, xzr // x22 += CF
umulh x10, x14 , x20
umulh x11, x15 , x20
umulh x12, x16 , x20
umulh x13, x17 , x20
adds x27, x27, x10
adcs x28, x28, x11
adcs x25, x25, x12
adcs x26, x26, x13
umulh x10, x6, x20
umulh x11, x7, x20
umulh x12, x8, x20
umulh x13, x9, x20
adcs x23, x23, x10
adcs x24, x24, x11
adcs x21, x21, x12
adc x22, x22, x13
cbnz x19, .LSqr8xSingleReduce // Need cycle 8 times
ldp x10, x11, [x2, #64] // x10 = t[8], x11 = t[9]
ldp x12, x13, [x2, #80]
adds x27, x27, x10
adcs x28, x28, x11
ldp x10, x11, [x2, #96]
adcs x25, x25, x12
adcs x26, x26, x13
adcs x23, x23, x10
ldp x12, x13, [x2, #112]
adcs x24, x24, x11
adcs x21, x21, x12
adcs x22, x22, x13
adc x20, xzr, xzr
ldr x0, [x29, #96] // r Pop-Stack
// t - mod
subs x14, x27, x14
sbcs x15, x28, x15
sbcs x16, x25, x16
sbcs x17, x26, x17
sbcs x6, x23, x6
sbcs x7, x24, x7
sbcs x8, x21, x8
sbcs x9, x22, x9
sbcs x20, x20, xzr // determine whether there is a borrowing
// according to CF choose our result
csel x14 , x27, x14 , lo
csel x15 , x28, x15 , lo
csel x16 , x25, x16 , lo
csel x17 , x26, x17 , lo
stp x14 , x15 , [x0, #8*0]
csel x6, x23, x6, lo
csel x7, x24, x7, lo
stp x16 , x17 , [x0, #8*2]
csel x8, x21, x8, lo
csel x9, x22, x9, lo
stp x6, x7, [x0, #8*4]
stp x8, x9, [x0, #8*6]
b .LMontSqr8xEnd
.LSqr8xReduceLoop:
add x3, x1, x5 // x3 = &n[size]
mov x30, xzr
ldp x14 , x15 , [x1], #16 // x14~x9 = n[0~7]
ldp x16 , x17 , [x1], #16
ldp x6, x7, [x1], #16
ldp x8, x9, [x1], #16
ldp x27, x28, [sp] // x27 = t[0], x28 = t[1]
ldp x25, x26, [sp,#8*2] // x25~x22 = t[2~7]
ldp x23, x24, [sp,#8*4]
ldp x21, x22, [sp,#8*6]
mov x19, #8
mov x2 , sp
.LSqr8xReduceProcess:
mul x20, x4, x27 // x20 = lo(k0 * t[0])
sub x19, x19, #1
//----- lo(n[1~7] * lo(t[0]*k0)) -----
mul x11, x15, x20 // x11 = n[1] * lo(t[0]*k0)
mul x12, x16, x20 // x12 = n[2] * lo(t[0]*k0)
mul x13, x17, x20 // x13 = n[3] * lo(t[0]*k0)
mul x10, x6, x20 // x10 = n[4] * lo(t[0]*k0)
str x20, [x2], #8 // Push lo(t[0]*k0) on the stack., x2 += 8
cmp x27, #1 // Check whether the low location is carried.
adcs x27, x28, x11 // x27 = t[1] + lo(n[1] * lo(t[0]*k0))
adcs x28, x25, x12 // x28 = t[2] + lo(n[2] * lo(t[0]*k0))
adcs x25, x26, x13 // x25 = t[3] + lo(n[3] * lo(t[0]*k0))
adcs x26, x23, x10 // x26 = t[4] + lo(n[4] * lo(t[0]*k0))
mul x11, x7, x20
mul x12, x8, x20
mul x13, x9, x20
//----- hi(n[0~7] * lo(t[0]*k0)) -----
adcs x23, x24, x11 // x23 = t[5] + lo(n[5] * lo(t[0]*k0))
adcs x24, x21, x12 // x24 = t[6] + lo(n[6] * lo(t[0]*k0))
adcs x21, x22, x13 // x21 = t[7] + lo(n[7] * lo(t[0]*k0))
adc x22, xzr, xzr // x22 += CF
umulh x10, x14 , x20
umulh x11, x15 , x20
umulh x12, x16 , x20
umulh x13, x17 , x20
adds x27, x27, x10 // x27 += hi(n[0] * lo(t[0]*k0))
adcs x28, x28, x11 // x28 += hi(n[1] * lo(t[0]*k0))
adcs x25, x25, x12 // x25 += hi(n[2] * lo(t[0]*k0))
adcs x26, x26, x13 // x26 += hi(n[3] * lo(t[0]*k0))
umulh x10, x6, x20
umulh x11, x7, x20
umulh x12, x8, x20
umulh x13, x9, x20
adcs x23, x23, x10 // x23 += hi(n[4] * lo(t[0]*k0))
adcs x24, x24, x11 // x24 += hi(n[5] * lo(t[0]*k0))
adcs x21, x21, x12 // x21 += hi(n[6] * lo(t[0]*k0))
adc x22, x22, x13 // x22 += hi(n[7] * lo(t[0]*k0))
cbnz x19, .LSqr8xReduceProcess // Cycle 8 times, and at the end of the cycle, x2 += 8*8
ldp x10, x11, [x2, #8*0] // x10 = t[8], x11 = t[9]
ldp x12, x13, [x2, #8*2]
mov x0, x2
adds x27, x27, x10
adcs x28, x28, x11
ldp x10, x11, [x2,#8*4]
adcs x25, x25, x12
adcs x26, x26, x13
ldp x12, x13, [x2,#8*6]
adcs x23, x23, x10
adcs x24, x24, x11
adcs x21, x21, x12
adcs x22, x22, x13
ldr x4 , [x2, #-8*8] // x4 = t[0]
ldp x14 , x15 , [x1], #16 // x14~x9 = &n[8]~&n[15]
ldp x16 , x17 , [x1], #16
ldp x6, x7, [x1], #16
ldp x8, x9, [x1], #16
mov x19, #-8*8
.LSqr8xReduce:
adc x20, xzr, xzr // x20 = CF
add x19, x19, #8
mul x10, x14 , x4
mul x11, x15 , x4
mul x12, x16 , x4
mul x13, x17 , x4
adds x27, x27, x10
adcs x28, x28, x11
adcs x25, x25, x12
adcs x26, x26, x13
mul x10, x6, x4
mul x11, x7, x4
mul x12, x8, x4
mul x13, x9, x4
adcs x23, x23, x10
adcs x24, x24, x11
adcs x21, x21, x12
adcs x22, x22, x13
umulh x10, x14 , x4
umulh x11, x15 , x4
umulh x12, x16 , x4
umulh x13, x17 , x4
adc x20, x20, xzr
str x27, [x2], #8 // x27 = t[8], x2 += 8
adds x27, x28, x10 // x27 = t[1] + lo(n[1] * lo(t[0]*k0))
adcs x28, x25, x11 // x28 = t[2] + lo(n[2] * lo(t[0]*k0))
adcs x25, x26, x12 // x25 = t[3] + lo(n[3] * lo(t[0]*k0))
adcs x26, x23, x13 // x26 = t[4] + lo(n[4] * lo(t[0]*k0))
umulh x10, x6, x4
umulh x11, x7, x4
umulh x12, x8, x4
umulh x13, x9, x4
// x0 = &t[8]
ldr x4 , [x0, x19]
adcs x23, x24, x10
adcs x24, x21, x11
adcs x21, x22, x12
adcs x22, x20, x13
cbnz x19, .LSqr8xReduce
ldp x14 , x15 , [x2, #8*0]
ldp x16 , x17 , [x2, #8*2]
sub x19, x3, x1 // x19 = (size-16)*8
ldp x6, x7, [x2, #8*4]
ldp x8, x9, [x2, #8*6]
cbz x19, .LSqr8xReduceBreak
ldr x4 , [x0, #-8*8]
adds x27, x27, x14
adcs x28, x28, x15
adcs x25, x25, x16
adcs x26, x26, x17
adcs x23, x23, x6
adcs x24, x24, x7
adcs x21, x21, x8
adcs x22, x22, x9
ldp x14 , x15 , [x1], #16
ldp x16 , x17 , [x1], #16
ldp x6, x7, [x1], #16
ldp x8, x9, [x1], #16
mov x19, #-8*8
b .LSqr8xReduce
.align 4
.LSqr8xReduceBreak:
sub x12, x3, x5 // x12 = n, reassign to n
ldr x4 , [x29, #112] // k0 pop-stack
cmp x30, #1 // Check whether the low location is carried.
adcs x10, x27, x14
adcs x11, x28, x15
stp x10, x11, [x2] , #16
ldp x27 ,x28, [x0 , #8*0]
ldp x14 , x15, [x12], #16 // x12 = &n[0] (Line 638 assigns a value)
adcs x25, x25, x16
adcs x26, x26, x17
adcs x23, x23, x6
adcs x24, x24, x7
adcs x21, x21, x8
adcs x22, x22, x9
adc x30, xzr, xzr
ldp x16, x17, [x12], #16
ldp x6, x7, [x12], #16
ldp x8, x9, [x12], #16
stp x25, x26, [x2], #16
ldp x25, x26, [x0, #8*2]
stp x23, x24, [x2], #16
ldp x23, x24, [x0, #8*4]
stp x21, x22, [x2], #16
ldp x21, x22, [x0, #8*6]
sub x20, x2, x29 // Check whether the loop ends
mov x1, x12
mov x2, x0 // sliding window
mov x19, #8
cbnz x20, .LSqr8xReduceProcess
// Final step
ldr x0 , [x29, #96] // r Pop-Stack
add x2 , x2 , #8*8
subs x10, x27, x14
sbcs x11, x28, x15
sub x19, x5 , #8*8
mov x3 , x0 // backup x0
.LSqr8xSubMod:
ldp x14 , x15, [x1], #16
sbcs x12, x25, x16
sbcs x13, x26, x17
ldp x16 , x17 , [x1], #16
stp x10, x11, [x0], #16
stp x12, x13, [x0], #16
sbcs x10, x23, x6
sbcs x11, x24, x7
ldp x6, x7, [x1], #16
sbcs x12, x21, x8
sbcs x13, x22, x9
ldp x8, x9, [x1], #16
stp x10, x11, [x0], #16
stp x12, x13, [x0], #16
ldp x27, x28, [x2], #16
ldp x25, x26, [x2], #16
ldp x23, x24, [x2], #16
ldp x21, x22, [x2], #16
sub x19, x19, #8*8
sbcs x10, x27, x14
sbcs x11, x28, x15
cbnz x19, .LSqr8xSubMod
mov x2 , sp
add x1 , sp , x5
sbcs x12, x25, x16
sbcs x13, x26, x17
stp x12, x13, [x0, #8*2]
stp x10, x11, [x0, #8*0]
sbcs x10, x23, x6
sbcs x11, x24, x7
stp x10, x11, [x0, #8*4]
sbcs x12, x21, x8
sbcs x13, x22, x9
stp x12, x13, [x0, #8*6]
sbcs xzr, x30, xzr // Determine whether there is a borrowing
.LSqr8xCopy:
ldp x14, x15, [x3, #8*0]
ldp x16, x17, [x3, #8*2]
ldp x6, x7, [x3, #8*4]
ldp x8, x9, [x3, #8*6]
ldp x27, x28, [x1], #16
ldp x25, x26, [x1], #16
ldp x23, x24, [x1], #16
ldp x21, x22, [x1], #16
sub x5, x5, #8*8
csel x10, x27, x14, lo // Condition selection instruction, lo = less than,
// equivalent to x14 = (conf==lo) ? x27 : x14
csel x11, x28, x15, lo
csel x12, x25, x16 , lo
csel x13, x26, x17, lo
csel x14, x23, x6, lo
csel x15, x24, x7, lo
csel x16, x21, x8, lo
csel x17, x22, x9, lo
stp x10, x11, [x3], #16
stp x12, x13, [x3], #16
stp x14, x15, [x3], #16
stp x16, x17, [x3], #16
cbnz x5, .LSqr8xCopy
.LMontSqr8xEnd:
ldr x30, [x29, #8] // Pop-Stack
ldp x27, x28, [x29, #16]
mov sp , x29
ldp x25, x26, [x29, #32]
mov x0 , #1
ldp x23, x24, [x29, #48]
ldp x21, x22, [x29, #64]
ldp x19, x20, [x29, #80] // x19 = [x29 + 80], x20 = [x29 + 80 + 8],
// ldp reads two 8-byte memory blocks at a time.
ldr x29, [sp], #128 // x29 = [sp], sp = sp + 128,ldr reads only an 8-byte block of memory
AARCH64_AUTIASP
ret
.size MontSqr8, .-MontSqr8
.type MontMul4, %function
MontMul4:
AARCH64_PACIASP
stp x29, x30, [sp, #-128]!
mov x29, sp
stp x27, x28, [sp, #16]
stp x25, x26, [sp, #32]
stp x23, x24, [sp, #48]
stp x21, x22, [sp, #64]
stp x19, x20, [sp, #80]
mov x27, xzr
mov x28, xzr
mov x25, xzr
mov x26, xzr
mov x30, xzr
lsl x5 , x5 , #3
sub x22, sp , x5
sub sp , x22, #8*4 // The space of size + 4 is applied for
mov x22, sp
sub x6, x5, #32
cbnz x6, .LMul4xProcesStart
ldp x14 , x15 , [x1, #8*0]
ldp x16 , x17 , [x1, #8*2] // x14~x17 = a[0~3]
ldp x10, x11, [x3] // x10~x13 = n[0~3]
ldp x12, x13, [x3, #8*2]
mov x1 , xzr
mov x20, #4
// if size == 4, goto single step
.LMul4xSingleStep:
sub x20, x20, #0x1
ldr x24, [x2], #8 // b[i]
//----- lo(a[0~3] * b[0]) -----
mul x6, x14 , x24
mul x7, x15 , x24
mul x8, x16 , x24
mul x9, x17 , x24
//----- hi(a[0~3] * b[0]) -----
adds x27, x27, x6
umulh x6, x14 , x24
adcs x28, x28, x7
umulh x7, x15 , x24
adcs x25, x25, x8
umulh x8, x16 , x24
adcs x26, x26, x9
umulh x9, x17 , x24
mul x21, x27, x4
adc x23, xzr, xzr
//----- lo(n[0~3] * t[0]*k0) -----
adds x28, x28, x6
adcs x25, x25, x7
mul x7, x11, x21
adcs x26, x26, x8
mul x8, x12, x21
adc x23, x23, x9
mul x9, x13, x21
cmp x27, #1
adcs x27, x28, x7
//----- hi(n[0~3] *t[0]*k0) -----
umulh x6, x10, x21
umulh x7, x11, x21
adcs x28, x25, x8
umulh x8, x12, x21
adcs x25, x26, x9
umulh x9, x13, x21
adcs x26, x23, x1
adc x1 , xzr, xzr
adds x27, x27, x6
adcs x28, x28, x7
adcs x25, x25, x8
adcs x26, x26, x9
adc x1 , x1 , xzr
cbnz x20, .LMul4xSingleStep
subs x14 , x27, x10
sbcs x15 , x28, x11
sbcs x16 , x25, x12
sbcs x17 , x26, x13
sbcs xzr, x1 , xzr // update CF, Determine whether to borrow
csel x14 , x27, x14 , lo
csel x15 , x28, x15 , lo
csel x16 , x25, x16 , lo
csel x17 , x26, x17 , lo
stp x14 , x15 , [x0, #8*0]
stp x16 , x17 , [x0, #8*2]
b .LMontMul4xEnd
.LMul4xProcesStart:
add x6, x5, #32
eor v0.16b,v0.16b,v0.16b
eor v1.16b,v1.16b,v1.16b
.LMul4xInitstack:
sub x6, x6, #32
st1 {v0.2d, v1.2d}, [x22], #32
cbnz x6, .LMul4xInitstack
mov x22, sp
add x6, x2 , x5 // x6 = &b[size]
adds x19, x1 , x5 // x19 = &a[size]
stp x0 , x6, [x29, #96] // r and b[size] push stack
mov x0 , xzr
mov x20, #0
.LMul4xLoopProces:
ldr x24, [x2] // x24 = b[0]
ldp x14 , x15 , [x1], #16
ldp x16 , x17 , [x1], #16 // x14~x17 = a[0~3]
ldp x10 , x11 , [x3], #16
ldp x12 , x13 , [x3], #16 // x10~x13 = n[0~3]
.LMul4xPrepare:
//----- lo(a[0~3] * b[0]) -----
adc x0 , x0 , xzr // x0 += CF
add x20, x20, #8
and x20, x20, #31 // x20 &= 0xff. The lower eight bits are used.
// When x28 = 32, the instruction becomes 0.
mul x6, x14 , x24
mul x7, x15 , x24
mul x8, x16 , x24
mul x9, x17 , x24
//----- hi(a[0~3] * b[0]) -----
adds x27, x27, x6 // t[0] += lo(a[0] * b[0])
adcs x28, x28, x7 // t[1] += lo(a[1] * b[0])
adcs x25, x25, x8 // t[2] += lo(a[2] * b[0])
adcs x26, x26, x9 // t[3] += lo(a[3] * b[0])
umulh x6, x14 , x24 // x6 = hi(a[0] * b[0])
umulh x7, x15 , x24
umulh x8, x16 , x24
umulh x9, x17 , x24
mul x21, x27, x4 // x21 = t[0] * k0, t[0]*k0 needs to be recalculated in each round.
// t[0] is different in each round.
adc x23, xzr, xzr // t[4] += CF(set by t[3] += lo(a[3] * b[0]) )
ldr x24, [x2, x20] // b[i]
str x21, [x22], #8 // t[0] * k0 push stack, x22 += 8
//----- lo(n[0~3] * t[0]*k0) -----
adds x28, x28, x6 // t[1] += hi(a[0] * b[0])
adcs x25, x25, x7 // t[2] += hi(a[1] * b[0])
adcs x26, x26, x8 // t[3] += hi(a[2] * b[0])
adc x23, x23, x9 // t[4] += hi(a[3] * b[0])
mul x7, x11, x21 // x7 = lo(n[1] * t[0]*k0)
mul x8, x12, x21 // x8 = lo(n[2] * t[0]*k0)
mul x9, x13, x21 // x9 = lo(n[3] * t[0]*k0)
cmp x27, #1
adcs x27, x28, x7 // (t[0]) = x27 = t[1] + lo(n[1] * t[0]*k0),
// Perform S/R operations, r=2^64, shift right 64 bits.
//----- hi(n[0~3] *t[0]*k0) -----
adcs x28, x25, x8 // x28 = t[2] + lo(n[2] * t[0]*k0)
adcs x25, x26, x9 // x25 = t[3] + lo(n[3] * t[0]*k0)
adcs x26, x23, x0 // x26 = t[4] + 0 + CF
adc x0 , xzr, xzr // x0 = CF
umulh x6, x10, x21 // x6 = hi(n[0] * t[0]*k0)
umulh x7, x11, x21 // x7 = hi(n[1] * t[0]*k0)
umulh x8, x12, x21 // x8 = hi(n[2] * t[0]*k0)
umulh x9, x13, x21 // x9 = hi(n[3] * t[0]*k0)
adds x27, x27, x6 // x27 = t[1] + hi(n[0] * t[0]*k0)
adcs x28, x28, x7 // x28 = t[2] + hi(n[1] * t[0]*k0)
adcs x25, x25, x8 // x25 = t[3] + hi(n[2] * t[0]*k0)
adcs x26, x26, x9 // x26 = t[4] + hi(n[3] * t[0]*k0)
cbnz x20, .LMul4xPrepare
// Four t[0] * k0s are stacked in each loop.
adc x0 , x0 , xzr
ldp x6, x7, [x22, #8*4] // load A (cal before)
ldp x8, x9, [x22, #8*6]
adds x27, x27, x6
adcs x28, x28, x7
adcs x25, x25, x8
adcs x26, x26, x9
ldr x21, [sp] // x21 = t[0] * k0
.LMul4xReduceBegin:
ldp x14 , x15 , [x1], #16
ldp x16 , x17 , [x1], #16 // x14~x17 = a[4~7]
ldp x10 , x11 , [x3], #16
ldp x12 , x13 , [x3], #16 // n[4~7]
.LMul4xReduceProces:
adc x0 , x0 , xzr
add x20, x20, #8
and x20, x20, #31
//----- lo(a[4~7] * b[i]) -----
mul x6, x14 , x24
mul x7, x15 , x24
mul x8, x16 , x24
mul x9, x17 , x24
//----- hi(a[4~7] * b[i]) -----
adds x27, x27, x6 // x27 += lo(a[4~7] * b[i])
adcs x28, x28, x7
adcs x25, x25, x8
adcs x26, x26, x9
adc x23, xzr, xzr
umulh x6, x14 , x24
umulh x7, x15 , x24
umulh x8, x16 , x24
umulh x9, x17 , x24
ldr x24, [x2, x20] // b[i]
//----- lo(n[4~7] * t[0]*k0) -----
adds x28, x28, x6
adcs x25, x25, x7
adcs x26, x26, x8
adc x23, x23, x9
mul x6, x10, x21
mul x7, x11, x21
mul x8, x12, x21
mul x9, x13, x21
//----- hi(n[4~7] * t[0]*k0) -----
adds x27, x27, x6
adcs x28, x28, x7
adcs x25, x25, x8
adcs x26, x26, x9
adcs x23, x23, x0
umulh x6, x10, x21
umulh x7, x11, x21
umulh x8, x12, x21
umulh x9, x13, x21
ldr x21, [sp, x20] // t[0]*k0
adc x0 , xzr, xzr // x0 = CF, record carry
str x27, [x22], #8 // s[i] the calculation is complete, write the result, x22 += 8
adds x27, x28, x6
adcs x28, x25, x7
adcs x25, x26, x8
adcs x26, x23, x9
cbnz x20, .LMul4xReduceProces
sub x6, x19, x1 // x6 = &a[size] - &a[i]
// (The value of x1 increases cyclically.) Check whether the loop ends
adc x0 , x0 , xzr
cbz x6, .LMul4xLoopExitCheck
ldp x6, x7, [x22, #8*4] // t[4~7]
ldp x8, x9, [x22, #8*6]
adds x27, x27, x6
adcs x28, x28, x7
adcs x25, x25, x8
adcs x26, x26, x9
b .LMul4xReduceBegin
.LMul4xLoopExitCheck:
ldr x9, [x29, #104] // b[size] Pop-Stack
add x2 , x2 , #8*4 // b subscript is offset once by 4 each time, &b[4], &b[8]......
sub x9 , x9, x2 // Indicates whether the outer loop ends.
adds x27, x27, x30
adcs x28, x28, xzr
stp x27, x28, [x22, #8*0] // x27, x20 After the calculation is complete, Push-stack storage
ldp x27, x28, [sp , #8*4] // t[0], t[1]
adcs x25, x25, xzr
adcs x26, x26, xzr
stp x25, x26, [x22, #8*2] // x25, x22 After the calculation is complete, Push-stack storage
ldp x25, x26, [sp , #8*6] // t[2], t[3]
adc x30, x0 , xzr
sub x3 , x3 , x5 // x1 = &n[0]
cbz x9, .LMul4xEnd
sub x1 , x1 , x5 // x1 = &a[0]
mov x22, sp
mov x0 , xzr
b .LMul4xLoopProces
.LMul4xEnd:
ldp x10, x11, [x3], #16
ldp x12, x13, [x3], #16
ldr x0, [x29, #96] // r[0] Pop-Stack
mov x19, x0 // backup, x19 = &r[0]
subs x6, x27, x10 // t[0] - n[0], modify CF
sbcs x7, x28, x11 // t[1] - n[1] - CF
add x22, sp , #8*8 // x22 = &S[8]
sub x20, x5 , #8*4 // x20 = (size - 4)*8
// t - n, x22 = &t[8], x3 = &n[0]
.LMul4xSubMod:
sbcs x8, x25, x12
sbcs x9, x26, x13
ldp x10, x11, [x3], #16
ldp x12, x13, [x3], #16
ldp x27, x28, [x22], #16
ldp x25, x26, [x22], #16
sub x20, x20, #8*4
stp x6, x7, [x0], 16
stp x8, x9, [x0], 16
sbcs x6, x27, x10
sbcs x7, x28, x11
cbnz x20, .LMul4xSubMod
sbcs x8, x25, x12
sbcs x9, x26, x13
sbcs xzr, x30, xzr // CF = x30 - CF, x30 recorded the previous carry
add x1 , sp , #8*4 // The size of the SP space is size + 4., x1 = sp + 4
stp x6, x7, [x0]
stp x8, x9, [x0, #8*2]
.LMul4xCopy:
ldp x14 , x15 , [x19] // x14~x17 = r[0~3]
ldp x16 , x17 , [x19, #8*2]
ldp x27, x28, [x1], #16 // x27~22 = S[4~7]
ldp x25, x26, [x1], #16
sub x5, x5, #8*4
csel x6, x27, x14, lo // x6 = (CF == 1) ? x27 : x14
csel x7, x28, x15, lo
csel x8, x25, x16, lo
csel x9, x26, x17, lo
stp x6, x7, [x19], #16
stp x8, x9, [x19], #16
cbnz x5, .LMul4xCopy
.LMontMul4xEnd:
ldr x30, [x29, #8] // Value Pop-Stack in x30 (address of next instruction)
ldp x27, x28, [x29, #16]
ldp x25, x26, [x29, #32]
ldp x23, x24, [x29, #48]
ldp x21, x22, [x29, #64]
ldp x19, x20, [x29, #80]
mov sp , x29
ldr x29, [sp], #128
AARCH64_AUTIASP
ret
.size MontMul4, .-MontMul4
#endif
|
2301_79861745/bench_create
|
crypto/bn/src/asm/bn_mont_armv8.S
|
Unix Assembly
|
unknown
| 51,548
|
/*
* 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_BN
.file "bn_mont_x86_64.S"
.text
.macro ADD_CARRY a b
addq \a,\b
adcq $0,%rdx
.endm
.macro SAVE_REGISTERS
pushq %r15 // Save non-volatile register.
pushq %r14
pushq %r13
pushq %r12
pushq %rbp
pushq %rbx
.endm
.macro RESTORE_REGISTERS
popq %rbx // Restore non-volatile register.
popq %rbp
popq %r12
popq %r13
popq %r14
popq %r15
.endm
/*
* void MontMul_Asm(uint64_t *r, const uint64_t *a, const uint64_t *b,
* const uint64_t *n, const uint64_t k0, uint32_t size);
*/
.globl MontMul_Asm
.type MontMul_Asm,@function
.align 16
MontMul_Asm:
.cfi_startproc
testl $3,%r9d
jnz .LMontMul // If size is not divisible by 4, LMontMul.
cmpl $8,%r9d
jb .LMontMul // LMontMul
cmpq %rsi,%rdx
jne MontMul4 // if a != b, MontMul4
testl $7,%r9d
jz MontSqr8 // If size is divisible by 8,enter MontSqr8.
jmp MontMul4
.align 16
.LMontMul:
SAVE_REGISTERS // Save non-volatile register.
movq %rsp,%rax // rax stores the rsp
movq %r9, %r15
negq %r15 // r15 = -size
leaq -16(%rsp, %r15, 8), %r15 // r15 = rsp - size * 8 - 16
andq $-1024, %r15 // r15 The address is aligned down by 1 KB.
movq %rsp, %r14 // r14 = rsp
subq %r15,%r14 // __chkstk implemention, called when the stack size needs to exceed 4096.
// (the size of a page) to allocate more pages.
andq $-4096,%r14 // r14 4K down-align.
leaq (%r15,%r14),%rsp // rsp = r15 + r14
cmpq %r15,%rsp // If you want to allocate more than one page, go to Lmul_page_walk.
ja .LoopPage
jmp .LMulBody
.align 16
.LoopPage:
leaq -4096(%rsp),%rsp // rsp - 4096 each time until rsp < r15.
cmpq %r15,%rsp
ja .LoopPage
.LMulBody:
movq %rax,8(%rsp,%r9,8) // Save the original rsp in the stack.
movq %rdx,%r13 // r13 = b
xorq %r11,%r11 // r11 = 0
xorq %r10,%r10 // r10 = 0
movq (%r13),%rbx // rbx = b[0]
movq (%rsi),%rax // rax = a[0]
mulq %rbx // (rdx, rax) = a[0] * b[0]
movq %rax,%r15 // r15 = t[0] = lo(a[0] * b[0])
movq %rdx,%r14 // r14 = hi(a[0] * b[0])
movq %r8,%rbp // rbp = k0
imulq %r15,%rbp // rbp = t[0] * k0
movq (%rcx),%rax // rax = n[0]
mulq %rbp // (rdx, rax) = t[0] * k0 * n[0]
ADD_CARRY %rax,%r15 // r15 = lo(t[0] * k0 * n[0]) + t[0]
leaq 1(%r10),%r10 // j++
.Loop1st:
movq (%rsi,%r10,8),%rax // rax = a[j]
movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[0])
mulq %rbx // (rdx, rax) = a[j] * b[0]
ADD_CARRY %rax,%r14 // r14 = hi(a[j - 1] * b[0]) + lo(a[j] * b[0])
movq %rdx,%r15 // r15 = hi(a[j] * b[0])
movq (%rcx,%r10,8),%rax // rax = n[j]
mulq %rbp // (rdx, rax) = t[0] * k0 * n[j]
leaq 1(%r10),%r10 // j++
cmpq %r9,%r10 // if j != size, loop L1st
je .Loop1stSkip
ADD_CARRY %rax,%r12 // r12 = hi(t[0] * k0 * n[j]) + lo(t[0] * k0 * n[j])
ADD_CARRY %r14,%r12 // r12 += lo(a[j] * b[0]) + hi(a[j] * b[0])
movq %r12,-16(%rsp,%r10,8) // t[j - 2] = r13
movq %r15,%r14 // r14 = hi(a[j] * b[0])
jmp .Loop1st
.Loop1stSkip:
ADD_CARRY %rax,%r12 // r12 = hi(t[0] * k0 * n[j - 1]) + lo(t[0] * k0 * n[j])
ADD_CARRY %r14,%r12 // r12 += hi(a[j - 1] * b[0]) + lo(a[j] * b[0])
movq %r12,-16(%rsp,%r10,8) // t[j - 2] = r13
movq %r15,%r14 // r14 = hi(a[j] * b[0])
movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j])
xorq %rdx,%rdx // rdx = 0, Clearing the CF.
ADD_CARRY %r14,%r12 // r12 = hi(t[0] * k0 * n[j]) + hi(a[j] * b[0])
movq %r12,-8(%rsp,%r9,8) // t[size - 1] = hi(t[0] * k0 * n[j]) + hi(a[j] * b[0]), save overflow bit.
movq %rdx,(%rsp,%r9,8)
leaq 1(%r11),%r11 // i++
.align 16
.LoopOuter:
xorq %r10,%r10 // j = 0
movq (%rsi),%rax // rax = a[0]
movq (%r13,%r11,8),%rbx // rbx = b[i]
mulq %rbx // (rdx, rax) = a[0] * b[i]
movq (%rsp),%r15 // r15 = lo(a[0] * b[i]) + t[0]
ADD_CARRY %rax,%r15
movq %rdx,%r14 // r14 = hi(a[0] * b[i])
movq %r8,%rbp // rbp = t[0] * k0
imulq %r15,%rbp
movq (%rcx),%rax // rax = n[0]
mulq %rbp // (rdx, rax) = t[0] * k0 * n[0]
ADD_CARRY %rax,%r15 // r15 = lo(t[0] * k0 * n[0])
leaq 1(%r10),%r10 // j++
.align 16
.LoopInner:
movq (%rsi,%r10,8),%rax // rax = a[j]
movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j])
movq (%rsp,%r10,8),%r15 // r15 = t[j]
mulq %rbx // (rdx, rax) = a[1] * b[i]
ADD_CARRY %rax,%r14 // r14 = hi(a[0] * b[i]) + lo(a[1] * b[i])
movq (%rcx,%r10,8),%rax // rax = n[j]
ADD_CARRY %r14,%r15 // r15 = a[j] * b[i] + t[j]
movq %rdx,%r14
leaq 1(%r10),%r10 // j++
mulq %rbp // (rdx, rax) = t[0] * k0 * n[j]
cmpq %r9,%r10 // if j != size, loop Linner
je .LoopInnerSkip
ADD_CARRY %rax,%r12 // r12 = t[0] * k0 * n[j]
ADD_CARRY %r15,%r12 // r12 = a[j] * b[i] + t[j] + n[j] * t[0] * k0
movq %r12,-16(%rsp,%r10,8) // t[j - 2] = r13
jmp .LoopInner
.LoopInnerSkip:
ADD_CARRY %rax,%r12 // r12 = t[0] * k0 * n[j]
ADD_CARRY %r15,%r12 // r12 = t[0] * k0 * n[j] + a[j] * b[i] + t[j]
movq (%rsp,%r10,8),%r15 // r15 = t[j]
movq %r12,-16(%rsp,%r10,8) // t[j - 2]
movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j])
xorq %rdx,%rdx // rdx 0
ADD_CARRY %r14,%r12 // r12 = hi(a[1] * b[i]) + hi(t[0] * k0 * n[j])
ADD_CARRY %r15,%r12 // r12 += t[j]
movq %r12,-8(%rsp,%r9,8) // t[size - 1] = r13
movq %rdx,(%rsp,%r9,8) // t[size] = CF
leaq 1(%r11),%r11 // i++
cmpq %r9,%r11 // if size < i (unsigned)
jne .LoopOuter
xorq %r11,%r11 // r11 = 0, clear CF.
movq (%rsp),%rax // rax = t[0]
movq %r9,%r10 // r10 = size
.align 16
.LoopSub:
sbbq (%rcx,%r11,8),%rax // r[i] = t[i] - n[i]
movq %rax,(%rdi,%r11,8)
movq 8(%rsp,%r11,8),%rax // rax = t[i + 1]
leaq 1(%r11),%r11 // i++
decq %r10 // j--
jnz .LoopSub // if j != 0
sbbq $0,%rax // rax -= CF
movq $-1,%rbx
xorq %rax,%rbx // rbx = !t[i + 1]
xorq %r11,%r11 // r11 = 0
movq %r9,%r10 // r10 = size
.LoopCopy:
movq (%rdi,%r11,8),%rcx // rcx = r[i] & t[i]
andq %rbx,%rcx
movq (%rsp,%r11,8),%rdx // rdx = CF & t[i]
andq %rax,%rdx
orq %rcx,%rdx
movq %rdx,(%rdi,%r11,8) // r[i] = t[i]
movq %r9,(%rsp,%r11,8) // t[i] = size
leaq 1(%r11),%r11 // i++
subq $1,%r10 // j--
jnz .LoopCopy // if j != 0
movq 8(%rsp,%r9,8),%rsi // rsi = pressed-stacked rsp.
movq $1,%rax // rax = 1
leaq (%rsi),%rsp // restore rsp.
RESTORE_REGISTERS // Restore non-volatile register.
ret
.cfi_endproc
.size MontMul_Asm,.-MontMul_Asm
.type MontMul4,@function
.align 16
MontMul4:
.cfi_startproc
SAVE_REGISTERS
movq %rsp,%rax // save rsp
movq %r9,%r15
negq %r15
leaq -32(%rsp,%r15,8),%r15 // Allocate space: size * 8 + 32 bytes.
andq $-1024,%r15
movq %rsp,%r14
subq %r15,%r14 // __chkstk implemention, called when the stack size needs to exceed 4096.
andq $-4096,%r14
leaq (%r15,%r14),%rsp
cmpq %r15,%rsp // If you want to allocate more than one page, go to LoopPage4x.
ja .LoopPage4x
jmp .LoopMul4x
.LoopPage4x:
leaq -4096(%rsp),%rsp // rsp - 4096each time until rsp >= r10.
cmpq %r15,%rsp
ja .LoopPage4x
.LoopMul4x:
xorq %r11,%r11 // i = 0
xorq %r10,%r10 // j = 0
movq %rax,8(%rsp,%r9,8)
movq %rdi,16(%rsp,%r9,8) // t[size + 2] = r
movq %rdx,%r13 // r13 = b
movq (%rsi),%rax // rax = a[0]
movq %r8,%rbp // rbp = k0
movq (%r13),%rbx // rbx = b[0]
/* 计算a[i] * b[0] * k[0] * n[j] */
mulq %rbx // (rdx, rax) = a[0] * b[0]
movq %rax,%r15 // r15 = t[0] = lo(b[0] * a[0])
movq (%rcx),%rax // rax = n[0]
imulq %r15,%rbp // rbp = t[0] * k0
movq %rdx,%r14 // r14 = hi(a[0] * b[0])
mulq %rbp // (rdx, rax) = t[0] * k0 * n[0]
ADD_CARRY %rax,%r15 // r15 = lo(t[0] * k0 * n[0])
movq 8(%rsi),%rax // rax = a[1]
movq %rdx,%rdi // rdi = hi(t[0] * k0 * n[0])
mulq %rbx // (rdx, rax) = a[1] * b[0]
ADD_CARRY %rax,%r14 // r14 = lo(a[1] * b[0]) + hi(a[0] * b[0])
movq 8(%rcx),%rax // rax = n[1]
movq %rdx,%r15 // r15 = hi(a[1] * b[0])
mulq %rbp // (rdx, rax) = t[0] * k0 * n[1]
ADD_CARRY %rax,%rdi // rdi = lo(t[0] * k0 * n[1]) + hi(t[0] * k0 * n[0])
movq 16(%rsi),%rax // rax = a[2]
ADD_CARRY %r14,%rdi // rdi += hi(a[0] * b[0]) + lo(a[1] * b[0])
movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[1])
movq %rdi,(%rsp) // t[0] = rdi
leaq 4(%r10),%r10 // j += 4
.align 16
.Loop1st4x:
mulq %rbx // (rdx, rax) = a[2] * b[0]
ADD_CARRY %rax,%r15 // r15 = hi(a[1] * b[0]) + lo(a[2] * b[0])
movq -16(%rcx,%r10,8),%rax // rax = n[j - 2]
movq %rdx,%r14 // r14 = hi[a[2] * b[0]]
mulq %rbp // (rdx, rax) = t[0] * k0 * n[j - 2]
ADD_CARRY %rax,%r12 // r12 = hi(t[0] * k0 * n[1]) + lo(t[0] * k0 * n[j - 2])
movq -8(%rsi,%r10,8),%rax // rax = a[j - 1]
ADD_CARRY %r15,%r12 // r12 += hi(a[1] * b[0]) + lo(a[2] * b[0])
movq %r12,-24(%rsp,%r10,8) // t[j - 3] = r13
movq %rdx,%rdi // rdi = hi(t[0] * k0 * n[j - 2])
mulq %rbx // (rdx, rax) = a[j - 1] * b[0]
ADD_CARRY %rax,%r14 // r14 = hi[a[2] * b[0]] + lo(a[j - 1] * b[0])
movq -8(%rcx,%r10,8),%rax // rax = n[j - 1]
movq %rdx,%r15 // r15 = hi(a[j - 1] * b[0])
mulq %rbp // (rdx, rax) = t[0] * k0 * n[j - 1]
ADD_CARRY %rax,%rdi // rdi = hi(t[0] * k0 * n[j - 2]) + lo(t[0] * k0 * n[j - 1]
movq (%rsi,%r10,8),%rax // rax = a[j]
ADD_CARRY %r14,%rdi // rdi += hi[a[2] * b[0]] + lo(a[j - 1] * b[0])
movq %rdi,-16(%rsp,%r10,8) // t[j - 2] = rdi
movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j - 1])
mulq %rbx // (rdx, rax) = a[j] * b[0]
ADD_CARRY %rax,%r15 // r15 = hi(a[j - 1] * b[0]) + lo(a[j] * b[0])
movq (%rcx,%r10,8),%rax // rax = n[j]
movq %rdx,%r14 // r14 = hi(a[j] * b[0])
mulq %rbp // (rdx, rax) = t[0] * k0 * n[j]
ADD_CARRY %rax,%r12 // r12 = hi(t[0] * k0 * n[j - 1]) + lo(t[0] * k0 * n[j])
movq 8(%rsi,%r10,8),%rax // rax = a[j + 1]
ADD_CARRY %r15,%r12 // r12 += hi(a[j - 1] * b[0]) + lo(a[j] * b[0])
movq %r12,-8(%rsp,%r10,8) // t[j - 1] = r13
movq %rdx,%rdi // rdi = hi(t[0] * k0 * n[j])
mulq %rbx // (rdx, rax) = a[j + 1] * b[0]
ADD_CARRY %rax,%r14 // r14 = hi(a[j] * b[0]) + lo(a[j + 1] * b[0])
movq 8(%rcx,%r10,8),%rax // rax = n[j + 1]
movq %rdx,%r15 // r15 = hi(a[j + 1] * b[0])
mulq %rbp // (rdx, rax) = t[0] * k0 * n[j + 1]
ADD_CARRY %rax,%rdi // rdi = hi(t[0] * k0 * n[j]) + lo(t[0] * k0 * n[j + 1])
movq 16(%rsi,%r10,8),%rax // rax = a[j + 2]
ADD_CARRY %r14,%rdi // rdi += hi(a[j] * b[0]) + lo(a[j + 1] * b[0])
movq %rdi,(%rsp,%r10,8) // t[j - 4] = rdi
movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j + 1])
leaq 4(%r10),%r10 // j += 4
cmpq %r9,%r10 // if size != j
jb .Loop1st4x
mulq %rbx // (rdx, rax) = a[j - 2] * b[0]
ADD_CARRY %rax,%r15 // r15 = hi(a[j - 3] * b[0]) + lo(a[j - 2] * b[0])
movq -16(%rcx,%r10,8),%rax // rax = n[j - 2]
movq %rdx,%r14 // r14 = hi(a[j - 2] * b[0])
mulq %rbp // (rdx, rax) = t[0] * k0 * n[j - 2]
ADD_CARRY %rax,%r12 // r12 = hi(t[0] * k0 * n[j - 3]) + lo(t[0] * k0 * n[j - 2])
movq -8(%rsi,%r10,8),%rax // rax = a[j - 1]
ADD_CARRY %r15,%r12 // r12 += hi(a[j - 3] * b[0]) + lo(a[j - 2] * b[0])
movq %r12,-24(%rsp,%r10,8) // t[j - 3] = r13
movq %rdx,%rdi // rdi = hi(t[0] * k0 * n[j - 2])
mulq %rbx // (rdx, rax) = a[j - 1] * b[0]
ADD_CARRY %rax,%r14 // r14 = hi(a[j - 2] * b[0]) + lo(a[j- 1] * b[0])
movq -8(%rcx,%r10,8),%rax // rax = n[j - 1]
movq %rdx,%r15 // r15 = hi(a[j - 1] * b[0])
mulq %rbp // (rdx, rax) = t[0] * k0 * n[j - 1]
ADD_CARRY %rax,%rdi // rdi = hi(t[0] * k0 * n[j - 2]) + lo(t[0] * k0 * n[j - 1])
ADD_CARRY %r14,%rdi // rdi += hi(a[j - 2] * b[0]) + lo(a[j- 1] * b[0])
movq %rdi,-16(%rsp,%r10,8) // t[j - 2] = rdi
movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j - 1])
xorq %rdx,%rdx // rdx = 0
ADD_CARRY %r15,%r12 // r12 = hi(a[j - 1] * b[0]) + hi(t[0] * k0 * n[j - 1])
movq %r12,-8(%rsp,%r10,8) // t[j - 1] = r13
movq %rdx,(%rsp,%r10,8) // t[j] = CF
leaq 1(%r11),%r11 // i++
.align 4
.LoopOuter4x:
/* Calculate a[i] * b + q * N */
movq (%rsi),%rax // rax = a[0]
movq (%r13,%r11,8),%rbx // rbx = b[i]
xorq %r10,%r10 // j = 0
movq (%rsp),%r15 // r15 = t[0]
movq %r8,%rbp // rbp = k0
mulq %rbx // (rdx, rax) = a[0] * b[i]
ADD_CARRY %rax,%r15 // r15 = lo(a[0] * b[i]) + t[0]
movq (%rcx),%rax // rax = n[0]
imulq %r15,%rbp // rbp = t[0] * k0
movq %rdx,%r14 // r14 = hi[a[0] * b[i]]
mulq %rbp // (rdx, rax) = t[0] * k0 * n[0]
ADD_CARRY %rax,%r15 // r15 = lo(t[0] * k0 * n[0])
movq 8(%rsi),%rax // rax = a[1]
movq %rdx,%rdi // rdi = hi(t[0] * k0 * n[0])
mulq %rbx // (rdx, rax) = a[1] * b[i]
ADD_CARRY %rax,%r14 // r14 = hi[a[0] * b[i]] + lo(a[1] * b[i])
movq 8(%rcx),%rax // rax = n[1]
ADD_CARRY 8(%rsp),%r14 // r14 = t[1]
movq %rdx,%r15 // r15 = hi(a[1] * b[i])
mulq %rbp // (rdx, rax) = t[0] * k0 * n[1]
ADD_CARRY %rax,%rdi // rdi = hi(t[0] * k0 * n[0]) + lo(t[0] * k0 * n[1])
movq 16(%rsi),%rax // rax = a[2]
ADD_CARRY %r14,%rdi // rdi += t[1]
leaq 4(%r10),%r10 // j += 4
movq %rdi,(%rsp) // t[0] = rdi
movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[1])
.align 16
.Linner4x:
mulq %rbx // (rdx, rax) = a[2] * b[i]
ADD_CARRY %rax,%r15 // r15 = hi(a[1] * b[i]) + lo(a[2] * b[i])
addq -16(%rsp,%r10,8),%r15 // r15 = t[j - 2]
adcq $0,%rdx
movq -16(%rcx,%r10,8),%rax // rax = n[j - 2]
movq %rdx,%r14 // r14 = hi(a[2] * b[i])
mulq %rbp // (rdx, rax) = t[0] * k0 * n[j - 2]
ADD_CARRY %rax,%r12 // r12 = hi(t[0] * k0 * n[j - 3]) * lo(t[0] * k0 * n[j - 2])
ADD_CARRY %r15,%r12 // r12 += t[j - 2]
movq %r12,-24(%rsp,%r10,8) // t[j - 3] = r13
movq %rdx,%rdi // rdi = hi(t[0] * k0 * n[j - 2])
movq -8(%rsi,%r10,8),%rax // rax = a[j - 1]
mulq %rbx // (rdx, rax) = a[j - 1] * b[i]
ADD_CARRY %rax,%r14 // r14 = lo(a[j - 1] * b[i])
addq -8(%rsp,%r10,8),%r14 // r14 += t[j - 1]
adcq $0,%rdx
movq %rdx,%r15 // r15 = hi(a[j - 1] * b[i])
movq -8(%rcx,%r10,8),%rax // rax = n[j - 1]
mulq %rbp // (rdx, rax) = t[0] * k0 * n[j - 1]
ADD_CARRY %rax,%rdi // rdi = hi(t[0] * k0 * n[j - 2]) + lo(t[0] * k0 * n[j - 1])
ADD_CARRY %r14,%rdi // rdi += t[j - 1]
movq %rdi,-16(%rsp,%r10,8) // t[j - 2] = rdi
movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j - 1])
movq (%rsi,%r10,8),%rax // rax = a[j]
mulq %rbx // (rdx, rax) = a[j] * b[i]
ADD_CARRY %rax,%r15 // r15 = hi(a[j - 1] * b[i]) + lo(a[j] * b[i])
addq (%rsp,%r10,8),%r15 // r15 = t[j]
adcq $0,%rdx
movq %rdx,%r14 // r14 = hi(a[j] * b[i])
movq (%rcx,%r10,8),%rax // rax = n[j]
mulq %rbp // (rdx, rax) = t[0] * k0 * n[j]
ADD_CARRY %rax,%r12 // r12 = hi(t[0] * k0 * n[j - 1]) + lo(t[0] * k0 * n[j])
ADD_CARRY %r15,%r12 // r12 += t[j]
movq %r12,-8(%rsp,%r10,8) // t[j - 1] = r13
movq %rdx,%rdi // rdi = hi(t[0] * k0 * n[j])
movq 8(%rsi,%r10,8),%rax // rax = a[j + 1]
mulq %rbx // (rdx, rax) = a[j + 1] * b[i]
ADD_CARRY %rax,%r14 // r14 = hi(a[j] * b[i]) + lo(a[j + 1] * b[i])
addq 8(%rsp,%r10,8),%r14 // r14 = t[j + 1]
adcq $0,%rdx
movq %rdx,%r15 // r15 = hi(a[j + 1] * b[i])
movq 8(%rcx,%r10,8),%rax // rax = n[j + 1]
mulq %rbp // (rdx, rax) = t[0] * k0 * n[j + 1]
ADD_CARRY %rax,%rdi // rdi = hi(t[0] * k0 * n[j]) + lo(t[0] * k0 * n[j + 1])
ADD_CARRY %r14,%rdi // rdi += t[j + 1]
movq %rdi,(%rsp,%r10,8) // t[j] = rdi
movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j + 1])
movq 16(%rsi,%r10,8),%rax // rax = a[j + 2]
leaq 4(%r10),%r10 // j += 4
cmpq %r9,%r10 // if j != size
jb .Linner4x
mulq %rbx // (rdx, rax) = a[j - 2] * b[i]
ADD_CARRY %rax,%r15 // r15 = hi(a[j + 1] * b[i]) + lo(a[j - 2] * b[i])
addq -16(%rsp,%r10,8),%r15 // r15 = t[j - 2]
adcq $0,%rdx
movq %rdx,%r14 // r14 = hi(a[j - 2] * b[i])
movq -16(%rcx,%r10,8),%rax // rax = n[j - 2]
mulq %rbp // (rdx, rax) = t[0] * k0 * n[j - 2]
ADD_CARRY %rax,%r12 // r12 = hi(t[0] * k0 * n[j + 1]) + lo(t[0] * k0 * n[j - 2])
ADD_CARRY %r15,%r12 // r12 += t[j - 2]
movq %r12,-24(%rsp,%r10,8) // t[j - 3] = r13
movq %rdx,%rdi // rdi = hi(t[0] * k0 * n[j - 2])
movq -8(%rsi,%r10,8),%rax // rax = a[j - 1]
mulq %rbx // (rdx, rax) = a[j - 1] * b[i]
ADD_CARRY %rax,%r14 // r14 = hi(a[j - 2] * b[i]) + lo(a[j - 1] * b[i])
addq -8(%rsp,%r10,8),%r14 // r14 = t[j - 1]
adcq $0,%rdx
leaq 1(%r11),%r11 // i++
movq %rdx,%r15 // r15 = hi(a[j - 1] * b[i])
movq -8(%rcx,%r10,8),%rax // rax = n[j - 1]
mulq %rbp // (rdx, rax) = t[0] * k0 * n[j - 1]
ADD_CARRY %rax,%rdi // rdi = hi(t[0] * k0 * n[j - 2]) + lo(t[0] * k0 * n[j - 1])
ADD_CARRY %r14,%rdi // rdi += t[j - 1]
movq %rdi,-16(%rsp,%r10,8) // t[j - 2] = rdi
movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j - 1])
xorq %rdx,%rdx // rdi = 0
ADD_CARRY %r15,%r12 // r12 = hi(t[0] * k0 * n[j - 1]) + r10
addq (%rsp,%r9,8),%r12 // r12 += t[size]
adcq $0,%rdx
movq %r12,-8(%rsp,%r10,8) // t[j - 1] = r13
movq %rdx,(%rsp,%r10,8) // t[j] = CF
cmpq %r9,%r11 // if i != size
jb .LoopOuter4x
movq 16(%rsp,%r9,8),%rdi // rdi = t[size + 2]
leaq -4(%r9),%r10 // j = size - 4
movq (%rsp),%rax // rax = t[0]
movq 8(%rsp),%rdx // rdx = t[1]
shrq $2,%r10 // r10 = (size - 4) / 4
leaq (%rsp),%rsi // rsi = t[0]
xorq %r11,%r11 // i = 0
subq (%rcx),%rax // rax = t[0] - n[0]
sbbq 8(%rcx),%rdx // rdx = t[1] - (n[1] + CF)
movq 16(%rsi),%rbx // rbx = t[2]
movq 24(%rsi),%rbp // rbp = t[3]
/* 计算 S-N */
.LoopSub4x:
movq %rax,(%rdi,%r11,8) // r[i] = n[0]
movq %rdx,8(%rdi,%r11,8) // r[i + 1] = n[1]
movq 32(%rsi,%r11,8),%rax // rax = t[i + 4]
movq 40(%rsi,%r11,8),%rdx // rdx = t[i + 5]
sbbq 16(%rcx,%r11,8),%rbx // rbx = t[2] - (n[i + 2] + CF)
sbbq 24(%rcx,%r11,8),%rbp // rbp = t[3] - (n[i + 3] + CF)
sbbq 32(%rcx,%r11,8),%rax // rax = t[i + 4] - (n[j + 4] + CF)
sbbq 40(%rcx,%r11,8),%rdx // rdx = t[i + 5] - (n[i + 5] + CF)
movq %rbx,16(%rdi,%r11,8) // r[i + 2] = rbx
movq %rbp,24(%rdi,%r11,8) // r[i + 3] = rbp
movq 48(%rsi,%r11,8),%rbx // rbx = t[i + 6]
movq 56(%rsi,%r11,8),%rbp // rbp = t[i + 7]
leaq 4(%r11),%r11 // i += 4
decq %r10 // j--
jnz .LoopSub4x // if j != 0
sbbq 16(%rcx,%r11,8),%rbx // rbx = rbx = t[i + 6] - (n[i + 2] + CF)
sbbq 24(%rcx,%r11,8),%rbp // rbp = t[i + 7] - (n[i + 3] + CF)
movq %rax,(%rdi,%r11,8) // r[i] = rax
movq %rdx,8(%rdi,%r11,8) // r[i + 1] = rdx
movq %rbx,16(%rdi,%r11,8) // r[i + 2] = rbx
movq %rbp,24(%rdi,%r11,8) // r[i + 3] = rbp
movq 32(%rsi,%r11,8),%rax // rax = t[i + 4]
sbbq $0,%rax // rax -= CF
pxor %xmm2,%xmm2 // xmm0 = 0
movq %rax, %xmm0
pcmpeqd %xmm1,%xmm1 // xmm5 = -1
pshufd $0,%xmm0,%xmm0
movq %r9,%r10 // j = size
pxor %xmm0,%xmm1
shrq $2,%r10 // j = size / 4
xorl %eax,%eax // i = 0
.align 16
.LoopCopy4x:
movdqa (%rsp,%rax),%xmm5 // Copy the result to r.
movdqu (%rdi,%rax),%xmm3
pand %xmm0,%xmm5
pand %xmm1,%xmm3
movdqa 16(%rsp,%rax),%xmm4
movdqa %xmm2,(%rsp,%rax)
por %xmm3,%xmm5
movdqu 16(%rdi,%rax),%xmm3
movdqu %xmm5,(%rdi,%rax)
pand %xmm0,%xmm4
pand %xmm1,%xmm3
movdqa %xmm2,16(%rsp,%rax)
por %xmm3,%xmm4
movdqu %xmm4,16(%rdi,%rax)
leaq 32(%rax),%rax
decq %r10 // j--
jnz .LoopCopy4x
movq 8(%rsp,%r9,8),%rsi // rsi = pressed-stacked rsp.
movq $1,%rax
leaq (%rsi),%rsp // Restore srsp.
RESTORE_REGISTERS
ret
.cfi_endproc
.size MontMul4,.-MontMul4
.type MontSqr8,@function
.align 32
MontSqr8:
.cfi_startproc
SAVE_REGISTERS
movq %rsp,%rax
movl %r9d,%r15d
shll $3,%r9d // Calculate size * 8 bytes.
shlq $5,%r15 // size * 8 * 4
negq %r9
leaq -64(%rsp,%r9,2),%r14 // r14 = rsp[size * 2 - 8]
subq %rsi,%r14
andq $4095,%r14
movq %rsp,%rbp
cmpq %r14,%r15
jae .Loop8xCheckstk
leaq 4032(,%r9,2),%r15 // r15 = 4096 - frame - 2 * size
subq %r15,%r14
movq $0,%r15
cmovcq %r15,%r14
.Loop8xCheckstk:
subq %r14,%rbp
leaq -64(%rbp,%r9,2),%rbp // Allocate a frame + 2 x size.
andq $-64,%rbp // __checkstk implementation,
// which is invoked when the stack size needs to exceed one page.
movq %rsp,%r14
subq %rbp,%r14
andq $-4096,%r14
leaq (%r14,%rbp),%rsp
cmpq %rbp,%rsp
jbe .LoopMul8x
.align 16
.LoopPage8x:
leaq -4096(%rsp),%rsp // Change sp - 4096 each time until sp <= the space to be allocated
cmpq %rbp,%rsp
ja .LoopPage8x
.LoopMul8x:
movq %r9,%r15 // r15 = -size * 8
negq %r9 // Restoresize.
movq %r8,32(%rsp) // Save the values of k0 and sp.
movq %rax,40(%rsp)
movq %rcx, %xmm1 // Pointer to saving n.
pxor %xmm2,%xmm2 // xmm0 = 0
movq %rdi, %xmm0 // Pointer to saving r.
movq %r15, %xmm5 // Save size.
call MontSqr8Inner
leaq (%rdi,%r9),%rbx // rbx = t[size]
movq %r9,%rcx // rcx = -size
movq %r9,%rdx // rdx = -size
movq %xmm0, %rdi // rdi = r
sarq $5,%rcx // rcx >>= 5
.align 32
/* T -= N */
.LoopSub8x:
movq (%rbx),%r13 // r13 = t[i]
movq 8(%rbx),%r12 // r12 = t[i + 1]
movq 16(%rbx),%r11 // r11 = t[i + 2]
movq 24(%rbx),%r10 // r10 = t[i + 3]
sbbq (%rbp),%r13 // r13 = t[i] - (n[i] + CF)
sbbq 8(%rbp),%r12 // r12 = t[i + 1] - (n[i + 1] + CF)
sbbq 16(%rbp),%r11 // r11 = t[i + 2] - (n[i + 2] + CF)
sbbq 24(%rbp),%r10 // r10 = t[i + 3] - (n[i + 3] + CF)
movq %r13,0(%rdi) // Assigning value to r.
movq %r12,8(%rdi)
movq %r11,16(%rdi)
movq %r10,24(%rdi)
leaq 32(%rbp),%rbp // n += 4
leaq 32(%rdi),%rdi // r += 4
leaq 32(%rbx),%rbx // t += 4
incq %rcx
jnz .LoopSub8x
sbbq $0,%rax // rax -= CF
leaq (%rbx,%r9),%rbx
leaq (%rdi,%r9),%rdi
movq %rax,%xmm0
pxor %xmm2,%xmm2
pshufd $0,%xmm0,%xmm0
movq 40(%rsp),%rsi // rsi = pressed-stacked rsp.
.align 32
.LoopCopy8x:
movdqa 0(%rbx),%xmm1 // Copy the result to r.
movdqa 16(%rbx),%xmm5
leaq 32(%rbx),%rbx
movdqu 0(%rdi),%xmm3
movdqu 16(%rdi),%xmm4
leaq 32(%rdi),%rdi
movdqa %xmm2,-32(%rbx)
movdqa %xmm2,-16(%rbx)
movdqa %xmm2,-32(%rbx,%rdx)
movdqa %xmm2,-16(%rbx,%rdx)
pcmpeqd %xmm0,%xmm2
pand %xmm0,%xmm1
pand %xmm0,%xmm5
pand %xmm2,%xmm3
pand %xmm2,%xmm4
pxor %xmm2,%xmm2
por %xmm1,%xmm3
por %xmm5,%xmm4
movdqu %xmm3,-32(%rdi)
movdqu %xmm4,-16(%rdi)
addq $32,%r9
jnz .LoopCopy8x
movq $1,%rax
leaq (%rsi),%rsp // Restore rsp.
RESTORE_REGISTERS // Restore non-volatile register.
ret
.cfi_endproc
.size MontSqr8,.-MontSqr8
.type MontSqr8Inner,@function
.align 32
MontSqr8Inner:
.cfi_startproc
leaq 32(%r15),%rbp // i = -size + 32
leaq (%rsi,%r9),%rsi // rsi = a[size]
movq %r9,%rcx // j = size
movq -32(%rsi,%rbp),%r11 // r11 = a[0]
movq -24(%rsi,%rbp),%r10 // r10 = a[1]
leaq 56(%rsp,%r9,2),%rdi // rdi = t[2 * size]
leaq -16(%rsi,%rbp),%rbx // rbx = a[2]
leaq -32(%rdi,%rbp),%rdi // rdi = t[2 * size - i]
movq %r10,%rax // rax = a[1]
mulq %r11 // (rdx, rax) = a[1] * a[0]
movq %rax,%r15 // r15 = lo(a[1] * a[0])
movq %rdx,%r14 // r14 = hi(a[1] * a[0])
movq %r15,-24(%rdi,%rbp) // t[1] = lo(a[1] * a[0])
movq (%rbx),%rax // rax = a[2]
mulq %r11 // (rdx, rax) = a[2] * a[0]
ADD_CARRY %rax,%r14 // r14 = hi(a[1] * a[0]) + lo(a[2] * a[0])
movq %r14,-16(%rdi,%rbp) // t[2] = hi(a[1] * a[0]) + lo(a[2] * a[0])
movq %rdx,%r15 // r15 = hi(a[2] * a[0])
movq (%rbx),%rax // rax = a[2]
mulq %r10 // (rdx, rax) = a[2] * a[1]
movq %rax,%r13 // r13 = lo(a[2] * a[1])
movq %rdx,%r12 // r12 = hi(a[2] * a[1])
leaq 8(%rbx),%rbx // rbx = a[3]
movq (%rbx),%rax // rax = a[3]
mulq %r11 // (rdx, rax) = a[3] * a[0]
ADD_CARRY %rax,%r15 // r15 = hi(a[2] * a[0]) + lo(a[3] * a[0])
ADD_CARRY %r13,%r15 // r15 = hi(a[2] * a[0]) + lo(a[3] * a[0]) + lo(a[2] * a[1])
movq %rdx,%r14 // r14 = hi(a[3] * a[0])
movq (%rbx),%rax // rax = a[3]
leaq (%rbp),%rcx // j = i
movq %r15,-8(%rdi,%rcx) // t[3] = hi(a[2] * a[0]) + lo(a[3] * a[0]) + lo(a[2] * a[1])
.align 32
.Loop1stSqr4x:
leaq (%rsi,%rcx),%rbx // rbx = a[4]
mulq %r10 // (rdx, rax) = a[3] * a[1]
ADD_CARRY %rax,%r12 // r12 = hi(a[2] * a[1]) + lo(a[3] * a[1])
movq %rdx,%r13 // r13 = hi(a[3] * a[1])
movq (%rbx),%rax // rax = a[4]
mulq %r11 // (rdx, rax) = a[4] * a[0]
ADD_CARRY %rax,%r14 // r14 = hi(a[3] * a[0]) + lo(a[4] * a[0])
ADD_CARRY %r12,%r14 // r14 = hi(a[3] * a[0]) + lo(a[4] * a[0]) + lo(a[3] * a[1])
movq (%rbx),%rax // rax = a[4]
movq %rdx,%r15 // r15 = hi(a[4] * a[0])
mulq %r10 // (rdx, rax) = a[4] * a[1]
ADD_CARRY %rax,%r13 // r13 = hi(a[3] * a[1]) + lo(a[4] * a[1])
movq %r14,(%rdi,%rcx) // t[4] = hi(a[3] * a[0]) + lo(a[4] * a[0]) + lo(a[3] * a[1])
movq %rdx,%r12 // r12 = hi(a[4] * a[1])
leaq 8(%rbx),%rbx // rbx = a[5]
movq (%rbx),%rax // rax = a[5]
mulq %r11 // (rdx, rax) = a[5] * a[0]
ADD_CARRY %rax,%r15 // r15 = hi(a[4] * a[0]) + lo(a[5] * a[0])
ADD_CARRY %r13,%r15 // r15 = hi(a[4] * a[0]) + lo(a[5] * a[0]) + hi(a[3] * a[1]) + lo(a[4] * a[1])
movq (%rbx),%rax // rax = a[5]
movq %rdx,%r14 // r14 = hi(a[5] * a[0])
mulq %r10 // (rdx, rax) = a[5] * a[1]
ADD_CARRY %rax,%r12 // r12 = hi(a[4] * a[1]) + lo(a[5] * a[1])
movq %r15,8(%rdi,%rcx) // t[5] = r10
movq %rdx,%r13 // r13 = hi(a[5] * a[1])
leaq 8(%rbx),%rbx // rbx = a[6]
movq (%rbx),%rax // rax = a[6]
mulq %r11 // (rdx, rax) = a[6] * a[0]
ADD_CARRY %rax,%r14 // r14 = hi(a[5] * a[0]) + lo(a[6] * a[0])
ADD_CARRY %r12,%r14 // r14 = hi(a[5] * a[0]) + lo(a[6] * a[0]) + hi(a[4] * a[1]) + lo(a[5] * a[1])
movq (%rbx),%rax // rax = a[6]
movq %rdx,%r15 // r15 = hi(a[6] * a[0])
mulq %r10 // (rdx, rax) = a[6] * a[1]
ADD_CARRY %rax,%r13 // r13 = lo(a[6] * a[1])
movq %r14,16(%rdi,%rcx) // t[6] = r11
movq %rdx,%r12 // r12 = hi(a[6] * a[1])
leaq 8(%rbx),%rbx // rbx = a[7]
movq (%rbx),%rax // rax = a[7]
mulq %r11 // (rdx, rax) = a[7] * a[0]
ADD_CARRY %rax,%r15 // r15 = hi(a[6] * a[0]) + lo(a[7] * a[0])
ADD_CARRY %r13,%r15 // r15 = hi(a[6] * a[0]) + lo(a[7] * a[0]) + lo(a[6] * a[1])
movq %r15,24(%rdi,%rcx) // t[7] = hi(a[6] * a[0]) + lo(a[7] * a[0]) + lo(a[6] * a[1])
movq %rdx,%r14 // r14 = hi(a[7] * a[0])
movq (%rbx),%rax // rax = a[7]
leaq 32(%rcx),%rcx // j += 2
cmpq $0,%rcx // if j != 0
jne .Loop1stSqr4x
mulq %r10 // (rdx, rax) = a[7] * a[1]
ADD_CARRY %rax,%r12 // r12 = hi(a[6] * a[1]) + lo(a[7] * a[1])
leaq 16(%rbp),%rbp // i++
ADD_CARRY %r14,%r12 // r12 = hi(a[6] * a[1]) + hi(a[7] * a[0]) + lo(a[7] * a[1])
movq %r12,(%rdi) // t[8] = r13
movq %rdx,%r13 // r13 = hi(a[7] * a[1])
movq %rdx,8(%rdi) // t[9] = hi(a[7] * a[1])
.align 32
.LoopOuterSqr4x:
movq -32(%rsi,%rbp),%r11 // r11 = a[0]
movq -24(%rsi,%rbp),%r10 // r10 = a[1]
leaq -16(%rsi,%rbp),%rbx // rbx = a[2]
leaq 56(%rsp,%r9,2),%rdi // rdi = t[size * 2 - i]
leaq -32(%rdi,%rbp),%rdi
movq %r10,%rax // rax = a[1]
mulq %r11 // (rdx, rax) = a[1] * a[0]
movq -24(%rdi,%rbp),%r15 // r15 = t[1]
ADD_CARRY %rax,%r15 // r15 = lo(a[1] * a[0]) + t[1]
movq %r15,-24(%rdi,%rbp) // t[1] = r10
movq %rdx,%r14 // r14 = hi(a[1] * a[0])
movq (%rbx),%rax // rax = a[2]
mulq %r11 // (rdx, rax) = a[2] * a[0]
ADD_CARRY %rax,%r14 // r14 = hi(a[1] * a[0]) + lo(a[2] * a[0])
addq -16(%rdi,%rbp),%r14 // r14 = hi(a[1] * a[0]) + lo(a[2] * a[0]) + t[2]
adcq $0,%rdx // r10 += CF
movq %rdx,%r15 // r10 = hi(a[2] * a[0])
movq %r14,-16(%rdi,%rbp) // t[2] = r11
xorq %r13,%r13 // Clear CF.
movq (%rbx),%rax // rax = a[2]
mulq %r10 // (rdx, rax) = a[2] * a[1]
ADD_CARRY %rax,%r13 // r13 = lo(a[2] * a[1])
addq -8(%rdi,%rbp),%r13 // r13 = lo(a[2] * a[1]) + t[3]
adcq $0,%rdx
movq %rdx,%r12 // r12 = hi(a[2] * a[1])
leaq 8(%rbx),%rbx // rbx = a[3]
movq (%rbx),%rax // rax = a[3]
mulq %r11 // (rdx, rax) = a[3] * a[0]
ADD_CARRY %rax,%r15 // r15 = hi(a[2] * a[0]) + lo(a[3] * a[0])
ADD_CARRY %r13,%r15 // r15 = hi(a[2] * a[0]) + lo(a[3] * a[0]) + lo(a[2] * a[1]) + t[3]
movq (%rbx),%rax // rax = a[3]
leaq (%rbp),%rcx // j = i
movq %r15,-8(%rdi,%rbp) // t[3] = r10
movq %rdx,%r14 // r14 = hi(a[3] * a[0])
.align 32
.LoopInnerSqr4x:
leaq (%rsi,%rcx),%rbx // rbx = a[4]
mulq %r10 // (rdx, rax) = a[3] * a[1]
ADD_CARRY %rax,%r12 // r12 = hi(a[2] * a[1]) + lo(a[3] * a[1])
movq (%rbx),%rax // rax = a[4]
movq %rdx,%r13 // r13 = hi(a[3] * a[1])
addq (%rdi,%rcx),%r12 // r12 = hi(a[2] * a[1]) + lo(a[3] * a[1]) + t[4]
adcq $0,%rdx // r13 += CF
movq %rdx,%r13 // r13 = hi(a[3] * a[1])
mulq %r11 // (rdx, rax) = a[4] * a[0]
ADD_CARRY %rax,%r14 // r14 = hi(a[3] * a[0]) + lo(a[4] * a[0])
ADD_CARRY %r12,%r14 // r14 = hi(a[3] * a[0]) + lo(a[4] * a[0]) + hi(a[2] * a[1]) + lo(a[3] * a[1]) + t[4]
movq %r14,(%rdi,%rcx) // t[4] = r11
movq %rdx,%r15 // r15 = hi(a[4] * a[0])
movq (%rbx),%rax // rax = a[4]
mulq %r10 // (rdx, rax) = a[4] * a[1]
ADD_CARRY %rax,%r13 // r13 = hi(a[3] * a[1]) + lo(a[4] * a[1])
addq 8(%rdi,%rcx),%r13 // r13 = hi(a[3] * a[1]) + lo(a[4] * a[1]) + t[5]
adcq $0,%rdx // r12 += CF
leaq 8(%rbx),%rbx // rbx = a[5]
movq (%rbx),%rax // rax = a[5]
movq %rdx,%r12 // r12 = hi(a[4] * a[1])
mulq %r11 // (rdx, rax) = a[5] * a[0]
ADD_CARRY %rax,%r15 // r15 = hi(a[4] * a[0]) + lo(a[5] * a[0])
ADD_CARRY %r13,%r15 // r15 = hi(a[4] * a[0]) + lo(a[5] * a[0]) + hi(a[3] * a[1]) + lo(a[4] * a[1]) + t[5]
movq %r15,8(%rdi,%rcx) // t[5] = r10
movq %rdx,%r14 // r14 = hi(a[5] * a[0])
movq (%rbx),%rax // rax = a[5]
leaq 16(%rcx),%rcx // j++
cmpq $0,%rcx // if j != 0
jne .LoopInnerSqr4x
mulq %r10 // (rdx, rax) = a[5] * a[1]
ADD_CARRY %rax,%r12 // r12 = hi(a[4] * a[1]) + lo(a[5] * a[1])
ADD_CARRY %r14,%r12 // r12 = hi(a[4] * a[1]) + lo(a[5] * a[1]) + hi(a[5] * a[0])
movq %r12,(%rdi) // t[6] = r13
movq %rdx,%r13 // r13 = hi(a[5] * a[1])
movq %rdx,8(%rdi) // t[7] = hi(a[5] * a[1])
addq $16,%rbp // i++
jnz .LoopOuterSqr4x // if i != 0
movq -32(%rsi),%r11 // r11 = a[0]
leaq 56(%rsp,%r9,2),%rdi // rdi = t[2 * size]
movq -24(%rsi),%rax // rax = a[1]
leaq -32(%rdi,%rbp),%rdi // rdi = t[2 * size - i]
movq -16(%rsi),%rbx // rbx = a[2]
movq %rax,%r10 // r10 = a[1]
mulq %r11 // (rdx, rax) = a[1] * a[0]
ADD_CARRY %rax,%r15 // r15 = lo(a[1] * a[0]) + t[1]
movq %rbx,%rax // rax = a[2]
movq %rdx,%r14 // r14 = hi(a[1] * a[0])
mulq %r11 // (rdx, rax) = a[2] * a[0]
ADD_CARRY %rax,%r14 // r14 = hi(a[1] * a[0]) + lo(a[2] * a[0])
movq %r15,-24(%rdi) // t[1] = r10
ADD_CARRY %r12,%r14 // r14 = lo(a[2] * a[0]) + t[2]
movq %rbx,%rax // rax = a[2]
movq %rdx,%r15 // r15 = hi(a[2] * a[0])
mulq %r10 // (rdx, rax) = a[2] * a[1]
ADD_CARRY %rax,%r13 // r13 = lo(a[2] * a[1]) + t[3]
movq %r14,-16(%rdi) // t[2] = r11
movq %rdx,%r12 // r12 = hi(a[2] * a[1])
movq -8(%rsi),%rbx // rbx = a[3]
movq %rbx,%rax // rax = a[3]
mulq %r11 // (rdx, rax) = a[3] * a[0]
ADD_CARRY %rax,%r15 // r15 = hi(a[2] * a[0]) + lo(a[3] * a[0])
ADD_CARRY %r13,%r15 // r15 = hi(a[2] * a[0]) + lo(a[3] * a[0]) + lo(a[2] * a[1]) + t[3]
movq %rbx,%rax // rax = a[3]
movq %r15,-8(%rdi) // t[3] = r10
movq %rdx,%r14 // r14 = hi(a[3] * a[0])
mulq %r10 // (rdx, rax) = a[3] * a[1]
ADD_CARRY %rax,%r12 // r12 = hi(a[2] * a[1]) + lo(a[3] * a[1])
ADD_CARRY %r14,%r12 // r12 = hi(a[3] * a[0]) + hi(a[2] * a[1]) + lo(a[3] * a[1])
movq %r12,(%rdi) // t[4] = r13
movq %rdx,%r13 // r13 = hi(a[3] * a[1])
movq %rdx,8(%rdi) // t[5] = hi(a[3] * a[1])
movq -16(%rsi),%rax // rax = a[2]
mulq %rbx // (rdx, rax) = a[3] * a[2]
addq $16,%rbp
xorq %r11,%r11
subq %r9,%rbp // i = 16 - size
xorq %r10,%r10
ADD_CARRY %r13,%rax // rax = hi(a[3] * a[1]) + lo(a[3] * a[2])
movq %rax,8(%rdi) // t[5] = hi(a[3] * a[1]) + lo(a[3] * a[2])
movq %rdx,16(%rdi) // t[6] = hi(a[3] * a[2])
movq %r10,24(%rdi) // t[7] = 0
movq -16(%rsi,%rbp),%rax // rax = a[0]
leaq 56(%rsp),%rdi // rdi = t[0]
xorq %r15,%r15
movq 8(%rdi),%r14 // r14 = t[1]
leaq (%r11,%r15,2),%r13
shrq $63,%r15 // Cyclically shifts 63 bits to the right to obtain the lower bits.
leaq (%rcx,%r14,2),%r12 // r12 = t[1] * 2
shrq $63,%r14 // r14 = t[1] >> 63
orq %r15,%r12 // r12 = t[1] * 2
movq 16(%rdi),%r15 // r15 = t[2]
movq %r14,%r11 // r11 = t[1] >> 63
mulq %rax // (rdx, rax) = a[0] * a[0]
negq %r10 // If the value is not 0, CF is set to 1.
adcq %rax,%r13 // r13 = lo(a[0] * a[0])
movq 24(%rdi),%r14 // r14 = t[3]
movq %r13,(%rdi) // t[0] = 0
adcq %rdx,%r12 // r12 = t[1] * 2 + hi(a[0] * a[0])
leaq (%r11,%r15,2),%rbx // rbx = t[2] * 2 + t[1] >> 63
movq -8(%rsi,%rbp),%rax // rax = a[1]
movq %r12,8(%rdi) // t[1] = t[1] * 2 + hi(a[0] * a[0])
sbbq %r10,%r10 // r10 = -CF clear CF
shrq $63,%r15 // r15 = t[2] >> 63
leaq (%rcx,%r14,2),%r8 // r8 = t[3] * 2
shrq $63,%r14 // r14 = t[3] >> 63
orq %r15,%r8 // r8 = (t[3] * 2) + (t[2] >> 63)
movq 32(%rdi),%r15 // r15 = t[4]
movq %r14,%r11 // r11 = t[3] >> 63
mulq %rax // (rdx, rax) = a[1] * a[1]
negq %r10 // If the value is not 0, CF is set to 1.
movq 40(%rdi),%r14 // r14 = t[5]
adcq %rax,%rbx // rbx = t[2] * 2 + t[1] >> 63 + lo(a[1] * a[1])
movq (%rsi,%rbp),%rax // rax = a[2]
movq %rbx,16(%rdi) // t[2] = t[2] * 2 + t[1] >> 63 + lo(a[1] * a[1])
adcq %rdx,%r8 // r8 = t[3] * 2 + t[2] >> 63 + hi(a[1] * a[1])
leaq 16(%rbp),%rbp // i++
movq %r8,24(%rdi) // t[3] = r8
sbbq %r10,%r10 // r10 = -CF clear CF.
leaq 64(%rdi),%rdi // t += 64
.align 32
.LoopShiftAddSqr4x:
leaq (%r11,%r15,2),%r13 // r13 = t[4] * 2 + t[3] >> 63
shrq $63,%r15 // r15 = t[4] >> 63
leaq (%rcx,%r14,2),%r12 // r12 = t[5] * 2
shrq $63,%r14 // r14 = t[5] >> 63
orq %r15,%r12 // r12 = (t[5] * 2) + t[4] >> 63
movq -16(%rdi),%r15 // r15 = t[6]
movq %r14,%r11 // r11 = t[5] >> 63
mulq %rax // (rdx, rax) = a[2] * a[2]
negq %r10 // r10 = CF
movq -8(%rdi),%r14 // r14 = t[7]
adcq %rax,%r13 // r13 = t[4] * 2 + t[3] >> 63 + lo(a[2] * a[2])
movq %r13,-32(%rdi) // t[4] = r12
adcq %rdx,%r12 // r12 = (t[5] * 2) + t[4] >> 63 + hi(a[2] * a[2])
leaq (%r11,%r15,2),%rbx // rbx = t[6] * 2 + t[5] >> 63
movq -8(%rsi,%rbp),%rax // rax = a[3]
movq %r12,-24(%rdi) // t[5] = hi(a[2] * a[2])
sbbq %r10,%r10 // r10 = -CF
shrq $63,%r15 // r15 = t[6] >> 63
leaq (%rcx,%r14,2),%r8 // r8 = t[7] * 2
shrq $63,%r14 // r14 = t[7] >> 63
orq %r15,%r8 // r8 = t[7] * 2 + t[6] >> 63
movq 0(%rdi),%r15 // r15 = t[8]
movq %r14,%r11 // r11 = t[7] >> 63
mulq %rax // (rdx, rax) = a[3] * a[3]
negq %r10 // r10 = CF
movq 8(%rdi),%r14 // r14 = t[9]
adcq %rax,%rbx // rbx = t[6] * 2 + t[5] >> 63 + lo(a[3] * a[3])
movq %rbx,-16(%rdi) // t[6] = rbx
adcq %rdx,%r8 // r8 = t[7] * 2 + t[6] >> 63 + hi(a[3] * a[3])
leaq (%r11,%r15,2),%r13 // r13 = t[8] * 2 + t[7] >> 63
movq %r8,-8(%rdi) // t[7] = hi(a[3] * a[3])
movq (%rsi,%rbp),%rax // rax = a[4]
sbbq %r10,%r10 // r10 = -CF
shrq $63,%r15 // r15 = t[8] >> 63
leaq (%rcx,%r14,2),%r12 // r12 = t[9] * 2
shrq $63,%r14 // r14 = t[9] >> 63
orq %r15,%r12 // r12 = t[9] * 2 + t[8] >> 63
movq 16(%rdi),%r15 // r15 = t[10]
movq %r14,%r11 // r11 = t[9] >> 63
mulq %rax // (rdx, rax) = a[4] * a[4]
negq %r10 // r10 = -CF
movq 24(%rdi),%r14 // r14 = t[11]
adcq %rax,%r13 // r13 = t[8] * 2 + t[7] >> 63 + lo(a[4] * a[4])
movq %r13,(%rdi) // t[8] = r12
adcq %rdx,%r12 // r12 = t[9] * 2 + t[8] >> 63 + hi(a[4] * a[4])
leaq (%r11,%r15,2),%rbx // rbx = t[10] * 2 + t[9] >> 63
movq 8(%rsi,%rbp),%rax // rax = a[5]
movq %r12,8(%rdi) // t[9] = r13
sbbq %r10,%r10 // r10 = -CF
shrq $63,%r15 // r15 = t[10] >> 63
leaq (%rcx,%r14,2),%r8 // r8 = t[11] * 2
shrq $63,%r14 // r14 = t[11] >> 63
orq %r15,%r8 // r8 = t[11] * 2 + t[10] >> 63
movq 32(%rdi),%r15 // r15 = t[12]
movq %r14,%r11 // r11 = t[11] >> 63
mulq %rax // (rdx, rax) = a[5] * a[5]
negq %r10 // r10 = CF
movq 40(%rdi),%r14 // r14 = t[13]
adcq %rax,%rbx // rbx = t[10] * 2 + t[9] >> 63 + lo(a[5] * a[5])
movq 16(%rsi,%rbp),%rax // rax = a[6]
movq %rbx,16(%rdi) // t[10] = rbx
adcq %rdx,%r8 // r8 = t[11] * 2 + t[10] >> 63 + hi(a[5] * a[5])
movq %r8,24(%rdi) // t[11] = r8
sbbq %r10,%r10 // r10 = -CF
leaq 64(%rdi),%rdi // t += 64
addq $32,%rbp // i += 4
jnz .LoopShiftAddSqr4x // if i != 0
leaq (%r11,%r15,2),%r13 // r13 = t[12] * 2 + t[11] >> 63
shrq $63,%r15 // r15 = t[12] >> 63
leaq (%rcx,%r14,2),%r12 // r12 = t[13] * 2
shrq $63,%r14 // r14 = t[13] >> 63
orq %r15,%r12 // r12 = t[13] * 2 + t[12] >> 63
movq -16(%rdi),%r15 // r15 = t[14]
movq %r14,%r11 // r11 = t[13] >> 63
mulq %rax // (rdx, rax) = a[6] * a[6]
negq %r10 // r10 = CF
movq -8(%rdi),%r14 // r14 = t[15]
adcq %rax,%r13 // r13 = t[12] * 2 + t[11] >> 63 + lo(a[6] * a[6])
movq %r13,-32(%rdi) // t[12] = r12
adcq %rdx,%r12 // r12 = t[13] * 2 + t[12] >> 63 + hi(a[6] * a[6])
leaq (%r11,%r15,2),%rbx // rbx = t[14] * 2 + t[13] >> 63
movq -8(%rsi),%rax // rax = a[7]
movq %r12,-24(%rdi) // t[13] = r13
sbbq %r10,%r10 // r10 = -CF
shrq $63,%r15 // r15 = t[14] >> 63
leaq (%rcx,%r14,2),%r8 // r8 = t[15] * 2
shrq $63,%r14 // r14 = t[15] >> 63
orq %r15,%r8 // r8 = t[15] * 2 + t[14] >> 63
mulq %rax // (rdx, rax) = a[7] * a[7]
negq %r10 // r10 = CF
adcq %rax,%rbx // rbx = t[14] * 2 + t[13] >> 63 + lo(a[7] * a[7])
adcq %rdx,%r8 // r8 = t[15] * 2 + t[14] >> 63 + hi(a[7] * a[7])
movq %rbx,-16(%rdi) // t[14] = rbx
movq %r8,-8(%rdi) // t[15] = r8
movq %xmm1,%rbp // rbp = n
xorq %rax,%rax // rax = 0
leaq (%r9,%rbp),%rcx // rcx = n[size]
leaq 56(%rsp,%r9,2),%rdx // rdx = t[size * 2]
movq %rcx,8(%rsp)
leaq 56(%rsp,%r9),%rdi
movq %rdx,16(%rsp)
negq %r9
.align 32
.LoopReduceSqr8x:
leaq (%rdi,%r9),%rdi // rdi = t[]
movq (%rdi),%rbx // rbx = t[0]
movq 8(%rdi),%r9 // r9 = t[1]
movq 16(%rdi),%r15 // r15 = t[2]
movq 24(%rdi),%r14 // r14 = t[3]
movq 32(%rdi),%r13 // r13 = t[4]
movq 40(%rdi),%r12 // r12 = t[5]
movq 48(%rdi),%r11 // r11 = t[6]
movq 56(%rdi),%r10 // r10 = t[7]
movq %rax,(%rdx) // Store the highest carry bit.
leaq 64(%rdi),%rdi // rdi = t[8]
movq %rbx,%r8 // r8 = t[0]
imulq 40(%rsp),%rbx // rbx = k0 * t[0]
movl $8,%ecx
.align 32
.LoopReduce8x:
movq (%rbp),%rax // rax = n[0]
mulq %rbx // (rdx, rax) = t[0] * k0 * n[0]
negq %r8 // r8 = -t[0], If t[0] is not 0, set CF to 1.
movq %rdx,%r8 // r8 = hi(t[0] * k0 * n[0])
adcq $0,%r8 // r8 += CF
movq 8(%rbp),%rax // rax = n[1]
mulq %rbx // (rdx, rax) = t[0] * k0 * n[1]
movq %rbx,48(%rsp,%rcx,8)
ADD_CARRY %rax,%r9 // r9 = t[1] + lo(t[0] * k0 * n[1])
ADD_CARRY %r9,%r8 // r8 = hi(t[0] * k0 * n[0]) + lo(t[0] * k0 * n[1]) + t[1]
movq 16(%rbp),%rax // rax = n[2]
movq %rdx,%r9 // r9 = hi(t[0] * k0 * n[1])
mulq %rbx // (rdx, rax) = t[0] * k0 * n[2]
ADD_CARRY %rax,%r15 // r15 = lo(t[0] * k0 * n[2]) + t[2]
ADD_CARRY %r15,%r9 // r9 = hi(t[0] * k0 * n[1]) + lo(t[0] * k0 * n[2]) + t[2]
movq 40(%rsp),%rsi // rsi = k0
movq %rdx,%r15 // r15 = hi(t[0] * k0 * n[2])
movq 24(%rbp),%rax // rax = n[3]
mulq %rbx // (rdx, rax) = t[0] * k0 * n[3]
ADD_CARRY %rax,%r14 // r14 = lo(t[0] * k0 * n[3])
imulq %r8,%rsi // rsi = k0 * r8
ADD_CARRY %r14,%r15 // r15 = hi(t[0] * k0 * n[2]) + lo(t[0] * k0 * n[3])
movq %rdx,%r14 // r14 = hi(t[0] * k0 * n[3])
movq 32(%rbp),%rax // rax = n[4]
mulq %rbx // (rdx, rax) = t[0] * k0 * n[4]
ADD_CARRY %rax,%r13 // r13 = lo(t[0] * k0 * n[4]) + t[4]
ADD_CARRY %r13,%r14 // r14 = hi(t[0] * k0 * n[3]) + lo(t[0] * k0 * n[4]) + t[4]、
movq 40(%rbp),%rax // rax = n[5]
movq %rdx,%r13 // r13 = hi(t[0] * k0 * n[4])
mulq %rbx // (rdx, rax) = t[0] * k0 * n[5]
ADD_CARRY %rax,%r12 // r12 = lo(t[0] * k0 * n[5]) + t[5]
ADD_CARRY %r12,%r13 // r13 = hi(t[0] * k0 * n[4]) + lo(t[0] * k0 * n[5]) + t[5]
movq 48(%rbp),%rax // rax = n[6]
movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[5])
mulq %rbx // (rdx, rax) = t[0] * k0 * n[6]
ADD_CARRY %rax,%r11 // r11 = lo(t[0] * k0 * n[6]) + t[6]
ADD_CARRY %r11,%r12 // r12 = hi(t[0] * k0 * n[5]) + lo(t[0] * k0 * n[6]) + t[6]
movq 56(%rbp),%rax // rax = n[7]
movq %rdx,%r11 // r11 = hi(t[0] * k0 * n[6])
mulq %rbx // (rdx, rax) = t[0] * k0 * n[7]
movq %rsi,%rbx // rbx = k0 * r8
ADD_CARRY %rax,%r10 // r10 = lo(t[0] * k0 * n[7]) + t[7]
ADD_CARRY %r10,%r11 // r11 = hi(t[0] * k0 * n[6]) + lo(t[0] * k0 * n[7]) + t[7]
movq %rdx,%r10 // r10 = hi(t[0] * k0 * n[7])
decl %ecx // ecx--
jnz .LoopReduce8x // if ecx != 0
leaq 64(%rbp),%rbp // rbp += 64, n Pointer Offset.
xorq %rax,%rax // rax = 0
movq 16(%rsp),%rdx // rdx = t[size * 2]
cmpq 8(%rsp),%rbp // rbp = n[size]
jae .LoopEndCondMul8x
addq (%rdi),%r8 // r8 += t[0]
adcq 8(%rdi),%r9 // r9 += t[1]
adcq 16(%rdi),%r15 // r15 += t[2]
adcq 24(%rdi),%r14 // r14 += t[3]
adcq 32(%rdi),%r13 // r13 += t[4]
adcq 40(%rdi),%r12 // r12 += t[5]
adcq 48(%rdi),%r11 // r11 += t[6]
adcq 56(%rdi),%r10 // r10 += t[7]
sbbq %rsi,%rsi // rsi = -CF
movq 112(%rsp),%rbx // rbx = t[0] * k0, 48 + 56 + 8
movl $8,%ecx
.align 32
.LoopLastSqr8x:
movq (%rbp),%rax // rax = n[0]
mulq %rbx // (rdx, rax) = t[0] * k0 * n[0]
ADD_CARRY %rax,%r8 // r8 += lo(t[0] * k0 * n[0])
movq %r8,(%rdi) // t[0] = r8
leaq 8(%rdi),%rdi // t++
movq %rdx,%r8 // r8 = hi(t[0] * k0 * n[0])
movq 8(%rbp),%rax // rax = n[1]
mulq %rbx // (rdx, rax) = t[0] * k0 * n[1]
ADD_CARRY %rax,%r9 // r9 += lo(t[0] * k0 * n[1])
ADD_CARRY %r9,%r8 // r8 = hi(t[0] * k0 * n[0]) + r9
movq 16(%rbp),%rax // rax = n[2]
movq %rdx,%r9 // r9 = hi(t[0] * k0 * n[1])
mulq %rbx // (rdx, rax) = t[0] * k0 * n[2]
ADD_CARRY %rax,%r15 // r15 += lo(t[0] * k0 * n[2])
ADD_CARRY %r15,%r9 // r9 = hi(t[0] * k0 * n[1]) + r10
movq 24(%rbp),%rax // rax = n[3]
movq %rdx,%r15 // r15 = hi(t[0] * k0 * n[2])
mulq %rbx // (rdx, rax) = t[0] * k0 * n[3]
ADD_CARRY %rax,%r14 // r14 += lo(t[0] * k0 * n[3])
ADD_CARRY %r14,%r15 // r15 = hi(t[0] * k0 * n[2]) + r11
movq 32(%rbp),%rax // rax = n[4]
movq %rdx,%r14 // r14 = hi(t[0] * k0 * n[3])
mulq %rbx // (rdx, rax) = t[0] * k0 * n[4]
ADD_CARRY %rax,%r13 // r13 += lo(t[0] * k0 * n[4])
ADD_CARRY %r13,%r14 // r14 = hi(t[0] * k0 * n[3]) + r12
movq 40(%rbp),%rax // rax = n[5]
movq %rdx,%r13 // r13 = hi(t[0] * k0 * n[4])
mulq %rbx // (rdx, rax) = t[0] * k0 * n[5]
ADD_CARRY %rax,%r12 // r12 += lo(t[0] * k0 * n[5])
ADD_CARRY %r12,%r13 // r13 = hi(t[0] * k0 * n[4]) + r13
movq 48(%rbp),%rax // rax = n[6]
movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[5])
mulq %rbx // (rdx, rax) = t[0] * k0 * n[6]
ADD_CARRY %rax,%r11 // r11 += lo(t[0] * k0 * n[6])
ADD_CARRY %r11,%r12 // r12 = hi(t[0] * k0 * n[5]) + r14
movq 56(%rbp),%rax // rax = n[7]
movq %rdx,%r11 // r11 = hi(t[0] * k0 * n[6])
mulq %rbx // (rdx, rax) = t[0] * k0 * n[7]
movq 40(%rsp,%rcx,8),%rbx // rbx = t[i] * k0
ADD_CARRY %rax,%r10 // r10 += lo(t[0] * k0 * n[7])
ADD_CARRY %r10,%r11 // r11 = hi(t[0] * k0 * n[6]) + r10
movq %rdx,%r10 // r10 = hi(t[0] * k0 * n[7])
decl %ecx // ecx--
jnz .LoopLastSqr8x // if ecx != 0
leaq 64(%rbp),%rbp // n += 8
movq 16(%rsp),%rdx // rdx = t[size * 2]
cmpq 8(%rsp),%rbp // Check whether rbp is at the end of the n array. If yes, exit the loop.
jae .LoopSqrBreak8x
movq 112(%rsp),%rbx // rbx = t[0] * k0
negq %rsi // rsi = CF
movq (%rbp),%rax // rax = = n[0]
adcq (%rdi),%r8 // r8 = t[0]
adcq 8(%rdi),%r9 // r9 = t[1]
adcq 16(%rdi),%r15 // r15 = t[2]
adcq 24(%rdi),%r14 // r14 = t[3]
adcq 32(%rdi),%r13 // r13 = t[4]
adcq 40(%rdi),%r12 // r12 = t[5]
adcq 48(%rdi),%r11 // r11 = t[6]
adcq 56(%rdi),%r10 // r10 = t[7]
sbbq %rsi,%rsi // rsi = -CF
movl $8,%ecx // ecx = 8
jmp .LoopLastSqr8x
.align 32
.LoopSqrBreak8x:
xorq %rax,%rax // rax = 0
addq (%rdx),%r8 // r8 += Highest carry bit.
adcq $0,%r9 // r9 += CF
adcq $0,%r15 // r15 += CF
adcq $0,%r14 // r14 += CF
adcq $0,%r13 // r13 += CF
adcq $0,%r12 // r12 += CF
adcq $0,%r11 // r11 += CF
adcq $0,%r10 // r10 += CF
adcq $0,%rax // rax += CF
negq %rsi // rsi = CF
.LoopEndCondMul8x:
adcq (%rdi),%r8 // r8 += t[0]
adcq 8(%rdi),%r9 // r9 += t[1]
adcq 16(%rdi),%r15 // r15 += t[2]
adcq 24(%rdi),%r14 // r14 += t[3]
adcq 32(%rdi),%r13 // r13 += t[4]
adcq 40(%rdi),%r12 // r12 += t[5]
adcq 48(%rdi),%r11 // r11 += t[6]
adcq 56(%rdi),%r10 // r10 += t[7]
adcq $0,%rax // rax += CF
movq -8(%rbp),%rcx // rcx = n[7]
xorq %rsi,%rsi // rsi = 0
movq %xmm1,%rbp // rbp = n
movq %r8,(%rdi) // Save the calculated result back to t[].
movq %r9,8(%rdi)
movq %xmm5,%r9
movq %r15,16(%rdi)
movq %r14,24(%rdi)
movq %r13,32(%rdi)
movq %r12,40(%rdi)
movq %r11,48(%rdi)
movq %r10,56(%rdi)
leaq 64(%rdi),%rdi // t += 8
cmpq %rdx,%rdi // Cycle the entire t[].
jb .LoopReduceSqr8x
ret
.cfi_endproc
.size MontSqr8Inner,.-MontSqr8Inner
#endif
|
2301_79861745/bench_create
|
crypto/bn/src/asm/bn_mont_x86_64.S
|
Unix Assembly
|
unknown
| 61,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_BN
.file "bn_mont_x86_64.S"
.text
.macro ADD_CARRY a b
addq \a,\b
adcq $0,%rdx
.endm
.macro SAVE_REGISTERS
pushq %r15 // Save non-volatile register.
pushq %r14
pushq %r13
pushq %r12
pushq %rbp
pushq %rbx
.endm
.macro RESTORE_REGISTERS
popq %rbx // Restore non-volatile register.
popq %rbp
popq %r12
popq %r13
popq %r14
popq %r15
.endm
/*
* void MontMulx_Asm(uint64_t *r, const uint64_t *a, const uint64_t *b,
* const uint64_t *n, const uint64_t k0, uint32_t size);
*/
.globl MontMulx_Asm
.type MontMulx_Asm,@function
.align 16
MontMulx_Asm:
.cfi_startproc
testl $3,%r9d
jnz .LMontMul // If size is not divisible by 4, LMontMul.
cmpl $8,%r9d
jb .LMontMul // LMontMul
cmpq %rsi,%rdx
jne MontMul4x // if a != b, MontMul4x
testl $7,%r9d
jz MontSqr8x // If size is divisible by 8,enter MontSqr8x.
jmp MontMul4x
.align 16
.LMontMul:
SAVE_REGISTERS // Save non-volatile register.
movq %rsp,%rax // rax stores the rsp
movq %r9, %r15
negq %r15 // r15 = -size
leaq -16(%rsp, %r15, 8), %r15 // r15 = rsp - size * 8 - 16
andq $-1024, %r15 // r15 The address is aligned down by 1 KB.
movq %rsp, %r14 // r14 = rsp
subq %r15,%r14 // __chkstk implemention, called when the stack size needs to exceed 4096.
// (the size of a page) to allocate more pages.
andq $-4096,%r14 // r14 4K down-align.
leaq (%r15,%r14),%rsp // rsp = r15 + r14
cmpq %r15,%rsp // If you want to allocate more than one page, go to Lmul_page_walk.
ja .LoopPage
jmp .LMulBody
.align 16
.LoopPage:
leaq -4096(%rsp),%rsp // rsp - 4096 each time until rsp < r15.
cmpq %r15,%rsp
ja .LoopPage
.LMulBody:
movq %rax,8(%rsp,%r9,8) // Save the original rsp in the stack.
movq %rdx,%r13 // r13 = b
xorq %r11,%r11 // r11 = 0
xorq %r10,%r10 // r10 = 0
movq (%r13),%rbx // rbx = b[0]
movq (%rsi),%rax // rax = a[0]
mulq %rbx // (rdx, rax) = a[0] * b[0]
movq %rax,%r15 // r15 = t[0] = lo(a[0] * b[0])
movq %rdx,%r14 // r14 = hi(a[0] * b[0])
movq %r8,%rbp // rbp = k0
imulq %r15,%rbp // rbp = t[0] * k0
movq (%rcx),%rax // rax = n[0]
mulq %rbp // (rdx, rax) = t[0] * k0 * n[0]
ADD_CARRY %rax,%r15 // r15 = lo(t[0] * k0 * n[0]) + t[0]
leaq 1(%r10),%r10 // j++
.Loop1st:
movq (%rsi,%r10,8),%rax // rax = a[j]
movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[0])
mulq %rbx // (rdx, rax) = a[j] * b[0]
ADD_CARRY %rax,%r14 // r14 = hi(a[j - 1] * b[0]) + lo(a[j] * b[0])
movq %rdx,%r15 // r15 = hi(a[j] * b[0])
movq (%rcx,%r10,8),%rax // rax = n[j]
mulq %rbp // (rdx, rax) = t[0] * k0 * n[j]
leaq 1(%r10),%r10 // j++
cmpq %r9,%r10 // if j != size, loop L1st
je .Loop1stSkip
ADD_CARRY %rax,%r12 // r12 = hi(t[0] * k0 * n[j]) + lo(t[0] * k0 * n[j])
ADD_CARRY %r14,%r12 // r12 += lo(a[j] * b[0]) + hi(a[j] * b[0])
movq %r12,-16(%rsp,%r10,8) // t[j - 2] = r13
movq %r15,%r14 // r14 = hi(a[j] * b[0])
jmp .Loop1st
.Loop1stSkip:
ADD_CARRY %rax,%r12 // r12 = hi(t[0] * k0 * n[j - 1]) + lo(t[0] * k0 * n[j])
ADD_CARRY %r14,%r12 // r12 += hi(a[j - 1] * b[0]) + lo(a[j] * b[0])
movq %r12,-16(%rsp,%r10,8) // t[j - 2] = r13
movq %r15,%r14 // r14 = hi(a[j] * b[0])
movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j])
xorq %rdx,%rdx // rdx = 0, Clearing the CF.
ADD_CARRY %r14,%r12 // r12 = hi(t[0] * k0 * n[j]) + hi(a[j] * b[0])
movq %r12,-8(%rsp,%r9,8) // t[size - 1] = hi(t[0] * k0 * n[j]) + hi(a[j] * b[0]), save overflow bit.
movq %rdx,(%rsp,%r9,8)
leaq 1(%r11),%r11 // i++
.align 16
.LoopOuter:
xorq %r10,%r10 // j = 0
movq (%rsi),%rax // rax = a[0]
movq (%r13,%r11,8),%rbx // rbx = b[i]
mulq %rbx // (rdx, rax) = a[0] * b[i]
movq (%rsp),%r15 // r15 = lo(a[0] * b[i]) + t[0]
ADD_CARRY %rax,%r15
movq %rdx,%r14 // r14 = hi(a[0] * b[i])
movq %r8,%rbp // rbp = t[0] * k0
imulq %r15,%rbp
movq (%rcx),%rax // rax = n[0]
mulq %rbp // (rdx, rax) = t[0] * k0 * n[0]
ADD_CARRY %rax,%r15 // r15 = lo(t[0] * k0 * n[0])
leaq 1(%r10),%r10 // j++
.align 16
.LoopInner:
movq (%rsi,%r10,8),%rax // rax = a[j]
movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j])
movq (%rsp,%r10,8),%r15 // r15 = t[j]
mulq %rbx // (rdx, rax) = a[1] * b[i]
ADD_CARRY %rax,%r14 // r14 = hi(a[0] * b[i]) + lo(a[1] * b[i])
movq (%rcx,%r10,8),%rax // rax = n[j]
ADD_CARRY %r14,%r15 // r15 = a[j] * b[i] + t[j]
movq %rdx,%r14
leaq 1(%r10),%r10 // j++
mulq %rbp // (rdx, rax) = t[0] * k0 * n[j]
cmpq %r9,%r10 // if j != size, loop Linner
je .LoopInnerSkip
ADD_CARRY %rax,%r12 // r12 = t[0] * k0 * n[j]
ADD_CARRY %r15,%r12 // r12 = a[j] * b[i] + t[j] + n[j] * t[0] * k0
movq %r12,-16(%rsp,%r10,8) // t[j - 2] = r13
jmp .LoopInner
.LoopInnerSkip:
ADD_CARRY %rax,%r12 // r12 = t[0] * k0 * n[j]
ADD_CARRY %r15,%r12 // r12 = t[0] * k0 * n[j] + a[j] * b[i] + t[j]
movq (%rsp,%r10,8),%r15 // r15 = t[j]
movq %r12,-16(%rsp,%r10,8) // t[j - 2]
movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j])
xorq %rdx,%rdx // rdx 0
ADD_CARRY %r14,%r12 // r12 = hi(a[1] * b[i]) + hi(t[0] * k0 * n[j])
ADD_CARRY %r15,%r12 // r12 += t[j]
movq %r12,-8(%rsp,%r9,8) // t[size - 1] = r13
movq %rdx,(%rsp,%r9,8) // t[size] = CF
leaq 1(%r11),%r11 // i++
cmpq %r9,%r11 // if size < i (unsigned)
jne .LoopOuter
xorq %r11,%r11 // r11 = 0, clear CF.
movq (%rsp),%rax // rax = t[0]
movq %r9,%r10 // r10 = size
.align 16
.LoopSub:
sbbq (%rcx,%r11,8),%rax // r[i] = t[i] - n[i]
movq %rax,(%rdi,%r11,8)
movq 8(%rsp,%r11,8),%rax // rax = t[i + 1]
leaq 1(%r11),%r11 // i++
decq %r10 // j--
jnz .LoopSub // if j != 0
sbbq $0,%rax // rax -= CF
movq $-1,%rbx
xorq %rax,%rbx // rbx = !t[i + 1]
xorq %r11,%r11 // r11 = 0
movq %r9,%r10 // r10 = size
.LoopCopy:
movq (%rdi,%r11,8),%rcx // rcx = r[i] & t[i]
andq %rbx,%rcx
movq (%rsp,%r11,8),%rdx // rdx = CF & t[i]
andq %rax,%rdx
orq %rcx,%rdx
movq %rdx,(%rdi,%r11,8) // r[i] = t[i]
movq %r9,(%rsp,%r11,8) // t[i] = size
leaq 1(%r11),%r11 // i++
subq $1,%r10 // j--
jnz .LoopCopy // if j != 0
movq 8(%rsp,%r9,8),%rsi // rsi = pressed-stacked rsp.
movq $1,%rax // rax = 1
leaq (%rsi),%rsp // restore rsp.
RESTORE_REGISTERS // Restore non-volatile register.
ret
.cfi_endproc
.size MontMulx_Asm,.-MontMulx_Asm
.type MontMul4x,@function
.align 16
MontMul4x:
.cfi_startproc
SAVE_REGISTERS
movq %rsp,%rax // save rsp
movq %r9,%r15
negq %r15
leaq -48(%rsp,%r15,8),%r15 // Allocate space: size * 8 + 48 bytes.
andq $-1024,%r15
movq %rsp,%r14
subq %r15,%r14 // __chkstk implemention, called when the stack size needs to exceed 4096.
andq $-4096,%r14
leaq (%r15,%r14),%rsp
cmpq %r15,%rsp // If you want to allocate more than one page, go to LoopPage4x.
ja .LoopPage4x
jmp .LoopMul4x
.LoopPage4x:
leaq -4096(%rsp),%rsp // rsp - 4096each time until rsp >= r10.
cmpq %r15,%rsp
ja .LoopPage4x
.LoopMul4x:
movq %rax, 0(%rsp) // save stack pointer
movq %rdi, 8(%rsp) // save r
movq %r8, 16(%rsp) // save k0
movq %r9, %r10
shrq $2, %r9
decq %r9
movq %r9, 24(%rsp) // save (size/4) - 1
shlq $3, %r10
movq %rdx, %r12 // r12 = b
movq %r10, 32(%rsp) // save (size * 8) -> bytes
addq %r10, %r12 // r12 = loc(b[size - 1])
leaq 80(%rsp),%rbp // rbp: start position of the tmp buffer
movq %rdx,%r13 // r13 = b
movq %r12, 40(%rsp) // save loc(b + size * 8)
movq (%r13),%rdx // rbx = b[0]
// cal a[0 ~ 3] * b[0]
mulx (%rsi), %r12, %r14 // r14 = hi(a[0] * b[0]), r12 = lo(b[0] * a[0])
mulx 8(%rsi), %rax, %r15 // (r15, rax) = a[1] * b[0]
addq %rax, %r14 // r14 = hi(a[0] * b[0]) + lo(a[1] * b[0])
mulx 16(%rsi), %rax, %r11 // (rax, r11) = a[2] * b[0]
adcq %rax, %r15 // r15 = hi(a[1] * b[0]) + lo(a[2] * b[0])
adcq $0, %r11 // r11 = hi(a[2] * b[0]) + CF
imulq %r12,%r8 // r8 = t[0] * k0, will change CF
xorq %r10,%r10 // get r10 = 0
mulx 24(%rsi), %rax, %rbx // (rax, rbx) = a[3] * b[0]
movq %r8, %rdx // rdx = t[0] * k0 = m'
adcx %rax, %r11 // r11 = hi(a[2] * b[0]) + lo(a[3] * b[0])
adcx %r10, %rbx // rbx = hi(a[3] * b[0])
// cal n[0 ~ 3] * t[0] * k0
mulx (%rcx), %rax, %rdi // (rdi, rax) = n[0] * m'
adcx %rax, %r12 // r12 = lo(b[0] * a[0]) + lo(n[0] * m')
adox %r14, %rdi // r8 = hi(n[0] * m') + hi(a[0] * b[0]) + hi(n[0] * m')
mulx 8(%rcx), %rax, %r14 // (r14, rax) = n[1] * m'
adcx %rax, %rdi
adox %r15, %r14 // r11 = hi(a[1] * b[0]) + lo(a[2] * b[0]) + hi(n[1] * m')
movq %rdi, -32(%rbp)
mulx 16(%rcx), %rax, %r15 // (r15, rax) = n[2] * m'
adcx %rax, %r14
adox %r11, %r15 // r11 = hi(a[2] * b[0]) + lo(a[3] * b[0]) + hi(n[2] * m')
movq %r14, -24(%rbp)
mulx 24(%rcx), %rax, %r11 // (r11, rax) = n[3] * m'
adcx %rax, %r15
adox %r10, %r11 // r11 = hi(n[3] * m')
movq %r15, -16(%rbp)
leaq 4*8(%rsi),%rsi // a offset 4 blocks
leaq 4*8(%rcx),%rcx // n offset 4 blocks
movq (%r13),%rdx // rdx = b[0]
.align 16
.Loop1st4x:
mulx (%rsi), %r12, %r14 // r14 = hi(a[4] * b[0]), r12 = lo(a[4] * b[0])
adcx %r10, %r11 // r11 += carry
mulx 8(%rsi), %rax, %r15 // r15 = hi(a[5] * b[0]), rax = lo(a[5] * b[0])
adcx %rbx, %r12 // r12 = hi(a[3] * b[0]) + lo(a[4] * b[0])
adcx %rax, %r14 // r14 = hi(a[4] * b[0]) + lo(a[5] * a[0])
mulx 16(%rsi), %rax, %rdi // rax = hi(a[6] * b[0]), rax = lo(a[6] * b[0])
adcx %rax, %r15 // r15 = hi(a[5] * b[0]) + lo(a[6] * a[0])
mulx 24(%rsi), %rax, %rbx // rax = hi(a[7] * b[0]), rdi = lo(a[7] * b[0])
adcx %rax, %rdi // rbx = hi(a[6] * b[0]) + lo(a[7] * b[0])
adcx %r10, %rbx // rdi = hi(a[7] * b[0]) + CF
movq %r8, %rdx
adox %r11,%r12 // r12 = hi(a[3] * b[0]) + lo(b[4] * a[0]) + hi(n[3] * m')
mulx (%rcx), %rax, %r11 // (rax, r8) = n[4] * m'
leaq 4*8(%rsi), %rsi // a offset 4 blocks
adcx %rax,%r12 // r12 = hi(a[3] * b[0]) + lo(b[4] * a[0])
// + hi(n[3] * m') + lo(n[4] * m')
adox %r14, %r11 // r8 = hi(a[4] * b[0]) + lo(a[5] * b[0]) + hi(n[4] * m')
mulx 8(%rcx), %rax, %r14 // (rax, r14) = n[5] * m'
leaq 4*8(%rbp), %rbp // tmp offset 4 blocks
adcx %rax, %r11 // r8 = hi(a[4] * b[0]) + lo(a[5] * b[0])
// + hi(n[4] * m') + lo(n[5] * m')
adox %r15, %r14 // r14 = hi(a[5] * b[0]) + lo(a[6] * a[0])
// + ho(n[5] * m')
mulx 16(%rcx), %rax, %r15 // (rax, r15) = n[6] * m'
movq %r12, -5*8(%rbp)
adcx %rax, %r14 // r14 = hi(a[5] * b[0]) + lo(a[6] * a[0])
// + hi(n[5] * m') + lo(n[6] * m')
adox %rdi, %r15 // r15 = hi(a[6] * b[0]) + lo(a[7] * b[0])
// + hi(n[6] * m')
movq %r11, -4*8(%rbp)
mulx 24(%rcx), %rax, %r11 // (rax, r11) = n[7] * m'
movq %r14, -3*8(%rbp)
adcx %rax, %r15 // r15 = hi(a[6] * b[0]) + lo(a[7] * b[0])
// + hi(n[6] * m') + lo(n[7] * m')
adox %r10, %r11
movq %r15, -2*8(%rbp)
leaq 4*8(%rcx), %rcx // n offset 4 blocks
movq (%r13),%rdx // recover rdx
dec %r9
jnz .Loop1st4x
movq 32(%rsp), %r15 // r15 = size * 8
leaq 8(%r13), %r13 // b offset 1 blocks
adcx %r10, %r11 // hi(n[7] * m') + CF, here OX CF are carried.
addq %r11, %rbx // hi(a[7] * b[0]) + hi(n[7] * m')
sbbq %r11,%r11 // check r11 > 0
movq %rbx, -1*8(%rbp)
.align 4
.LoopOuter4x:
// cal a[0 ~ 3] * b[i]
movq (%r13),%rdx // rdx = b[i]
mov %r11, (%rbp) // keep the highest carry
subq %r15, %rsi // get a[0]
subq %r15, %rcx // get n[0]
leaq 80(%rsp),%rbp // get tmp[0]
// from here, a[0 ~ 3] * b[i] needs to add tmp
mulx (%rsi), %r12, %r14 // r14 = hi(a[0] * b[i]), r12 = lo(b[i] * a[0])
xorq %r10,%r10 // get r10 = 0, and clear CF OF
mulx 8(%rsi), %rax, %r15 // (r15, rax) = a[1] * b[i]
adox -4*8(%rbp), %r12 // lo(a[1] * b[i]) + tmp[0]
adcx %rax, %r14 // r14 = hi(a[0] * b[i]) + lo(a[1] * b[i])
mulx 16(%rsi), %rax, %r11 // (rax, r11) = a[2] * b[0]
adox -3*8(%rbp),%r14 // r14 = hi(a[1] * b[i]) + lo(a[1] * b[i]) + tmp[1]
adcx %rax, %r15 // r15 = hi(a[1] * b[i]) + lo(a[2] * b[i])
mulx 24(%rsi), %rax, %rbx // (rax, rbx) = a[3] * b[0]
adox -2*8(%rbp),%r15 // r15 = hi(a[2] * b[i]) + lo(a[2] * b[i]) + tmp[2]
adcx %rax, %r11 // r11 = hi(a[2] * b[0]) + lo(a[3] * b[0])
adox -1*8(%rbp),%r11 // r11 = hi(a[2] * b[i]) + lo(a[3] * b[i]) + tmp[3]
adcx %r10,%rbx
movq %r12, %rdx
adox %r10,%rbx
imulq 16(%rsp),%rdx // 16(%rsp) save k0, r8 = t[0] * k0 = m', imulq will change CF
mulx (%rcx), %rax, %r8 // (rax, r8) = n[0] * m'
xorq %r10, %r10 // clear CF
adcx %rax, %r12 // r12 = lo(b[0] * a[0]) + lo(n[0] * m')
adox %r14, %r8 // r8 = hi(n[0] * m') + hi(a[0] * b[0]) + hi(n[0] * m')
mulx 8(%rcx), %rax, %rdi // (rdi, rax) = n[1] * m'
leaq 4*8(%rsi),%rsi // a offsets 4
adcx %rax, %r8
adox %r15, %rdi // r11 = hi(a[1] * b[0]) + lo(a[2] * b[0]) + hi(n[1] * m')
mulx 16(%rcx), %rax, %r15 // (rdi, rax) = n[2] * m'
movq %r8, -32(%rbp)
adcx %rax, %rdi
adox %r11, %r15 // r11 = hi(a[2] * b[0]) + lo(a[3] * b[0]) + hi(n[2] * m')
mulx 24(%rcx), %rax, %r11 // (rdi, rax) = n[3] * m'
movq %rdi, -24(%rbp)
adcx %rax, %r15
adox %r10, %r11 // r11 = hi(n[3] * m')
movq %r15, -16(%rbp)
leaq 4*8(%rcx),%rcx // n offsets 4
movq %rdx, %r8 // r8 = t[0] * k0 = m'
movq (%r13), %rdx // rdx = b[i]
movq 24(%rsp), %r9
.align 16
.Linner4x:
mulx (%rsi), %r12, %r14 // r14 = hi(a[4] * b[i]), r12 = lo(a[4] * b[i])
adcx %r10, %r11 // carry of previous round
adox %rbx, %r12 // r12 = hi(a[3] * b[i]) + lo(a[4] * b[i])
mulx 8(%rsi), %rax, %r15 // r15 = hi(a[5] * b[i]), rax = lo(a[5] * b[0])
adcx (%rbp), %r12 // r12 = hi(a[3] * b[i]) + lo(a[4] * b[i]) + tmp[4] --> 所以这里t不偏移
adox %rax, %r14 // r14 = hi(a[4] * b[i]) + lo(a[5] * b[0])
mulx 16(%rsi), %rax, %rdi // rax = hi(a[6] * b[i]), rax = lo(a[6] * b[i])
adcx 8(%rbp), %r14 // r12 = hi(a[3] * b[i]) + lo(a[4] * b[i]) + tmp[5]
adox %rax, %r15 // r15 = hi(a[5] * b[i]) + lo(a[6] * b[i])
mulx 24(%rsi), %rax, %rbx // rax = hi(a[7] * b[i]), rdi = lo(a[7] * b[i])
adcx 16(%rbp), %r15 // r12 = hi(a[3] * b[i]) + lo(a[4] * b[i]) + tmp[6]
adox %rax, %rdi // rbx = hi(a[6] * b[i]) + lo(a[7] * b[i])
adox %r10, %rbx // rbx += OF
adcx 24(%rbp), %rdi // rdi = hi(a[6] * b[i]) + lo(a[7] * b[i]) + tmp[7]
adcx %r10, %rbx // rbx += CF
// update rdx, begin cal n[i] * k0 * m
adox %r11,%r12 // r12 = hi(a[3] * b[i]) + lo(a[4] * b[i]) + hi(n[3] * m')
movq %r8, %rdx
mulx (%rcx), %rax, %r11 // (rax, r8) = n[4] * m'
leaq 4*8(%rbp), %rbp // tmp offsets 4
adcx %rax,%r12 // r12 = hi(a[3] * b[i]) + lo(b[4] * a[i])
// + hi(n[3] * m') + lo(n[4] * m')
adox %r14, %r11 // r8 = hi(a[4] * b[i]) + lo(a[5] * b[i]) + hi(n[4] * m')
mulx 8(%rcx), %rax, %r14 // (rax, r14) = n[5] * m'
leaq 4*8(%rsi), %rsi // a offsets 4
adcx %rax, %r11 // r8 = hi(a[4] * b[i]) + lo(a[5] * b[i])
// + hi(n[4] * m') + lo(n[5] * m')
adox %r15, %r14 // r14 = hi(a[5] * b[i]) + lo(a[6] * a[i])
// + ho(n[5] * m')
mulx 16(%rcx), %rax, %r15 // (rax, r15) = n[6] * m'
movq %r12, -5*8(%rbp)
adcx %rax, %r14 // r14 = hi(a[5] * b[i]) + lo(a[6] * b[i])
// + hi(n[5] * m') + lo(n[6] * m')
movq %r11, -4*8(%rbp)
adox %rdi, %r15 // r15 = hi(a[6] * b[i]) + lo(a[7] * b[i])
// + hi(n[6] * m')
mulx 24(%rcx), %rax, %r11 // (rax, r11) = n[7] * m'
movq %r14, -3*8(%rbp)
adcx %rax, %r15 // r15 = hi(a[6] * b[0]) + lo(a[7] * b[0])
// + hi(n[6] * m') + lo(n[7] * m')
adox %r10, %r11
movq %r15, -2*8(%rbp)
leaq 4*8(%rcx), %rcx // n offsets 4
movq (%r13), %rdx
dec %r9
jnz .Linner4x
movq 32(%rsp), %r15 // r15 = size * 8
leaq 8(%r13), %r13 // b offsets 1.
adcx %r10, %r11 // hi(n[7] * m') + OF + CF
subq 0*8(%rbp), %r10
adcx %r11, %rbx // hi(a[7] * b[0]) + hi(n[7] * m')
sbbq %r11,%r11
movq %rbx, -1*8(%rbp)
cmp 40(%rsp), %r13
jne .LoopOuter4x
leaq 48(%rsp),%rbp // rbp = tmp[0]
subq %r15, %rcx // rcx= n[0]
negq %r11
movq 24(%rsp), %rdx // rdx = size/4
movq 8(%rsp), %rdi // get r[0]
// cal tmp - n
movq 0(%rbp), %rax // rax = tmp[0]
movq 8(%rbp), %rbx // rbx = tmp[1]
movq 16(%rbp), %r10 // r10 = tmp[2]
movq 24(%rbp), %r12 // r12 = tmp[3]
leaq 32(%rbp), %rbp // tmp += 4
subq 0(%rcx), %rax // tmp[0] - n[0]
sbbq 8(%rcx), %rbx // tmp[1] - n[1]
sbbq 16(%rcx), %r10 // tmp[2] - n[2]
sbbq 24(%rcx), %r12 // tmp[3] - n[3]
leaq 32(%rcx), %rcx // n += 4
movq %rax, 0(%rdi) // r save the tmp - n
movq %rbx, 8(%rdi)
movq %r10, 16(%rdi)
movq %r12, 24(%rdi)
leaq 32(%rdi), %rdi // r += 4
.LoopSub4x:
movq 0(%rbp), %rax // rax = tmp[0]
movq 8(%rbp), %rbx // rbx = tmp[1]
movq 16(%rbp), %r10 // r10 = tmp[2]
movq 24(%rbp), %r12 // r12 = tmp[3]
leaq 32(%rbp), %rbp
sbbq 0(%rcx), %rax // tmp[0] - n[0]
sbbq 8(%rcx), %rbx // tmp[1] - n[1]
sbbq 16(%rcx), %r10 // tmp[2] - n[2]
sbbq 24(%rcx), %r12 // tmp[3] - n[3]
leaq 32(%rcx), %rcx
movq %rax, 0(%rdi)
movq %rbx, 8(%rdi)
movq %r10, 16(%rdi)
movq %r12, 24(%rdi)
leaq 32(%rdi), %rdi
decq %rdx // j--
jnz .LoopSub4x // if j != 0
sbbq $0,%r11 // cancellation of highest carry
subq %r15, %rbp // rbp = tmp[0]
subq %r15, %rdi // r = n[0]
movq 24(%rsp), %r10 // r10 = size/4 - 1
pxor %xmm2,%xmm2 // xmm0 = 0
movq %r11, %xmm0
pcmpeqd %xmm1,%xmm1 // xmm5 = -1
pshufd $0,%xmm0,%xmm0
pxor %xmm0,%xmm1
xorq %rax,%rax
movdqa (%rbp,%rax),%xmm5 // Copy the result to r.
movdqu (%rdi,%rax),%xmm3
pand %xmm0,%xmm5
pand %xmm1,%xmm3
movdqa 16(%rbp,%rax),%xmm4
movdqu %xmm2,(%rbp,%rax)
por %xmm3,%xmm5
movdqu 16(%rdi,%rax),%xmm3
movdqu %xmm5,(%rdi,%rax)
pand %xmm0,%xmm4
pand %xmm1,%xmm3
movdqa %xmm2,16(%rbp,%rax)
por %xmm3,%xmm4
movdqu %xmm4,16(%rdi,%rax)
leaq 32(%rax),%rax
.align 16
.LoopCopy4x:
movdqa (%rbp,%rax),%xmm5
movdqu (%rdi,%rax),%xmm3
pand %xmm0,%xmm5
pand %xmm1,%xmm3
movdqa 16(%rbp,%rax),%xmm4
movdqu %xmm2,(%rbp,%rax)
por %xmm3,%xmm5
movdqu 16(%rdi,%rax),%xmm3
movdqu %xmm5,(%rdi,%rax)
pand %xmm0,%xmm4
pand %xmm1,%xmm3
movdqa %xmm2,16(%rbp,%rax)
por %xmm3,%xmm4
movdqu %xmm4,16(%rdi,%rax)
leaq 32(%rax),%rax
decq %r10 // j--
jnz .LoopCopy4x
movq 0(%rsp),%rsi // rsi = pressed-stacked rsp.
movq $1,%rax
leaq (%rsi),%rsp // Restore srsp.
RESTORE_REGISTERS
ret
.cfi_endproc
.size MontMul4x,.-MontMul4x
.type MontSqr8x,@function
.align 32
MontSqr8x:
.cfi_startproc
SAVE_REGISTERS
movq %rsp,%rax
movl %r9d,%r15d
shll $3,%r9d // Calculate size * 8 bytes.
shlq $5,%r15 // size * 8 * 4
negq %r9
leaq -64(%rsp,%r9,2),%r14 // r14 = rsp[size * 2 - 8]
subq %rsi,%r14
andq $4095,%r14
movq %rsp,%rbp
cmpq %r14,%r15
jae .Loop8xCheckstk
leaq 4032(,%r9,2),%r15 // r15 = 4096 - frame - 2 * size
subq %r15,%r14
movq $0,%r15
cmovcq %r15,%r14
.Loop8xCheckstk:
subq %r14,%rbp
leaq -96(%rbp,%r9,2),%rbp // Allocate a frame + 2 x size.
andq $-64,%rbp // __checkstk implementation,
// which is invoked when the stack size needs to exceed one page.
movq %rsp,%r14
subq %rbp,%r14
andq $-4096,%r14
leaq (%r14,%rbp),%rsp
cmpq %rbp,%rsp
jbe .LoopMul8x
.align 16
.LoopPage8x:
leaq -4096(%rsp),%rsp // Change sp - 4096 each time until sp <= the space to be allocated
cmpq %rbp,%rsp
ja .LoopPage8x
.LoopMul8x:
movq %r9,%r15 // r15 = -size * 8
negq %r9 // Restoresize.
movq %r8,32(%rsp) // Save the values of k0 and sp.
movq %rax,40(%rsp)
movq %rcx, %xmm1 // Pointer to saving n.
pxor %xmm2,%xmm2 // xmm0 = 0
movq %rdi, %xmm0 // Pointer to saving r.
movq %r15, %xmm5 // Save size.
call MontSqr8Inner
leaq (%rdi,%r9),%rbx // rbx = t[size]
movq %r9,%rcx // rcx = -size
movq %r9,%rdx // rdx = -size
movq %xmm0, %rdi // rdi = r
sarq $5,%rcx // rcx >>= 5
.align 32
/* T -= N */
.LoopSub8x:
movq (%rbx),%r13 // r13 = t[i]
movq 8(%rbx),%r12 // r12 = t[i + 1]
movq 16(%rbx),%r11 // r11 = t[i + 2]
movq 24(%rbx),%r10 // r10 = t[i + 3]
sbbq (%rbp),%r13 // r13 = t[i] - (n[i] + CF)
sbbq 8(%rbp),%r12 // r12 = t[i + 1] - (n[i + 1] + CF)
sbbq 16(%rbp),%r11 // r11 = t[i + 2] - (n[i + 2] + CF)
sbbq 24(%rbp),%r10 // r10 = t[i + 3] - (n[i + 3] + CF)
movq %r13,0(%rdi) // Assigning value to r.
movq %r12,8(%rdi)
movq %r11,16(%rdi)
movq %r10,24(%rdi)
leaq 32(%rbp),%rbp // n += 4
leaq 32(%rdi),%rdi // r += 4
leaq 32(%rbx),%rbx // t += 4
incq %rcx
jnz .LoopSub8x
sbbq $0,%rax // rax -= CF
leaq (%rbx,%r9),%rbx
leaq (%rdi,%r9),%rdi
movq %rax,%xmm0
pxor %xmm2,%xmm2
pshufd $0,%xmm0,%xmm0
movq 40(%rsp),%rsi // rsi = pressed-stacked rsp.
.align 32
.LoopCopy8x:
movdqa 0(%rbx),%xmm1 // Copy the result to r.
movdqa 16(%rbx),%xmm5
leaq 32(%rbx),%rbx
movdqu 0(%rdi),%xmm3
movdqu 16(%rdi),%xmm4
leaq 32(%rdi),%rdi
movdqa %xmm2,-32(%rbx)
movdqa %xmm2,-16(%rbx)
movdqa %xmm2,-32(%rbx,%rdx)
movdqa %xmm2,-16(%rbx,%rdx)
pcmpeqd %xmm0,%xmm2
pand %xmm0,%xmm1
pand %xmm0,%xmm5
pand %xmm2,%xmm3
pand %xmm2,%xmm4
pxor %xmm2,%xmm2
por %xmm1,%xmm3
por %xmm5,%xmm4
movdqu %xmm3,-32(%rdi)
movdqu %xmm4,-16(%rdi)
addq $32,%r9
jnz .LoopCopy8x
movq $1,%rax
leaq (%rsi),%rsp // Restore rsp.
RESTORE_REGISTERS // Restore non-volatile register.
ret
.cfi_endproc
.size MontSqr8x,.-MontSqr8x
.type MontSqr8Inner,@function
.align 32
MontSqr8Inner:
.cfi_startproc
movq %rsi, %r8
addq %r9, %r8
movq %r8, 64(%rsp) // save a[size]
movq %r9, 56(%rsp) // save size * 8
leaq 88(%rsp), %rbp // tmp的首地址
leaq 88(%rsp,%r9,2),%rbx
movq %rbx,16(%rsp) // t[size * 2]
leaq (%rcx,%r9),%rax
movq %rax,8(%rsp) // n[size]
jmp .MontSqr8xBegin
.MontSqr8xInitStack:
movdqa %xmm2,0*8(%rbp)
movdqa %xmm2,2*8(%rbp)
movdqa %xmm2,4*8(%rbp)
movdqa %xmm2,6*8(%rbp)
.MontSqr8xBegin:
movdqa %xmm2,8*8(%rbp)
movdqa %xmm2,10*8(%rbp)
movdqa %xmm2,12*8(%rbp)
movdqa %xmm2,14*8(%rbp)
lea 128(%rbp), %rbp
subq $64, %r9
jnz .MontSqr8xInitStack
xorq %rbx, %rbx // clear CF OF
movq $0, %r13
movq $0, %r12
movq $0, %r11
movq $0, %rdi
movq $0, %r15
movq $0, %rcx
leaq 88(%rsp), %rbp // set tmp[0]
movq 0(%rsi), %rdx // rdx = a[0]
movq $0, %r10
.LoopOuterSqr8x:
// begin a[0] * a[1~7]
mulx 8(%rsi), %rax, %r14 // rax = lo(a[1] * a[0]), r14 = hi(a[1] * a[0])
adcx %rbx, %rax
movq %rax, 8(%rbp)
adox %r13, %r14
mulx 16(%rsi), %rax, %r13 // (rax, r13) = a[2] * a[0]
adcx %rax, %r14 // r14 = hi(a[1] * a[0]) + lo(a[2] * a[0])
adox %r12, %r13
mulx 24(%rsi), %rax, %r12 // (rax, r12) = a[3] * a[0]
movq %r14, 16(%rbp)
adcx %rax, %r13 // r13 = hi(a[2] * a[0]) + lo(a[3] * a[0])
adox %r11, %r12
mulx 32(%rsi), %rax, %r11 // (rax, r11) = a[4] * a[0]
adcx %rax, %r12 // r12 = hi(a[3] * a[0]) + lo(a[4] * a[0])
adox %rdi, %r11
mulx 40(%rsi), %rax, %rdi // (rax, rdi) = a[5] * a[0]
adcx %rax, %r11 // r11 = hi(a[4] * a[0]) + lo(a[5] * a[0])
adox %r15, %rdi
mulx 48(%rsi), %rax, %r8 // (rax, r8) = a[6] * a[0]
adcx %rax, %rdi // rdi = hi(a[5] * a[0]) + lo(a[6] * a[0])
adox %rcx, %r8
mulx 56(%rsi), %rax, %rbx // (rax, rbx) = a[7] * a[0]
adcx %rax, %r8 // r8 = hi(a[6] * a[0]) + lo(a[7] * a[0])
adox %r10, %rbx // rbx += CF
adcq 64(%rbp), %rbx // rbx += CF
sbbq %r9, %r9 // get high CF
xorq %r10, %r10 // clear CF OF
// begin a[1] * a[2~7]
movq 8(%rsi), %rdx // rdx = a[1]
mulx 16(%rsi), %rax, %rcx // rax = lo(a[2] * a[1]), rcx = hi(a[2] * a[1])
adcx %rax, %r13 // r13 = hi(a[2] * a[0]) + lo(a[3] * a[0]) + lo(a[2] * a[1])
mulx 24(%rsi), %rax, %r14 // rax = lo(a[3] * a[1]), r14 = hi(a[3] * a[1])
movq %r13, 24(%rbp)
adox %rax, %rcx // rcx = lo(a[3] * a[1]) + hi(a[2] * a[1])
mulx 32(%rsi), %rax, %r13 // (rax, r13) = a[4] * a[1]
adcx %r12, %rcx // rcx = hi(a[3] * a[0]) + lo(a[4] * a[0]) + lo(a[3] * a[1]) + hi(a[2] * a[1])
adox %rax, %r14 // r14 = lo(a[4] * a[1]) + hi(a[3] * a[1])
mulx 40(%rsi), %rax, %r12 // (rax, r12) = a[5] * a[1]
movq %rcx, 32(%rbp)
adcx %r11, %r14 // r14 = lo(a[4] * a[1]) + hi(a[3] * a[1]) + hi(a[4] * a[0]) + lo(a[5] * a[0])
adox %rax, %r13 // r13 = lo(a[5] * a[1]) + hi(a[4] * a[1])
mulx 48(%rsi), %rax, %r11 // (rax, r11) = a[6] * a[1]
adcx %rdi, %r13 // r13 = lo(a[5] * a[1]) + hi(a[4] * a[1]) + hi(a[5] * a[0]) + lo(a[6] * a[0])
adox %rax, %r12 // r12 = hi(a[5] * a[1]) + lo(a[6] * a[1])
mulx 56(%rsi), %rax, %rdi // (rax, rdi) = a[7] * a[1]
adcx %r8, %r12 // r12 = hi(a[5] * a[1]) + lo(a[6] * a[1]) + hi(a[6] * a[0]) + lo(a[7] * a[0])
adox %rax, %r11 // r11 = hi(a[6] * a[1]) + lo(a[7] * a[1])
adcx %rbx, %r11 // r11 = hi(a[6] * a[1]) + lo(a[7] * a[1]) + hi(a[7] * a[0])
adcx %r10, %rdi // rdi += CF
adox %r10, %rdi // rdi += OF
movq 16(%rsi), %rdx // rdx = a[2]
// begin a[2] * a[3~7]
mulx 24(%rsi), %rax, %rbx // rax = lo(a[2] * a[3]), rbx = hi(a[2] * a[3])
adcx %rax, %r14 // r14 = lo(a[4] * a[1]) + hi(a[3] * a[1]) + hi(a[4] * a[0]) + lo(a[5] * a[0])
// + lo(a[2] * a[3])
mulx 32(%rsi), %rax, %rcx // rax = lo(a[2] * a[4]), rcx = hi(a[2] * a[4])
movq %r14, 40(%rbp)
adox %rax, %rbx // r13 = lo(a[2] * a[4]) + hi(a[2] * a[3])
mulx 40(%rsi), %rax, %r8 // rax = lo(a[2] * a[5]), rcx = hi(a[2] * a[5])
adcx %r13, %rbx // rbx = lo(a[2] * a[4]) + hi(a[2] * a[3])
// + lo(a[5] * a[1]) + hi(a[4] * a[1]) + hi(a[5] * a[0]) + lo(a[6] * a[0])
adox %rax, %rcx // rcx = hi(a[2] * a[4]) + lo(a[2] * a[5])
movq %rbx, 48(%rbp)
mulx 48(%rsi), %rax, %r13 // rax = lo(a[2] * a[6]), r13 = hi(a[2] * a[6])
adcx %r12, %rcx // rcx = hi(a[5] * a[1]) + lo(a[6] * a[1]) + hi(a[6] * a[0])
// + lo(a[7] * a[0]) + hi(a[2] * a[4]) + lo(a[2] * a[5])
adox %rax, %r8 // r8 = hi(a[2] * a[5]) + lo(a[2] * a[6])
mulx 56(%rsi), %rax, %r12 // rax = lo(a[2] * a[7]), r12 = hi(a[2] * a[7])
adcx %r11, %r8 // r8 = hi(a[2] * a[5]) + lo(a[2] * a[6])
// + hi(a[6] * a[1]) + lo(a[7] * a[1]) + hi(a[7] * a[0])
adox %rax, %r13 // r13 = hi(a[2] * a[6]) + lo(a[2] * a[7])
adcx %rdi, %r13 // r13 = hi(a[2] * a[6]) + lo(a[2] * a[7]) + hi(a[7] * a[1])
adcx %r10, %r12 // r12 += CF
adox %r10, %r12 // r12 += OF
movq 24(%rsi), %rdx // rdx = a[3]
// begin a[3] * a[4~7]
mulx 32(%rsi), %rax, %r14 // rax = lo(a[3] * a[4]), r14 = hi(a[3] * a[4])
adcx %rax, %rcx // rcx = hi(a[5] * a[1]) + lo(a[6] * a[1]) + hi(a[6] * a[0])
// + lo(a[7] * a[0]) + hi(a[2] * a[4]) + lo(a[2] * a[5]) + lo(a[3] * a[4])
mulx 40(%rsi), %rax, %rbx // rax = lo(a[3] * a[5]), rbx = hi(a[3] * a[5])
adox %rax, %r14 // r14 = hi(a[3] * a[4]) + lo(a[3] * a[5])
mulx 48(%rsi), %rax, %r11 // rax = lo(a[3] * a[6]), r11 = hi(a[3] * a[6])
adcx %r8, %r14 // r14 = hi(a[3] * a[4]) + lo(a[3] * a[5])+ hi(a[2] * a[5]) + lo(a[2] * a[6])
// + hi(a[6] * a[1]) + lo(a[7] * a[1]) + hi(a[7] * a[0])
adox %rax, %rbx // rbx = hi(a[3] * a[5]) + lo(a[3] * a[6])
mulx 56(%rsi), %rax, %rdi // rax = lo(a[3] * a[7]), rdi = hi(a[3] * a[7])
adcx %r13, %rbx // rbx = hi(a[3] * a[5]) + lo(a[3] * a[6])
// + hi(a[2] * a[6]) + lo(a[2] * a[7]) + hi(a[7] * a[1])
adox %rax, %r11 // r11 = hi(a[3] * a[6]) + lo(a[3] * a[7])
adcx %r12, %r11 // r11 = hi(a[2] * a[7]) + hi(a[3] * a[6]) + lo(a[3] * a[7])
adcx %r10, %rdi // rdi += CF
adox %r10, %rdi // rdi += OF
movq %rcx, 56(%rbp)
movq %r14, 64(%rbp)
movq 32(%rsi), %rdx // rdx = a[4]
// begin a[4] * a[5~7]
mulx 40(%rsi), %rax, %r13 // rax = lo(a[4] * a[5]), r13 = hi(a[4] * a[5])
adcx %rax, %rbx // rbx = hi(a[3] * a[5]) + lo(a[3] * a[6])
// + hi(a[2] * a[6]) + lo(a[2] * a[7]) + hi(a[7] * a[1]) + lo(a[4] * a[5])
mulx 48(%rsi), %rax, %r12 // rax = lo(a[4] * a[6]), r12 = hi(a[4] * a[6])
adox %rax, %r13 // r13 = lo(a[4] * a[6]) + hi(a[4] * a[5])
mulx 56(%rsi), %rax, %r14 // rax = lo(a[4] * a[7]), r14 = hi(a[4] * a[7])
adcx %r11, %r13 // r13 = hi(a[4] * a[5]) + hi(a[2] * a[7]) + hi(a[3] * a[6])
// + lo(a[3] * a[7])
adox %rax, %r12 // r12 = hi(a[4] * a[6]) + lo(a[4] * a[7])
adcx %rdi, %r12 // r12 = hi(a[4] * a[6]) + lo(a[4] * a[7]) + hi(a[3] * a[7])
adcx %r10, %r14 // r14 += CF
adox %r10, %r14 // r14 += OF
movq 40(%rsi), %rdx // rdx = a[5]
// begin a[5] * a[6~7]
mulx 48(%rsi), %rax, %r11 // rax = lo(a[5] * a[6]), r11 = hi(a[5] * a[6])
adcx %rax, %r12 // r14 = hi(a[4] * a[6]) + lo(a[4] * a[7]) + hi(a[3] * a[7]) + lo(a[5] * a[6])
mulx 56(%rsi), %rax, %rdi // rax = lo(a[5] * a[7]), rdi = hi(a[5] * a[7])
adox %rax, %r11 // r11 = hi(a[5] * a[6]) + lo(a[5] * a[7])
adcx %r14, %r11 // r11 = hi(a[5] * a[6]) + lo(a[5] * a[7]) + hi(a[4] * a[7])
adcx %r10, %rdi // rdi += CF
adox %r10, %rdi // rdi += OF
movq 48(%rsi), %rdx // rdx = a[6]
mulx 56(%rsi), %rax, %r15 // rax = lo(a[7] * a[6]), r15 = hi(a[7] * a[6])
adcx %rax, %rdi // rdi = hi(a[5] * a[6]) + lo(a[7] * a[6])
adcx %r10, %r15 // r15 += CF
leaq 64(%rsi), %rsi
cmp 64(%rsp), %rsi // cmpared with a[size]
je .Lsqrx8xEnd
neg %r9
movq $0, %rcx
movq 64(%rbp),%r14
adcx 9*8(%rbp),%rbx
adcx 10*8(%rbp),%r13
adcx 11*8(%rbp),%r12
adcx 12*8(%rbp),%r11
adcx 13*8(%rbp),%rdi
adcx 14*8(%rbp),%r15
adcx 15*8(%rbp),%rcx
leaq (%rsi), %r10 // r10 = a[8]
leaq 128(%rbp), %rbp
sbbq %rax,%rax
movq %rax, 72(%rsp)
movq %rbp, 80(%rsp)
xor %eax, %eax
movq -64(%rsi), %rdx
movq $-8, %r9
.align 32
.LoopSqr8x:
movq %r14,%r8
// begin a[0] * a[8~11]
mulx 0(%r10), %rax, %r14 // rax = lo(a[8] * a[0]), r14 = hi(a[8] * a[0])
adcx %rax, %r8
adox %rbx, %r14
mulx 8(%r10), %rax, %rbx // rax = lo(a[9] * a[0]), rbx = hi(a[8] * a[0])
adcx %rax, %r14
adox %r13, %rbx
movq %r8,(%rbp,%r9,8)
mulx 16(%r10), %rax, %r13 // rax = lo(a[10] * a[0]), r13 = hi(a[10] * a[0])
adcx %rax, %rbx
adox %r12, %r13
mulx 24(%r10), %rax, %r12 // rax = lo(a[11] * a[0]), r12 = hi(a[11] * a[0])
adcx %rax, %r13
adox %r11, %r12
movq $0, %r8
mulx 32(%r10), %rax, %r11 // rax = lo(a[12] * a[0]), r11 = hi(a[12] * a[0])
adcx %rax, %r12
adox %rdi, %r11
mulx 40(%r10), %rax, %rdi // rax = lo(a[13] * a[0]), rdi = hi(a[13] * a[0])
adcx %rax, %r11
adox %r15, %rdi
mulx 48(%r10), %rax, %r15 // rax = lo(a[14] * a[0]), r15 = hi(a[14] * a[0])
adcx %rax, %rdi
adox %rcx, %r15
mulx 56(%r10), %rax, %rcx // rax = lo(a[15] * a[0]), rcx = hi(a[15] * a[0])
adcx %rax, %r15
adcx %r8, %rcx // here r8 = 0
adox %r8, %rcx
movq 8(%rsi,%r9,8),%rdx
inc %r9
jnz .LoopSqr8x
leaq 64(%r10), %r10
movq $-8, %r9
cmp 64(%rsp), %r10 // cmpared with a[size]
je .LoopSqr8xBreak
subq 72(%rsp), %r8 // read the CF of the previous round.
movq -64(%rsi), %rdx
adcx 0*8(%rbp),%r14
adcx 1*8(%rbp),%rbx
adcx 2*8(%rbp),%r13
adcx 3*8(%rbp),%r12
adcx 4*8(%rbp),%r11
adcx 5*8(%rbp),%rdi
adcx 6*8(%rbp),%r15
adcx 7*8(%rbp),%rcx
leaq 8*8(%rbp),%rbp
sbbq %rax, %rax
xorq %r8, %r8
movq %rax, 72(%rsp)
jmp .LoopSqr8x
.align 32
.LoopSqr8xBreak:
xorq %r10, %r10
subq 72(%rsp),%r8
adcx %r10, %r14
movq 0(%rsi),%rdx
movq %r14,0(%rbp)
movq 80(%rsp), %r8
adcx %r10,%rbx
adcx %r10,%r13
adcx %r10,%r12
adcx %r10,%r11
adcx %r10,%rdi
adcx %r10,%r15
adcx %r10,%rcx
cmp %r8, %rbp
je .LoopOuterSqr8x
// if tmp does not go to the end. The current value needs to be stored in tmp and updated.
movq %rbx,1*8(%rbp)
movq 1*8(%r8),%rbx
movq %r13,2*8(%rbp)
movq 2*8(%r8),%r13
movq %r12,3*8(%rbp)
movq 3*8(%r8),%r12
movq %r11,4*8(%rbp)
movq 4*8(%r8),%r11
movq %rdi,5*8(%rbp)
movq 5*8(%r8),%rdi
movq %r15,6*8(%rbp)
movq 6*8(%r8),%r15
movq %rcx,7*8(%rbp)
movq 7*8(%r8),%rcx
movq %r8,%rbp
jmp .LoopOuterSqr8x
.align 32
.Lsqrx8xEnd:
mov %rbx,9*8(%rbp)
mov %r13,10*8(%rbp)
mov %r12,11*8(%rbp)
mov %r11,12*8(%rbp)
mov %rdi,13*8(%rbp)
mov %r15,14*8(%rbp)
leaq 88(%rsp), %rbp // tmp[0]
movq 56(%rsp), %rcx // rcx = size * 8
sbbq %rcx, %rsi // get a[0]
xorq %r15, %r15 // clear CF OF, r15 = tmp[0] = 0
movq 8(%rbp), %r14 // r14 = tmp[1]
movq 16(%rbp), %r13 // r13 = tmp[2]
movq 24(%rbp), %r12 // r12 = tmp[3]
adox %r14, %r14 // r14 = 2 * tmp[1]
movq 0(%rsi), %rdx
.align 32
.LoopShiftAddSqr4x:
mulx %rdx, %rax, %rbx // (rbx, rax) = a[0] * a[0]
adox %r13, %r13 // r13 = 2 * tmp[1]
adox %r12, %r12 // r12 = 2 * tmp[3]
adcx %rax, %r15 // r15 = 2 * tmp[0] + lo(a[0] * a[0])
adcx %rbx, %r14 // r14 = 2 * tmp[1] + hi(a[0] * a[0])
movq %r15, (%rbp)
movq %r14, 8(%rbp)
movq 8(%rsi), %rdx
mulx %rdx, %rax, %rbx // (rbx, rax) = a[1] * a[1]
adcx %rax, %r13 // r13 = 2 * tmp[2] + lo(a[1] * a[1])
adcx %rbx, %r12 // r12 = 2 * tmp[3] + hi(a[1] * a[1])
movq %r13, 16(%rbp)
movq %r12, 24(%rbp)
movq 32(%rbp), %r15 // r15 = tmp[4]
movq 40(%rbp), %r14 // r14 = tmp[5]
movq 48(%rbp), %r13 // r13 = tmp[6]
movq 56(%rbp), %r12 // r12 = tmp[7]
movq 16(%rsi), %rdx
mulx %rdx, %rax, %rbx // (rbx, rax) = a[2] * a[2]
adox %r15, %r15 // r15 = 2 * tmp[4]
adcx %rax, %r15 // r15 = 2 * tmp[4] + lo(a[2] * a[2])
adox %r14, %r14 // r14 = 2 * tmp[4]
adcx %rbx, %r14 // r14 = 2 * tmp[5] + hi(a[2] * a[2])
movq %r15, 32(%rbp)
movq %r14, 40(%rbp)
movq 24(%rsi), %rdx
mulx %rdx, %rax, %rbx // (rbx, rax) = a[3] * a[3]
adox %r13, %r13 // r13 = 2 * tmp[5]
adcx %rax, %r13 // r13 = 2 * tmp[5] + lo(a[3] * a[3])
adox %r12, %r12 // r12 = 2 * tmp[5]
adcx %rbx, %r12 // rbx = 2 * tmp[5] + hi(a[3] * a[3])
movq %r13, 48(%rbp)
movq %r12, 56(%rbp)
leaq 32(%rsi), %rsi // a[4]
leaq -32(%rcx),%rcx
jrcxz .LoopReduceSqr8xBegin // if i != 0
movq 64(%rbp), %r15 // r15 = tmp[8]
movq 72(%rbp), %r14 // r14 = tmp[9]
adox %r15, %r15 // r15 = 2 * tmp[8]
adox %r14, %r14 // r14 = 2 * tmp[9]
movq 80(%rbp), %r13 // r13 = tmp[8]
movq 88(%rbp), %r12 // r12 = tmp[9]
leaq 64(%rbp), %rbp
movq 0(%rsi), %rdx
jmp .LoopShiftAddSqr4x // if i != 0
.LoopReduceSqr8xBegin:
xorq %rax,%rax // rax = 0
leaq 88(%rsp), %rdi // tmp[0]
movq $0, %r9 // Save size.
movq %xmm1, %rbp // get n[0]
xorq %rsi, %rsi // rsi = 0
.align 32
.LoopReduceSqr8x:
movq %rax,80(%rsp) // Store the highest carry bit.
leaq (%rdi,%r9),%rdi // rdi = t[0]
movq (%rdi),%rdx // rdx = t[0]
movq 8(%rdi),%r9 // r9 = t[1]
movq 16(%rdi),%r15 // r15 = t[2]
movq 24(%rdi),%r14 // r14 = t[3]
movq 32(%rdi),%r13 // r13 = t[4]
movq 40(%rdi),%r12 // r12 = t[5]
movq 48(%rdi),%r11 // r11 = t[6]
movq 56(%rdi),%r10 // r10 = t[7]
leaq 64(%rdi),%rdi // rdi = t[8]
movq %rdx,%r8 // r8 = t[0]
imulq 40(%rsp),%rdx // rbx = k0 * t[0]
xorq %rbx,%rbx // clear CF OF
movl $8,%ecx
.align 32
.LoopReduce8x:
movq %r8, %rbx
movq %rdx, 80(%rsp,%rcx,8)
mulx (%rbp), %rax, %r8 // (r8, rax) = m' * n[0]
adcx %rbx, %rax
adox %r9, %r8 // r9 = hi(m' * n[]) + t[1]
mulx 8(%rbp), %rax, %r9 // (rdx, r9) = m' * n[0]
adcx %rax,%r8 // r9 = t[1] + lo(m' * n[1])
adox %r9, %r15 // r15 = hi(m' * n[1]) + t[2]
mulx 16(%rbp), %r9, %rax // (r9, rax) = m' * n[2]
adcx %r15, %r9 // r9 = hi(m' * n[1]) + lo(m' * n[2]) + t[2]
adox %rax, %r14 // rbx = hi(m' * n[2]) + t[3]
mulx 24(%rbp), %r15, %rax // (r15, rax) = m' * n[3]
adcx %r14,%r15 // r15 = hi(m' * n[2]) + lo(m' * n[3]) + t[3]
adox %rax,%r13 // r13 = hi(m' * n[3]) + t[4]
mulx 32(%rbp), %r14, %rax // (r14, rax) = m' * n[4]
adcx %r13,%r14 // r14 = hi(m' * n[3]) + lo(m' * n[4]) + t[4]
adox %rax,%r12 // r12 = hi(m' * n[4]) + t[5]
mulx 40(%rbp), %r13, %rax // (r13, rax) = m' * n[5]
adcx %r12,%r13 // r13 = hi(m' * n[4]) + lo(m' * n[5]) + t[5]
adox %rax,%r11 // r12 = hi(m' * n[5]) + t[6]
mulx 48(%rbp), %r12, %rax // (r12, rax) = m' * n[6]
adcx %r11,%r12 // r13 = hi(m' * n[5]) + lo(m' * n[6]) + t[6]
adox %r10,%rax // r12 = hi(m' * n[5]) + t[7]
mulx 56(%rbp), %r11, %r10 // (r11, r10) = m' * n[7]
adcx %rax,%r11 // r13 = hi(m' * n[6]) + lo(m' * n[7]) + t[7]
adcx %rsi,%r10 // r12 = hi(m' * n[7]) + t[8]
adox %rsi,%r10 // r12 = hi(m' * n[7]) + t[8]
movq %r8, %rdx
mulx 40(%rsp), %rdx, %rax // (rdx, rax) = m' * n[7]
decl %ecx // ecx--
jnz .LoopReduce8x // if ecx != 0
leaq 64(%rbp),%rbp // rbp += 64, n Pointer Offset.
xorq %rax,%rax // rax = 0
cmpq 8(%rsp),%rbp // rbp = n[size]
jae .LoopEndCondMul8x
addq (%rdi),%r8 // r8 += t[0]
adcq 8(%rdi),%r9 // r9 += t[1]
adcq 16(%rdi),%r15 // r15 += t[2]
adcq 24(%rdi),%r14 // r14 += t[3]
adcq 32(%rdi),%r13 // r13 += t[4]
adcq 40(%rdi),%r12 // r12 += t[5]
adcq 48(%rdi),%r11 // r11 += t[6]
adcq 56(%rdi),%r10 // r10 += t[7]
sbbq %rsi,%rsi // rsi = -CF
movq 144(%rsp),%rdx // rbx = m', 80 + 64
movl $8,%ecx
xor %eax,%eax
.align 32
.LoopLastSqr8x:
mulx (%rbp), %rax, %rbx // (rbx, rax) = m' * n[0]
adcx %rax,%r8 // r8 = lo(m' * n[0]) + t[0]
movq %r8,(%rdi) // t[0] = r8
leaq 8(%rdi),%rdi // t++
adox %rbx,%r9 // r9 = hi(m' * n[]) + t[2]
mulx 8(%rbp), %r8, %rbx // (r8, rbx) = m' * n[0]
adcx %r9,%r8 // r9 = t[1] + lo(m' * n[1])
adox %rbx, %r15 // r15 = hi(m' * n[1]) + t[2]
mulx 16(%rbp), %r9, %rbx // (r9, rbx) = m' * n[2]
adcx %r15, %r9 // r9 = hi(m' * n[1]) + lo(m' * n[2]) + t[2]
adox %rbx, %r14 // r14 = hi(m' * n[2]) + t[3]
mulx 24(%rbp), %r15, %rbx // (r15, rbx) = m' * n[3]
adcx %r14,%r15 // r15 = hi(m' * n[2]) + lo(m' * n[3]) + t[3]
adox %rbx,%r13 // r13 = hi(m' * n[3]) + t[4]
mulx 32(%rbp), %r14, %rbx // (r14, rbx) = m' * n[4]
adcx %r13,%r14 // r14 = hi(m' * n[3]) + lo(m' * n[4]) + t[4]
adox %rbx,%r12 // r12 = hi(m' * n[4]) + t[5]
mulx 40(%rbp), %r13, %rbx // (r13, rbx) = m' * n[5]
adcx %r12,%r13 // r13 = hi(m' * n[4]) + lo(m' * n[5]) + t[5]
adox %rbx,%r11 // r11 = hi(m' * n[5]) + t[6]
mulx 48(%rbp), %r12, %rbx // (r12, rbx) = m' * n[6]
adcx %r11,%r12 // r12 = hi(m' * n[5]) + lo(m' * n[6]) + t[6]
adox %r10,%rbx // rbx = hi(m' * n[5]) + t[7]
movq $0, %rax
mulx 56(%rbp), %r11, %r10 // (r11, r10) = m' * n[7]
adcx %rbx,%r11 // r11 = hi(m' * n[6]) + lo(m' * n[7]) + t[7]
adcx %rax,%r10 // r10 = hi(m' * n[7]) + t[8]
adox %rax,%r10 // r10 = hi(m' * n[7]) + t[8]
movq 72(%rsp,%rcx,8),%rdx // rbx = t[i] * k0
decl %ecx // ecx--
jnz .LoopLastSqr8x // if ecx != 0
leaq 64(%rbp),%rbp // n += 8
cmpq 8(%rsp),%rbp // Check whether rbp is at the end of the n array. If yes, exit the loop.
jae .LoopSqrBreak8x
movq 144(%rsp),%rdx // rbx = m'
negq %rsi // rsi = CF
movq (%rbp),%rax // rax = = n[0]
adcq (%rdi),%r8 // r8 = t[0]
adcq 8(%rdi),%r9 // r9 = t[1]
adcq 16(%rdi),%r15 // r15 = t[2]
adcq 24(%rdi),%r14 // r14 = t[3]
adcq 32(%rdi),%r13 // r13 = t[4]
adcq 40(%rdi),%r12 // r12 = t[5]
adcq 48(%rdi),%r11 // r11 = t[6]
adcq 56(%rdi),%r10 // r10 = t[7]
sbbq %rsi,%rsi // rsi = -CF
movl $8,%ecx // ecx = 8
xorq %rax, %rax
jmp .LoopLastSqr8x
.align 32
.LoopSqrBreak8x:
xorq %rax,%rax // rax = 0
addq 80(%rsp),%r8 // r8 += Highest carry bit.
adcq $0,%r9 // r9 += CF
adcq $0,%r15 // r15 += CF
adcq $0,%r14 // r14 += CF
adcq $0,%r13 // r13 += CF
adcq $0,%r12 // r12 += CF
adcq $0,%r11 // r11 += CF
adcq $0,%r10 // r10 += CF
adcq $0,%rax // rax += CF
negq %rsi // rsi = CF
.LoopEndCondMul8x:
adcq (%rdi),%r8 // r8 += t[0]
adcq 8(%rdi),%r9 // r9 += t[1]
adcq 16(%rdi),%r15 // r15 += t[2]
adcq 24(%rdi),%r14 // r14 += t[3]
adcq 32(%rdi),%r13 // r13 += t[4]
adcq 40(%rdi),%r12 // r12 += t[5]
adcq 48(%rdi),%r11 // r11 += t[6]
adcq 56(%rdi),%r10 // r10 += t[7]
adcq $0,%rax // rax += CF
movq -8(%rbp),%rcx // rcx = n[7]
xorq %rsi,%rsi // rsi = 0
movq %xmm1,%rbp // rbp = n
movq %r8,(%rdi) // Save the calculated result back to t[].
movq %r9,8(%rdi)
movq %xmm5,%r9
movq %r15,16(%rdi)
movq %r14,24(%rdi)
movq %r13,32(%rdi)
movq %r12,40(%rdi)
movq %r11,48(%rdi)
movq %r10,56(%rdi)
leaq 64(%rdi),%rdi // t += 8
cmpq 16(%rsp),%rdi // Cycle the entire t[].
jb .LoopReduceSqr8x
ret
.cfi_endproc
.size MontSqr8Inner,.-MontSqr8Inner
#endif
|
2301_79861745/bench_create
|
crypto/bn/src/asm/bn_montx_x86_64.S
|
Unix Assembly
|
unknown
| 53,538
|
/*
* 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_BN
#include <stdint.h>
#include "crypt_errno.h"
#include "bn_bincal.h"
#include "bn_asm.h"
#if defined(HITLS_CRYPTO_BN_X8664) && defined(__x86_64__)
#include "crypt_utils.h"
#endif
int32_t MontSqrBin(BN_UINT *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime)
{
if (mont->mSize > 1) {
#if defined(HITLS_CRYPTO_BN_X8664) && defined(__x86_64__)
if (IsSupportBMI2() && IsSupportADX()) {
MontMulx_Asm(r, r, r, mont->mod, mont->k0, mont->mSize);
return CRYPT_SUCCESS;
}
#endif
MontMul_Asm(r, r, r, mont->mod, mont->k0, mont->mSize);
return CRYPT_SUCCESS;
}
return MontSqrBinCore(r, mont, opt, consttime);
}
int32_t MontMulBin(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, BN_Mont *mont,
BN_Optimizer *opt, bool consttime)
{
if (mont->mSize > 1) {
#if defined(HITLS_CRYPTO_BN_X8664) && defined(__x86_64__)
if (IsSupportBMI2() && IsSupportADX()) {
MontMulx_Asm(r, a, b, mont->mod, mont->k0, mont->mSize);
return CRYPT_SUCCESS;
}
#endif
MontMul_Asm(r, a, b, mont->mod, mont->k0, mont->mSize);
return CRYPT_SUCCESS;
}
return MontMulBinCore(r, a, b, mont, opt, consttime);
}
int32_t MontEncBin(BN_UINT *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime)
{
if (mont->mSize > 1) {
#if defined(HITLS_CRYPTO_BN_X8664) && defined(__x86_64__)
if (IsSupportBMI2() && IsSupportADX()) {
MontMulx_Asm(r, r, mont->montRR, mont->mod, mont->k0, mont->mSize);
return CRYPT_SUCCESS;
}
#endif
MontMul_Asm(r, r, mont->montRR, mont->mod, mont->k0, mont->mSize);
return CRYPT_SUCCESS;
}
return MontEncBinCore(r, mont, opt, consttime);
}
void Reduce(BN_UINT *r, BN_UINT *x, const BN_UINT *one, const BN_UINT *m, uint32_t mSize, BN_UINT m0)
{
if (mSize <= 1) {
ReduceCore(r, x, m, mSize, m0);
return;
}
#if defined(HITLS_CRYPTO_BN_X8664) && defined(__x86_64__)
if (IsSupportBMI2() && IsSupportADX()) {
MontMulx_Asm(r, x, one, m, m0, mSize);
return;
}
#endif
MontMul_Asm(r, x, one, m, m0, mSize);
return;
}
#endif /* HITLS_CRYPTO_BN */
|
2301_79861745/bench_create
|
crypto/bn/src/asm_bn_mont.c
|
C
|
unknown
| 2,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.
*/
#ifndef BN_ASM_H
#define BN_ASM_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_BN
#include <stdint.h>
#include <stdlib.h>
#include "crypt_bn.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* Function description: r = reduce(a * b) mod n
* Function prototype: void MontMul_Asm(uint64_t *r, const uint64_t *a, const uint64_t *b,
* const uint64_t *n, const uint64_t k0, uint32_t size);
* Input register:
* x0: result array pointer r
* x1: source data array pointer a
* x2: source data array pointer b
* x3: source data array pointer n
* x4: k0 in the mont structure
* x5: The size of the first four arrays is 'size'.
* Modify registers: x0-x17, x19-x24
* Output register: None
* Function/Macro Call: bn_mont_sqr8x, bn_mont_mul4x
* Remarks: The four arrays must have the same length.
* If these are different, expand the length to the length of the longest array.
* In addition, the expanded part needs to be cleared to 0.
*/
void MontMul_Asm(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, const BN_UINT *n, const BN_UINT k0, size_t size);
#if defined(HITLS_CRYPTO_BN_X8664)
void MontMulx_Asm(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, const BN_UINT *n, const BN_UINT k0, size_t size);
#endif
#ifdef __cplusplus
}
#endif
#endif /* HITLS_CRYPTO_BN */
#endif
|
2301_79861745/bench_create
|
crypto/bn/src/bn_asm.h
|
C
|
unknown
| 1,978
|
/*
* 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_BN
#include "securec.h"
#include "bsl_sal.h"
#include "bsl_err_internal.h"
#include "crypt_errno.h"
#include "bn_bincal.h"
#include "bn_basic.h"
BN_BigNum *BN_Create(uint32_t bits)
{
if (bits > BN_MAX_BITS) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_BITS_INVALID);
return NULL;
}
uint32_t room = BITS_TO_BN_UNIT(bits);
BN_BigNum *r = (BN_BigNum *)BSL_SAL_Calloc(1u, sizeof(BN_BigNum));
if (r == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
if (room != 0) {
r->room = room;
r->data = (BN_UINT *)BSL_SAL_Calloc(1u, room * sizeof(BN_UINT));
if (r->data == NULL) {
BSL_SAL_FREE(r);
return NULL;
}
}
return r;
}
void BN_Destroy(BN_BigNum *a)
{
if (a == NULL) {
return;
}
// clear sensitive information
BSL_SAL_CleanseData((void *)(a->data), a->size * sizeof(BN_UINT));
if (a->flag == CRYPT_BN_FLAG_STATIC) {
return;
}
BSL_SAL_FREE(a->data);
if (!BN_IsFlag(a, CRYPT_BN_FLAG_OPTIMIZER)) {
BSL_SAL_FREE(a);
}
}
inline void BN_Init(BN_BigNum *bn, BN_UINT *data, uint32_t room, int32_t number)
{
for (uint32_t i = 0; i < (uint32_t)number; i++) {
bn[i].data = &data[room * i];
bn[i].room = room;
bn[i].flag = CRYPT_BN_FLAG_STATIC;
}
}
#ifdef HITLS_CRYPTO_EAL_BN
bool BnVaild(const BN_BigNum *a)
{
if (a == NULL) {
return false;
}
if (a->size == 0) {
return !a->sign;
}
if (a->data == NULL || a->size > a->room) {
return false;
}
if ((a->size <= a->room) && (a->data[a->size - 1] != 0)) {
return true;
}
return false;
}
#endif
#ifdef HITLS_CRYPTO_BN_CB
BN_CbCtx *BN_CbCtxCreate(void)
{
BN_CbCtx *r = (BN_CbCtx *)BSL_SAL_Calloc(1u, sizeof(BN_CbCtx));
if (r == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
return r;
}
void BN_CbCtxSet(BN_CbCtx *gencb, BN_CallBack callBack, void *arg)
{
if (gencb == NULL) {
return;
}
BN_CbCtx *tmpCb = gencb;
tmpCb->arg = arg;
tmpCb->cb = callBack;
}
void *BN_CbCtxGetArg(BN_CbCtx *callBack)
{
if (callBack == NULL) {
return NULL;
}
return callBack->arg;
}
int32_t BN_CbCtxCall(BN_CbCtx *callBack, int32_t process, int32_t target)
{
if (callBack == NULL || callBack->cb == NULL) {
return CRYPT_SUCCESS;
}
int32_t ret = callBack->cb(callBack, process, target);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
void BN_CbCtxDestroy(BN_CbCtx *cb)
{
if (cb == NULL) {
return;
}
BSL_SAL_FREE(cb);
}
#endif
int32_t BN_SetSign(BN_BigNum *a, bool sign)
{
if (a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
/* 0 must be a positive number symbol */
if (BN_IsZero(a) == true && sign == true) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_NO_NEGATIVE_ZERO);
return CRYPT_BN_NO_NEGATIVE_ZERO;
}
a->sign = sign;
return CRYPT_SUCCESS;
}
static bool IsLegalFlag(uint32_t flag)
{
switch (flag) {
case CRYPT_BN_FLAG_CONSTTIME:
case CRYPT_BN_FLAG_OPTIMIZER:
case CRYPT_BN_FLAG_STATIC:
return true;
default:
return false;
}
}
int32_t BN_SetFlag(BN_BigNum *a, uint32_t flag)
{
if (a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (!IsLegalFlag(flag)) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_FLAG_INVALID);
return CRYPT_BN_FLAG_INVALID;
}
a->flag |= flag;
return CRYPT_SUCCESS;
}
int32_t BN_Copy(BN_BigNum *r, const BN_BigNum *a)
{
if (r == NULL || a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (r != a) {
int32_t ret = BnExtend(r, a->size);
if (ret != CRYPT_SUCCESS) {
return ret;
}
r->sign = a->sign;
BN_COPY_BYTES(r->data, r->size, a->data, a->size);
r->size = a->size;
}
return CRYPT_SUCCESS;
}
BN_BigNum *BN_Dup(const BN_BigNum *a)
{
if (a == NULL) {
return NULL;
}
BN_BigNum *r = BN_Create(a->room * BN_UINT_BITS);
if (r != NULL) {
r->sign = a->sign;
(void)memcpy_s(r->data, a->size * sizeof(BN_UINT), a->data, a->size * sizeof(BN_UINT));
r->size = a->size;
}
return r;
}
bool BN_IsZero(const BN_BigNum *a)
{
if (a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return true;
}
return (a->size == 0);
}
bool BN_IsOne(const BN_BigNum *a)
{
if (a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return false;
}
return (a->size == 1 && a->data[0] == 1 && a->sign == false);
}
bool BN_IsNegative(const BN_BigNum *a)
{
if (a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return false;
}
return a->sign;
}
bool BN_IsOdd(const BN_BigNum *a)
{
if (a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return false;
}
return (a->size > 0) && (a->data[0] & 1) != 0;
}
bool BN_IsFlag(const BN_BigNum *a, uint32_t flag)
{
if (a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return false;
}
return a->flag & flag;
}
int32_t BN_Zeroize(BN_BigNum *a)
{
if (a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
// clear sensitive information
BSL_SAL_CleanseData(a->data, a->size * sizeof(BN_UINT));
a->sign = false;
a->size = 0;
return CRYPT_SUCCESS;
}
bool BN_IsLimb(const BN_BigNum *a, const BN_UINT w)
{
if (a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return (w == 0);
}
return !a->sign && (((a->size == 1) && (a->data[0] == w)) || ((w == 0) && (a->size == 0)));
}
int32_t BN_SetLimb(BN_BigNum *r, BN_UINT w)
{
if (r == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret = BnExtend(r, 1);
if (ret != CRYPT_SUCCESS) {
return ret;
}
BN_Zeroize(r);
if (w != 0) {
r->data[r->size] = w;
r->size++;
}
return CRYPT_SUCCESS;
}
BN_UINT BN_GetLimb(const BN_BigNum *a)
{
if (a == NULL) {
return 0;
}
if (a->size > 1) {
return BN_MASK;
} else if (a->size == 1) {
return a->data[0];
}
return 0;
}
bool BN_GetBit(const BN_BigNum *a, uint32_t n)
{
if (a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return false;
}
uint32_t nw = n / BN_UINT_BITS;
uint32_t nb = n % BN_UINT_BITS;
if (nw >= a->size) {
return false;
}
return (uint32_t)(((a->data[nw]) >> nb) & ((BN_UINT)1));
}
int32_t BN_SetBit(BN_BigNum *a, uint32_t n)
{
if (a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
uint32_t nw = n / BN_UINT_BITS;
uint32_t nb = n % BN_UINT_BITS;
if (nw >= a->room) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_SPACE_NOT_ENOUGH);
return CRYPT_BN_SPACE_NOT_ENOUGH;
}
a->data[nw] |= (((BN_UINT)1) << nb);
if (a->size < nw + 1) {
a->size = nw + 1;
}
return CRYPT_SUCCESS;
}
int32_t BN_ClrBit(BN_BigNum *a, uint32_t n)
{
if (a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
uint32_t nw = n / BN_UINT_BITS;
uint32_t nb = n % BN_UINT_BITS;
if (nw >= a->size) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_SPACE_NOT_ENOUGH);
return CRYPT_BN_SPACE_NOT_ENOUGH;
}
a->data[nw] &= (~(((BN_UINT)1) << nb));
// check whether the size changes
a->size = BinFixSize(a->data, a->size);
if (a->size == 0) {
a->sign = false;
}
return CRYPT_SUCCESS;
}
int32_t BN_MaskBit(BN_BigNum *a, uint32_t n)
{
if (a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
uint32_t nw = n / BN_UINT_BITS;
uint32_t nb = n % BN_UINT_BITS;
if (a->size <= nw) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_SPACE_NOT_ENOUGH);
return CRYPT_BN_SPACE_NOT_ENOUGH;
}
if (nb == 0) {
a->size = nw;
} else {
a->size = nw + 1;
a->data[nw] &= ~(BN_MASK << nb);
}
a->size = BinFixSize(a->data, a->size);
if (a->size == 0) {
a->sign = false;
}
return CRYPT_SUCCESS;
}
uint32_t BN_Bits(const BN_BigNum *a)
{
if (a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return 0;
}
return BinBits(a->data, a->size);
}
uint32_t BN_Bytes(const BN_BigNum *a)
{
return BN_BITS_TO_BYTES(BN_Bits(a));
}
int32_t BnExtend(BN_BigNum *a, uint32_t words)
{
if (a->room >= words) {
return CRYPT_SUCCESS;
}
if (a->flag == CRYPT_BN_FLAG_STATIC) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_NOT_SUPPORT_EXTENSION);
return CRYPT_BN_NOT_SUPPORT_EXTENSION;
}
if (words > BITS_TO_BN_UNIT(BN_MAX_BITS)) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_BITS_TOO_MAX);
return CRYPT_BN_BITS_TOO_MAX;
}
BN_UINT *tmp = (BN_UINT *)BSL_SAL_Calloc(1u, words * sizeof(BN_UINT));
if (tmp == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
if (a->size > 0) {
(void)memcpy_s(tmp, a->size * sizeof(BN_UINT), a->data, a->size * sizeof(BN_UINT));
BSL_SAL_CleanseData(a->data, a->size * sizeof(BN_UINT));
}
BSL_SAL_FREE(a->data);
a->data = tmp;
a->room = words;
return CRYPT_SUCCESS;
}
// ref. NIST.SP.800-57 Section 5.6.1.1
int32_t BN_SecBits(int32_t pubLen, int32_t prvLen)
{
int32_t bits = 256; // the secure length is initialized to a maximum of 256
int32_t level[] = {1024, 2048, 3072, 7680, 15360, INT32_MAX};
int32_t secbits[] = {0, 80, 112, 128, 192, 256};
for (int32_t loc = 0; loc < (int32_t)(sizeof(level) / sizeof(level[0])); loc++) {
if (pubLen < level[loc]) {
bits = secbits[loc];
break;
}
}
if (prvLen == -1) { // In IFC algorithm, the security length only needs to consider the modulus number.
return bits;
}
bits = ((prvLen / 2) >= bits) ? bits : (prvLen / 2); // The security length of FFC algorithm is considering prvLen/2
// Encryption does not use the algorithm/key combination which security strength is less than 112 bits
// such as less than 80 bits
return (bits < 80) ? 0 : bits;
}
#endif /* HITLS_CRYPTO_BN */
|
2301_79861745/bench_create
|
crypto/bn/src/bn_basic.c
|
C
|
unknown
| 11,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 BN_BASIC_H
#define BN_BASIC_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_BN
#include "crypt_bn.h"
#ifdef __cplusplus
extern "C" {
#endif
struct BnMont {
uint32_t mSize; /* *< size of mod in BN_UINT */
BN_UINT k0; /* *< low word of (1/(r - mod[0])) mod r */
BN_UINT *mod; /* *< mod */
BN_UINT *one; /* *< store one */
BN_UINT *montRR; /* *< mont_enc(1) */
BN_UINT *b; /* *< tmpb(1) */
BN_UINT *t; /* *< tmpt(1) ^ 2 */
};
struct BnCbCtx {
void *arg; // callback parameter
BN_CallBack cb; // callback function, which is defined by the user
};
/* Find a pointer address aligned by 'alignment' bytes in the [ptr, ptr + alignment - 1] range.
The input parameter alignment cannot be 0. */
static inline BN_UINT *AlignedPointer(const void *ptr, uintptr_t alignment)
{
uint8_t *p = (uint8_t *)(uintptr_t)ptr + alignment - 1;
return (BN_UINT *)((uintptr_t)p - (uintptr_t)p % alignment);
}
int32_t BnExtend(BN_BigNum *a, uint32_t words);
#ifdef __cplusplus
}
#endif
#endif /* HITLS_CRYPTO_BN */
#endif
|
2301_79861745/bench_create
|
crypto/bn/src/bn_basic.h
|
C
|
unknown
| 1,642
|
/*
* 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_BN
#include <stdint.h>
#include "securec.h"
#include "bn_bincal.h"
/* r = a + w, the length of r and a array is 'size'. The return value is the carry. */
BN_UINT BinInc(BN_UINT *r, const BN_UINT *a, uint32_t size, BN_UINT w)
{
uint32_t i;
BN_UINT carry = w;
for (i = 0; i < size && carry != 0; i++) {
ADD_AB(carry, r[i], a[i], carry);
}
if (r != a) {
for (; i < size; i++) {
r[i] = a[i];
}
}
return carry;
}
/* r = a - w, the length of r and a array is 'size'. The return value is the borrow-digit. */
BN_UINT BinDec(BN_UINT *r, const BN_UINT *a, uint32_t n, BN_UINT w)
{
uint32_t i;
BN_UINT borrow = w;
for (i = 0; (i < n) && (borrow > 0); i++) {
SUB_AB(borrow, r[i], a[i], borrow);
}
if (r != a) {
for (; i < n; i++) {
r[i] = a[i];
}
}
return borrow;
}
/* r = a >> bits, the return value is the valid length of r after the shift.
* The array length of a is n. The length of the r array must meet the requirements of the accepted calculation result,
* which is guaranteed by the input parameter.
*/
uint32_t BinRshift(BN_UINT *r, const BN_UINT *a, uint32_t n, uint32_t bits)
{
uint32_t nw = bits / BN_UINT_BITS; /* shift words */
uint32_t nb = bits % BN_UINT_BITS; /* shift bits */
/**
* unsigned shift operand cannot be greater than or equal to the data bit width
* Otherwise, undefined behavior is triggered.
*/
uint32_t na = (BN_UINT_BITS - nb) % BN_UINT_BITS;
uint32_t rsize = n - nw;
uint32_t i;
BN_UINT hi;
BN_UINT lo = a[nw];
/* When nb == 0, discard the value of (hi << na) with the all-zero mask. */
BN_UINT mask = ~BN_IsZeroUintConsttime(nb);
/* Assigns values from the lower bits. */
for (i = nw; i < n - 1; i++) {
hi = a[i + 1];
r[i - nw] = (lo >> nb) | ((hi << na) & mask);
lo = hi;
}
lo >>= nb;
if (lo != 0) {
r[rsize - 1] = lo;
} else {
rsize--;
}
return rsize;
}
/* r = a << bits. The return value is the valid length of r after the shift.
* The array length of a is n. The length of the r array must meet the requirements of the accepted calculation result,
* which is guaranteed by the input parameter.
*/
uint32_t BinLshift(BN_UINT *r, const BN_UINT *a, uint32_t n, uint32_t bits)
{
uint32_t nw = bits / BN_UINT_BITS; /* shift words */
uint32_t nb = bits % BN_UINT_BITS; /* shift bits */
/**
* unsigned shift operand cannot be greater than or equal to the data bit width
* Otherwise, undefined behavior is triggered.
*/
uint32_t na = (BN_UINT_BITS - nb) % BN_UINT_BITS;
uint32_t rsize = n + nw;
uint32_t i;
BN_UINT hi = a[n - 1];
BN_UINT lo;
/* When nb == 0, discard the value of (hi << na) with the all-zero mask. */
BN_UINT mask = ~BN_IsZeroUintConsttime(nb);
lo = (hi >> na) & mask;
/* Assign a value to the most significant bit. */
if (lo != 0) {
r[rsize++] = lo;
}
/* Assign a value from the most significant bits. */
for (i = n - 1; i > 0; i--) {
lo = a[i - 1];
r[i + nw] = (hi << nb) | ((lo >> na) & mask);
hi = lo;
}
r[nw] = a[0] << nb;
/* Clear the lower bits to 0. */
if (nw != 0) {
(void)memset_s(r, nw * sizeof(BN_UINT), 0, nw * sizeof(BN_UINT));
}
return rsize;
}
/* r = a * b + r. The return value is a carry. */
BN_UINT BinMulAcc(BN_UINT *r, const BN_UINT *a, uint32_t aSize, BN_UINT b)
{
BN_UINT c = 0;
BN_UINT *rr = r;
const BN_UINT *aa = a;
uint32_t size = aSize;
#ifndef HITLS_CRYPTO_BN_SMALL_MEM
while (size >= 4) { /* a group of 4 */
MULADD_ABC(c, rr[0], aa[0], b); /* offset 0 */
MULADD_ABC(c, rr[1], aa[1], b); /* offset 1 */
MULADD_ABC(c, rr[2], aa[2], b); /* offset 2 */
MULADD_ABC(c, rr[3], aa[3], b); /* offset 3 */
aa += 4; /* a group of 4 */
rr += 4; /* a group of 4 */
size -= 4; /* a group of 4 */
}
#endif
while (size > 0) {
MULADD_ABC(c, rr[0], aa[0], b);
aa++;
rr++;
size--;
}
return c;
}
/* r = a * b rRoom >= aSize + bSize. The length is guaranteed by the input parameter. r != a, r != b.
* The return value is the valid length of the result. */
uint32_t BinMul(BN_UINT *r, uint32_t rRoom, const BN_UINT *a, uint32_t aSize, const BN_UINT *b, uint32_t bSize)
{
BN_UINT carry = 0;
(void)memset_s(r, rRoom * sizeof(BN_UINT), 0, rRoom * sizeof(BN_UINT));
/* Result combination of cyclic calculation data units. */
for (uint32_t i = 0; i < bSize; i++) {
carry = 0;
uint32_t j = 0;
BN_UINT t = b[i];
for (; j < aSize; j++) {
MULADC_AB(r[i + j], a[j], t, carry);
}
if (carry != 0) {
r[i + j] = carry;
}
}
return aSize + bSize - (carry == 0);
}
/* r = a * a rRoom >= aSize * 2. The length is guaranteed by the input parameter. r != a.
* The return value is the valid length of the result. */
uint32_t BinSqr(BN_UINT *r, uint32_t rRoom, const BN_UINT *a, uint32_t aSize)
{
uint32_t i;
BN_UINT carry;
(void)memset_s(r, rRoom * sizeof(BN_UINT), 0, rRoom * sizeof(BN_UINT));
/* Calculate unequal data units, similar to trapezoid. */
for (i = 0; i < aSize - 1; i++) {
BN_UINT t = a[i];
uint32_t j;
for (j = i + 1, carry = 0; j < aSize; j++) {
MULADC_AB(r[i + j], a[j], t, carry);
}
r[i + j] = carry;
}
/* In the square, the multiplier unit is symmetrical. r = r * 2 */
BinLshift(r, r, 2 * aSize - 1, 1);
/* Calculate the direct squared data unit and add it to the result. */
for (i = 0, carry = 0; i < aSize; i++) {
BN_UINT rh, rl;
SQR_A(rh, rl, a[i]);
ADD_ABC(carry, r[i << 1], r[i << 1], rl, carry);
ADD_ABC(carry, r[(i << 1) + 1], r[(i << 1) + 1], rh, carry);
}
return aSize + aSize - (r[(aSize << 1) - 1] == 0);
}
/* refresh the size */
uint32_t BinFixSize(const BN_UINT *data, uint32_t size)
{
uint32_t fix = size;
uint32_t i = size;
for (; i > 0; i--) {
if (data[i - 1] != 0) {
return fix;
};
fix--;
}
return fix;
}
/* compare BN array. Maybe aSize != bSize;
* return 0, if a == b
* return 1, if a > b
* return -1, if a < b
*/
int32_t BinCmp(const BN_UINT *a, uint32_t aSize, const BN_UINT *b, uint32_t bSize)
{
if (aSize == bSize) {
uint32_t len = aSize;
while (len > 0) {
len--;
if (a[len] != b[len]) {
return a[len] > b[len] ? 1 : -1;
}
}
return 0;
}
return aSize > bSize ? 1 : -1;
}
/* obtain bits */
uint32_t BinBits(const BN_UINT *data, uint32_t size)
{
if (size == 0) {
return 0;
}
return (size * BN_UINT_BITS - GetZeroBitsUint(data[size - 1]));
}
/**
* Try to reduce the borrowing cost, guarantee h|l >= q * yl. If q is too large, reduce q.
* Each time q decreases by 1, h increases by yh. y was previously offset, and the most significant bit of yh is 1.
* Therefore (q * yl << BN_UINT_BITS) < (yh * 2), number of borrowing times ≤ 2.
*/
static BN_UINT TryDiv(BN_UINT q, BN_UINT h, BN_UINT l, BN_UINT yh, BN_UINT yl)
{
BN_UINT rh, rl;
MUL_AB(rh, rl, q, yl);
/* Compare h|l >= rh|rl. Otherwise, reduce q. */
if (rh < h || (rh == h && rl <= l)) {
return q;
}
BN_UINT nq = q - 1;
BN_UINT nh = h + yh;
/* If carry occurs, no judgment is required. */
if (nh < yh) {
return nq;
}
/* rh|rl - yl */
if (rl < yl) {
rh--;
}
rl -= yl;
/* Compare r|l >= rh|rl. Otherwise, reduce q. */
if (rh < nh || (rh == nh && rl <= l)) {
return nq;
}
nq--;
return nq;
}
/* Divide core operation */
static void BinDivCore(BN_UINT *q, uint32_t *qSize, BN_UINT *x, uint32_t xSize, const BN_UINT *y, uint32_t ySize)
{
BN_UINT yy = y[ySize - 1]; /* Obtain the most significant bit of the data. */
uint32_t i;
for (i = xSize; i >= ySize; i--) {
BN_UINT qq;
if (x[i] == yy) {
qq = (BN_UINT)-1;
} else {
BN_UINT rr;
DIV_ND(qq, rr, x[i], x[i - 1], yy);
if (ySize > 1) { /* If ySize is 1, do not need to try divide. */
/* Obtain the least significant bit data, that is, make subscript - 2. */
qq = TryDiv(qq, rr, x[i - 2], yy, y[ySize - 2]);
}
}
if (qq > 0) {
/* After the TryDiv is complete, perform the double subtraction. */
BN_UINT extend = BinSubMul(&x[i - ySize], y, ySize, qq);
extend = (x[i] -= extend);
if (extend > 0) {
/* reverse, borrowing required */
extend = BinAdd(&x[i - ySize], &x[i - ySize], y, ySize);
x[i] += extend;
qq--;
}
if (q != NULL && qq != 0) {
/* update quotient */
q[i - ySize] = qq;
*qSize = (*qSize) > (i - ySize + 1) ? (*qSize) : (i - ySize + 1);
}
}
}
}
// The L-shift of the divisor does not exceed the highest BN_UINT.
static void BnLshiftSimple(BN_UINT *a, uint32_t aSize, uint32_t bits)
{
uint32_t rem = BN_UNIT_BITS - bits;
BN_UINT nextBits = 0;
for (uint32_t i = 0; i < aSize; i++) {
BN_UINT n = a[i];
a[i] = (n << bits) | nextBits;
nextBits = (n >> rem);
}
return;
}
/**
* x / y = q...x, the return value is the updated xSize.
* q and asize are both NULL or not NULL. Other input parameters must be valid.
* q, x and y cannot be the same pointer, the data in q must be 0.
* Ensure that x->room >= xSize + 2, and the extra two spaces need to be cleared. Extra space is used during try divide.
* this interface does not ensure that the y is consistent after running.
*/
uint32_t BinDiv(BN_UINT *q, uint32_t *qSize, BN_UINT *x, uint32_t xSize, BN_UINT *y, uint32_t ySize)
{
uint32_t shifts = GetZeroBitsUint(y[ySize - 1]);
uint32_t xNewSize = xSize;
/* Left shift until the maximum displacement of the divisor is full. */
if (shifts != 0) {
BnLshiftSimple(y, ySize, shifts);
xNewSize = BinLshift(x, x, xSize, shifts);
}
BinDivCore(q, qSize, x, xSize, y, ySize);
/* shift compensation */
if (shifts != 0) {
xNewSize = BinRshift(x, x, xNewSize, shifts);
}
return BinFixSize(x, xNewSize);
}
#endif /* HITLS_CRYPTO_BN */
|
2301_79861745/bench_create
|
crypto/bn/src/bn_bincal.c
|
C
|
unknown
| 11,223
|
/*
* 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 BN_BINCAL_H
#define BN_BINCAL_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_BN
#include <stdint.h>
#include "bn_basic.h"
#if defined(HITLS_CRYPTO_BN_X8664)
#include "bn_bincal_x8664.h"
#elif defined(HITLS_CRYPTO_BN_ARMV8)
#include "bn_bincal_armv8.h"
#else
#include "bn_bincal_noasm.h"
#endif
#ifdef __cplusplus
extern "c" {
#endif
/* r = a + b, input 'carry' means carry */
#define ADD_AB(carry, r, a, b) \
do { \
BN_UINT macroTmpT = (a) + (b); \
(carry) = macroTmpT < (a) ? 1 : 0; \
(r) = macroTmpT; \
} while (0)
/* r = a - b, input 'borrow' means borrow digit */
#define SUB_AB(borrow, r, a, b) \
do { \
BN_UINT macroTmpT = (a) - (b); \
(borrow) = ((a) < (b)) ? 1 : 0; \
(r) = macroTmpT; \
} while (0)
/* r = a - b - c, input 'borrow' means borrow digit */
#define SUB_ABC(borrow, r, a, b, c) \
do { \
BN_UINT macroTmpS = (a) - (b); \
BN_UINT macroTmpB = ((a) < (b)) ? 1 : 0; \
macroTmpB += (macroTmpS < (c)) ? 1 : 0; \
(r) = macroTmpS - (c); \
borrow = macroTmpB; \
} while (0)
#define BN_UINT_HALF_BITS (BN_UINT_BITS >> 1)
/* carry value of the upper part */
#define BN_UINT_HC ((BN_UINT)1 << BN_UINT_HALF_BITS)
/* Takes the low bit and assigns it to the high bit. */
#define BN_UINT_LO_TO_HI(t) ((t) << BN_UINT_HALF_BITS)
/* Takes the high bit and assigns it to the high bit. */
#define BN_UINT_HI_TO_HI(t) ((t) & ((BN_UINT)0 - BN_UINT_HC))
/* Takes the low bit and assigns it to the low bit. */
#define BN_UINT_LO(t) ((t) & (BN_UINT_HC - 1))
/* Takes the high bit and assigns it to the low bit. */
#define BN_UINT_HI(t) ((t) >> BN_UINT_HALF_BITS)
/* copy bytes, ensure that dstLen >= srcLen */
#define BN_COPY_BYTES(dst, dstlen, src, srclen) \
do { \
uint32_t macroTmpI; \
for (macroTmpI = 0; macroTmpI < (srclen); macroTmpI++) { (dst)[macroTmpI] = (src)[macroTmpI]; } \
for (; macroTmpI < (dstlen); macroTmpI++) { (dst)[macroTmpI] = 0; } \
} while (0)
// Modular operation, satisfy d < (1 << BN_UINT_HALF_BITS) r = nh | nl % d
#define MOD_HALF(r, nh, nl, d) \
do { \
BN_UINT macroTmpD = (d); \
(r) = (nh) % macroTmpD; \
(r) = ((r) << BN_UINT_HALF_BITS) | BN_UINT_HI((nl)); \
(r) = (r) % macroTmpD; \
(r) = ((r) << BN_UINT_HALF_BITS) | BN_UINT_LO((nl)); \
(r) = (r) % macroTmpD; \
} while (0)
/* r = a * b + r + c, where c is refreshed as the new carry value */
#define MULADD_ABC(c, r, a, b) \
do { \
BN_UINT macroTmpAl = BN_UINT_LO(a); \
BN_UINT macroTmpAh = BN_UINT_HI(a); \
BN_UINT macroTmpBl = BN_UINT_LO(b); \
BN_UINT macroTmpBh = BN_UINT_HI(b); \
BN_UINT macroTmpX3 = macroTmpAh * macroTmpBh; \
BN_UINT macroTmpX2 = macroTmpAh * macroTmpBl; \
BN_UINT macroTmpX1 = macroTmpAl * macroTmpBh; \
BN_UINT macroTmpX0 = macroTmpAl * macroTmpBl; \
(r) += (c); \
(c) = ((r) < (c)) ? 1 : 0; \
macroTmpX1 += macroTmpX2; \
(c) += (macroTmpX1 < macroTmpX2) ? BN_UINT_HC : 0; \
macroTmpX2 = macroTmpX0; \
macroTmpX0 += macroTmpX1 << BN_UINT_HALF_BITS; \
(c) += (macroTmpX0 < macroTmpX2) ? 1 : 0; \
(c) += BN_UINT_HI(macroTmpX1); \
(c) += macroTmpX3; \
(r) += macroTmpX0; \
(c) += ((r) < macroTmpX0) ? 1 : 0; \
} while (0)
/* r = a + b + c, input 'carry' means carry. Note that a and carry cannot be the same variable. */
#define ADD_ABC(carry, r, a, b, c) \
do { \
BN_UINT macroTmpS = (b) + (c); \
carry = (macroTmpS < (c)) ? 1 : 0; \
(r) = macroTmpS + (a); \
carry += ((r) < macroTmpS) ? 1 : 0; \
} while (0)
BN_UINT BinAdd(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t n);
BN_UINT BinSub(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t n);
BN_UINT BinInc(BN_UINT *r, const BN_UINT *a, uint32_t size, BN_UINT w);
BN_UINT BinDec(BN_UINT *r, const BN_UINT *a, uint32_t n, BN_UINT w);
uint32_t BinRshift(BN_UINT *r, const BN_UINT *a, uint32_t n, uint32_t bits);
BN_UINT BinSubMul(BN_UINT *r, const BN_UINT *a, BN_UINT aSize, BN_UINT m);
uint32_t BinLshift(BN_UINT *r, const BN_UINT *a, uint32_t n, uint32_t bits);
BN_UINT BinMulAcc(BN_UINT *r, const BN_UINT *a, uint32_t aSize, BN_UINT b);
uint32_t BinMul(BN_UINT *r, uint32_t rRoom, const BN_UINT *a, uint32_t aSize, const BN_UINT *b, uint32_t bSize);
uint32_t BinSqr(BN_UINT *r, uint32_t rRoom, const BN_UINT *a, uint32_t aSize);
uint32_t GetZeroBitsUint(BN_UINT x);
uint32_t BinFixSize(const BN_UINT *data, uint32_t size);
int32_t BinCmp(const BN_UINT *a, uint32_t aSize, const BN_UINT *b, uint32_t bSize);
uint32_t BinBits(const BN_UINT *data, uint32_t size);
uint32_t BinDiv(BN_UINT *q, uint32_t *qSize, BN_UINT *x, uint32_t xSize, BN_UINT *y, uint32_t ySize);
#ifdef HITLS_CRYPTO_BN_COMBA
uint32_t SpaceSize(uint32_t size);
// Perform a multiplication calculation of 4 blocks of data, r = a^2,
// where the length of r is 8, and the length of a is 4.
void MulComba4(BN_UINT *r, const BN_UINT *a, const BN_UINT *b);
// Calculate the square of 4 blocks of data, r = a^2, where the length of r is 8, and the length of a is 4.
void SqrComba4(BN_UINT *r, const BN_UINT *a);
// Perform a multiplication calculation of 6 blocks of data, r = a*b,
// where the length of r is 12, the length of a and b is 6.
void MulComba6(BN_UINT *r, const BN_UINT *a, const BN_UINT *b);
// Calculate the square of 6 blocks of data, r = a^2, where the length of r is 12, and the length of a is 6.
void SqrComba6(BN_UINT *r, const BN_UINT *a);
void MulConquer(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t size, BN_UINT *space, bool consttime);
void SqrConquer(BN_UINT *r, const BN_UINT *a, uint32_t size, BN_UINT *space, bool consttime);
#endif
int32_t MontSqrBinCore(BN_UINT *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime);
int32_t MontMulBinCore(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, BN_Mont *mont,
BN_Optimizer *opt, bool consttime);
int32_t MontEncBinCore(BN_UINT *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime);
void ReduceCore(BN_UINT *r, BN_UINT *x, const BN_UINT *m, uint32_t mSize, BN_UINT m0);
#ifdef __cplusplus
}
#endif
#endif /* HITLS_CRYPTO_BN */
#endif
|
2301_79861745/bench_create
|
crypto/bn/src/bn_bincal.h
|
C
|
unknown
| 7,894
|
/*
* 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 BN_BINCAL_ARMV8_H
#define BN_BINCAL_ARMV8_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_BN
#include "bn_basic.h"
#ifdef __cplusplus
extern "c" {
#endif
// wh | wl = u * v
#define MUL_AB(wh, wl, u, v) \
{ \
__asm("mul %1, %2, %3 \n\t" \
"umulh %0, %2, %3 \n\t" \
: "=&r"(wh), "=&r"(wl) \
: "r"(u), "r"(v) \
: "cc"); \
}
// wh | wl = u ^ 2
#define SQR_A(wh, wl, u) \
{ \
__asm("mul %1, %2, %2 \n\t" \
"umulh %0, %2, %2 \n\t" \
: "=&r"(wh), "=&r"(wl) \
: "r"(u) \
: "cc"); \
}
/* nh|nl / d = q...r */
#define DIV_ND(q, r, nh, nl, d) \
do { \
BN_UINT macroTmpD1, macroTmpD0, macroTmpQ1, macroTmpQ0, macroTmpR1, macroTmpR0, macroTmpM; \
\
macroTmpD1 = BN_UINT_HI(d); \
macroTmpD0 = BN_UINT_LO(d); \
\
macroTmpQ1 = (nh) / macroTmpD1; \
macroTmpR1 = (nh) - macroTmpQ1 * macroTmpD1; \
macroTmpM = macroTmpQ1 * macroTmpD0; \
macroTmpR1 = (macroTmpR1 << (BN_UINT_BITS >> 1)) | BN_UINT_HI(nl); \
if (macroTmpR1 < macroTmpM) { \
macroTmpQ1--, macroTmpR1 += (d); \
if (macroTmpR1 >= (d)) { \
if (macroTmpR1 < macroTmpM) { \
macroTmpQ1--; \
macroTmpR1 += (d); \
} \
} \
} \
macroTmpR1 -= macroTmpM; \
\
macroTmpQ0 = macroTmpR1 / macroTmpD1; \
macroTmpR0 = macroTmpR1 - macroTmpQ0 * macroTmpD1; \
macroTmpM = macroTmpQ0 * macroTmpD0; \
macroTmpR0 = (macroTmpR0 << (BN_UINT_BITS >> 1)) | BN_UINT_LO(nl); \
if (macroTmpR0 < macroTmpM) { \
macroTmpQ0--, macroTmpR0 += (d); \
if (macroTmpR0 >= (d)) { \
if (macroTmpR0 < macroTmpM) { \
macroTmpQ0--; \
macroTmpR0 += (d); \
} \
} \
} \
macroTmpR0 -= macroTmpM; \
\
(q) = (macroTmpQ1 << (BN_UINT_BITS >> 1)) | macroTmpQ0; \
(r) = macroTmpR0; \
} while (0)
// (hi, lo) = a * b
// r += lo + carry
// carry = hi + c
#define MULADC_AB(r, a, b, carry) \
do { \
BN_UINT hi, lo; \
__asm("mul %0, %2, %3 \n\t" \
"umulh %1, %2, %3 \n\t" \
: "=&r"(lo), "=&r"(hi) \
: "r"(a), "r"(b) \
: "cc"); \
__asm("adds %1, %1, %3 \n\t" \
"adc %2, %2, xzr \n\t " \
"adds %0, %0, %1 \n\t" \
"adc %2, %2, xzr \n\t " \
"mov %1, %2 \n\t" \
: "+&r"(r), "+&r"(carry), "+&r"(hi) \
: "r"(lo) \
: "cc"); \
} while (0)
/* h|m|l = h|m|l + u * v. Ensure that the value of h is not too large to avoid carry. */
#define MULADD_AB(h, m, l, u, v) \
do { \
BN_UINT hi, lo; \
__asm("mul %0, %2, %3 \n\t" \
"umulh %1, %2, %3 \n\t" \
: "=&r"(lo), "=&r"(hi) \
: "r"(u), "r"(v) \
: "cc"); \
__asm("adds %0, %0, %3 \n\t " \
"adcs %1, %1, %4 \n\t " \
"adc %2, %2, xzr \n\t " \
: "+&r"(l), "+&r"(m), "+&r"(h) \
: "r"(lo), "r"(hi) \
: "cc"); \
} while (0)
/* h|m|l = h|m|l + 2 * u * v. Ensure that the value of h is not too large to avoid carry. */
#define MULADD_AB2(h, m, l, u, v) \
do { \
BN_UINT hi, lo; \
__asm("mul %0, %2, %3 \n\t" \
"umulh %1, %2, %3 \n\t" \
: "=&r"(lo), "=&r"(hi) \
: "r"(u), "r"(v) \
: "cc"); \
__asm("adds %0, %0, %3 \n\t " \
"adcs %1, %1, %4 \n\t " \
"adc %2, %2, xzr \n\t " \
"adds %0, %0, %3 \n\t " \
"adcs %1, %1, %4 \n\t " \
"adc %2, %2, xzr \n\t " \
: "+&r"(l), "+&r"(m), "+&r"(h) \
: "r"(lo), "r"(hi) \
: "cc"); \
} while (0)
/* h|m|l = h|m|l + u * u. Ensure that the value of h is not too large to avoid carry. */
#define SQRADD_A(h, m, l, u) MULADD_AB(h, m, l, u, u)
#ifdef __cplusplus
}
#endif
#endif /* HITLS_CRYPTO_BN */
#endif
|
2301_79861745/bench_create
|
crypto/bn/src/bn_bincal_armv8.h
|
C
|
unknown
| 7,144
|
/*
* 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 BN_BINCAL_NOASM_H
#define BN_BINCAL_NOASM_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_BN
#include <stdint.h>
#include "bn_basic.h"
#ifdef __cplusplus
extern "c" {
#endif
/* nh|nl / d = q...r */
#define DIV_ND(q, r, nh, nl, d) \
do { \
BN_UINT macroTmpD1, macroTmpD0, macroTmpQ1, macroTmpQ0, macroTmpR1, macroTmpR0, macroTmpM; \
\
macroTmpD1 = BN_UINT_HI(d); \
macroTmpD0 = BN_UINT_LO(d); \
\
macroTmpQ1 = (nh) / macroTmpD1; \
macroTmpR1 = (nh) - macroTmpQ1 * macroTmpD1; \
macroTmpM = macroTmpQ1 * macroTmpD0; \
macroTmpR1 = (macroTmpR1 << (BN_UINT_BITS >> 1)) | BN_UINT_HI(nl); \
if (macroTmpR1 < macroTmpM) { \
macroTmpQ1--, macroTmpR1 += (d); \
if (macroTmpR1 >= (d)) { \
if (macroTmpR1 < macroTmpM) { \
macroTmpQ1--; \
macroTmpR1 += (d); \
} \
} \
} \
macroTmpR1 -= macroTmpM; \
\
macroTmpQ0 = macroTmpR1 / macroTmpD1; \
macroTmpR0 = macroTmpR1 - macroTmpQ0 * macroTmpD1; \
macroTmpM = macroTmpQ0 * macroTmpD0; \
macroTmpR0 = (macroTmpR0 << (BN_UINT_BITS >> 1)) | BN_UINT_LO(nl); \
if (macroTmpR0 < macroTmpM) { \
macroTmpQ0--, macroTmpR0 += (d); \
if (macroTmpR0 >= (d)) { \
if (macroTmpR0 < macroTmpM) { \
macroTmpQ0--; \
macroTmpR0 += (d); \
} \
} \
} \
macroTmpR0 -= macroTmpM; \
\
(q) = (macroTmpQ1 << (BN_UINT_BITS >> 1)) | macroTmpQ0; \
(r) = macroTmpR0; \
} while (0)
#define MUL_AB(wh, wl, u, v) \
do { \
BN_UINT macroTmpUl = BN_UINT_LO(u); \
BN_UINT macroTmpUh = BN_UINT_HI(u); \
BN_UINT macroTmpVl = BN_UINT_LO(v); \
BN_UINT macroTmpVh = BN_UINT_HI(v); \
\
BN_UINT macroTmpX0 = macroTmpUl * macroTmpVl; \
BN_UINT macroTmpX1 = macroTmpUl * macroTmpVh; \
BN_UINT macroTmpX2 = macroTmpUh * macroTmpVl; \
BN_UINT macroTmpX3 = macroTmpUh * macroTmpVh; \
\
macroTmpX1 += BN_UINT_HI(macroTmpX0); \
macroTmpX1 += macroTmpX2; \
if (macroTmpX1 < macroTmpX2) { macroTmpX3 += BN_UINT_HC; } \
\
(wh) = macroTmpX3 + BN_UINT_HI(macroTmpX1); \
(wl) = (macroTmpX1 << (BN_UINT_BITS >> 1)) | BN_UINT_LO(macroTmpX0); \
} while (0)
#define SQR_A(wh, wl, u) \
do { \
BN_UINT macroTmpUl = BN_UINT_LO(u); \
BN_UINT macroTmpUh = BN_UINT_HI(u); \
\
BN_UINT macroTmpX0 = macroTmpUl * macroTmpUl; \
BN_UINT macroTmpX1 = macroTmpUl * macroTmpUh; \
BN_UINT macroTmpX2 = macroTmpUh * macroTmpUh; \
\
BN_UINT macroTmpT = macroTmpX1 << 1; \
macroTmpT += BN_UINT_HI(macroTmpX0); \
if (macroTmpT < macroTmpX1) { macroTmpX2 += BN_UINT_HC; } \
\
(wh) = macroTmpX2 + BN_UINT_HI(macroTmpT); \
(wl) = (macroTmpT << (BN_UINT_BITS >> 1)) | BN_UINT_LO(macroTmpX0); \
} while (0)
/* r = a + b + c, input 'carry' means carry. Note that a and carry cannot be the same variable. */
#define ADD_ABC(carry, r, a, b, c) \
do { \
BN_UINT macroTmpS = (b) + (c); \
carry = (macroTmpS < (c)) ? 1 : 0; \
(r) = macroTmpS + (a); \
carry += ((r) < macroTmpS) ? 1 : 0; \
} while (0)
// (hi, lo) = a * b
// r += lo + carry
// carry = hi + c
#define MULADC_AB(r, a, b, carry) \
do { \
BN_UINT hi, lo; \
MUL_AB(hi, lo, a, b); \
ADD_ABC(carry, r, r, lo, carry); \
carry += hi; \
} while (0)
/* h|m|l = h|m|l + u * v. Ensure that the value of h is not too large to avoid carry. */
#define MULADD_AB(h, m, l, u, v) \
do { \
BN_UINT macroTmpUl = BN_UINT_LO(u); \
BN_UINT macroTmpUh = BN_UINT_HI(u); \
BN_UINT macroTmpVl = BN_UINT_LO(v); \
BN_UINT macroTmpVh = BN_UINT_HI(v); \
\
BN_UINT macroTmpX3 = macroTmpUh * macroTmpVh; \
BN_UINT macroTmpX2 = macroTmpUh * macroTmpVl; \
BN_UINT macroTmpX1 = macroTmpUl * macroTmpVh; \
BN_UINT macroTmpX0 = macroTmpUl * macroTmpVl; \
macroTmpX1 += BN_UINT_HI(macroTmpX0); \
macroTmpX0 = (u) * (v); \
macroTmpX1 += macroTmpX2; \
macroTmpX3 = macroTmpX3 + BN_UINT_HI(macroTmpX1); \
\
(l) += macroTmpX0; \
\
if (macroTmpX1 < macroTmpX2) { macroTmpX3 += BN_UINT_HC; } \
macroTmpX3 += ((l) < macroTmpX0); \
(m) += macroTmpX3; \
(h) += ((m) < macroTmpX3); \
} while (0)
/* h|m|l = h|m|l + 2 * u * v. Ensure that the value of h is not too large to avoid carry. */
#define MULADD_AB2(h, m, l, u, v) \
do { \
MULADD_AB((h), (m), (l), (u), (v)); \
MULADD_AB((h), (m), (l), (u), (v)); \
} while (0)
/* h|m|l = h|m|l + v * v. Ensure that the value of h is not too large to avoid carry. */
#define SQRADD_A(h, m, l, v) \
do { \
BN_UINT macroTmpVl = BN_UINT_LO(v); \
BN_UINT macroTmpVh = BN_UINT_HI(v); \
\
BN_UINT macroTmpX3 = macroTmpVh * macroTmpVh; \
BN_UINT macroTmpX2 = macroTmpVh * macroTmpVl; \
BN_UINT macroTmpX1 = macroTmpX2; \
BN_UINT macroTmpX0 = macroTmpVl * macroTmpVl; \
macroTmpX1 += BN_UINT_HI(macroTmpX0); \
macroTmpX0 = (v) * (v); \
macroTmpX1 += macroTmpX2; \
macroTmpX3 = macroTmpX3 + BN_UINT_HI(macroTmpX1); \
\
(l) += macroTmpX0; \
\
if (macroTmpX1 < macroTmpX2) { macroTmpX3 += BN_UINT_HC; } \
if ((l) < macroTmpX0) { macroTmpX3 += 1; } \
(m) += macroTmpX3; \
if ((m) < macroTmpX3) { (h)++; } \
} while (0)
#ifdef __cplusplus
}
#endif
#endif /* HITLS_CRYPTO_BN */
#endif
|
2301_79861745/bench_create
|
crypto/bn/src/bn_bincal_noasm.h
|
C
|
unknown
| 9,332
|
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef BN_BINCAL_X8664_H
#define BN_BINCAL_X8664_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_BN
#include <stdint.h>
#include "bn_basic.h"
#ifdef __cplusplus
extern "c" {
#endif
// wh | wl = u * v
#define MUL_AB(wh, wl, u, v) \
{ \
__asm("mulq %3" : "=d"(wh), "=a"(wl) : "a"(u), "r"(v) : "cc"); \
}
// wh | wl = u ^ 2
#define SQR_A(wh, wl, u) \
{ \
__asm("mulq %2 " : "=d"(wh), "=a"(wl) : "a"(u) : "cc"); \
}
// nh | nl / d = q...r
#define DIV_ND(q, r, nh, nl, d) \
{ \
__asm("divq %4" : "=a"(q), "=d"(r) : "d"(nh), "a"(nl), "r"(d) : "cc"); \
}
/* r += c
* c = carry
*/
#define ADD_CARRY(carry, r) \
do { \
__asm("addq %1, %0 \n\t " \
"adcq %4, %1 \n\t " \
"adcq $0, %2 \n\t " \
: "+m"(l), "+r"(carry) \
: \
: "cc"); \
} while (0)
/* h|m|l = h|m|l + u * v. Ensure that the value of h is not too large to avoid carry. */
#define MULXADD_AB(h, m, l, u, v) \
do { \
BN_UINT hi, lo; \
__asm("mulq %0, %1, %2" : "=a"(lo), "=d"(hi) : "a"(u), "m"(v) : "cc"); \
__asm("addq %3, %0 \n\t " \
"adcq %4, %1 \n\t " \
"adcq $0, %2 \n\t " \
: "+r"(l), "+r"(m), "+r"(h) \
: "r"(lo), "r"(hi) \
: "cc"); \
} while (0)
// (hi, lo) = a * b
// r += lo + carry
// carry = hi + c
#define MULADC_AB(r, a, b, carry) \
do { \
BN_UINT hi, lo; \
__asm("mulq %3" : "=a"(lo), "=d"(hi) : "a"(a), "g"(b) : "cc"); \
__asm("addq %3, %1 \n\t" \
"adcq $0, %2 \n\t" \
"addq %1, %0 \n\t" \
"adcq $0, %2 \n\t" \
"movq %2, %1 \n\t" \
: "+r"(r), "+r"(carry), "+r"(hi) \
: "r"(lo) \
: "cc"); \
} while (0)
/* h|m|l = h|m|l + u * v. Ensure that the value of h is not too large to avoid carry. */
#define MULADD_AB(h, m, l, u, v) \
do { \
BN_UINT hi, lo; \
__asm("mulq %3" : "=a"(lo), "=d"(hi) : "a"(u), "m"(v) : "cc"); \
__asm("addq %3, %0 \n\t " \
"adcq %4, %1 \n\t " \
"adcq $0, %2 \n\t " \
: "+r"(l), "+r"(m), "+r"(h) \
: "r"(lo), "r"(hi) \
: "cc"); \
} while (0)
/* h|m|l = h|m|l + 2 * u * v. Ensure that the value of h is not too large to avoid carry. */
#define MULADD_AB2(h, m, l, u, v) \
do { \
BN_UINT hi, lo; \
__asm("mulq %3" : "=a"(lo), "=d"(hi) : "a"(u), "m"(v) : "cc"); \
__asm("addq %3, %0 \n\t " \
"adcq %4, %1 \n\t " \
"adcq $0, %2 \n\t " \
"addq %3, %0 \n\t " \
"adcq %4, %1 \n\t " \
"adcq $0, %2 \n\t " \
: "+r"(l), "+r"(m), "+r"(h) \
: "r"(lo), "r"(hi) \
: "cc"); \
} while (0)
/* h|m|l = h|m|l + u * u. Ensure that the value of h is not too large to avoid carry. */
#define SQRADD_A(h, m, l, u) MULADD_AB(h, m, l, u, u)
#ifdef __cplusplus
}
#endif
#endif /* HITLS_CRYPTO_BN */
#endif
|
2301_79861745/bench_create
|
crypto/bn/src/bn_bincal_x8664.h
|
C
|
unknown
| 5,705
|
/*
* 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_BN) && defined(HITLS_CRYPTO_BN_COMBA)
#include <stdint.h>
#include "bn_bincal.h"
#define SQR_COMBA_BEGIN_1(r, a, h, m, l) do { \
SQRADD_A((h), (m), (l), (a)[0]); \
(r)[0] = (l); \
(l) = 0; \
MULADD_AB2((l), (h), (m), (a)[0], (a)[1]); \
(r)[1] = (m); \
(m) = 0; \
MULADD_AB2((m), (l), (h), (a)[0], (a)[2]); /* 0 + 2 = 2 */ \
SQRADD_A((m), (l), (h), (a)[1]); /* 1 + 1 = 2 */ \
(r)[2] = (h); /* 2 */ \
(h) = 0; \
MULADD_AB2((h), (m), (l), (a)[1], (a)[2]); /* 1 + 2 = 3 */ \
MULADD_AB2((h), (m), (l), (a)[0], (a)[3]); /* 0 + 3 = 3 */ \
(r)[3] = (l); /* 3 */ \
(l) = 0; \
} while (0)
#define SQR_COMBA_BEGIN_2(r, a, h, m, l) do { \
MULADD_AB2((l), (h), (m), (a)[0], (a)[4]); /* 0 + 4 = 4 */ \
MULADD_AB2((l), (h), (m), (a)[1], (a)[3]); /* 1 + 3 = 4 */ \
SQRADD_A((l), (h), (m), (a)[2]); /* 2 + 2 = 4 */ \
(r)[4] = (m); /* 4 */ \
(m) = 0; \
MULADD_AB2((m), (l), (h), (a)[2], (a)[3]); /* 2 + 3 = 5 */ \
MULADD_AB2((m), (l), (h), (a)[1], (a)[4]); /* 1 + 4 = 5 */ \
MULADD_AB2((m), (l), (h), (a)[0], (a)[5]); /* 0 + 5 = 5 */ \
(r)[5] = (h); /* 5 */ \
(h) = 0; \
} while (0)
#define MUL_COMBA_BEGIN_1(r, a, b, h, m, l) do { \
MULADD_AB((h), (m), (l), (a)[0], (b)[0]); \
(r)[0] = (l); \
(l) = 0; \
MULADD_AB((l), (h), (m), (a)[0], (b)[1]); \
MULADD_AB((l), (h), (m), (a)[1], (b)[0]); \
(r)[1] = (m); \
(m) = 0; \
MULADD_AB((m), (l), (h), (a)[2], (b)[0]); /* 2 + 0 = 2 */ \
MULADD_AB((m), (l), (h), (a)[1], (b)[1]); /* 1 + 1 = 2 */ \
MULADD_AB((m), (l), (h), (a)[0], (b)[2]); /* 0 + 2 = 2 */ \
(r)[2] = (h); \
(h) = 0; \
MULADD_AB((h), (m), (l), (a)[0], (b)[3]); /* 0 + 3 = 3 */ \
MULADD_AB((h), (m), (l), (a)[1], (b)[2]); /* 1 + 2 = 3 */ \
MULADD_AB((h), (m), (l), (a)[2], (b)[1]); /* 2 + 1 = 3 */ \
MULADD_AB((h), (m), (l), (a)[3], (b)[0]); /* 3 + 9 = 3 */ \
(r)[3] = (l); /* 3 */ \
(l) = 0; \
} while (0)
#define MUL_COMBA_BEGIN_2(r, a, b, h, m, l) do { \
MULADD_AB((l), (h), (m), (a)[4], (b)[0]); /* 4 + 0 = 4 */ \
MULADD_AB((l), (h), (m), (a)[3], (b)[1]); /* 3 + 1 = 4 */ \
MULADD_AB((l), (h), (m), (a)[2], (b)[2]); /* 2 + 2 = 4 */ \
MULADD_AB((l), (h), (m), (a)[1], (b)[3]); /* 1 + 3 = 4 */ \
MULADD_AB((l), (h), (m), (a)[0], (b)[4]); /* 0 + 4 = 4 */ \
(r)[4] = (m); /* 4 */ \
(m) = 0; \
MULADD_AB((m), (l), (h), (a)[0], (b)[5]); /* 0 + 5 = 5 */ \
MULADD_AB((m), (l), (h), (a)[1], (b)[4]); /* 1 + 4 = 5 */ \
MULADD_AB((m), (l), (h), (a)[2], (b)[3]); /* 2 + 3 = 5 */ \
MULADD_AB((m), (l), (h), (a)[3], (b)[2]); /* 3 + 2 = 5 */ \
MULADD_AB((m), (l), (h), (a)[4], (b)[1]); /* 4 + 1 = 5 */ \
MULADD_AB((m), (l), (h), (a)[5], (b)[0]); /* 5 + 0 = 5 */ \
(r)[5] = (h); /* 5 */ \
(h) = 0; \
} while (0)
#define MUL_COMBA_BEGIN_3(r, a, b, h, m, l) do { \
MULADD_AB((h), (m), (l), (a)[6], (b)[0]); /* 6 + 0 = 6 */ \
MULADD_AB((h), (m), (l), (a)[5], (b)[1]); /* 5 + 1 = 6 */ \
MULADD_AB((h), (m), (l), (a)[4], (b)[2]); /* 4 + 2 = 6 */ \
MULADD_AB((h), (m), (l), (a)[3], (b)[3]); /* 3 + 3 = 6 */ \
MULADD_AB((h), (m), (l), (a)[2], (b)[4]); /* 2 + 4 = 6 */ \
MULADD_AB((h), (m), (l), (a)[1], (b)[5]); /* 1 + 5 = 6 */ \
MULADD_AB((h), (m), (l), (a)[0], (b)[6]); /* 0 + 6 = 6 */ \
(r)[6] = (l); /* 6 */ \
(l) = 0; \
MULADD_AB((l), (h), (m), (a)[0], (b)[7]); /* 0 + 7 = 7 */ \
MULADD_AB((l), (h), (m), (a)[1], (b)[6]); /* 1 + 6 = 7 */ \
MULADD_AB((l), (h), (m), (a)[2], (b)[5]); /* 2 + 5 = 7 */ \
MULADD_AB((l), (h), (m), (a)[3], (b)[4]); /* 3 + 4 = 7 */ \
MULADD_AB((l), (h), (m), (a)[4], (b)[3]); /* 4 + 3 = 7 */ \
MULADD_AB((l), (h), (m), (a)[5], (b)[2]); /* 5 + 2 = 7 */ \
MULADD_AB((l), (h), (m), (a)[6], (b)[1]); /* 6 + 1 = 7 */ \
MULADD_AB((l), (h), (m), (a)[7], (b)[0]); /* 7 + 0 = 7 */ \
(r)[7] = (m); /* 7 */ \
(m) = 0; \
MULADD_AB((m), (l), (h), (a)[7], (b)[1]); /* 7 + 1 = 8 */ \
MULADD_AB((m), (l), (h), (a)[6], (b)[2]); /* 6 + 2 = 8 */ \
MULADD_AB((m), (l), (h), (a)[5], (b)[3]); /* 5 + 3 = 8 */ \
MULADD_AB((m), (l), (h), (a)[4], (b)[4]); /* 4 + 4 = 8 */ \
MULADD_AB((m), (l), (h), (a)[3], (b)[5]); /* 3 + 5 = 8 */ \
MULADD_AB((m), (l), (h), (a)[2], (b)[6]); /* 2 + 6 = 8 */ \
MULADD_AB((m), (l), (h), (a)[1], (b)[7]); /* 1 + 7 = 8 */ \
(r)[8] = (h); /* 8 */ \
(h) = 0; \
} while (0)
static void SqrComba8(BN_UINT *r, const BN_UINT *a)
{
BN_UINT h = 0;
BN_UINT m = 0;
BN_UINT l = 0;
SQR_COMBA_BEGIN_1(r, a, h, m, l);
SQR_COMBA_BEGIN_2(r, a, h, m, l);
MULADD_AB2(h, m, l, a[0], a[6]); /* 0 + 6 = 6 */
MULADD_AB2(h, m, l, a[1], a[5]); /* 1 + 5 = 6 */
MULADD_AB2(h, m, l, a[2], a[4]); /* 2 + 4 = 6 */
SQRADD_A(h, m, l, a[3]); /* 3 + 3 = 6 */
r[6] = l; /* 6 */
l = 0;
MULADD_AB2(l, h, m, a[3], a[4]); /* 3 + 4 = 7 */
MULADD_AB2(l, h, m, a[2], a[5]); /* 2 + 5 = 7 */
MULADD_AB2(l, h, m, a[1], a[6]); /* 1 + 6 = 7 */
MULADD_AB2(l, h, m, a[0], a[7]); /* 0 + 7 = 7 */
r[7] = m; /* 7 */
m = 0;
MULADD_AB2(m, l, h, a[1], a[7]); /* 1 + 7 = 8 */
MULADD_AB2(m, l, h, a[2], a[6]); /* 2 + 6 = 8 */
MULADD_AB2(m, l, h, a[3], a[5]); /* 3 + 5 = 8 */
SQRADD_A(m, l, h, a[4]); /* 4 + 4 = 8 */
r[8] = h; /* 8 */
h = 0;
MULADD_AB2(h, m, l, a[4], a[5]); /* 4 + 5 = 9 */
MULADD_AB2(h, m, l, a[3], a[6]); /* 3 + 6 = 9 */
MULADD_AB2(h, m, l, a[2], a[7]); /* 2 + 7 = 9 */
r[9] = l; /* 9 */
l = 0;
MULADD_AB2(l, h, m, a[3], a[7]); /* 3 + 7 = 10 */
MULADD_AB2(l, h, m, a[4], a[6]); /* 4 + 6 = 10 */
SQRADD_A(l, h, m, a[5]); /* 5 + 5 = 10 */
r[10] = m; /* 10 */
m = 0;
MULADD_AB2(m, l, h, a[5], a[6]); /* 5 + 6 = 11 */
MULADD_AB2(m, l, h, a[4], a[7]); /* 4 + 7 = 11 */
r[11] = h; /* 11 */
h = 0;
MULADD_AB2(h, m, l, a[5], a[7]); /* 5 + 7 = 12 */
SQRADD_A(h, m, l, a[6]); /* 6 + 6 = 12 */
r[12] = l; /* 12 */
l = 0;
MULADD_AB2(l, h, m, a[6], a[7]); /* 6 + 7 = 13 */
r[13] = m; /* 13 */
m = 0;
SQRADD_A(m, l, h, a[7]); /* 7 + 7 = 14 */
r[14] = h; /* 14 */
r[15] = l; /* 15 */
}
void SqrComba6(BN_UINT *r, const BN_UINT *a)
{
BN_UINT h = 0;
BN_UINT m = 0;
BN_UINT l = 0;
SQR_COMBA_BEGIN_1(r, a, h, m, l);
SQR_COMBA_BEGIN_2(r, a, h, m, l);
MULADD_AB2(h, m, l, a[1], a[5]); /* 1 + 5 = 6 */
MULADD_AB2(h, m, l, a[2], a[4]); /* 2 + 4 = 6 */
SQRADD_A(h, m, l, a[3]); /* 3 + 3 = 6 */
r[6] = l; /* 6 */
l = 0;
MULADD_AB2(l, h, m, a[3], a[4]); /* 3 + 4 = 7 */
MULADD_AB2(l, h, m, a[2], a[5]); /* 2 + 5 = 7 */
r[7] = m; /* 7 */
m = 0;
MULADD_AB2(m, l, h, a[3], a[5]); /* 3 + 5 = 8 */
SQRADD_A(m, l, h, a[4]); /* 4 + 4 = 8 */
r[8] = h; /* 8 */
h = 0;
MULADD_AB2(h, m, l, a[4], a[5]); /* 4 + 5 = 9 */
r[9] = l; /* 9 */
l = 0;
SQRADD_A(l, h, m, a[5]); /* 5 + 5 = 10 */
r[10] = m; /* 10 */
r[11] = h; /* 11 */
}
void SqrComba4(BN_UINT *r, const BN_UINT *a)
{
BN_UINT h = 0;
BN_UINT m = 0;
BN_UINT l = 0;
SQR_COMBA_BEGIN_1(r, a, h, m, l);
MULADD_AB2(l, h, m, a[1], a[3]); /* 1 + 3 = 4 */
SQRADD_A(l, h, m, a[2]); /* 2 + 2 = 4 */
r[4] = m; /* 4 */
m = 0;
MULADD_AB2(m, l, h, a[2], a[3]); /* 2 + 3 = 5 */
r[5] = h; /* 5 */
h = 0;
SQRADD_A(h, m, l, a[3]); /* 3 + 3 = 6 */
r[6] = l; /* 6 */
r[7] = m; /* 7 */
}
static void SqrComba(BN_UINT *r, const BN_UINT *a, uint32_t size)
{
BN_UINT h = 0;
BN_UINT m = 0;
BN_UINT l = 0;
if (size == 3) { /* 3 */
SQRADD_A(h, m, l, a[0]);
r[0] = l;
l = 0;
MULADD_AB2(l, h, m, a[0], a[1]);
r[1] = m;
m = 0;
MULADD_AB2(m, l, h, a[0], a[2]); /* 0 + 2 = 2 */
SQRADD_A(m, l, h, a[1]); /* 1 + 1 = 2 */
r[2] = h; /* 2 */
h = 0;
MULADD_AB2(h, m, l, a[1], a[2]); /* 1 + 2 = 3 */
r[3] = l; /* 3 */
l = 0;
SQRADD_A(l, h, m, a[2]); /* 2 + 2 = 4 */
r[4] = m; /* 4 */
r[5] = h; /* 5 */
return;
}
if (size == 2) { /* 2 */
SQRADD_A(h, m, l, a[0]);
r[0] = l;
l = 0;
MULADD_AB2(l, h, m, a[0], a[1]);
r[1] = m;
m = 0;
SQRADD_A(m, l, h, a[1]); /* 1 + 1 = 2 */
r[2] = h; /* 2 */
r[3] = l; /* 3 */
return;
}
SQR_A(r[1], r[0], a[0]); /* size == 1 */
}
void MulComba8(BN_UINT *r, const BN_UINT *a, const BN_UINT *b)
{
BN_UINT h = 0;
BN_UINT m = 0;
BN_UINT l = 0;
MUL_COMBA_BEGIN_1(r, a, b, h, m, l);
MUL_COMBA_BEGIN_2(r, a, b, h, m, l);
MUL_COMBA_BEGIN_3(r, a, b, h, m, l);
MULADD_AB(h, m, l, a[2], b[7]); /* 2 + 7 = 9 */
MULADD_AB(h, m, l, a[3], b[6]); /* 3 + 6 = 9 */
MULADD_AB(h, m, l, a[4], b[5]); /* 4 + 5 = 9 */
MULADD_AB(h, m, l, a[5], b[4]); /* 5 + 4 = 9 */
MULADD_AB(h, m, l, a[6], b[3]); /* 6 + 3 = 9 */
MULADD_AB(h, m, l, a[7], b[2]); /* 7 + 2 = 9 */
r[9] = l; /* 9 */
l = 0;
MULADD_AB(l, h, m, a[7], b[3]); /* 7 + 3 = 10 */
MULADD_AB(l, h, m, a[6], b[4]); /* 6 + 4 = 10 */
MULADD_AB(l, h, m, a[5], b[5]); /* 5 + 5 = 10 */
MULADD_AB(l, h, m, a[4], b[6]); /* 4 + 6 = 10 */
MULADD_AB(l, h, m, a[3], b[7]); /* 3 + 7 = 10 */
r[10] = m; /* 10 */
m = 0;
MULADD_AB(m, l, h, a[4], b[7]); /* 4 + 7 = 11 */
MULADD_AB(m, l, h, a[5], b[6]); /* 5 + 6 = 11 */
MULADD_AB(m, l, h, a[6], b[5]); /* 6 + 5 = 11 */
MULADD_AB(m, l, h, a[7], b[4]); /* 7 + 4 = 11 */
r[11] = h; /* 11 */
h = 0;
MULADD_AB(h, m, l, a[7], b[5]); /* 7 + 5 = 12 */
MULADD_AB(h, m, l, a[6], b[6]); /* 6 + 6 = 12 */
MULADD_AB(h, m, l, a[5], b[7]); /* 5 + 7 = 12 */
r[12] = l; /* 12 */
l = 0;
MULADD_AB(l, h, m, a[6], b[7]); /* 6 + 7 = 13 */
MULADD_AB(l, h, m, a[7], b[6]); /* 7 + 6 = 13 */
r[13] = m; /* 13 */
m = 0;
MULADD_AB(m, l, h, a[7], b[7]); /* 7 + 7 = 14 */
r[14] = h; /* 14 */
r[15] = l; /* 15 */
}
void MulComba6(BN_UINT *r, const BN_UINT *a, const BN_UINT *b)
{
BN_UINT h = 0;
BN_UINT m = 0;
BN_UINT l = 0;
MUL_COMBA_BEGIN_1(r, a, b, h, m, l);
MUL_COMBA_BEGIN_2(r, a, b, h, m, l);
MULADD_AB(h, m, l, a[5], b[1]); /* 5 + 1 = 6 */
MULADD_AB(h, m, l, a[4], b[2]); /* 4 + 2 = 6 */
MULADD_AB(h, m, l, a[3], b[3]); /* 3 + 3 = 6 */
MULADD_AB(h, m, l, a[2], b[4]); /* 2 + 4 = 6 */
MULADD_AB(h, m, l, a[1], b[5]); /* 1 + 5 = 6 */
r[6] = l; /* 6 */
l = 0;
MULADD_AB(l, h, m, a[2], b[5]); /* 2 + 5 = 7 */
MULADD_AB(l, h, m, a[3], b[4]); /* 3 + 4 = 7 */
MULADD_AB(l, h, m, a[4], b[3]); /* 4 + 3 = 7 */
MULADD_AB(l, h, m, a[5], b[2]); /* 5 + 2 = 7 */
r[7] = m; /* 7 */
m = 0;
MULADD_AB(m, l, h, a[5], b[3]); /* 5 + 3 = 8 */
MULADD_AB(m, l, h, a[4], b[4]); /* 4 + 4 = 8 */
MULADD_AB(m, l, h, a[3], b[5]); /* 3 + 5 = 8 */
r[8] = h; /* 8 */
h = 0;
MULADD_AB(h, m, l, a[4], b[5]); /* 4 + 5 = 9 */
MULADD_AB(h, m, l, a[5], b[4]); /* 5 + 4 = 9 */
r[9] = l; /* 9 */
l = 0;
MULADD_AB(l, h, m, a[5], b[5]); /* 5 + 5 = 10 */
r[10] = m; /* 10 */
r[11] = h; /* 11 */
}
void MulComba4(BN_UINT *r, const BN_UINT *a, const BN_UINT *b)
{
BN_UINT h = 0;
BN_UINT m = 0;
BN_UINT l = 0;
MUL_COMBA_BEGIN_1(r, a, b, h, m, l);
MULADD_AB(l, h, m, a[3], b[1]); /* 3 + 1 = 4 */
MULADD_AB(l, h, m, a[2], b[2]); /* 2 + 2 = 4 */
MULADD_AB(l, h, m, a[1], b[3]); /* 1 + 3 = 4 */
r[4] = m; /* 4 */
m = 0;
MULADD_AB(m, l, h, a[2], b[3]); /* 2 + 3 = 5 */
MULADD_AB(m, l, h, a[3], b[2]); /* 3 + 2 = 5 */
r[5] = h; /* 5 */
h = 0;
MULADD_AB(h, m, l, a[3], b[3]); /* 3 + 3 = 6 */
r[6] = l; /* 6 */
r[7] = m; /* 7 */
}
static void MulComba(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t size)
{
BN_UINT h = 0;
BN_UINT m = 0;
BN_UINT l = 0;
if (size == 3) { /* 3 */
MULADD_AB(h, m, l, a[0], b[0]);
r[0] = l;
l = 0;
MULADD_AB(l, h, m, a[0], b[1]);
MULADD_AB(l, h, m, a[1], b[0]);
r[1] = m;
m = 0;
MULADD_AB(m, l, h, a[2], b[0]); /* 2 + 0 = 2 */
MULADD_AB(m, l, h, a[1], b[1]); /* 1 + 1 = 2 */
MULADD_AB(m, l, h, a[0], b[2]); /* 0 + 2 = 2 */
r[2] = h;
h = 0;
MULADD_AB(h, m, l, a[1], b[2]); /* 1 + 2 = 3 */
MULADD_AB(h, m, l, a[2], b[1]); /* 2 + 1 = 3 */
r[3] = l; /* 3 */
l = 0;
MULADD_AB(l, h, m, a[2], b[2]); /* 2 + 2 = 4 */
r[4] = m; /* 4 */
r[5] = h; /* 5 */
return;
}
if (size == 2) { /* 2 */
MULADD_AB(h, m, l, a[0], b[0]);
r[0] = l;
l = 0;
MULADD_AB(l, h, m, a[0], b[1]);
MULADD_AB(l, h, m, a[1], b[0]);
r[1] = m;
m = 0;
MULADD_AB(m, l, h, a[1], b[1]);
r[2] = h; /* 2 */
r[3] = l; /* 3 */
return;
}
MUL_AB(r[1], r[0], a[0], b[0]); /* size == 1 */
}
uint32_t SpaceSize(uint32_t size)
{
uint32_t base = 8; /* Perform 8x batch processing */
while (size > base) {
base <<= 1;
}
return base * 4; /* 2x expansion. Each layer requires 2 * size temporary space, 2 * 2 = 4 */
}
/* compare BN array.
* return 0, if a == b
* return 1, if a > b
* return -1, if a < b
*/
static int32_t BinCmpSame(const BN_UINT *a, const BN_UINT *b, uint32_t size)
{
int64_t idx = (int64_t)size;
while (--idx >= 0) {
if (a[idx] != b[idx]) {
return a[idx] > b[idx] ? 1 : -1;
}
}
return 0;
}
/* The caller promised that aSize >= bSize.
* r = ABS(a - b). Need to ensure that aSize == bSize + (0 || 1).
* return 0 if a > b
* return 1 if a <= b
*/
static uint32_t ABS_Sub(BN_UINT *t, const BN_UINT *a, uint32_t aSize, const BN_UINT *b, uint32_t bSize)
{
int32_t ret;
do {
if (aSize > bSize) {
t[bSize] = a[bSize]; /* bSize = aSize - 1 */
if (a[bSize] > 0) {
ret = 1;
break;
}
}
ret = BinCmpSame(a, b, bSize);
} while (0);
if (ret > 0) {
BN_UINT borrow = BinSub(t, a, b, bSize);
if (aSize > bSize) { /* When the length difference exists and a > b exists, the borrowing is processed. */
t[bSize] -= borrow;
}
return 0;
} else {
BinSub(t, b, a, bSize);
return 1;
}
return 0;
}
/** Only aSize == bSize is supported. This interface will recurse. The recursion depth is O(deep) = log2(size)
* Ensure that space >= SpaceSize(size)
* (ah|al * bh|bl) = (((ah*bh) << 2) + (((ah*bh) + (al*bl) - (ah - al)(bh - bl)) << 1) + (al*bl))
*/
void MulConquer(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t size, BN_UINT *space, bool consttime)
{
if (!consttime) {
if (size == 8) { /* Perform 8x batch processing */
MulComba8(r, a, b);
return;
}
if (size == 6) { /* Perform 6x batch processing */
MulComba6(r, a, b);
return;
}
if (size == 4) { /* Perform 4x batch processing */
MulComba4(r, a, b);
return;
}
if (size < 4) { /* Less than 4, simple processing */
MulComba(r, a, b, size);
return;
}
} else if (size <= 8) { /* Calculate if the block size is smaller than 8. */
BinMul(r, size << 1, a, size, b, size);
return;
}
/* truncates the length of the low bits of the BigNum, that is the length of al bl. */
const uint32_t sizeLo = size >> 1;
const uint32_t sizeLo2 = sizeLo << 1;
const uint32_t shift1 = sizeLo; /* (((ah*bh) + (al*bl) - (ah - al)(bh - bl)) << 1) location */
const uint32_t shift2 = shift1 << 1; /* ((ah*bh) << 2) location */
/* truncates the length of the high bits of the BigNum, that is the length of ah bh. */
const uint32_t sizeHi = size - sizeLo;
const uint32_t sizeHi2 = sizeHi << 1;
/* Split the input 'space'. The current function uses tmp1 and tmp2,
* and the remaining newspace is used by the lower layer.
* space = tmp1_lo..tmp1_hi | tmp2_lo..tmp2_hi | newSpace, sizeof(tmp1_lo) == sizeHi.
*/
BN_UINT *tmp1 = space;
BN_UINT *tmp2 = tmp1 + sizeHi2;
BN_UINT *newSpace = tmp2 + sizeHi2;
/* tmp2_lo = (ah-al) */
uint32_t sign = ABS_Sub(tmp2, a + shift1, sizeHi, a, sizeLo);
/* tmp2_hi = (bh-bl) */
sign ^= ABS_Sub(tmp2 + sizeHi, b + shift1, sizeHi, b, sizeLo);
MulConquer(r, a, b, sizeLo, newSpace, consttime); /* calculate (al*bl) */
MulConquer(r + shift2, a + shift1, b + shift1, sizeHi, newSpace, consttime); /* calculate (ah*bh) */
MulConquer(tmp1, tmp2, tmp2 + sizeHi, sizeHi, newSpace, consttime); /* calculate (ah-al)(bh-bl) */
/* At this time r has stored ((ah*bh) << 2) and (al*bl) */
/* carry should be added in (r + shift1)[sizeHi * 2] */
/* tmp2 is (ah*bh) + (al*bl), but the processing length here is sizeLo * 2 */
BN_UINT carry = BinAdd(tmp2, r, r + shift2, sizeLo2);
if (sizeHi > sizeLo) {
/* If there is a length difference, the length of (ah*bh) is sizeLo * 2 + 2,
and the tail of (ah*bh) needs to be processed. */
/* point to (r + shift2)[sizeLo * 2], the unprocessed tail of (ah*bh) */
const uint32_t position = shift2 + (sizeLo2);
tmp2[sizeLo2] = r[position] + carry;
carry = (tmp2[sizeLo2] < carry) ? 1 : 0;
/* continue the processing */
tmp2[(sizeLo2) + 1] = r[position + 1] + carry;
carry = (tmp2[sizeLo2 + 1] < carry) ? 1 : 0;
}
/* tmp1 = (ah*bh) + (al*bl) - (ah-al)(bh-bl), tmp2 is (ah*bh) + (al*bl) */
if (sign == 1) {
carry += BinAdd(tmp1, tmp2, tmp1, sizeHi2);
} else {
carry -= BinSub(tmp1, tmp2, tmp1, sizeHi2);
}
/* finally r adds tmp1, that is (ah*bh) + (al*bl) - (ah - al)(bh - bl) */
carry += BinAdd(r + shift1, r + shift1, tmp1, sizeHi2);
for (uint32_t i = shift1 + sizeHi2; carry > 0 && i < (size << 1); i++) {
ADD_AB(carry, r[i], r[i], carry);
}
}
/** This interface will recurse. The recursion depth is O(deep) = log2(size)
* Ensure that space >= SpaceSize(size)
* (x|y)^2 = ((x^2 << 2) + ((x^2 + y^2 - (x - y)^2)) << 1) + y^2)
*/
void SqrConquer(BN_UINT *r, const BN_UINT *a, uint32_t size, BN_UINT *space, bool consttime)
{
if (!consttime) {
if (size == 8) { /* Perform 8x batch processing */
SqrComba8(r, a);
return;
}
if (size == 6) { /* Perform 6x batch processing */
SqrComba6(r, a);
return;
}
if (size == 4) { /* Perform 4x batch processing */
SqrComba4(r, a);
return;
}
if (size < 4) { /* Less than 4, simple processing */
SqrComba(r, a, size);
return;
}
} else if (size <= 8) { /* Calculate if the block size is smaller than 8. */
BinSqr(r, size << 1, a, size);
return;
}
/* truncates the length of the high bits of the BigNum, that is the length of x. */
const uint32_t sizeHi = (size + 1) >> 1;
/* truncates the length of the low bits of the BigNum, that is the length of y. */
const uint32_t sizeLo = size >> 1;
const uint32_t shift1 = sizeLo; /* ((x^2 + y^2 - (x - y)^2)) << 1) location */
const uint32_t shift2 = shift1 << 1; /* ((x^2 << 2) location */
/* Split the input 'space'. The current function uses tmp1 and tmp2,
and the remaining newspace is used by the lower layer. */
BN_UINT *tmp1 = space;
BN_UINT *tmp2 = tmp1 + (sizeHi << 1);
BN_UINT *newSpace = tmp2 + (sizeHi << 1);
/* tmp2 is the upper bits of num minus the lower bits of num, (x-y) */
(void)ABS_Sub(tmp2, a + shift1, sizeHi, a, sizeLo);
SqrConquer(r, a, sizeLo, newSpace, consttime); /* calculate y^2 */
SqrConquer(r + shift2, a + shift1, sizeHi, newSpace, consttime); /* calculate x^2 */
SqrConquer(tmp1, tmp2, sizeHi, newSpace, consttime); /* calculate (x-y)^2 */
/* At this time r has stored (x^2 << 2) and y^2 */
/* carry should be added in (r + shift1)[sizeHi * 2] */
/* tmp2 = x^2 + y^2, but the processing length here is sizeLo * 2 */
BN_UINT carry = BinAdd(tmp2, r, r + shift2, sizeLo << 1);
if (sizeHi > sizeLo) {
/* If there is a length difference, the length of x^2 is sizeLo * 2 + 2,
and the tail of x^2 needs to be processed. */
/* point to (r + shift2)[sizeLo * 2], the unprocessed tail of x^2 */
const uint32_t position = shift2 + (sizeLo << 1);
tmp2[sizeLo << 1] = r[position] + carry;
carry = (tmp2[sizeLo << 1] < carry) ? 1 : 0;
/* continue the processing */
tmp2[(sizeLo << 1) + 1] = r[position + 1] + carry;
carry = (tmp2[(sizeLo << 1) + 1] < carry) ? 1 : 0;
}
/* tmp1 = x^2 + y^2 - (x-y)^2, tmp2 is x^2 + y^2 */
carry -= BinSub(tmp1, tmp2, tmp1, sizeHi << 1);
/* finally r adds x^2 + y^2 - (x-y)^2 */
carry += BinAdd(r + shift1, r + shift1, tmp1, sizeHi << 1);
uint32_t i;
for (i = shift1 + (sizeHi << 1); carry > 0 && i < (size << 1); i++) {
ADD_AB(carry, r[i], r[i], carry);
}
}
#endif /* HITLS_CRYPTO_BN_COMBA */
|
2301_79861745/bench_create
|
crypto/bn/src/bn_comba.c
|
C
|
unknown
| 25,469
|
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_BN_PRIME_RFC3526
#include "crypt_errno.h"
#include "bn_basic.h"
#if defined(HITLS_SIXTY_FOUR_BITS)
// RFC 3526: 2048-bit MODP GroupUL, this prime is: 2^2048 - 2^1984 - 1 + 2^64 * { [2^1918 pi] + 124476 }
static const BN_UINT RFC3526_PRIME_2048[] = {
0xFFFFFFFFFFFFFFFFUL, 0x15728E5A8AACAA68UL, 0x15D2261898FA0510UL, 0x3995497CEA956AE5UL,
0xDE2BCBF695581718UL, 0xB5C55DF06F4C52C9UL, 0x9B2783A2EC07A28FUL, 0xE39E772C180E8603UL,
0x32905E462E36CE3BUL, 0xF1746C08CA18217CUL, 0x1C62F356208552BBUL, 0x83655D23DCA3AD96UL,
0x69163FA8FD24CF5FUL, 0x98DA48361C55D39AUL, 0xC2007CB8A163BF05UL, 0x49286651ECE45B3DUL,
0xAE9F24117C4B1FE6UL, 0xEE386BFB5A899FA5UL, 0x0BFF5CB6F406B7EDUL, 0xF44C42E9A637ED6BUL,
0xE485B576625E7EC6UL, 0x4FE1356D6D51C245UL, 0x302B0A6DF25F1437UL, 0xEF9519B3CD3A431BUL,
0x514A08798E3404DDUL, 0x020BBEA63B139B22UL, 0x29024E088A67CC74UL, 0xC4C6628B80DC1CD1UL,
0xC90FDAA22168C234UL, 0xFFFFFFFFFFFFFFFFUL
};
// RFC 3526: 3072-bit MODP GroupUL, this prime is: 2^3072 - 2^3008 - 1 + 2^64 * { [2^2942 pi] + 1690314 }
static const BN_UINT RFC3526_PRIME_3072[] = {
0xFFFFFFFFFFFFFFFFUL, 0x4B82D120A93AD2CAUL, 0x43DB5BFCE0FD108EUL, 0x08E24FA074E5AB31UL,
0x770988C0BAD946E2UL, 0xBBE117577A615D6CUL, 0x521F2B18177B200CUL, 0xD87602733EC86A64UL,
0xF12FFA06D98A0864UL, 0xCEE3D2261AD2EE6BUL, 0x1E8C94E04A25619DUL, 0xABF5AE8CDB0933D7UL,
0xB3970F85A6E1E4C7UL, 0x8AEA71575D060C7DUL, 0xECFB850458DBEF0AUL, 0xA85521ABDF1CBA64UL,
0xAD33170D04507A33UL, 0x15728E5A8AAAC42DUL, 0x15D2261898FA0510UL, 0x3995497CEA956AE5UL,
0xDE2BCBF695581718UL, 0xB5C55DF06F4C52C9UL, 0x9B2783A2EC07A28FUL, 0xE39E772C180E8603UL,
0x32905E462E36CE3BUL, 0xF1746C08CA18217CUL, 0x670C354E4ABC9804UL, 0x9ED529077096966DUL,
0x1C62F356208552BBUL, 0x83655D23DCA3AD96UL, 0x69163FA8FD24CF5FUL, 0x98DA48361C55D39AUL,
0xC2007CB8A163BF05UL, 0x49286651ECE45B3DUL, 0xAE9F24117C4B1FE6UL, 0xEE386BFB5A899FA5UL,
0x0BFF5CB6F406B7EDUL, 0xF44C42E9A637ED6BUL, 0xE485B576625E7EC6UL, 0x4FE1356D6D51C245UL,
0x302B0A6DF25F1437UL, 0xEF9519B3CD3A431BUL, 0x514A08798E3404DDUL, 0x020BBEA63B139B22UL,
0x29024E088A67CC74UL, 0xC4C6628B80DC1CD1UL, 0xC90FDAA22168C234UL, 0xFFFFFFFFFFFFFFFFUL
};
// RFC 3526: 4096-bit MODP GroupUL, this prime is: 2^4096 - 2^4032 - 1 + 2^64 * { [2^3966 pi] + 240904 }
static const BN_UINT RFC3526_PRIME_4096[] = {
0xFFFFFFFFFFFFFFFFUL, 0x4DF435C934063199UL, 0x86FFB7DC90A6C08FUL, 0x93B4EA988D8FDDC1UL,
0xD0069127D5B05AA9UL, 0xB81BDD762170481CUL, 0x1F612970CEE2D7AFUL, 0x233BA186515BE7EDUL,
0x99B2964FA090C3A2UL, 0x287C59474E6BC05DUL, 0x2E8EFC141FBECAA6UL, 0xDBBBC2DB04DE8EF9UL,
0x2583E9CA2AD44CE8UL, 0x1A946834B6150BDAUL, 0x99C327186AF4E23CUL, 0x88719A10BDBA5B26UL,
0x1A723C12A787E6D7UL, 0x4B82D120A9210801UL, 0x43DB5BFCE0FD108EUL, 0x08E24FA074E5AB31UL,
0x770988C0BAD946E2UL, 0xBBE117577A615D6CUL, 0x521F2B18177B200CUL, 0xD87602733EC86A64UL,
0xF12FFA06D98A0864UL, 0xCEE3D2261AD2EE6BUL, 0x1E8C94E04A25619DUL, 0xABF5AE8CDB0933D7UL,
0xB3970F85A6E1E4C7UL, 0x8AEA71575D060C7DUL, 0xECFB850458DBEF0AUL, 0xA85521ABDF1CBA64UL,
0xAD33170D04507A33UL, 0x15728E5A8AAAC42DUL, 0x15D2261898FA0510UL, 0x3995497CEA956AE5UL,
0xDE2BCBF695581718UL, 0xB5C55DF06F4C52C9UL, 0x9B2783A2EC07A28FUL, 0xE39E772C180E8603UL,
0x32905E462E36CE3BUL, 0xF1746C08CA18217CUL, 0x670C354E4ABC9804UL, 0x9ED529077096966DUL,
0x1C62F356208552BBUL, 0x83655D23DCA3AD96UL, 0x69163FA8FD24CF5FUL, 0x98DA48361C55D39AUL,
0xC2007CB8A163BF05UL, 0x49286651ECE45B3DUL, 0xAE9F24117C4B1FE6UL, 0xEE386BFB5A899FA5UL,
0x0BFF5CB6F406B7EDUL, 0xF44C42E9A637ED6BUL, 0xE485B576625E7EC6UL, 0x4FE1356D6D51C245UL,
0x302B0A6DF25F1437UL, 0xEF9519B3CD3A431BUL, 0x514A08798E3404DDUL, 0x020BBEA63B139B22UL,
0x29024E088A67CC74UL, 0xC4C6628B80DC1CD1UL, 0xC90FDAA22168C234UL, 0xFFFFFFFFFFFFFFFFUL
};
#elif defined(HITLS_THIRTY_TWO_BITS)
// RFC 3526: 2048-bit MODP Group, this prime is: 2^2048 - 2^1984 - 1 + 2^64 * { [2^1918 pi] + 124476 }
static const BN_UINT RFC3526_PRIME_2048[] = {
0xFFFFFFFF, 0xFFFFFFFF, 0x8AACAA68, 0x15728E5A, 0x98FA0510, 0x15D22618, 0xEA956AE5, 0x3995497C,
0x95581718, 0xDE2BCBF6, 0x6F4C52C9, 0xB5C55DF0, 0xEC07A28F, 0x9B2783A2, 0x180E8603, 0xE39E772C,
0x2E36CE3B, 0x32905E46, 0xCA18217C, 0xF1746C08, 0x4ABC9804, 0x670C354E, 0x7096966D, 0x9ED52907,
0x208552BB, 0x1C62F356, 0xDCA3AD96, 0x83655D23, 0xFD24CF5F, 0x69163FA8, 0x1C55D39A, 0x98DA4836,
0xA163BF05, 0xC2007CB8, 0xECE45B3D, 0x49286651, 0x7C4B1FE6, 0xAE9F2411, 0x5A899FA5, 0xEE386BFB,
0xF406B7ED, 0x0BFF5CB6, 0xA637ED6B, 0xF44C42E9, 0x625E7EC6, 0xE485B576, 0x6D51C245, 0x4FE1356D,
0xF25F1437, 0x302B0A6D, 0xCD3A431B, 0xEF9519B3, 0x8E3404DD, 0x514A0879, 0x3B139B22, 0x020BBEA6,
0x8A67CC74, 0x29024E08, 0x80DC1CD1, 0xC4C6628B, 0x2168C234, 0xC90FDAA2, 0xFFFFFFFF, 0xFFFFFFFF
};
// RFC 3526: 3072-bit MODP Group, this prime is: 2^3072 - 2^3008 - 1 + 2^64 * { [2^2942 pi] + 1690314 }
static const BN_UINT RFC3526_PRIME_3072[] = {
0xFFFFFFFF, 0xFFFFFFFF, 0xA93AD2CA, 0x4B82D120, 0xE0FD108E, 0x43DB5BFC, 0x74E5AB31, 0x08E24FA0,
0xBAD946E2, 0x770988C0, 0x7A615D6C, 0xBBE11757, 0x177B200C, 0x521F2B18, 0x3EC86A64, 0xD8760273,
0xD98A0864, 0xF12FFA06, 0x1AD2EE6B, 0xCEE3D226, 0x4A25619D, 0x1E8C94E0, 0xDB0933D7, 0xABF5AE8C,
0xA6E1E4C7, 0xB3970F85, 0x5D060C7D, 0x8AEA7157, 0x58DBEF0A, 0xECFB8504, 0xDF1CBA64, 0xA85521AB,
0x04507A33, 0xAD33170D, 0x8AAAC42D, 0x15728E5A, 0x98FA0510, 0x15D22618, 0xEA956AE5, 0x3995497C,
0x95581718, 0xDE2BCBF6, 0x6F4C52C9, 0xB5C55DF0, 0xEC07A28F, 0x9B2783A2, 0x180E8603, 0xE39E772C,
0x2E36CE3B, 0x32905E46, 0xCA18217C, 0xF1746C08, 0x4ABC9804, 0x670C354E, 0x7096966D, 0x9ED52907,
0x208552BB, 0x1C62F356, 0xDCA3AD96, 0x83655D23, 0xFD24CF5F, 0x69163FA8, 0x1C55D39A, 0x98DA4836,
0xA163BF05, 0xC2007CB8, 0xECE45B3D, 0x49286651, 0x7C4B1FE6, 0xAE9F2411, 0x5A899FA5, 0xEE386BFB,
0xF406B7ED, 0x0BFF5CB6, 0xA637ED6B, 0xF44C42E9, 0x625E7EC6, 0xE485B576, 0x6D51C245, 0x4FE1356D,
0xF25F1437, 0x302B0A6D, 0xCD3A431B, 0xEF9519B3, 0x8E3404DD, 0x514A0879, 0x3B139B22, 0x020BBEA6,
0x8A67CC74, 0x29024E08, 0x80DC1CD1, 0xC4C6628B, 0x2168C234, 0xC90FDAA2, 0xFFFFFFFF, 0xFFFFFFFF
};
// RFC 3526: 4096-bit MODP Group, this prime is: 2^4096 - 2^4032 - 1 + 2^64 * { [2^3966 pi] + 240904 }
static const BN_UINT RFC3526_PRIME_4096[] = {
0xFFFFFFFF, 0xFFFFFFFF, 0x34063199, 0x4DF435C9, 0x90A6C08F, 0x86FFB7DC, 0x8D8FDDC1, 0x93B4EA98,
0xD5B05AA9, 0xD0069127, 0x2170481C, 0xB81BDD76, 0xCEE2D7AF, 0x1F612970, 0x515BE7ED, 0x233BA186,
0xA090C3A2, 0x99B2964F, 0x4E6BC05D, 0x287C5947, 0x1FBECAA6, 0x2E8EFC14, 0x04DE8EF9, 0xDBBBC2DB,
0x2AD44CE8, 0x2583E9CA, 0xB6150BDA, 0x1A946834, 0x6AF4E23C, 0x99C32718, 0xBDBA5B26, 0x88719A10,
0xA787E6D7, 0x1A723C12, 0xA9210801, 0x4B82D120, 0xE0FD108E, 0x43DB5BFC, 0x74E5AB31, 0x08E24FA0,
0xBAD946E2, 0x770988C0, 0x7A615D6C, 0xBBE11757, 0x177B200C, 0x521F2B18, 0x3EC86A64, 0xD8760273,
0xD98A0864, 0xF12FFA06, 0x1AD2EE6B, 0xCEE3D226, 0x4A25619D, 0x1E8C94E0, 0xDB0933D7, 0xABF5AE8C,
0xA6E1E4C7, 0xB3970F85, 0x5D060C7D, 0x8AEA7157, 0x58DBEF0A, 0xECFB8504, 0xDF1CBA64, 0xA85521AB,
0x04507A33, 0xAD33170D, 0x8AAAC42D, 0x15728E5A, 0x98FA0510, 0x15D22618, 0xEA956AE5, 0x3995497C,
0x95581718, 0xDE2BCBF6, 0x6F4C52C9, 0xB5C55DF0, 0xEC07A28F, 0x9B2783A2, 0x180E8603, 0xE39E772C,
0x2E36CE3B, 0x32905E46, 0xCA18217C, 0xF1746C08, 0x4ABC9804, 0x670C354E, 0x7096966D, 0x9ED52907,
0x208552BB, 0x1C62F356, 0xDCA3AD96, 0x83655D23, 0xFD24CF5F, 0x69163FA8, 0x1C55D39A, 0x98DA4836,
0xA163BF05, 0xC2007CB8, 0xECE45B3D, 0x49286651, 0x7C4B1FE6, 0xAE9F2411, 0x5A899FA5, 0xEE386BFB,
0xF406B7ED, 0x0BFF5CB6, 0xA637ED6B, 0xF44C42E9, 0x625E7EC6, 0xE485B576, 0x6D51C245, 0x4FE1356D,
0xF25F1437, 0x302B0A6D, 0xCD3A431B, 0xEF9519B3, 0x8E3404DD, 0x514A0879, 0x3B139B22, 0x020BBEA6,
0x8A67CC74, 0x29024E08, 0x80DC1CD1, 0xC4C6628B, 0x2168C234, 0xC90FDAA2, 0xFFFFFFFF, 0xFFFFFFFF
};
#endif
static BN_BigNum g_bnRfc3526Prime2048 = {
false,
(uint32_t)sizeof(RFC3526_PRIME_2048) / sizeof(RFC3526_PRIME_2048[0]),
(uint32_t)sizeof(RFC3526_PRIME_2048) / sizeof(RFC3526_PRIME_2048[0]),
0,
(BN_UINT *)(uintptr_t)RFC3526_PRIME_2048
};
static BN_BigNum g_bnRfc3526Prime3072 = {
false,
(uint32_t)sizeof(RFC3526_PRIME_3072) / sizeof(RFC3526_PRIME_3072[0]),
(uint32_t)sizeof(RFC3526_PRIME_3072) / sizeof(RFC3526_PRIME_3072[0]),
0,
(BN_UINT *)(uintptr_t)RFC3526_PRIME_3072
};
static BN_BigNum g_bnRfc3526Prime4096 = {
false,
(uint32_t)sizeof(RFC3526_PRIME_4096) / sizeof(RFC3526_PRIME_4096[0]),
(uint32_t)sizeof(RFC3526_PRIME_4096) / sizeof(RFC3526_PRIME_4096[0]),
0,
(BN_UINT *)(uintptr_t)RFC3526_PRIME_4096
};
static BN_BigNum *GetBnConst(BN_BigNum *outConst, BN_BigNum *inConst)
{
if (outConst == NULL) {
return BN_Dup(inConst);
} else {
if (BN_Copy(outConst, inConst) != CRYPT_SUCCESS) {
return NULL;
}
return outConst;
}
}
BN_BigNum *BN_GetRfc3526Prime(BN_BigNum *r, uint32_t len)
{
switch (len) {
case 2048: // return 2048-bit MODP bn
return GetBnConst(r, &g_bnRfc3526Prime2048);
case 3072: // return 3072-bit MODP bn
return GetBnConst(r, &g_bnRfc3526Prime3072);
case 4096: // return 4096-bit MODP bn
return GetBnConst(r, &g_bnRfc3526Prime4096);
default:
return NULL;
}
}
#endif /* HITLS_CRYPTO_BN_PRIME_RFC3526 */
|
2301_79861745/bench_create
|
crypto/bn/src/bn_const.c
|
C
|
unknown
| 10,049
|
/*
* 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_BN
#include <stdbool.h>
#include "securec.h"
#include "bsl_sal.h"
#include "bsl_err_internal.h"
#include "crypt_errno.h"
#include "bn_basic.h"
#include "bn_bincal.h"
#include "bn_optimizer.h"
/* Euclidean algorithm */
static int32_t BnGcdDiv(BN_BigNum *r, BN_BigNum *max, BN_BigNum *min, BN_Optimizer *opt)
{
int32_t ret = CRYPT_SUCCESS;
BN_BigNum *tmp = NULL;
BN_BigNum *big = max;
BN_BigNum *small = min;
do {
ret = BN_Div(NULL, big, big, small, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (BN_IsOne(big)) {
return BN_Copy(r, big);
}
if (BN_IsZero(big)) {
return BN_Copy(r, small);
}
/* ensure that big > small in the next calculation of remainder */
tmp = big;
big = small;
small = tmp;
} while (true);
return CRYPT_SUCCESS;
}
int32_t BnGcdCheckInput(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, const BN_Optimizer *opt)
{
bool invalidInput = (a == NULL || b == NULL || r == NULL || opt == NULL);
if (invalidInput) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
/* The GCD may be the minimum value between a and b. Ensure the r space before calculation. */
uint32_t needSize = (a->size < b->size) ? a->size : b->size;
int32_t ret = BnExtend(r, needSize);
if (ret != CRYPT_SUCCESS) {
return ret;
}
// a and b cannot be 0
if (BN_IsZero(a) || BN_IsZero(b)) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_GCD_NO_ZERO);
return CRYPT_BN_ERR_GCD_NO_ZERO;
}
return CRYPT_SUCCESS;
}
int32_t BN_Gcd(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, BN_Optimizer *opt)
{
int32_t ret = BnGcdCheckInput(r, a, b, opt);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = BinCmp(a->data, a->size, b->data, b->size);
if (ret == 0) { // For example, a == b is the greatest common divisor of itself
ret = BN_Copy(r, a);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
r->sign = false; // the greatest common divisor is a positive integer
return CRYPT_SUCCESS;
}
const BN_BigNum *bigNum = (ret > 0) ? a : b;
const BN_BigNum *smallNum = (ret > 0) ? b : a;
ret = OptimizerStart(opt); // use the optimizer
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
/* Apply for temporary space of BN objects a and b. */
BN_BigNum *max = OptimizerGetBn(opt, bigNum->size);
BN_BigNum *min = OptimizerGetBn(opt, smallNum->size);
if (max == NULL || min == NULL) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
ret = BN_Copy(max, bigNum);
if (ret != CRYPT_SUCCESS) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = BN_Copy(min, smallNum);
if (ret != CRYPT_SUCCESS) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// obtain the GCD, ensure that input parameter max > min
ret = BnGcdDiv(r, max, min, opt);
if (ret == CRYPT_SUCCESS) {
r->sign = false; // The GCD is a positive integer
}
OptimizerEnd(opt); // release occupation from the optimizer
return ret;
}
static int32_t InverseReady(BN_BigNum *a, BN_BigNum *b, const BN_BigNum *x, const BN_BigNum *m, BN_Optimizer *opt)
{
int32_t ret = BN_Copy(a, m);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
a->sign = false;
ret = BN_Mod(b, x, m, opt); // b must be a positive number and do not need to convert symbols.
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (BN_IsZero(b)) { // does not satisfy x and m interprime, so it cannot obtain the inverse module.
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_NO_INVERSE);
return CRYPT_BN_ERR_NO_INVERSE;
}
return CRYPT_SUCCESS;
}
static int32_t InverseCore(BN_BigNum *r, BN_BigNum *x, BN_BigNum *y, uint32_t mSize, BN_Optimizer *opt)
{
BN_BigNum *a = x;
BN_BigNum *b = y;
BN_BigNum *c = OptimizerGetBn(opt, mSize); // One more bit is reserved for addition and subtraction.
BN_BigNum *d = OptimizerGetBn(opt, mSize);
BN_BigNum *e = OptimizerGetBn(opt, mSize * 2); // multiplication of c requires 2x space
BN_BigNum *t = OptimizerGetBn(opt, mSize);
if (c == NULL || d == NULL || e == NULL || t == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
(void)BN_SetBit(d, 0); // can ignore the return value
do {
int32_t ret = BN_Div(t, a, a, b, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (BN_IsZero(a)) {
if (BN_IsOne(b)) { // b is 1
return BN_SetLimb(r, 1); // obtains the inverse modulus value 1
}
break; // Failed to obtain the inverse modulus value.
}
t->sign = !t->sign;
ret = BN_Mul(e, t, d, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = BN_Add(c, c, e);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (BN_IsOne(a)) {
return BN_Copy(r, c); // Obtain the module inverse.
}
// Switch a b
BN_BigNum *tmp = a;
a = b;
b = tmp;
// Switch c d
tmp = c;
c = d;
d = tmp;
} while (true);
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_NO_INVERSE);
return CRYPT_BN_ERR_NO_INVERSE;
}
int32_t InverseInputCheck(BN_BigNum *r, const BN_BigNum *x, const BN_BigNum *m, const BN_Optimizer *opt)
{
bool invalidInput = (r == NULL || x == NULL || m == NULL || opt == NULL);
if (invalidInput) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
/* cannot be 0 */
if (BN_IsZero(x) || BN_IsZero(m)) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_DIVISOR_ZERO);
return CRYPT_BN_ERR_DIVISOR_ZERO;
}
return BnExtend(r, m->size);
}
int32_t BN_ModInv(BN_BigNum *r, const BN_BigNum *x, const BN_BigNum *m, BN_Optimizer *opt)
{
int32_t ret = InverseInputCheck(r, x, m, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = OptimizerStart(opt); // use the optimizer
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BN_BigNum *a = OptimizerGetBn(opt, m->size);
BN_BigNum *b = OptimizerGetBn(opt, m->size);
BN_BigNum *t = OptimizerGetBn(opt, m->size);
bool invalidInput = (a == NULL || b == NULL || t == NULL);
if (invalidInput) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
ret = CRYPT_BN_OPTIMIZER_GET_FAIL;
goto ERR;
}
/* Take positive numbers a and b first. */
ret = InverseReady(a, b, x, m, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
/* Extended Euclidean algorithm */
ret = InverseCore(t, a, b, m->size, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
// Prevent the negative number.
ret = BN_Mod(r, t, m, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
ERR:
OptimizerEnd(opt); // Release occupation from the optimizer.
return ret;
}
#endif /* HITLS_CRYPTO_BN */
|
2301_79861745/bench_create
|
crypto/bn/src/bn_gcd.c
|
C
|
unknown
| 8,304
|
/*
* 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_BN
#include <stdbool.h>
#include "securec.h"
#include "bsl_sal.h"
#include "bsl_err_internal.h"
#include "crypt_errno.h"
#include "bn_basic.h"
#include "bn_bincal.h"
#include "bn_optimizer.h"
int32_t BN_Lcm(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, BN_Optimizer *opt)
{
if (r == NULL || a == NULL || b == NULL || opt == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
BN_BigNum *gcd = BN_Create(BN_Bits(r));
if (gcd == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
int32_t ret = BN_Gcd(gcd, a, b, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
BN_Destroy(gcd);
return ret;
}
if (BN_IsOne(gcd) == false) {
ret = BN_Div(r, NULL, a, gcd, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
BN_Destroy(gcd);
return ret;
}
BN_Destroy(gcd);
return BN_Mul(r, r, b, opt);
}
BN_Destroy(gcd); // a and b are coprime.
return BN_Mul(r, a, b, opt);
}
#endif /* HITLS_CRYPTO_BN */
|
2301_79861745/bench_create
|
crypto/bn/src/bn_lcm.c
|
C
|
unknown
| 1,728
|
/*
* 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_BN
#include <stdint.h>
#include <stdbool.h>
#include "securec.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "bn_bincal.h"
#include "bn_optimizer.h"
#include "crypt_utils.h"
#include "bn_montbin.h"
// The mont contains 4 BN_UINT* fields and 2 common fields.
#define MAX_MONT_SIZE ((BITS_TO_BN_UNIT(BN_MAX_BITS) * 4 + 2) * sizeof(BN_UINT))
static void CopyConsttime(BN_UINT *dst, const BN_UINT *a, const BN_UINT *b, uint32_t len, BN_UINT mask)
{
BN_UINT rmask = ~mask;
for (uint32_t i = 0; i < len; i++) {
dst[i] = (a[i] & mask) ^ (b[i] & rmask);
}
}
/* reduce(r) */
static void MontDecBin(BN_UINT *r, BN_Mont *mont)
{
uint32_t mSize = mont->mSize;
BN_UINT *x = mont->t;
BN_COPY_BYTES(x, mSize << 1, r, mSize);
Reduce(r, x, mont->one, mont->mod, mSize, mont->k0);
}
/* Return value is (r - m0)' mod r */
static BN_UINT Inverse(BN_UINT m0)
{
BN_UINT x = 2; /* 2^1 */
BN_UINT y = 1;
BN_UINT mask = 1; /* Mask */
for (uint32_t i = 1; i < BN_UINT_BITS; i++, x <<= 1) {
BN_UINT rH, rL;
mask = (mask << 1) | 1;
MUL_AB(rH, rL, m0, y);
if (x < (rL & mask)) {
y += x;
}
(void)rH;
}
return (BN_UINT)(0 - y);
}
/* Pre-computation */
static int32_t MontExpReady(BN_BigNum *table[], uint32_t num, BN_Mont *mont, BN_Optimizer *opt, bool consttime)
{
BN_UINT *b = mont->b;
uint32_t i;
for (i = 1; i < num; i++) { /* Request num - 1 data blocks */
table[i] = OptimizerGetBn(opt, mont->mSize);
if (table[i] == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
}
table[0] = table[1];
(void)memcpy_s(table[1]->data, mont->mSize * sizeof(BN_UINT), b, mont->mSize * sizeof(BN_UINT));
for (i = 2; i < num; i++) { /* precompute num - 2 data blocks */
int32_t ret = MontMulBin(table[i]->data, table[0]->data, table[i - 1]->data, mont, opt, consttime);
if (ret != CRYPT_SUCCESS) {
return ret;
}
}
return CRYPT_SUCCESS;
}
static uint32_t GetELimb(const BN_UINT *e, BN_UINT *eLimb, uint32_t base, uint32_t bits)
{
if (bits > base) { /* Required data */
(*eLimb) = e[0] & (((1u) << base) - 1);
return base;
}
(*eLimb) = 0;
for (uint32_t i = 0; i < bits; i++) {
uint32_t bit = base - i - 1;
uint32_t nw = bit / BN_UINT_BITS; /* shift words */
uint32_t nb = bit % BN_UINT_BITS; /* shift bits */
(*eLimb) <<= 1;
(*eLimb) |= ((e[nw] >> nb) & 1);
}
return bits;
}
static uint32_t GetReadySize(uint32_t bits)
{
if (bits > 512) { /* If bits are greater than 512 */
return 6; /* The size is 6. */
}
if (bits > 256) { /* If bits are greater than 256 */
return 5; /* The size is 5. */
}
if (bits > 128) { /* If bits are greater than 128 */
return 4; /* The size is 4. */
}
if (bits > 64) { /* If bits are greater than 64 */
return 3; /* The size is 3. */
}
if (bits > 32) { /* If bits are greater than 32 */
return 2; /* The size is 2. */
}
return 1;
}
/* r = r ^ e mod mont */
static int32_t MontExpBin(BN_UINT *r, const BN_UINT *e, uint32_t eSize, BN_Mont *mont,
BN_Optimizer *opt, bool consttime)
{
BN_BigNum *table[64] = { 0 }; /* 0 -- 2^6 that is 0 -- 64 */
int32_t ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
return ret;
}
(void)memcpy_s(mont->b, mont->mSize * sizeof(BN_UINT), r, mont->mSize * sizeof(BN_UINT));
uint32_t base = BinBits(e, eSize) - 1;
uint32_t perSize = GetReadySize(base);
const uint32_t readySize = 1 << perSize;
ret = MontExpReady(table, readySize, mont, opt, consttime);
if (ret != CRYPT_SUCCESS) {
OptimizerEnd(opt);
return ret;
}
do {
BN_UINT eLimb;
uint32_t bit = GetELimb(e, &eLimb, base, perSize);
for (uint32_t i = 0; i < bit; i++) {
ret = MontSqrBin(r, mont, opt, consttime);
if (ret != CRYPT_SUCCESS) {
OptimizerEnd(opt);
return ret;
}
}
if (consttime == true) {
BN_UINT *x = mont->t;
BN_UINT mask = ~BN_IsZeroUintConsttime(eLimb);
ret = MontMulBin(x, r, table[eLimb]->data, mont, opt, consttime);
if (ret != CRYPT_SUCCESS) {
OptimizerEnd(opt);
return ret;
}
CopyConsttime(r, x, r, mont->mSize, mask);
} else if (eLimb != 0) {
ret = MontMulBin(r, r, table[eLimb]->data, mont, opt, consttime);
if (ret != CRYPT_SUCCESS) {
OptimizerEnd(opt);
return ret;
}
}
base -= bit;
} while (base != 0);
OptimizerEnd(opt);
return CRYPT_SUCCESS;
}
static int32_t MontParaCheck(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e, const BN_Mont *mont)
{
if (r == NULL || a == NULL || e == NULL || mont == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (e->sign) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_EXP_NO_NEGATIVE);
return CRYPT_BN_ERR_EXP_NO_NEGATIVE;
}
return BnExtend(r, mont->mSize);
}
static const BN_BigNum *DealBaseNum(const BN_BigNum *a, BN_Mont *mont, BN_Optimizer *opt, int32_t *ret)
{
const BN_BigNum *aTmp = a;
if (BinCmp(a->data, a->size, mont->mod, mont->mSize) >= 0) {
BN_BigNum *tmpval = OptimizerGetBn(opt, a->size + 2); // BinDiv need a->room >= a->size + 2
BN_BigNum *tmpMod = OptimizerGetBn(opt, mont->mSize); // BinDiv need a->room >= a->size + 2
if (tmpval == NULL || tmpMod == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
*ret = CRYPT_BN_OPTIMIZER_GET_FAIL;
return NULL;
}
*ret = BN_Copy(tmpval, a);
if (*ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(*ret);
return NULL;
}
(void)memcpy_s(tmpMod->data, mont->mSize * sizeof(BN_UINT), mont->mod, mont->mSize * sizeof(BN_UINT));
tmpval->size = BinDiv(NULL, NULL, tmpval->data, tmpval->size, tmpMod->data, mont->mSize);
aTmp = tmpval;
}
return aTmp;
}
static const BN_UINT *TmpValueHandle(BN_BigNum *r, const BN_BigNum *e, const BN_BigNum *a, BN_Optimizer *opt)
{
const BN_UINT *te = e->data;
uint32_t esize = e->size;
if (e == r) {
BN_BigNum *ee = OptimizerGetBn(opt, esize);
if (ee == NULL) {
return NULL;
}
(void)memcpy_s(ee->data, esize * sizeof(BN_UINT), e->data, esize * sizeof(BN_UINT));
te = ee->data;
}
BN_COPY_BYTES(r->data, r->room, a->data, a->size);
return te;
}
/* must satisfy the absolute value x < mod */
static int32_t MontExpCore(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e,
BN_Mont *mont, BN_Optimizer *opt, bool consttime)
{
if ((BinBits(e->data, e->size) == 0)) {
if (mont->mSize != 1) {
return BN_SetLimb(r, 1);
}
return (mont->mod[0] == 1) ? BN_Zeroize(r) : BN_SetLimb(r, 1);
}
if (a->size == 0) {
return BN_Zeroize(r);
}
int32_t ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
return ret;
}
/* if a >= mod */
const BN_BigNum *aTmp = DealBaseNum(a, mont, opt, &ret);
if (aTmp == NULL) {
OptimizerEnd(opt);
return ret;
}
const BN_UINT *te = TmpValueHandle(r, e, aTmp, opt);
if (te == NULL) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
/* field conversion */
ret = MontEncBin(r->data, mont, opt, consttime);
if (ret != CRYPT_SUCCESS) {
OptimizerEnd(opt);
return ret;
}
/* modular exponentiation */
ret = MontExpBin(r->data, te, e->size, mont, opt, consttime);
if (ret != CRYPT_SUCCESS) {
OptimizerEnd(opt);
return ret;
}
/* field conversion */
MontDecBin(r->data, mont);
/* negative number processing */
r->size = BinFixSize(r->data, mont->mSize);
if (aTmp->sign && ((te[0] & 0x1) == 1) && r->size != 0) {
BinSub(r->data, mont->mod, r->data, mont->mSize);
r->size = BinFixSize(r->data, mont->mSize);
}
r->sign = false;
OptimizerEnd(opt);
return CRYPT_SUCCESS;
}
static int32_t MontExp(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e, BN_Mont *mont,
BN_Optimizer *opt, bool consttime)
{
int32_t ret = MontParaCheck(r, a, e, mont);
if (ret != CRYPT_SUCCESS) {
return ret;
}
bool newOpt = (opt == NULL);
if (newOpt) {
opt = BN_OptimizerCreate();
if (opt == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
}
ret = MontExpCore(r, a, e, mont, opt, consttime);
if (newOpt) {
BN_OptimizerDestroy(opt);
}
return ret;
}
int32_t BN_MontExp(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e, BN_Mont *mont, BN_Optimizer *opt)
{
bool consttime = (BN_IsFlag(a, CRYPT_BN_FLAG_CONSTTIME) || BN_IsFlag(e, CRYPT_BN_FLAG_CONSTTIME));
return MontExp(r, a, e, mont, opt, consttime);
}
/* must satisfy the absolute value x < mod */
int32_t BN_MontExpConsttime(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e, BN_Mont *mont, BN_Optimizer *opt)
{
return MontExp(r, a, e, mont, opt, true);
}
static uint32_t MontSize(uint32_t room)
{
uint32_t size = (uint32_t)(sizeof(BN_Mont) + sizeof(BN_UINT));
/* Requires 6 * room + 1 space. mod(1) + montRR(1) + b(1) + t(2) + one = 6.
In addition, one more room is required when the modulus is set later. */
size += (room * 6 + 1) * ((uint32_t)sizeof(BN_UINT));
return size;
}
void BN_MontDestroy(BN_Mont *mont)
{
if (mont == NULL) {
return;
}
(void)memset_s(mont, MontSize(mont->mSize), 0, MontSize(mont->mSize));
BSL_SAL_FREE(mont);
}
/* set the modulus */
static void SetMod(BN_Mont *mont, const BN_BigNum *mod)
{
uint32_t mSize = mod->size;
(void)memcpy_s(mont->mod, mSize * sizeof(BN_UINT), mod->data, mSize * sizeof(BN_UINT));
(void)memset_s(mont->one, mSize * 3 * sizeof(BN_UINT), 0, mSize * 3 * sizeof(BN_UINT)); /* clear one and RR */
mont->one[0] = 1; /* set one */
mont->k0 = Inverse(mod->data[0]);
mont->montRR[mSize * 2] = 1; /* 2^2n */
mont->montRR[mSize * 2 + 1] = 0; /* 2 more rooms are provided to ensure the division does not exceed the limit */
mont->montRR[mSize * 2 + 2] = 0; /* 2 more rooms are provided to ensure the division does not exceed the limit */
// The size of the space required for calculating the montRR is 2 * mSize + 1
(void)BinDiv(NULL, NULL, mont->montRR, 2 * mSize + 1, mont->mod, mSize);
(void)memcpy_s(mont->mod, mSize * sizeof(BN_UINT), mod->data, mSize * sizeof(BN_UINT));
}
/* create a Montgomery structure, where m is a modulo */
BN_Mont *BN_MontCreate(const BN_BigNum *m)
{
if (m == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return NULL;
}
if (!BN_GetBit(m, 0) || m->sign) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return NULL;
}
uint32_t mSize = m->size;
uint32_t montSize = MontSize(mSize);
if (montSize > MAX_MONT_SIZE) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_BITS_TOO_MAX);
return NULL;
}
BN_Mont *mont = BSL_SAL_Malloc(montSize);
if (mont == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
BN_UINT *base = AlignedPointer((uint8_t *)mont + sizeof(BN_Mont), sizeof(BN_UINT));
mont->mSize = mSize;
mont->mod = base; /* mSize */
mont->one = (base += mSize); /* mSize */
mont->montRR = (base += mSize); /* mSize */
mont->b = (base += mSize); /* mSize */
mont->t = base + mSize; /* 2 * mSize */
SetMod(mont, m);
return mont;
}
int32_t MontSqrBinCore(BN_UINT *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime)
{
int32_t ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
return ret;
}
uint32_t mSize = mont->mSize;
BN_UINT *x = mont->t;
#ifdef HITLS_CRYPTO_BN_COMBA
BN_BigNum *bnSpace = OptimizerGetBn(opt, SpaceSize(mSize));
if (bnSpace == NULL) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
SqrConquer(x, r, mSize, bnSpace->data, consttime);
#else
(void)consttime;
BinSqr(x, mSize << 1, r, mSize);
#endif
Reduce(r, x, mont->one, mont->mod, mSize, mont->k0);
OptimizerEnd(opt);
return CRYPT_SUCCESS;
}
/* reduce(a)= (a * R') mod N) */
void ReduceCore(BN_UINT *r, BN_UINT *x, const BN_UINT *m, uint32_t mSize, BN_UINT m0)
{
BN_UINT carry = 0;
uint32_t n = 0;
/* Cyclic shift, obtain r = (x / R) mod N */
do {
BN_UINT q = x[n] * m0; /* q = (s[0] + x[i]) * m0 */
BN_UINT tmp = BinMulAcc(x + n, m, mSize, q); /* (s + qm) mod m == s. Refresh s[0] to x[0] */
/* Add carry to tmp and update carry flag. */
tmp = tmp + carry;
carry = (tmp < carry) ? 1 : 0;
/* Add tmp to x[mSize + n] and update the carry flag. */
x[mSize + n] += tmp;
carry = (x[mSize + n] < tmp) ? 1 : carry;
if (n + 1 == mSize) {
break;
}
n++;
} while (true);
/* If x < 2m, the carry value is 0 or -1. */
carry -= BinSub(r, x + mSize, m, mSize);
CopyConsttime(r, x + mSize, r, mSize, carry);
}
/* reduce(r * RR) */
int32_t MontEncBinCore(BN_UINT *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime)
{
int32_t ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
return ret;
}
uint32_t mSize = mont->mSize;
BN_UINT *x = mont->t;
#ifdef HITLS_CRYPTO_BN_COMBA
BN_BigNum *bnSpace = OptimizerGetBn(opt, SpaceSize(mSize));
if (bnSpace == NULL) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
MulConquer(x, r, mont->montRR, mSize, bnSpace->data, consttime);
#else
(void)consttime;
BinMul(x, mSize << 1, r, mSize, mont->montRR, mSize);
#endif
Reduce(r, x, mont->one, mont->mod, mSize, mont->k0);
OptimizerEnd(opt);
return CRYPT_SUCCESS;
}
/* reduce(r * b) */
int32_t MontMulBinCore(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, BN_Mont *mont, BN_Optimizer *opt, bool consttime)
{
int32_t ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
return ret;
}
uint32_t mSize = mont->mSize;
BN_UINT *x = mont->t;
#ifdef HITLS_CRYPTO_BN_COMBA
uint32_t size = SpaceSize(mSize);
BN_BigNum *bnSpace = OptimizerGetBn(opt, size);
if (bnSpace == NULL) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
MulConquer(x, a, b, mSize, bnSpace->data, consttime);
#else
(void)consttime;
BinMul(x, mSize << 1, a, mSize, b, mSize);
#endif
Reduce(r, x, mont->one, mont->mod, mSize, mont->k0);
OptimizerEnd(opt);
return CRYPT_SUCCESS;
}
#ifdef HITLS_CRYPTO_DSA
static int32_t GetFirstData(BN_UINT *r, uint32_t base1, uint32_t base2,
BN_BigNum *table1[], BN_BigNum *table2[], BN_Mont *mont,
BN_Optimizer *opt)
{
bool consttime = false;
if (base1 == base2) {
return MontMulBin(r, table1[0]->data, table2[0]->data, mont, opt, consttime);
} else if (base1 > base2) {
(void)memcpy_s(r, mont->mSize * sizeof(BN_UINT), table1[0]->data, mont->mSize * sizeof(BN_UINT));
} else {
(void)memcpy_s(r, mont->mSize * sizeof(BN_UINT), table2[0]->data, mont->mSize * sizeof(BN_UINT));
}
return CRYPT_SUCCESS;
}
/* Precalculate odd multiples of data. The data in the table is b^1, b^3, b^5...b^(2*num - 1) */
static int32_t MontExpOddReady(BN_BigNum *table[], uint32_t num, BN_Mont *mont, BN_Optimizer *opt, bool consttime)
{
BN_UINT *b = mont->b;
uint32_t i;
for (i = 0; i < num; i++) { /* Request num - 1 data blocks */
table[i] = OptimizerGetBn(opt, mont->mSize);
if (table[i] == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
}
(void)memcpy_s(table[0]->data, mont->mSize * sizeof(BN_UINT), b, mont->mSize * sizeof(BN_UINT));
if (num == 1) {
// When num is 1, pre-computation is not need.
return CRYPT_SUCCESS;
}
int32_t ret = MontSqrBin(table[0]->data, // b^2
mont, opt, consttime);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = MontMulBin(table[1]->data, table[0]->data, mont->b, // b^3
mont, opt, consttime);
if (ret != CRYPT_SUCCESS) {
return ret;
}
for (i = 2; i < num; i++) { /* precompute num - 2 data blocks */
// b^(2*i + 1)
ret = MontMulBin(table[i]->data, table[0]->data, table[i - 1]->data, mont, opt, consttime);
if (ret != CRYPT_SUCCESS) {
return ret;
}
}
(void)memcpy_s(table[0]->data, mont->mSize * sizeof(BN_UINT), b, mont->mSize * sizeof(BN_UINT));
return CRYPT_SUCCESS;
}
// Obtain the data with the length of bits from the start position of the base to the eLimb,
// ignore the high-order 0 data, and obtain an odd number or 0.
uint32_t GetOddLimbBin(const BN_UINT *e, BN_UINT *eLimb, uint32_t base, uint32_t bits, uint32_t size)
{
(*eLimb) = 0;
if (base == 0) {
return 0;
}
uint32_t loc = base;
uint32_t retBits = 0;
// Offset from current. Check whether non-zero data exists.
while (true) {
loc--;
uint32_t nw = loc / BN_UINT_BITS; /* shift words */
uint32_t nb = loc % BN_UINT_BITS; /* shift retBits */
if (nw < size && ((e[nw] >> nb) & 1) != 0) {
// Exit the loop when the bit is 1.
break;
}
retBits++;
if (loc == 0) {
// If no valid bit is encountered until the end, the subsequent bits are returned.
return retBits;
}
}
// Obtain valid data from the loc location.
for (uint32_t i = 0; i < bits; i++) {
uint32_t nw = loc / BN_UINT_BITS; /* shift words */
uint32_t nb = loc % BN_UINT_BITS; /* shift retBits */
(*eLimb) <<= 1;
(*eLimb) |= ((e[nw] >> nb) & 1);
retBits++;
if (loc == 0) {
// The remaining data is insufficient and the system exits early.
break;
}
loc--;
}
// The data must be 0 or an odd number.
while ((*eLimb) != 0 && ((*eLimb) & 1) == 0) {
// If eLimb is not 0 and is an even number, shift the eLimb to right.
(*eLimb) >>= 1;
retBits--;
}
return retBits;
}
/* r = (a1 ^ e1) * (a2 ^ e2) mod mont */
static int32_t MontExpMul(BN_UINT *r, const BN_BigNum *a1, const BN_BigNum *e1,
const BN_BigNum *a2, const BN_BigNum *e2, BN_Mont *mont, BN_Optimizer *opt)
{
bool consttime = false;
BN_UINT eLimb1, eLimb2;
uint32_t bit1 = 0;
uint32_t bit2 = 0;
// The window retains only the values whose exponent is an odd number, reduce storage in half.
BN_BigNum *table1[32] = { 0 }; /* 0 -- (2^6 >> 1), that is 0 -- 32 */
BN_BigNum *table2[32] = { 0 }; /* 0 -- (2^6 >> 1), that is 0 -- 32 */
int32_t ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
uint32_t base1 = BinBits(e1->data, e1->size);
uint32_t base2 = BinBits(e2->data, e2->size);
uint32_t base = (base1 > base2) ? base1 : base2;
uint32_t perSize1 = GetReadySize(base1);
uint32_t perSize2 = GetReadySize(base2);
const uint32_t readySize1 = 1 << (perSize1 - 1);
const uint32_t readySize2 = 1 << (perSize2 - 1);
// Generate the pre-computation table.
(void)memcpy_s(mont->b, mont->mSize * sizeof(BN_UINT), a1->data, mont->mSize * sizeof(BN_UINT));
GOTO_ERR_IF(MontExpOddReady(table1, readySize1, mont, opt, consttime), ret);
(void)memcpy_s(mont->b, mont->mSize * sizeof(BN_UINT), a2->data, mont->mSize * sizeof(BN_UINT));
GOTO_ERR_IF(MontExpOddReady(table2, readySize2, mont, opt, consttime), ret);
// Obtain the first data.
GOTO_ERR_IF(GetFirstData(r, base1, base2, table1, table2, mont, opt), ret);
base--;
while (base != 0) {
bit1 = (bit1 == 0) ? GetOddLimbBin(e1->data, &eLimb1, base, perSize1, e1->size) : bit1;
bit2 = (bit2 == 0) ? GetOddLimbBin(e2->data, &eLimb2, base, perSize2, e2->size) : bit2;
uint32_t bit = (bit1 < bit2) ? bit1 : bit2;
for (uint32_t i = 0; i < bit; i++) {
GOTO_ERR_IF(MontSqrBin(r, mont, opt, consttime), ret);
}
if (bit == bit1 && eLimb1 != 0) {
GOTO_ERR_IF(MontMulBin(r, r, table1[(eLimb1 - 1) >> 1]->data, mont, opt, consttime), ret);
}
if (bit == bit2 && eLimb2 != 0) {
GOTO_ERR_IF(MontMulBin(r, r, table2[(eLimb2 - 1) >> 1]->data, mont, opt, consttime), ret);
}
bit1 -= bit;
bit2 -= bit;
base -= bit;
};
ERR:
OptimizerEnd(opt);
return ret;
}
static int32_t MontExpMulParaCheck(BN_BigNum *r, const BN_BigNum *a1,
const BN_BigNum *e1, const BN_BigNum *a2, const BN_BigNum *e2, const BN_Mont *mont,
const BN_Optimizer *opt)
{
if (r == NULL || a1 == NULL || e1 == NULL || a2 == NULL || e2 == NULL || mont == NULL || opt == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (e1->sign || e2->sign) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_EXP_NO_NEGATIVE);
return CRYPT_BN_ERR_EXP_NO_NEGATIVE;
}
return BnExtend(r, mont->mSize);
}
typedef struct {
BN_BigNum *a1;
BN_BigNum *a2;
BN_BigNum *e1;
BN_BigNum *e2;
} MontsMulFactor;
static int32_t MontsFactorGetByOptThenCopy(MontsMulFactor *dst, const MontsMulFactor *src,
uint32_t mSize, BN_Optimizer *opt)
{
dst->a1 = OptimizerGetBn(opt, mSize);
dst->a2 = OptimizerGetBn(opt, mSize);
dst->e1 = OptimizerGetBn(opt, mSize);
dst->e2 = OptimizerGetBn(opt, mSize);
if (dst->a1 == NULL || dst->a2 == NULL || dst->e1 == NULL || dst->e2 == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
int32_t ret = BN_Copy(dst->a1, src->a1);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = BN_Copy(dst->a2, src->a2);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = BN_Copy(dst->e1, src->e1);
if (ret != CRYPT_SUCCESS) {
return ret;
}
return BN_Copy(dst->e2, src->e2);
}
/* r = (a1 ^ e1) * (a2 ^ e2) mod mont */
int32_t BN_MontExpMul(BN_BigNum *r, const BN_BigNum *a1, const BN_BigNum *e1,
const BN_BigNum *a2, const BN_BigNum *e2, BN_Mont *mont, BN_Optimizer *opt)
{
int32_t ret = MontExpMulParaCheck(r, a1, e1, a2, e2, mont, opt);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if (BinCmp(a2->data, a2->size, mont->mod, mont->mSize) >= 0 ||
BinCmp(a1->data, a1->size, mont->mod, mont->mSize) >= 0) {
/* a1 >= mod || a2 >= mod */
BSL_ERR_PUSH_ERROR(CRYPT_BN_MONT_BASE_TOO_MAX);
return CRYPT_BN_MONT_BASE_TOO_MAX;
}
if (BN_IsZero(a1) || BN_IsZero(a2)) {
return BN_Zeroize(r);
}
if (BN_IsZero(e1)) {
return MontExpCore(r, a2, e2, mont, opt, false);
}
if (BN_IsZero(e2)) {
return MontExpCore(r, a1, e1, mont, opt, false);
}
ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
MontsMulFactor factor;
const MontsMulFactor srcFactor = {(BN_BigNum *)(uintptr_t)a1, (BN_BigNum *)(uintptr_t)a2,
(BN_BigNum *)(uintptr_t)e1, (BN_BigNum *)(uintptr_t)e2};
GOTO_ERR_IF_EX(MontsFactorGetByOptThenCopy(&factor, &srcFactor, mont->mSize, opt), ret);
/* field conversion */
GOTO_ERR_IF(MontEncBin(factor.a1->data, mont, opt, false), ret);
GOTO_ERR_IF(MontEncBin(factor.a2->data, mont, opt, false), ret);
/* modular exponentiation */
GOTO_ERR_IF_EX(MontExpMul(r->data, factor.a1, factor.e1, factor.a2, factor.e2, mont, opt), ret);
/* field conversion */
MontDecBin(r->data, mont);
r->size = BinFixSize(r->data, mont->mSize);
r->sign = false;
ERR:
OptimizerEnd(opt);
return ret;
}
#endif
#if defined(HITLS_CRYPTO_RSA)
int32_t MontMulCore(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, BN_Mont *mont, BN_Optimizer *opt)
{
int32_t ret;
BN_BigNum *t1 = OptimizerGetBn(opt, mont->mSize);
if (t1 == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
BN_COPY_BYTES(t1->data, mont->mSize, a->data, a->size);
BN_COPY_BYTES(r->data, mont->mSize, b->data, b->size);
GOTO_ERR_IF(MontEncBin(t1->data, mont, opt, false), ret);
GOTO_ERR_IF(MontEncBin(r->data, mont, opt, false), ret);
GOTO_ERR_IF(MontMulBin(r->data, t1->data, r->data, mont, opt, false), ret);
MontDecBin(r->data, mont);
r->size = BinFixSize(r->data, mont->mSize);
ERR:
return ret;
}
#endif // HITLS_CRYPTO_RSA
#if defined(HITLS_CRYPTO_BN_PRIME)
int32_t MontSqrCore(BN_BigNum *r, const BN_BigNum *a, BN_Mont *mont, BN_Optimizer *opt)
{
int32_t ret;
BN_COPY_BYTES(r->data, mont->mSize, a->data, a->size);
GOTO_ERR_IF(MontEncBin(r->data, mont, opt, false), ret);
GOTO_ERR_IF(MontSqrBin(r->data, mont, opt, false), ret);
MontDecBin(r->data, mont);
r->size = BinFixSize(r->data, mont->mSize);
ERR:
return ret;
}
#endif // HITLS_CRYPTO_BN_PRIME
#ifdef HITLS_CRYPTO_CURVE_MONT
int32_t BnMontEnc(BN_BigNum *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime)
{
int32_t ret;
GOTO_ERR_IF(MontEncBin(r->data, mont, opt, consttime), ret);
r->size = BinFixSize(r->data, mont->mSize);
ERR:
return ret;
}
void BnMontDec(BN_BigNum *r, BN_Mont *mont)
{
MontDecBin(r->data, mont);
r->size = BinFixSize(r->data, mont->mSize);
}
int32_t BN_EcPrimeMontSqr(BN_BigNum *r, const BN_BigNum *a, void *data, BN_Optimizer *opt)
{
if (r == NULL || a == NULL || data == NULL || opt == NULL) {
BSL_ERR_PUSH_ERROR((CRYPT_NULL_INPUT));
return CRYPT_NULL_INPUT;
}
int32_t ret;
BN_Mont *mont = (BN_Mont *)data;
BN_COPY_BYTES(r->data, mont->mSize, a->data, a->size);
GOTO_ERR_IF(MontSqrBin(r->data, mont, opt, false), ret);
r->size = BinFixSize(r->data, mont->mSize);
ERR:
return ret;
}
int32_t BN_EcPrimeMontMul(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, void *data, BN_Optimizer *opt)
{
if (r == NULL || a == NULL || b == NULL || data == NULL || opt == NULL) {
BSL_ERR_PUSH_ERROR((CRYPT_NULL_INPUT));
return CRYPT_NULL_INPUT;
}
int32_t ret;
BN_Mont *mont = (BN_Mont *)data;
GOTO_ERR_IF(MontMulBin(r->data, a->data, b->data, mont, opt, false), ret);
r->size = BinFixSize(r->data, mont->mSize);
ERR:
return ret;
}
#endif // HITLS_CRYPTO_CURVE_MONT
#endif /* HITLS_CRYPTO_BN */
|
2301_79861745/bench_create
|
crypto/bn/src/bn_mont.c
|
C
|
unknown
| 27,907
|
/*
* 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 BN_MONTBIN_H
#define BN_MONTBIN_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_BN
#include <stdint.h>
#include "crypt_bn.h"
#ifdef __cplusplus
extern "c" {
#endif
/* r = reduce(r * r) mod mont */
int32_t MontSqrBin(BN_UINT *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime);
/* r = reduce(a * b) mod mont */
int32_t MontMulBin(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, BN_Mont *mont,
BN_Optimizer *opt, bool consttime);
/* r = reduce(r * montRR) mod mont */
int32_t MontEncBin(BN_UINT *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime);
/* r = reduce(x * 1) mod m = (x * R') mod m */
void Reduce(BN_UINT *r, BN_UINT *x, const BN_UINT *one, const BN_UINT *m, uint32_t mSize, BN_UINT m0);
#ifdef __cplusplus
}
#endif
#endif /* HITLS_CRYPTO_BN */
#endif
|
2301_79861745/bench_create
|
crypto/bn/src/bn_montbin.h
|
C
|
unknown
| 1,328
|
/*
* 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_BN) && defined(HITLS_CRYPTO_ECC)
#include "securec.h"
#include "bsl_sal.h"
#include "bsl_err_internal.h"
#include "crypt_errno.h"
#include "bn_bincal.h"
// Refresh the valid length of the BigNum r. The maximum length is modSize.
static void UpdateSize(BN_BigNum *r, uint32_t modSize)
{
uint32_t size = modSize;
while (size > 0) {
if (r->data[size - 1] != 0) {
break;
}
size--;
}
if (r->size > modSize) {
// Clear the high bits.
uint32_t i = 0;
for (i = modSize; i < r->size; i++) {
r->data[i] = 0;
}
}
r->size = size;
r->sign = false;
}
#define P521SIZE SIZE_OF_BNUINT(521)
#define SIZE_OF_BNUINT(bits) (((bits) + BN_UINT_BITS - 1) / BN_UINT_BITS) // 1byte = 8bit
#if defined(HITLS_SIXTY_FOUR_BITS)
#define P224SIZE SIZE_OF_BNUINT(224)
#define P256SIZE SIZE_OF_BNUINT(256)
#define P384SIZE SIZE_OF_BNUINT(384)
BN_UINT g_modDataP224[][P224SIZE] = {
{ // 1p
0x0000000000000001UL, 0xffffffff00000000UL,
0xffffffffffffffffUL, 0x00000000ffffffffUL
},
{ // 2p
0x0000000000000002UL, 0xfffffffe00000000UL,
0xffffffffffffffffUL, 0x00000001ffffffffUL
}
};
BN_UINT g_modDataP256[][P256SIZE] = {
{ // p
0xffffffffffffffffUL, 0x00000000ffffffffUL,
0x0000000000000000UL, 0xffffffff00000001UL
},
{ // 2p
0xfffffffffffffffeUL, 0x00000001ffffffffUL,
0x0000000000000000UL, 0xfffffffe00000002UL
},
{ // 3p
0xfffffffffffffffdUL, 0x00000002ffffffffUL,
0x0000000000000000UL, 0xfffffffd00000003UL
},
{ // 4p
0xfffffffffffffffcUL, 0x00000003ffffffffUL,
0x0000000000000000UL, 0xfffffffc00000004UL
},
{ // 5p
0xfffffffffffffffbUL, 0x00000004ffffffffUL,
0x0000000000000000UL, 0xfffffffb00000005UL
},
};
#ifdef HITLS_CRYPTO_CURVE_SM2
const BN_UINT MODDATASM2P256[][P256SIZE] = {
{ // p
0xffffffffffffffffUL, 0xffffffff00000000UL,
0xffffffffffffffffUL, 0xfffffffeffffffffUL
},
{ // 2p
0xfffffffffffffffeUL, 0xfffffffe00000001UL,
0xffffffffffffffffUL, 0xfffffffdffffffffUL
},
{ // 3p
0xfffffffffffffffdUL, 0xfffffffd00000002UL,
0xffffffffffffffffUL, 0xfffffffcffffffffUL
},
{ // 4p
0xfffffffffffffffcUL, 0xfffffffc00000003UL,
0xffffffffffffffffUL, 0xfffffffbffffffffUL
},
{ // 5p
0xfffffffffffffffbUL, 0xfffffffb00000004UL,
0xffffffffffffffffUL, 0xfffffffaffffffffUL
},
{ // 6p
0xfffffffffffffffaUL, 0xfffffffa00000005UL,
0xffffffffffffffffUL, 0xfffffff9ffffffffUL
},
{ // 7p
0xfffffffffffffff9UL, 0xfffffff900000006UL,
0xffffffffffffffffUL, 0xfffffff8ffffffffUL
},
{ // 8p
0xfffffffffffffff8UL, 0xfffffff800000007UL,
0xffffffffffffffffUL, 0xfffffff7ffffffffUL
},
{ // 9p
0xfffffffffffffff7UL, 0xfffffff700000008UL,
0xffffffffffffffffUL, 0xfffffff6ffffffffUL
},
{ // 10p
0xfffffffffffffff6UL, 0xfffffff600000009UL,
0xffffffffffffffffUL, 0xfffffff5ffffffffUL
},
{ // 11p
0xfffffffffffffff5UL, 0xfffffff50000000aUL,
0xffffffffffffffffUL, 0xfffffff4ffffffffUL
},
{ // 12p
0xfffffffffffffff4UL, 0xfffffff40000000bUL,
0xffffffffffffffffUL, 0xfffffff3ffffffffUL
},
{ // 13p
0xfffffffffffffff3UL, 0xfffffff30000000cUL,
0xffffffffffffffffUL, 0xfffffff2ffffffffUL
},
};
#endif
const BN_UINT MOD_DATA_P384[][P384SIZE] = {
{
0x00000000ffffffffUL, 0xffffffff00000000UL, 0xfffffffffffffffeUL,
0xffffffffffffffffUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL
},
{
0x00000001fffffffeUL, 0xfffffffe00000000UL, 0xfffffffffffffffdUL,
0xffffffffffffffffUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL
},
{
0x00000002fffffffdUL, 0xfffffffd00000000UL, 0xfffffffffffffffcUL,
0xffffffffffffffffUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL
},
{
0x00000003fffffffcUL, 0xfffffffc00000000UL, 0xfffffffffffffffbUL,
0xffffffffffffffffUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL
},
{
0x00000004fffffffbUL, 0xfffffffb00000000UL, 0xfffffffffffffffaUL,
0xffffffffffffffffUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL
},
};
const BN_UINT MOD_DATA_P521[P521SIZE] = {
0xffffffffffffffffUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL,
0xffffffffffffffffUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL,
0xffffffffffffffffUL, 0xffffffffffffffffUL, 0x00000000000001ffUL
};
static BN_UINT NistP384Add(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t n)
{
(void)n;
BN_UINT carry = 0;
ADD_ABC(carry, r[0], a[0], b[0], carry); /* offset 0 */
ADD_ABC(carry, r[1], a[1], b[1], carry); /* offset 1 */
ADD_ABC(carry, r[2], a[2], b[2], carry); /* offset 2 */
ADD_ABC(carry, r[3], a[3], b[3], carry); /* offset 3 */
ADD_ABC(carry, r[4], a[4], b[4], carry); /* offset 4 */
ADD_ABC(carry, r[5], a[5], b[5], carry); /* offset 5 */
return carry;
}
static BN_UINT NistP384Sub(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t n)
{
(void)n;
BN_UINT borrow = 0;
SUB_ABC(borrow, r[0], a[0], b[0], borrow); /* offset 0 */
SUB_ABC(borrow, r[1], a[1], b[1], borrow); /* offset 1 */
SUB_ABC(borrow, r[2], a[2], b[2], borrow); /* offset 2 */
SUB_ABC(borrow, r[3], a[3], b[3], borrow); /* offset 3 */
SUB_ABC(borrow, r[4], a[4], b[4], borrow); /* offset 4 */
SUB_ABC(borrow, r[5], a[5], b[5], borrow); /* offset 5 */
return borrow;
}
/**
* Reduction item: 2^128 + 2^96 - 2^32+ 2^0
*
* Reduction list 11 10 9 8 7 6 5 4 3 2 1 0
* a12 00, 00, 00, 00, 00, 00, 00, 01, 01, 00, -1, 01,
* a13 00, 00, 00, 00, 00, 00, 01, 01, 00, -1, 01, 00,
* a14 00, 00, 00, 00, 00, 01, 01, 00, -1, 01, 00, 00,
* a15 00, 00, 00, 00, 01, 01, 00, -1, 01, 00, 00, 00,
* a16 00, 00, 00, 01, 01, 00, -1, 01, 00, 00, 00, 00,
* a17 00, 00, 01, 01, 00, -1, 01, 00, 00, 00, 00, 00,
* a18 00, 01, 01, 00, -1, 01, 00, 00, 00, 00, 00, 00,
* a19 01, 01, 00, -1, 01, 00, 00, 00, 00, 00, 00, 00,
* a20 01, 00, -1, 01, 00, 00, 00, 01, 01, 00, -1, 01,
* a21 00, -1, 01, 00, 00, 00, 01, 02, 01, -1, 00, 01,
* a22 -1, 01, 00, 00, 00, 01, 02, 01, -1, 00, 01, 00,
* a23 01, 00, 00, 00, 01, 02, 01, -2, -1, 01, 01, -1
*
* Reduction chain
* Coefficient 11 10 9 8 7 6 5 4 3 2 1 0
* 1 a23 a22 a21 a20 a19 a18 a17 a16 a15 a14 a13 a12
* 1 a20 a19 a18 a17 a16 a15 a14 a13 a12 a23 a22 a21
* 1 a19 a18 a17 a16 a15 a14 a13 a12 a20 a23 a20
* 1 a23 a22 a21 a20 a21
* 1 a23 a22
* 2 a23 a22 a21
* -1 a22 a21 a20 a19 a18 a17 a16 a15 a14 a13 a12 a23
* -1 a23 a22 a21 a20
* -1 a23 a23
*/
int8_t ReduceNistP384(BN_UINT *r, const BN_UINT *a)
{
BN_UINT list[P384SIZE];
BN_UINT t[P384SIZE];
// 0
list[5] = a[11]; // offset 5 a23|a22 == ah[11]|al[11]
list[4] = a[10]; // offset 4 a21|a20 == ah[10]|al[10]
list[3] = a[9]; // offset 3 a19|a18 == ah[9]|al[9]
list[2] = a[8]; // offset 2 a17|a16 == ah[8]|al[8]
list[1] = a[7]; // offset 1 a15|a14 == ah[7]|al[7]
list[0] = a[6]; // offset 0 a13|a12 == ah[6]|al[6]
// 1
t[5] = BN_UINT_LO_TO_HI(a[10]) | BN_UINT_HI(a[9]); // offset 5 a20|a19 == al[10]|ah[9]
t[4] = BN_UINT_LO_TO_HI(a[9]) | BN_UINT_HI(a[8]); // offset 4 a18|a17 == al[9]|ah[8]
t[3] = BN_UINT_LO_TO_HI(a[8]) | BN_UINT_HI(a[7]); // offset 3 a16|a15 == al[8]|ah[7]
t[2] = BN_UINT_LO_TO_HI(a[7]) | BN_UINT_HI(a[6]); // offset 2 a14|a13 == al[7]|ah[6]
t[1] = BN_UINT_LO_TO_HI(a[6]) | BN_UINT_HI(a[11]); // offset 1 a12|a23 == al[6]|ah[11]
t[0] = BN_UINT_LO_TO_HI(a[11]) | BN_UINT_HI(a[10]); // offset 0 a22|a21 == al[11]|ah[10]
int8_t carry = (int8_t)NistP384Add(t, list, t, P384SIZE);
// 2
list[5] = a[9]; // offset 5 a19|a18 == ah[9]|al[9]
list[4] = a[8]; // offset 4 a17|a16 == ah[8]|al[8]
list[3] = a[7]; // offset 3 a15|a14 == ah[7]|al[7]
list[2] = a[6]; // offset 2 a13|a12 == ah[6]|al[6]
list[1] = BN_UINT_LO_TO_HI(a[10]); // offset 1 a20|0 == al[10]| 0
list[0] = BN_UINT_HI_TO_HI(a[11]) | BN_UINT_LO(a[10]); // offset 0 a23|a20 == ah[11]|al[10]
carry += (int8_t)NistP384Add(t, list, t, P384SIZE);
// 3
list[5] = 0; // offset 5 0
list[4] = 0; // offset 4 0
list[3] = a[11]; // offset 3 a23|a22 == ah[11]|al[11]
list[2] = a[10]; // offset 2 a21|a20 == ah[10]|al[10]
list[1] = BN_UINT_HI_TO_HI(a[10]); // offset 1 a21|0 == ah[10]|0
list[0] = 0; // offset 0 0
carry += (int8_t)NistP384Add(t, list, t, P384SIZE);
// 4
list[5] = 0; // offset 5 0
list[4] = 0; // offset 4 0
list[3] = 0; // offset 3 0
list[2] = a[11]; // offset 2 a23|a22 == ah[11]|al[11]
list[1] = 0; // offset 1 0
list[0] = 0; // offset 0 0
carry += (int8_t)NistP384Add(t, list, t, P384SIZE);
// 5
list[5] = 0; // offset 5 0
list[4] = 0; // offset 4 0
list[3] = BN_UINT_HI(a[11]); // offset 3 0|a23 == 0|ah[11]
list[2] = BN_UINT_LO_TO_HI(a[11]) | BN_UINT_HI(a[10]); // offset 2 a22|a21 == al[11]|ah[10]
list[1] = 0; // offset 1 0
list[0] = 0; // offset 0 0
// double 5
// list[3] is left-shifted by 1 bit and the most significant bit of list[2] is added.
list[3] = (list[2] >> (BN_UINT_BITS - 1)) | (list[3] << 1);
list[2] = list[2] << 1; // list[2] left-shifted by 1bit
carry += (int8_t)NistP384Add(t, list, t, P384SIZE);
// 6
list[5] = BN_UINT_LO_TO_HI(a[11]) | BN_UINT_HI(a[10]); // offset 5 a22|a21 == al[11]|ah[10]
list[4] = BN_UINT_LO_TO_HI(a[10]) | BN_UINT_HI(a[9]); // offset 4 a20|a19 == al[10]|ah[9]
list[3] = BN_UINT_LO_TO_HI(a[9]) | BN_UINT_HI(a[8]); // offset 3 a18|a17 == al[9]|ah[8]
list[2] = BN_UINT_LO_TO_HI(a[8]) | BN_UINT_HI(a[7]); // offset 2 a16|a15 == al[8]|ah[7]
list[1] = BN_UINT_LO_TO_HI(a[7]) | BN_UINT_HI(a[6]); // offset 1 a14|a13 == al[7]|ah[6]
list[0] = BN_UINT_LO_TO_HI(a[6]) | BN_UINT_HI(a[11]); // offset 0 a12|a23 == al[6]|ah[11]
carry -= (int8_t)NistP384Sub(t, t, list, P384SIZE);
// 7
list[5] = 0; // offset 5 0
list[4] = 0; // offset 4 0
list[3] = 0; // offset 3 0
list[2] = BN_UINT_HI(a[11]); // offset 2 0|a23 == 0|ah[11]
list[1] = BN_UINT_LO_TO_HI(a[11]) | BN_UINT_HI(a[10]); // offset 1 a22|a21 == al[11]|ah[10]
list[0] = BN_UINT_LO_TO_HI(a[10]); // offset 0 a20|0 == al[10]|0
carry -= (int8_t)NistP384Sub(t, t, list, P384SIZE);
// 8
list[5] = 0; // offset 5 0
list[4] = 0; // offset 4 0
list[3] = 0; // offset 3 0
list[2] = BN_UINT_HI(a[11]); // offset 2 0|a23 == 0|ah[11]
list[1] = BN_UINT_HI_TO_HI(a[11]); // offset 1 a23|0 == ah[11]|0
list[0] = 0; // offset 0
carry -= (int8_t)NistP384Sub(t, t, list, P384SIZE);
carry += (int8_t)NistP384Add(r, t, a, P384SIZE);
return carry;
}
// The size of a is 2*P384SIZE, and the size of r is P384SIZE
int32_t ModNistP384(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt)
{
(void)opt;
(void)m;
const BN_UINT *mod = MOD_DATA_P384[0];
int8_t carry = ReduceNistP384(r->data, a->data);
if (carry > 0) {
carry = (int8_t)1 - (int8_t)BinSub(r->data, r->data, MOD_DATA_P384[carry - 1], P384SIZE);
} else if (carry < 0) {
// For details could ref p256.
carry = (int8_t)1 - (int8_t)BinAdd(r->data, r->data, MOD_DATA_P384[-carry - 1], P384SIZE);
carry = -carry;
}
if (carry < 0) {
BinAdd(r->data, r->data, mod, P384SIZE);
} else if (carry > 0 || BinCmp(r->data, P384SIZE, mod, P384SIZE) >= 0) {
BinSub(r->data, r->data, mod, P384SIZE);
}
UpdateSize(r, P384SIZE);
return 0;
}
// Reduction item: 2^0
int8_t ReduceNistP521(BN_UINT *r, const BN_UINT *a)
{
#define P521LEFTBITS (521 % (sizeof(BN_UINT) * 8))
#define P521RIGHTBITS ((sizeof(BN_UINT) * 8) - P521LEFTBITS)
BN_UINT t[P521SIZE];
uint32_t base = P521SIZE - 1;
uint32_t i;
for (i = 0; i < P521SIZE - 1; i++) {
t[i] = (a[i + base] >> P521LEFTBITS) | (a[i + base + 1] << P521RIGHTBITS);
r[i] = a[i];
}
r[i] = a[i] & (((BN_UINT)1 << (P521LEFTBITS)) - 1);
t[i] = (a[i + base] >> P521LEFTBITS);
BinAdd(r, t, r, P521SIZE);
return 0;
}
// The size of a is 2*P521SIZE-1, and the size of r is P521SIZE
int32_t ModNistP521(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt)
{
(void)opt;
(void)m;
const BN_UINT *mod = MOD_DATA_P521;
ReduceNistP521(r->data, a->data);
if (BinCmp(r->data, P521SIZE, mod, P521SIZE) >= 0) {
BinSub(r->data, r->data, mod, P521SIZE);
}
UpdateSize(r, P521SIZE);
return 0;
}
static inline int8_t P256SUB(BN_UINT *rr, const BN_UINT *aa, const BN_UINT *bb)
{
BN_UINT borrow;
SUB_AB(borrow, rr[0], aa[0], bb[0]);
SUB_ABC(borrow, rr[1], aa[1], bb[1], borrow); /* offset 1 */
SUB_ABC(borrow, rr[2], aa[2], bb[2], borrow); /* offset 2 */
SUB_ABC(borrow, rr[3], aa[3], bb[3], borrow); /* offset 3 */
return (int8_t)borrow;
}
static inline int8_t P256ADD(BN_UINT *rr, const BN_UINT *aa, const BN_UINT *bb)
{
BN_UINT carry;
ADD_AB(carry, rr[0], aa[0], bb[0]); /* offset 0 */
ADD_ABC(carry, rr[1], aa[1], bb[1], carry); /* offset 1 */
ADD_ABC(carry, rr[2], aa[2], bb[2], carry); /* offset 2 */
ADD_ABC(carry, rr[3], aa[3], bb[3], carry); /* offset 3 */
return (int8_t)carry;
}
/**
* NIST_P256 curve reduction calculation for parameter P
* Reduction item: 2^224 - 2^192 - 2^96 + 2^0
* ref. https://csrc.nist.gov/csrc/media/events/workshop-on-elliptic-curve-cryptography-standards/documents/papers/session6-adalier-mehmet.pdf
*
* Reduction list:
* 7 6 5 4 3 2 1 0
* a8 01, -1, 00, 00, -1, 00, 00, 01,
* a9 00, -1, 00, -1, -1, 00, 01, 01,
* a10 -1, 00, -1, -1, 00, 01, 01, 00,
* a11 -1, 00, -1, 00, 02, 01, 00, -1,
* a12 -1, 00, 00, 02, 02, 00, -1, -1,
* a13 -1, 01, 02, 02, 01, -1, -1, -1,
* a14 00, 03, 02, 01, 00, -1, -1, -1,
* a15 03, 02, 01, 00, -1, -1, -1, 00
*
* Reduction chain
* Compared with the reduce flow of the paper, we have made proper transformation,
* which can reduce the splicing of upper 32 bits and lower 32 bits.
* Coefficient 7 6 5 4 3 2 1 0
* 2 a15 a14 a13 a12 a12 0 0 0
* 2 a15 a14 a13 a11
* 1 a15 a14 a15 a14 a13 a11 a9 a8
* 1 a8 a13 a10 a10 a9
* -1 a13 a9 a11 a10 a15 a14 a15 a14
* -1 a12 a8 a10 a9 a8 a13 a14 a13
* -1 a11 a9 a15 a13 a12
* -1 a10 a12 a11
*/
static int8_t ReduceNistP256(BN_UINT *r, const BN_UINT *a)
{
BN_UINT list[P256SIZE];
BN_UINT t[P256SIZE];
// Reduction chain 0
list[3] = a[7]; // offset 3 a15|a14 == ah[7]|al[7]
list[2] = a[6]; // offset 2 a13|a12 == ah[6]|al[6]
list[1] = BN_UINT_LO_TO_HI(a[6]); // offset 1 a12|0 == al[6]|0
list[0] = 0; // offset 0 0
// Reduction chain 1
t[3] = BN_UINT_HI(a[7]); // offset 3 0|a15 == 0|ah[7]
t[2] = BN_UINT_LO_TO_HI(a[7]) | BN_UINT_HI(a[6]); // offset 2 a14|a13 == al[7]|ah[6]
t[1] = BN_UINT_HI_TO_HI(a[5]); // offset 1 a11|0 == ah[5]|0
t[0] = 0; // offset 0 0
int8_t carry = P256ADD(t, t, list);
// carry multiplied by 2 and padded with the most significant bit of t[3]
carry = (carry * 2) + (int8_t)(t[3] >> (BN_UINT_BITS - 1));
t[3] = (t[3] << 1) | (t[2] >> (BN_UINT_BITS - 1)); // t[3] is shifted left by 1 bit and the MSB of t[2] is added.
t[2] = (t[2] << 1) | (t[1] >> (BN_UINT_BITS - 1)); // t[2] is shifted left by 1 bit and the MSB of t[1] is added.
t[1] = (t[1] << 1) | (t[0] >> (BN_UINT_BITS - 1)); // t[1] is shifted left by 1 bit and the MSB of t[0] is added.
t[0] <<= 1;
// 2
list[3] = a[7]; // offset 3 a15|a14 == ah[7]|al[7]
list[2] = a[7]; // offset 2 a15|a14 == ah[7]|al[7]
list[1] = BN_UINT_HI_TO_HI(a[6]) | BN_UINT_HI(a[5]); // offset 1 a13|a11 == ah[6]|ah[5]
list[0] = a[4]; // offset 0 a9|a8 == ah[4]|al[4]
carry += (int8_t)P256ADD(t, t, list);
// 3
list[3] = BN_UINT_LO_TO_HI(a[4]) | BN_UINT_HI(a[6]); // offset 3 a8|a13 == al[4]|ah[6]
list[2] = 0; // offset 2 0
list[1] = BN_UINT_LO(a[5]); // offset 1 0|a10 == 0|al[5]
list[0] = BN_UINT_LO_TO_HI(a[5]) | BN_UINT_HI(a[4]); // offset 0 a10|a9 == al[5]|ah[4]
carry += (int8_t)P256ADD(t, t, list);
// 4
list[3] = BN_UINT_HI_TO_HI(a[6]) | BN_UINT_HI(a[4]); // offset 3 a13|a9 == ah[6]|ah[4]
list[2] = a[5]; // offset 2 a11|a10 == ah[5]|al[5]
list[1] = a[7]; // offset 1 a15|a14 == ah[7]|al[7]
list[0] = a[7]; // offset 0 a15|a14 == ah[7]|al[7]
carry -= (int8_t)P256SUB(t, t, list);
// 5
list[3] = BN_UINT_LO_TO_HI(a[6]) | BN_UINT_LO(a[4]); // offset 3 a12|a8 == al[6]|al[4]
list[2] = BN_UINT_LO_TO_HI(a[5]) | BN_UINT_HI(a[4]); // offset 2 a10|a9 == al[5]|ah[4]
list[1] = BN_UINT_LO_TO_HI(a[4]) | BN_UINT_HI(a[6]); // offset 1 a8|a13 == al[4]|ah[6]
list[0] = BN_UINT_LO_TO_HI(a[7]) | BN_UINT_HI(a[6]); // offset 0 a14|a13 == al[7]|ah[6]
carry -= (int8_t)P256SUB(t, t, list);
// 6
list[3] = BN_UINT_HI_TO_HI(a[5]); // offset 3 a11|0 == ah[5]|0
list[2] = 0; // offset 2 0
list[1] = BN_UINT_HI_TO_HI(a[4]) | BN_UINT_HI(a[7]); // offset 1 a9|a15 == ah[4]|ah[7]
list[0] = a[6]; // offset 0 a13|a12 == ah[6]|al[6]
carry -= (int8_t)P256SUB(t, t, list);
// 7
list[3] = BN_UINT_LO_TO_HI(a[5]); // offset 3 a10|0 == al[5]|0
list[2] = 0; // offset 2 0
list[1] = 0; // offset 1 0
list[0] = BN_UINT_LO_TO_HI(a[6]) | BN_UINT_HI(a[5]); // offset 0 a12|a11 == al[6]|ah[5]
carry -= (int8_t)P256SUB(t, t, list);
carry += (int8_t)P256ADD(r, t, a);
return carry;
}
// For the NIST_P256 curve, perform modulo operation on parameter P.
// The size of a is 2*P256SIZE, and the size of r is P256SIZE
int32_t ModNistP256(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt)
{
(void)opt;
(void)m;
const BN_UINT *mod = g_modDataP256[0];
int8_t carry = ReduceNistP256(r->data, a->data);
if (carry > 0) {
carry = (int8_t)1 - (int8_t)P256SUB(r->data, r->data, g_modDataP256[carry - 1]);
} else if (carry < 0) {
/*
* Here, we take carry < 0 as an example.
* If carry = -3, it indicates that ReduceNistP256 needs to be borrowed three times. In this case,
* we need to add 3 * p. It is worth noting that we have estimated 3 * p in g_modDataP256,
* but the carry of 3 * p is not save, which is expressed by the following formula:
* g_modDataP256[2] = 3 * p mod 2^256, we denoted as 2 + (3 * p)_remain.
* Actually, we need to calculate the following formula:
* -3 + r_data + 2 + (3 * p)_remain = -1 + r_data + (3 * p)_remain
* Obviously, -1 is a mathematical borrowing, only r_data + (3 * p)_remain is calculated in actual P256ADD.
* Therefore, we still need to consider the carry case of P256ADD.
* 1. r_data + (3 * p)_remain has a carry. -1 has been eliminated. We only need to consider
* whether r_data + (3 * p)_remain belongs to [0, p).
* 2. r_data + (3*p)_remain does not carry. It indicates that –1 is not eliminated. We need to add another P
* to eliminate –1. Considering the value of 3 * p in g_modDataP256, r_data + (3 * p)_remain + P must
* generate a carry, and the final result value < P.
*/
carry = (int8_t)1 - (int8_t)P256ADD(r->data, r->data, g_modDataP256[-carry - 1]);
carry = -carry;
}
if (carry < 0) {
P256ADD(r->data, r->data, mod);
} else if (carry > 0 || BinCmp(r->data, P256SIZE, mod, P256SIZE) >= 0) {
P256SUB(r->data, r->data, mod);
}
UpdateSize(r, P256SIZE);
return 0;
}
/**
* NIST_P224 curve reduction calculation for parameter P
* Reduction item: 2^96 - 2^0
*
* Reduction list:
* 6 5 4 3 2 1 0
* a7 00, 00, 00, 01, 00, 00, -1
* a8 00, 00, 01, 00, 00, -1, 00
* a9 00, 01, 00, 00, -1, 00, 00
* a10 01, 00, 00, -1, 00, 00, 00
* a11 00, 00, -1, 01, 00, 00, -1
* a12 00, -1, 01, 00, 00, -1, 00
* a13 -1, 01, 00, 00, -1, 00, 00
*
* Reduction chain
* Coefficient 6 5 4 3 2 1 0
* 1 a10 a9 a8 a7
* 1 a13 a12 a11
* -1 a13 a12 a11 a10 a9 a8 a7
* -1 a13 a12 a11
*/
static int8_t ReduceNistP224(BN_UINT *r, const BN_UINT *a)
{
BN_UINT list[P224SIZE];
BN_UINT t[P224SIZE];
// 1
list[3] = BN_UINT_LO(a[5]); // offset 3 0|a10 == 0|al[5]
list[2] = a[4]; // offset 2 a9|a8 == ah[4]|al[4]
list[1] = BN_UINT_HI_TO_HI(a[3]); // offset 1 a7|0 == ah[3]|0
list[0] = 0; // offset 0 0
// 2
t[3] = 0; // offset 3 0
t[2] = a[6]; // offset 2 a13|a12 == ah[6]|al[6]
t[1] = BN_UINT_HI_TO_HI(a[5]); // offset 1 a11|0 == ah[5]|0
t[0] = 0; // offset 0 0
P256ADD(t, t, list);
// 3
list[3] = BN_UINT_HI(a[6]); // offset 3 0|a13 == 0|ah[6]
list[2] = BN_UINT_LO_TO_HI(a[6]) | BN_UINT_HI(a[5]); // offset 2 a12|a11 == al[6]|ah[5]
list[1] = BN_UINT_LO_TO_HI(a[5]) | BN_UINT_HI(a[4]); // offset 1 a10|a9 == al[5]|ah[4]
list[0] = BN_UINT_LO_TO_HI(a[4]) | BN_UINT_HI(a[3]); // offset 0 a8|a7 == al[4]|ah[3]
P256SUB(t, t, list);
// 4
list[3] = 0; // offset 3 0
list[2] = 0; // offset 2 0
list[1] = BN_UINT_HI(a[6]); // offset 1 0|a13 == 0|ah[6]
list[0] = BN_UINT_LO_TO_HI(a[6]) | BN_UINT_HI(a[5]); // offset 0 a12|a11 == al[6]|ah[5]
P256SUB(t, t, list);
r[3] = BN_UINT_LO(a[3]); // Take lower 32 bits of a[3]
r[2] = a[2]; // Take a[2]
r[1] = a[1];
r[0] = a[0];
P256ADD(r, r, t);
return 0;
}
// NIST_P224 curve reduction calculation for parameter P. The size of a is 2*P224SIZE-1, and the size of r is P224SIZE
int32_t ModNistP224(
BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt)
{
(void)opt;
(void)m;
const BN_UINT *mod = g_modDataP224[0];
ReduceNistP224(r->data, a->data);
// Obtain the high-order data of r[3] as carry information
int8_t carry = (int8_t)((uint8_t)(BN_UINT_HI(r->data[3]) & 0xFF));
if (carry > 0) {
(void)P256SUB(r->data, r->data, g_modDataP224[carry - 1]);
} else if (carry < 0) {
(void)P256ADD(r->data, r->data, g_modDataP224[-carry - 1]);
}
// Obtain the high-order data of r[3] as carry information
carry = (int8_t)((uint8_t)(BN_UINT_HI(r->data[3]) & 0xFF));
if (carry < 0) {
P256ADD(r->data, r->data, mod);
} else if (carry > 0 || BinCmp(r->data, P256SIZE, mod, P256SIZE) >= 0) {
P256SUB(r->data, r->data, mod);
}
UpdateSize(r, P224SIZE);
return 0;
}
/**
* Reduction item: 2^224 + 2^96 - 2^64 + 2^0
* 7 6 5 4 3 2 1 0
* a8 01, 00, 00, 00, 01, -1, 00, 01,
* a9 01, 00, 00, 01, 00, -1, 01, 01,
* a10 01, 00, 01, 00, 00, 00, 01, 01,
* a11 01, 01, 00, 00, 01, 00, 01, 01,
* a12 02, 00, 00, 01, 01, 00, 01, 01,
* a13 02, 00, 01, 01, 02, -1, 01, 02,
* a14 02, 01, 01, 02, 01, -1, 02, 02,
* a15 03, 01, 02, 01, 01, 00, 02, 02,
* Reduction chain
* The last two reduction chain can be combined into the third to last chain for calculation.
* Coefficient 7 6 5 4 3 2 1 0
* 2 a15 a14 a15 a14 a13 0 a15 a14
* 2 a14 0 0 0 0 0 a14 a13
* 2 a13 0 a13 a12 a11 0 a12 a11
* 2 a12 a11 a10 a9 0 0 a9 a8
* 1 a15 0 0 a15 a14 0 a13 a12
* 1 a11 0 0 0 a8 0 0 a15
* 1 a10 0 0 0 a15 0 a11 a10
* 1 a9 a10 a9
* 1 a8 a15 a14 a13 a12 a15
* -1 a14 a13 a12 a11 a13 a12 a11
* -1 a11 a10 a9 0 a14 a9 a8
* -1 a8
* -1 a9
*/
#ifdef HITLS_CRYPTO_CURVE_SM2
static int8_t ReduceSm2P256(BN_UINT *r, const BN_UINT *a)
{
BN_UINT list[P256SIZE];
BN_UINT t[P256SIZE];
// Reduction chain 0, Coefficient 2
list[3] = a[7]; // offset 3 a15|a14 == ah[7]|al[7]
list[2] = a[7]; // offset 2 a15|a14 == ah[7]|al[7]
list[1] = BN_UINT_HI_TO_HI(a[6]); // offset 1 a13|0 == ah[6]|0
list[0] = a[7]; // offset 0 a15|a14 == ah[7]|al[7]
// Reduction chain 1, Coefficient 2
t[3] = BN_UINT_LO_TO_HI(a[7]); // offset 3 a14|0 == al[7]|0
t[2] = 0; // offset 2 0
t[1] = 0; // offset 1 0
t[0] = BN_UINT_LO_TO_HI(a[7]) | BN_UINT_HI(a[6]); // offset 0 a14|a13 = al[7]|ah[6]
int8_t carry = P256ADD(t, t, list);
// Reduction chain 2, Coefficient 2
list[3] = BN_UINT_HI_TO_HI(a[6]); // offset 3 a13|0 == ah[6]|0
list[2] = a[6]; // offset 2 a13|a12 == ah[6]|al[6]
list[1] = BN_UINT_HI_TO_HI(a[5]); // offset 1 a11|0 == ah[5]|0
list[0] = BN_UINT_LO_TO_HI(a[6]) | BN_UINT_HI(a[5]); // offset 0 a12|a11 == al[6]|ah[5]
carry += (int8_t)P256ADD(t, t, list);
// Reduction chain 3, Coefficient 2
list[3] = BN_UINT_LO_TO_HI(a[6]) | BN_UINT_HI(a[5]); // offset 3 a12|a11 == al[6]|ah[5]
list[2] = BN_UINT_LO_TO_HI(a[5]) | BN_UINT_HI(a[4]); // offset 2 a10|a9 == al[5]|ah[4]
list[1] = 0; // offset 1 0
list[0] = a[4]; // offset 0 a9|a8 == ah[4]|al[4]
carry += (int8_t)P256ADD(t, t, list);
// carry multiplied by 2 and padded with the most significant bit of t[3]
carry = (carry * 2) + (int8_t)(t[3] >> (BN_UINT_BITS - 1));
t[3] = (t[3] << 1) | (t[2] >> (BN_UINT_BITS - 1)); // t[3] is shifted left by 1 bit and the MSB of t[2] is added.
t[2] = (t[2] << 1) | (t[1] >> (BN_UINT_BITS - 1)); // t[2] is shifted left by 1 bit and the MSB of t[1] is added.
t[1] = (t[1] << 1) | (t[0] >> (BN_UINT_BITS - 1)); // t[1] is shifted left by 1 bit and the MSB of t[0] is added.
t[0] <<= 1;
// Reduction chain 4, Coefficient 1
list[3] = BN_UINT_HI_TO_HI(a[7]); // offset 3 a15|0 == ah[7]|0
list[2] = BN_UINT_HI(a[7]); // offset 2 0|a15 == 0|ah[7]
list[1] = BN_UINT_LO_TO_HI(a[7]); // offset 1 a14|0 == al[7]|0
list[0] = a[6]; // offset 0 a13|a12 == ah[6]|al[6]
carry += (int8_t)P256ADD(t, t, list);
// Reduction chain 5, Coefficient 1
list[3] = BN_UINT_HI_TO_HI(a[5]); // offset 3 a11|0 == ah[5]|0
list[2] = 0; // offset 2 0
list[1] = BN_UINT_LO_TO_HI(a[4]); // offset 1 a8|0 == al[4]|0
list[0] = BN_UINT_HI(a[7]); // offset 0 0|a15 == 0|ah[7]
carry += (int8_t)P256ADD(t, t, list);
// Reduction chain 6, Coefficient 1
list[3] = BN_UINT_LO_TO_HI(a[5]); // offset 3 a10|0 == al[5]|0
list[2] = 0; // offset 2 0
list[1] = BN_UINT_HI_TO_HI(a[7]); // offset 1 a15|0 == ah[7]|0
list[0] = a[5]; // offset 0 a11|a10 == ah[5]|al[5]
carry += (int8_t)P256ADD(t, t, list);
// Reduction chain 7, Coefficient 1
list[3] = BN_UINT_HI_TO_HI(a[4]); // offset 3 a9|0 == ah[4]|0
list[2] = 0; // offset 2 0
list[1] = 0; // offset 1 0
list[0] = BN_UINT_LO_TO_HI(a[5]) | BN_UINT_HI(a[4]); // offset 0 a10|a9 == al[5]|ah[4]
carry += (int8_t)P256ADD(t, t, list);
// Reduction chain 8, Coefficient 1
list[3] = BN_UINT_LO_TO_HI(a[4]) | BN_UINT_HI(a[7]); // offset 3 a8|a15 == al[4]|ah[7]
list[2] = BN_UINT_LO_TO_HI(a[7]) | BN_UINT_HI(a[6]); // offset 2 a14|a13 = al[7]|ah[6]
list[1] = BN_UINT_LO_TO_HI(a[6]); // offset 1 a12|0 == al[6]|0
list[0] = BN_UINT_HI(a[7]); // offset 0 0|a15 == 0|ah[7]
carry += (int8_t)P256ADD(t, t, list);
// Reduction chain 9, Coefficient -1
list[3] = BN_UINT_LO(a[7]); // offset 3 0|a14 == 0|al[7]
list[2] = a[6]; // offset 2 a13|a12 == ah[6]|al[6]
list[1] = BN_UINT_HI_TO_HI(a[5]) | BN_UINT_HI(a[6]); // offset 1 a11|a13 == ah[5]|ah[6]
list[0] = BN_UINT_LO_TO_HI(a[6]) | BN_UINT_HI(a[5]); // offset 0 a12|a11 == al[6]|ah[5]
carry -= (int8_t)P256SUB(t, t, list);
// Reduction chain 10, Coefficient -1
list[3] = BN_UINT_HI(a[5]); // offset 3 0|a11 == 0|ah[5]
list[2] = BN_UINT_LO_TO_HI(a[5]) | BN_UINT_HI(a[4]); // offset 2 a10|a9 == al[5]|ah[4]
// offset 1 0|a14 == 0|al[7]. Add the values of the last two chains.
list[1] = BN_UINT_LO(a[7]) + BN_UINT_HI(a[4]) + BN_UINT_LO(a[4]);
list[0] = a[4]; // offset 0 a9|a8 == ah[4]|al[4]
carry -= (int8_t)P256SUB(t, t, list);
carry += (int8_t)P256ADD(r, t, a);
return carry;
}
// SM2_P256 curve modulo parameter P. The size of a is 2*P256SIZE, and the size of r is P256SIZE
int32_t ModSm2P256(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt)
{
(void)opt;
(void)m;
const BN_UINT *mod = MODDATASM2P256[0];
int8_t carry = ReduceSm2P256(r->data, a->data);
if (carry < 0) {
carry = (int8_t)1 - (int8_t)P256ADD(r->data, r->data, MODDATASM2P256[-carry - 1]);
carry = -carry;
} else if (carry > 0) {
// For details could ref p256.
carry = (int8_t)1 - (int8_t)P256SUB(r->data, r->data, MODDATASM2P256[carry - 1]);
}
if (carry < 0) {
P256ADD(r->data, r->data, mod);
} else if (carry > 0 || BinCmp(r->data, P256SIZE, mod, P256SIZE) >= 0) {
P256SUB(r->data, r->data, mod);
}
UpdateSize(r, P256SIZE);
return 0;
}
#endif
#elif defined(HITLS_THIRTY_TWO_BITS)
int32_t ModNistP224(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt)
{
return BN_Mod(r, a, m, opt);
}
int32_t ModNistP256(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt)
{
return BN_Mod(r, a, m, opt);
}
#ifdef HITLS_CRYPTO_CURVE_SM2
int32_t ModSm2P256(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt)
{
return BN_Mod(r, a, m, opt);
}
#endif
int32_t ModNistP384(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt)
{
return BN_Mod(r, a, m, opt);
}
int32_t ModNistP521(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt)
{
return BN_Mod(r, a, m, opt);
}
#endif
#if defined(HITLS_CRYPTO_BN_COMBA) && defined(HITLS_SIXTY_FOUR_BITS)
static uint32_t MulNistP256P224(BN_UINT *r, uint32_t rSize, const BN_UINT *a, uint32_t aSize,
const BN_UINT *b, uint32_t bSize)
{
(void)rSize;
(void)aSize;
(void)bSize;
MulComba4(r, a, b);
uint32_t size = P224SIZE << 1; // in 64-bit environment, P224SIZE = P256SIZE
while (size > 0) {
if (r[size - 1] != 0) {
break;
}
--size;
}
return size;
}
static uint32_t SqrNistP256P224(BN_UINT *r, uint32_t rSize, const BN_UINT *a, uint32_t aSize)
{
(void)rSize;
(void)aSize;
SqrComba4(r, a);
uint32_t size = P224SIZE << 1; // in 64-bit environment, P224SIZE = P256SIZE
while (size > 0) {
if (r[size - 1] != 0) {
break;
}
--size;
}
return size;
}
static uint32_t MulNistP384(BN_UINT *r, uint32_t rSize, const BN_UINT *a, uint32_t aSize,
const BN_UINT *b, uint32_t bSize)
{
(void)rSize;
(void)aSize;
(void)bSize;
MulComba6(r, a, b);
uint32_t size = P384SIZE << 1;
while (size > 0) {
if (r[size - 1] != 0) {
break;
}
size--;
}
return size;
}
static uint32_t SqrNistP384(BN_UINT *r, uint32_t rSize, const BN_UINT *a, uint32_t aSize)
{
(void)rSize;
(void)aSize;
SqrComba6(r, a);
uint32_t size = P384SIZE << 1;
while (size > 0) {
if (r[size - 1] != 0) {
break;
}
size--;
}
return size;
}
#else
static uint32_t MulNistP256P224(BN_UINT *r, uint32_t rSize, const BN_UINT *a, uint32_t aSize,
const BN_UINT *b, uint32_t bSize)
{
return BinMul(r, rSize, a, aSize, b, bSize);
}
static uint32_t SqrNistP256P224(BN_UINT *r, uint32_t rSize, const BN_UINT *a, uint32_t aSize)
{
return BinSqr(r, rSize, a, aSize);
}
static uint32_t MulNistP384(BN_UINT *r, uint32_t rSize, const BN_UINT *a, uint32_t aSize,
const BN_UINT *b, uint32_t bSize)
{
return BinMul(r, rSize, a, aSize, b, bSize);
}
static uint32_t SqrNistP384(BN_UINT *r, uint32_t rSize, const BN_UINT *a, uint32_t aSize)
{
return BinSqr(r, rSize, a, aSize);
}
#endif
static inline int32_t ModCalParaCheck(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, const BN_BigNum *mod)
{
if (r == NULL || a == NULL || b == NULL || mod == NULL) {
return CRYPT_NULL_INPUT;
}
// 保证不越界访问
if ((mod->size > a->room) || (mod->size > b->room)) {
return CRYPT_BN_SPACE_NOT_ENOUGH;
}
return BnExtend(r, mod->size);
}
// The user must ensure that a < m, and a->room & b->room are not less than mod->size.
// All the data must be not negative number, otherwise the API may be not functional.
int32_t BN_ModAddQuick(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b,
const BN_BigNum *mod, const BN_Optimizer *opt)
{
int32_t ret = ModCalParaCheck(r, a, b, mod);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
(void)opt;
BN_UINT carry = BinAdd(r->data, a->data, b->data, mod->size);
if (carry > 0 || BinCmp(r->data, mod->size, mod->data, mod->size) >= 0) {
BinSub(r->data, r->data, mod->data, mod->size);
}
UpdateSize(r, mod->size);
return CRYPT_SUCCESS;
}
// The user must ensure that a < m, and a->room & b->room are not less than mod->size.
// All the data must be not negative number, otherwise the API may be not functional.
int32_t BN_ModSubQuick(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b,
const BN_BigNum *mod, const BN_Optimizer *opt)
{
int32_t ret = ModCalParaCheck(r, a, b, mod);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
(void)opt;
int32_t res = BinCmp(a->data, a->size, b->data, b->size);
if (res < 0) {
/* Apply for the temporary space of the BN object. */
BinSub(r->data, a->data, b->data, mod->size);
BinAdd(r->data, r->data, mod->data, mod->size);
} else {
BinSub(r->data, a->data, b->data, mod->size);
}
UpdateSize(r, mod->size);
return CRYPT_SUCCESS;
}
static inline int32_t ModEccMulParaCheck(BN_BigNum *r, const BN_BigNum *a,
const BN_BigNum *b, const BN_BigNum *mod, BN_Optimizer *opt)
{
if (r == NULL || a == NULL || b == NULL || mod == NULL || opt == NULL) {
return CRYPT_NULL_INPUT;
}
// Ensure that no out-of-bounds access occurs.
if ((mod->size > b->room) || (mod->size > a->room)) {
return CRYPT_BN_SPACE_NOT_ENOUGH;
}
return BnExtend(r, mod->size);
}
// The user must ensure that a < m, and a->room & b->room are not less than mod->size.
// All the data must be not negative number, otherwise the API may be not functional.
int32_t BN_ModNistEccMul(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, void *data, BN_Optimizer *opt)
{
BN_BigNum *mod = (BN_BigNum *)data;
int32_t ret = ModEccMulParaCheck(r, a, b, mod, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (b->size == 0 || a->size == 0) {
return BN_Zeroize(r);
}
BN_UINT tData[P521SIZE << 1] = { 0 };
BN_BigNum rMul = {
.data = tData,
.size = 0,
.sign = false,
.room = P521SIZE << 1
};
uint32_t size = mod->size << 1;
uint32_t bits = BN_Bits(mod);
if (bits == 224) { // 224bit
rMul.size = MulNistP256P224(rMul.data, size, a->data, mod->size, b->data, mod->size);
ModNistP224(r, &rMul, mod, opt);
} else if (bits == 256) { // 256bit
rMul.size = MulNistP256P224(rMul.data, size, a->data, mod->size, b->data, mod->size);
ModNistP256(r, &rMul, mod, opt);
} else if (bits == 384) { // 384bit
rMul.size = MulNistP384(rMul.data, size, a->data, mod->size, b->data, mod->size);
ModNistP384(r, &rMul, mod, opt);
} else if (bits == 521) { // 521bit
rMul.size = BinMul(rMul.data, size, a->data, mod->size, b->data, mod->size);
ModNistP521(r, &rMul, mod, opt);
} else {
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_QUICK_MODDATA);
return CRYPT_BN_ERR_QUICK_MODDATA;
}
return CRYPT_SUCCESS;
}
static int32_t ModEccSqrParaCheck(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *mod, BN_Optimizer *opt)
{
if (r == NULL || a == NULL || mod == NULL || opt == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
// Ensure that no out-of-bounds access occurs.
if (mod->size > a->room) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_SPACE_NOT_ENOUGH);
return CRYPT_BN_SPACE_NOT_ENOUGH;
}
return BnExtend(r, mod->size);
}
// The user must ensure that a < m, and a->room & b->room are not less than mod->size.
// All the data must be not negative number, otherwise the API may be not functional.
int32_t BN_ModNistEccSqr(BN_BigNum *r, const BN_BigNum *a, void *data, BN_Optimizer *opt)
{
BN_BigNum *mod = (BN_BigNum *)data;
int32_t ret = ModEccSqrParaCheck(r, a, mod, opt);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if (a->size == 0) {
return BN_Zeroize(r);
}
BN_UINT tData[P521SIZE << 1] = { 0 };
BN_BigNum rSqr = {
.data = tData,
.size = 0,
.sign = false,
.room = P521SIZE << 1
};
uint32_t size = mod->size << 1;
uint32_t bits = BN_Bits(mod);
if (bits == 224) { // 224bit
rSqr.size = SqrNistP256P224(rSqr.data, size, a->data, mod->size);
ModNistP224(r, &rSqr, mod, opt);
} else if (bits == 256) { // 256bit
rSqr.size = SqrNistP256P224(rSqr.data, size, a->data, mod->size);
ModNistP256(r, &rSqr, mod, opt);
} else if (bits == 384) { // 384bit
rSqr.size = SqrNistP384(rSqr.data, size, a->data, mod->size);
ModNistP384(r, &rSqr, mod, opt);
} else if (bits == 521) { // 521bit
rSqr.size = BinSqr(rSqr.data, size, a->data, mod->size);
ModNistP521(r, &rSqr, mod, opt);
} else {
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_QUICK_MODDATA);
return CRYPT_BN_ERR_QUICK_MODDATA;
}
return CRYPT_SUCCESS;
}
#ifdef HITLS_CRYPTO_CURVE_SM2
#define SM2SIZE SIZE_OF_BNUINT(256)
// The user must ensure that a < m, and a->room & b->room are not less than mod->size.
// All the data must be not negative number, otherwise the API may be not functional.
int32_t BN_ModSm2EccMul(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, void *data, BN_Optimizer *opt)
{
BN_BigNum *mod = (BN_BigNum *)data;
int32_t ret = ModEccMulParaCheck(r, a, b, mod, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (a->size == 0 || b->size == 0) {
return BN_Zeroize(r);
}
BN_UINT tData[SM2SIZE << 1] = { 0 };
BN_BigNum rMul = {
.data = tData,
.size = 0,
.sign = false,
.room = SM2SIZE << 1
};
uint32_t size = mod->size << 1;
rMul.size = MulNistP256P224(rMul.data, size, a->data, mod->size, b->data, mod->size);
ModSm2P256(r, &rMul, mod, opt);
return CRYPT_SUCCESS;
}
// The user must ensure that a < m, and a->room & b->room are not less than mod->size.
// All the data must be not negative number, otherwise the API may be not functional.
int32_t BN_ModSm2EccSqr(BN_BigNum *r, const BN_BigNum *a, void *data, BN_Optimizer *opt)
{
BN_BigNum *mod = (BN_BigNum *)data;
int32_t ret = ModEccSqrParaCheck(r, a, mod, opt);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if (a->size == 0) {
return BN_Zeroize(r);
}
BN_UINT tData[SM2SIZE << 1] = { 0 };
BN_BigNum rSqr = {
.data = tData,
.size = 0,
.sign = false,
.room = SM2SIZE << 1
};
uint32_t size = mod->size << 1;
rSqr.size = SqrNistP256P224(rSqr.data, size, a->data, mod->size);
ModSm2P256(r, &rSqr, mod, opt);
return CRYPT_SUCCESS;
}
#endif
#endif
|
2301_79861745/bench_create
|
crypto/bn/src/bn_nistmod.c
|
C
|
unknown
| 45,086
|
/*
* 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_BN
#include "securec.h"
#include "bsl_sal.h"
#include "bsl_err_internal.h"
#include "crypt_errno.h"
#include "crypt_utils.h"
#include "bn_basic.h"
#include "bn_bincal.h"
#include "bn_ucal.h"
#include "bn_optimizer.h"
#define SMALL_CONQUER_SIZE 8
int32_t BN_Cmp(const BN_BigNum *a, const BN_BigNum *b)
{
if (a == NULL || b == NULL) {
if (a != NULL) {
return -1;
}
if (b != NULL) {
return 1;
}
return 0;
}
if (a->sign != b->sign) {
return a->sign == false ? 1 : -1;
}
if (a->sign == true) {
return BinCmp(b->data, b->size, a->data, a->size);
}
return BinCmp(a->data, a->size, b->data, b->size);
}
int32_t BN_Add(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b)
{
if (r == NULL || a == NULL || b == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (a->sign == b->sign) {
r->sign = a->sign;
return UAdd(r, a, b);
}
// compare absolute value
int32_t res = BinCmp(a->data, a->size, b->data, b->size);
if (res > 0) {
r->sign = a->sign;
return USub(r, a, b);
} else if (res < 0) {
r->sign = b->sign;
return USub(r, b, a);
}
return BN_Zeroize(r);
}
int32_t BN_AddLimb(BN_BigNum *r, const BN_BigNum *a, BN_UINT w)
{
if (r == NULL || a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (a->size == 0) {
return BN_SetLimb(r, w);
}
int32_t ret;
if (a->sign == false) { // a is positive
ret = BnExtend(r, a->size + 1);
if (ret != CRYPT_SUCCESS) {
return ret;
}
BN_UINT carry = BinInc(r->data, a->data, a->size, w);
if (carry != 0) {
uint32_t size = a->size;
r->size = size + 1;
r->data[size] = carry;
} else {
r->size = a->size;
}
r->sign = false;
return CRYPT_SUCCESS;
}
ret = BnExtend(r, a->size);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if (a->size == 1) {
if (a->data[0] > w) {
r->sign = true;
r->data[0] = a->data[0] - w;
r->size = 1;
} else if (a->data[0] == w) {
r->sign = false;
r->data[0] = 0;
r->size = 0;
} else {
r->sign = false;
r->data[0] = w - a->data[0];
r->size = 1;
}
return CRYPT_SUCCESS;
}
r->sign = true;
UDec(r, a, w);
return CRYPT_SUCCESS;
}
int32_t BN_Sub(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b)
{
if (r == NULL || a == NULL || b == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (a->sign != b->sign) {
r->sign = a->sign;
return UAdd(r, a, b);
}
// compare absolute value
int32_t res = BinCmp(a->data, a->size, b->data, b->size);
if (res == 0) {
return BN_Zeroize(r);
} else if (res > 0) {
r->sign = a->sign;
return USub(r, a, b);
}
r->sign = !b->sign;
return USub(r, b, a);
}
int32_t BN_SubLimb(BN_BigNum *r, const BN_BigNum *a, BN_UINT w)
{
if (r == NULL || a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret;
if (a->size == 0) {
if (BN_SetLimb(r, w) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
r->sign = (w == 0) ? false : true;
return CRYPT_SUCCESS;
}
if (a->sign == true) {
ret = BnExtend(r, a->size + 1);
if (ret != CRYPT_SUCCESS) {
return ret;
}
BN_UINT carry = BinInc(r->data, a->data, a->size, w);
if (carry != 0) {
uint32_t size = a->size;
r->data[size] = carry;
r->size = size + 1;
} else {
r->size = a->size;
}
r->sign = true;
return CRYPT_SUCCESS;
}
ret = BnExtend(r, a->size);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if (a->size == 1) {
if (a->data[0] >= w) {
r->data[0] = a->data[0] - w;
r->size = BinFixSize(r->data, 1);
} else {
r->sign = true;
r->data[0] = w - a->data[0];
r->size = 1;
}
return CRYPT_SUCCESS;
}
r->sign = false;
UDec(r, a, w);
return CRYPT_SUCCESS;
}
#ifdef HITLS_CRYPTO_BN_COMBA
static int32_t BnMulConquer(BN_BigNum *t, const BN_BigNum *a, const BN_BigNum *b, BN_Optimizer *opt)
{
if (a->size <= SMALL_CONQUER_SIZE && a->size % 2 == 0) { // 2 is to check if a->size is even
MulConquer(t->data, a->data, b->data, a->size, NULL, false);
} else {
BN_BigNum *tmpBn = OptimizerGetBn(opt, SpaceSize(a->size));
if (tmpBn == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
MulConquer(t->data, a->data, b->data, a->size, tmpBn->data, false);
}
t->size = a->size + b->size;
return CRYPT_SUCCESS;
}
#endif
int32_t BN_Mul(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, BN_Optimizer *opt)
{
if (r == NULL || a == NULL || b == NULL || opt == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (a->size == 0 || b->size == 0) {
return BN_Zeroize(r);
}
uint32_t size = a->size + b->size;
int32_t ret = BnExtend(r, size);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = OptimizerStart(opt); // using the Optimizer
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BN_BigNum *t = NULL;
if (r == a || r == b) {
t = OptimizerGetBn(opt, r->room); // apply for a BN object
if (t == NULL) {
OptimizerEnd(opt); // release occupation from the optimizer
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
} else {
t = r;
}
t->sign = a->sign != b->sign;
#ifdef HITLS_CRYPTO_BN_COMBA
if (a->size == b->size) {
ret = BnMulConquer(t, a, b, opt);
if (ret != CRYPT_SUCCESS) {
OptimizerEnd(opt);
return ret;
}
} else {
#endif
t->size = BinMul(t->data, t->room, a->data, a->size, b->data, b->size);
#ifdef HITLS_CRYPTO_BN_COMBA
}
#endif
if (r != t) {
ret = BN_Copy(r, t);
if (ret != CRYPT_SUCCESS) {
OptimizerEnd(opt); // release occupation from the optimizer
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
r->size = BinFixSize(r->data, size);
OptimizerEnd(opt);
return CRYPT_SUCCESS;
}
int32_t BN_MulLimb(BN_BigNum *r, const BN_BigNum *a, const BN_UINT w)
{
if (r == NULL || a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (BN_Bits(a) == 0 || w == 0) {
return BN_Zeroize(r);
}
int32_t ret = BnExtend(r, a->size + 1);
if (ret != CRYPT_SUCCESS) {
return ret;
}
BN_UINT carry = 0;
uint32_t loc;
for (loc = 0; loc < a->size; loc++) {
BN_UINT rh;
BN_UINT rl;
MUL_AB(rh, rl, a->data[loc], w);
ADD_AB(carry, r->data[loc], rl, carry);
carry += rh;
}
if (carry != 0) {
r->data[loc++] = carry; // Input parameter checking ensures that no out-of-bounds
}
r->sign = a->sign;
r->size = loc;
return CRYPT_SUCCESS;
}
int32_t BN_Sqr(BN_BigNum *r, const BN_BigNum *a, BN_Optimizer *opt)
{
if (r == NULL || a == NULL || opt == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (a->size == 0) {
return BN_Zeroize(r);
}
int32_t ret = BnExtend(r, a->size * 2); // The maximum bit required for mul is 2x that of a.
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = OptimizerStart(opt); // using the Optimizer
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
#ifdef HITLS_CRYPTO_BN_COMBA
if (a->size <= SMALL_CONQUER_SIZE && a->size % 2 == 0) { // 2 is to check if a->size is even.
SqrConquer(r->data, a->data, a->size, NULL, false);
} else {
BN_BigNum *tmpBn = OptimizerGetBn(opt, SpaceSize(a->size));
if (tmpBn == NULL) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
SqrConquer(r->data, a->data, a->size, tmpBn->data, false);
}
#else
BinSqr(r->data, a->size << 1, a->data, a->size);
#endif
r->size = BinFixSize(r->data, a->size * 2); // The r->data size is a->size * 2.
r->sign = false; // The square must be positive.
OptimizerEnd(opt);
return CRYPT_SUCCESS;
}
int32_t DivInputCheck(const BN_BigNum *q, const BN_BigNum *r, const BN_BigNum *x,
const BN_BigNum *y, const BN_Optimizer *opt)
{
if (x == NULL || y == NULL || opt == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (q == r) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
// The divisor cannot be 0.
if (y->size == 0) {
return CRYPT_BN_ERR_DIVISOR_ZERO;
}
return CRYPT_SUCCESS;
}
// If x <= y, perform special processing.
int32_t DivSimple(BN_BigNum *q, BN_BigNum *r, const BN_BigNum *x, const BN_BigNum *y, int32_t flag)
{
int32_t ret;
if (flag < 0) {
if (r != NULL) {
ret = BN_Copy(r, x);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
if (q != NULL) {
return BN_Zeroize(q);
}
} else {
if (q != NULL) {
bool sign = (x->sign != y->sign);
ret = BN_SetLimb(q, 1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
q->sign = sign;
}
if (r != NULL) {
return BN_Zeroize(r);
}
}
return CRYPT_SUCCESS;
}
int32_t BN_Div(BN_BigNum *q, BN_BigNum *r, const BN_BigNum *x, const BN_BigNum *y, BN_Optimizer *opt)
{
int32_t ret = DivInputCheck(q, r, x, y, opt);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = BinCmp(x->data, x->size, y->data, y->size);
if (ret <= 0) { // simple processing when dividend <= divisor
return DivSimple(q, r, x, y, ret);
}
ret = OptimizerStart(opt); // using the Optimizer
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
/* Apply for temporary space for the q and r of the BN. */
BN_BigNum *qTmp = OptimizerGetBn(opt, x->size + 2); // BinDiv:x->room >= xSize + 2
BN_BigNum *rTmp = OptimizerGetBn(opt, x->size + 2); // BinDiv:x->room >= xSize + 2
BN_BigNum *yTmp = OptimizerGetBn(opt, y->size);
if (qTmp == NULL || rTmp == NULL || yTmp == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
ret = CRYPT_BN_OPTIMIZER_GET_FAIL;
goto err;
}
(void)memcpy_s(yTmp->data, y->size * sizeof(BN_UINT), y->data, y->size * sizeof(BN_UINT));
(void)memcpy_s(rTmp->data, x->size * sizeof(BN_UINT), x->data, x->size * sizeof(BN_UINT));
rTmp->sign = x->sign;
rTmp->size = BinDiv(qTmp->data, &(qTmp->size), rTmp->data, x->size, yTmp->data, y->size);
if (q != NULL) {
ret = BnExtend(q, qTmp->size);
if (ret != CRYPT_SUCCESS) {
goto err;
}
q->sign = (x->sign != y->sign);
(void)memcpy_s(q->data, qTmp->size * sizeof(BN_UINT), qTmp->data, qTmp->size * sizeof(BN_UINT));
q->size = qTmp->size;
}
if (r != NULL) {
ret = BnExtend(r, rTmp->size);
if (ret != CRYPT_SUCCESS) {
goto err;
}
r->sign = (rTmp->size == 0) ? false : rTmp->sign; // The symbol can only be positive when the value is 0.
(void)memcpy_s(r->data, rTmp->size * sizeof(BN_UINT), rTmp->data, rTmp->size * sizeof(BN_UINT));
r->size = rTmp->size;
}
err:
OptimizerEnd(opt); // release occupation from the optimizer
return ret;
}
int32_t DivLimbInputCheck(const BN_BigNum *q, const BN_UINT *r, const BN_BigNum *x, const BN_UINT y)
{
if (x == NULL || (q == NULL && r == NULL)) { // q and r cannot be NULL at the same time
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (y == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_DIVISOR_ZERO);
return CRYPT_BN_ERR_DIVISOR_ZERO;
}
return CRYPT_SUCCESS;
}
int32_t BN_DivLimb(BN_BigNum *q, BN_UINT *r, const BN_BigNum *x, const BN_UINT y)
{
int32_t ret = DivLimbInputCheck(q, r, x, y);
if (ret != CRYPT_SUCCESS) {
return ret;
}
// Apply for a copy of object x.
BN_BigNum *xTmp = BN_Dup(x);
if (xTmp == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
BN_UINT rem = 0;
BN_UINT yTmp = y;
uint32_t shifts;
if (x->size == 0) {
goto end;
}
shifts = GetZeroBitsUint(yTmp);
if (shifts != 0) {
yTmp <<= shifts; // Ensure that the most significant bit of the divisor is 1.
ret = BN_Lshift(xTmp, xTmp, shifts);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
BN_Destroy(xTmp);
return ret;
}
}
for (int32_t i = (int32_t)(xTmp->size - 1); i >= 0; i--) {
BN_UINT quo;
DIV_ND(quo, rem, rem, xTmp->data[i], yTmp);
xTmp->data[i] = quo;
}
xTmp->size = BinFixSize(xTmp->data, xTmp->size);
if (xTmp->size == 0) {
xTmp->sign = 0;
}
rem >>= shifts;
end:
if (q != NULL) {
ret = BN_Copy(q, xTmp);
if (ret != CRYPT_SUCCESS) {
BN_Destroy(xTmp);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
if (r != NULL) {
*r = rem;
}
BN_Destroy(xTmp);
return ret;
}
int32_t BN_Mod(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt)
{
// check input parameters
if (r == NULL || a == NULL || m == NULL || opt == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (m->size == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_DIVISOR_ZERO);
return CRYPT_BN_ERR_DIVISOR_ZERO;
}
int32_t ret = BnExtend(r, m->size);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BN_BigNum *t = OptimizerGetBn(opt, m->size);
if (t == NULL) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
ret = BN_Div(NULL, t, a, m, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
OptimizerEnd(opt);
return ret;
}
// t is a positive number
if (t->sign == false) {
ret = BN_Copy(r, t);
OptimizerEnd(opt);
return ret;
}
// When t is a negative number, the modulo operation result must be positive.
if (m->sign == true) { // m is a negative number
ret = BN_Sub(r, t, m);
} else { // m is a positive number
ret = BN_Add(r, t, m);
}
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
OptimizerEnd(opt);
return ret;
}
int32_t BN_ModLimb(BN_UINT *r, const BN_BigNum *a, const BN_UINT m)
{
if (r == NULL || a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (m == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_DIVISOR_ZERO);
return CRYPT_BN_ERR_DIVISOR_ZERO;
}
if (a->size == 0) {
*r = 0;
return CRYPT_SUCCESS;
}
int32_t ret = BN_DivLimb(NULL, r, a, m);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (a->sign) {
*r = m - *r;
}
return ret;
}
// Check the input parameters of basic operations such as modulo addition, subtraction, and multiplication.
int32_t ModBaseInputCheck(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b,
const BN_BigNum *mod, const BN_Optimizer *opt)
{
if (r == NULL || a == NULL || b == NULL || mod == NULL || opt == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret = BnExtend(r, mod->size);
if (ret != CRYPT_SUCCESS) {
return ret;
}
// mod cannot be 0
if (BN_IsZero(mod)) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_DIVISOR_ZERO);
return CRYPT_BN_ERR_DIVISOR_ZERO;
}
return CRYPT_SUCCESS;
}
int32_t BN_ModSub(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, const BN_BigNum *mod, BN_Optimizer *opt)
{
int32_t ret;
ret = ModBaseInputCheck(r, a, b, mod, opt);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = OptimizerStart(opt); // using the Optimizer
if (ret != CRYPT_SUCCESS) {
return ret;
}
/* Difference: Apply for the temporary space of the BN object. */
uint32_t subTmpSize = (a->size > b ->size) ? a->size : b->size;
BN_BigNum *t = OptimizerGetBn(opt, subTmpSize);
if (t == NULL) {
ret = CRYPT_BN_OPTIMIZER_GET_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto err;
}
ret = BN_Sub(t, a, b);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto err;
}
ret = BN_Mod(r, t, mod, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
err:
OptimizerEnd(opt); // release occupation from the optimizer
return ret;
}
int32_t BN_ModAdd(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, const BN_BigNum *mod, BN_Optimizer *opt)
{
int32_t ret;
ret = ModBaseInputCheck(r, a, b, mod, opt);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = OptimizerStart(opt); // using the Optimizer
if (ret != CRYPT_SUCCESS) {
return ret;
}
/* Difference: Apply for the temporary space of the BN object. */
uint32_t addTmpSize = (a->size > b ->size) ? a->size : b->size;
BN_BigNum *t = OptimizerGetBn(opt, addTmpSize);
if (t == NULL) {
ret = CRYPT_BN_OPTIMIZER_GET_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto err;
}
ret = BN_Add(t, a, b);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto err;
}
ret = BN_Mod(r, t, mod, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
err:
OptimizerEnd(opt); // release occupation from the optimizer
return ret;
}
int32_t BN_ModMul(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, const BN_BigNum *mod, BN_Optimizer *opt)
{
int32_t ret;
ret = ModBaseInputCheck(r, a, b, mod, opt);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = OptimizerStart(opt); // using the Optimizer
if (ret != CRYPT_SUCCESS) {
return ret;
}
/* Apply for the temporary space of the BN object. */
BN_BigNum *t = OptimizerGetBn(opt, a->size + b->size + 1);
if (t == NULL) {
ret = CRYPT_BN_OPTIMIZER_GET_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto err;
}
ret = BN_Mul(t, a, b, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto err;
}
ret = BN_Mod(r, t, mod, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
err:
OptimizerEnd(opt); // release occupation from the optimizer
return ret;
}
int32_t BN_ModSqr(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *mod, BN_Optimizer *opt)
{
bool invalidInput = (r == NULL || a == NULL || mod == NULL || opt == NULL);
if (invalidInput) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
// mod cannot be 0
if (BN_IsZero(mod)) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_DIVISOR_ZERO);
return CRYPT_BN_ERR_DIVISOR_ZERO;
}
int32_t ret = BnExtend(r, mod->size);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = OptimizerStart(opt); // using the Optimizer
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
/* Apply for the temporary space of the BN object. */
BN_BigNum *t = OptimizerGetBn(opt, (a->size << 1) + 1);
if (t == NULL) {
ret = CRYPT_BN_OPTIMIZER_GET_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto err;
}
ret = BN_Sqr(t, a, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto err;
}
ret = BN_Mod(r, t, mod, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
err:
OptimizerEnd(opt); // release occupation from the optimizer
return ret;
}
int32_t ModExpInputCheck(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e,
const BN_BigNum *m, const BN_Optimizer *opt)
{
bool invalidInput = (r == NULL || a == NULL || e == NULL || m == NULL || opt == NULL);
if (invalidInput) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
// mod cannot be 0
if (BN_IsZero(m)) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_DIVISOR_ZERO);
return CRYPT_BN_ERR_DIVISOR_ZERO;
}
// the power cannot be negative
if (e->sign == true) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_EXP_NO_NEGATIVE);
return CRYPT_BN_ERR_EXP_NO_NEGATIVE;
}
return BnExtend(r, m->size);
}
int32_t ModExpCore(BN_BigNum *x, BN_BigNum *y, const BN_BigNum *e, const BN_BigNum *m, BN_Optimizer *opt)
{
int32_t ret;
if (BN_GetBit(e, 0) == 1) {
(void)BN_Copy(x, y); // ignores the returned value, we can ensure that no error occurs when applying memory
} else { // set the value to 1
(void)BN_SetLimb(x, 1); // ignores the returned value, we can ensure that no error occurs when applying memory
}
uint32_t bits = BN_Bits(e);
for (uint32_t i = 1; i < bits; i++) {
ret = BN_ModSqr(y, y, m, opt); // y is a temporary variable, which is multiplied by x
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (BN_GetBit(e, i) == 1) {
ret = BN_ModMul(x, x, y, m, opt); // x^1101 = x^1 * x^100 * x^1000
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
}
return CRYPT_SUCCESS;
}
static int32_t SwitchMont(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e, const BN_BigNum *m, BN_Optimizer *opt)
{
BN_Mont *mont = BN_MontCreate(m);
if (mont == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret = BN_MontExp(r, a, e, mont, opt);
BN_MontDestroy(mont);
return ret;
}
int32_t BN_ModExp(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e, const BN_BigNum *m, BN_Optimizer *opt)
{
int32_t ret = ModExpInputCheck(r, a, e, m, opt);
if (ret != CRYPT_SUCCESS) {
return ret;
}
// When m = 1 or -1
if (m->size == 1 && m->data[0] == 1) {
return BN_Zeroize(r);
}
if (BN_IsOdd(m) && !BN_IsNegative(m)) {
return SwitchMont(r, a, e, m, opt);
}
ret = OptimizerStart(opt); // using the Optimizer
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
/* Apply for the temporary space of the BN object. */
BN_BigNum *x = OptimizerGetBn(opt, m->size);
BN_BigNum *y = OptimizerGetBn(opt, m->size);
if (x == NULL || y == NULL) {
OptimizerEnd(opt); // release occupation from the optimizer
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
// step 1: Obtain the modulus once, and then determine the power and remainder.
ret = BN_Mod(y, a, m, opt);
if (ret != CRYPT_SUCCESS) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// step2: check the power. Any number to the power of 0 is 1. (0 to the power of 0 to the power of 0)
if (BN_IsZero(e) || BN_IsOne(y)) {
OptimizerEnd(opt);
return BN_SetLimb(r, 1);
}
// step3: The remainder is 0 and the result must be 0.
if (BN_IsZero(y)) {
OptimizerEnd(opt); // release occupation from the optimizer
return BN_Zeroize(r);
}
/* Power factorization: e binary x^1101 = x^1 * x^100 * x^1000
e Decimal x^13 = x^1 * x^4 * x^8 */
ret = ModExpCore(x, y, e, m, opt);
if (ret != CRYPT_SUCCESS) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = BN_Copy(r, x);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
OptimizerEnd(opt); // release occupation from the optimizer
return ret;
}
int32_t BN_Rshift(BN_BigNum *r, const BN_BigNum *a, uint32_t n)
{
if (r == NULL || a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (BN_Bits(a) <= n) {
return BN_Zeroize(r);
}
int32_t ret = BnExtend(r, BITS_TO_BN_UNIT(BN_Bits(a) - n));
if (ret != CRYPT_SUCCESS) {
return ret;
}
r->sign = a->sign;
uint32_t size = BinRshift(r->data, a->data, a->size, n);
if (size < r->size) {
if (memset_s(r->data + size, (r->room - size) * sizeof(BN_UINT), 0,
(r->size - size) * sizeof(BN_UINT)) != EOK) {
BSL_ERR_PUSH_ERROR(CRYPT_SECUREC_FAIL);
return CRYPT_SECUREC_FAIL;
}
}
r->size = size;
return CRYPT_SUCCESS;
}
int32_t BN_Lshift(BN_BigNum *r, const BN_BigNum *a, uint32_t n)
{
if (r == NULL || a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
uint32_t incUnit = n % BN_UINT_BITS == 0 ? (n / BN_UINT_BITS) : ((n / BN_UINT_BITS) + 1);
int32_t ret = BnExtend(r, a->size + incUnit);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if (a->size != 0) {
r->size = BinLshift(r->data, a->data, a->size, n);
} else {
(void)BN_Zeroize(r);
}
r->sign = a->sign;
return CRYPT_SUCCESS;
}
#ifdef HITLS_CRYPTO_ECC
// '~mask' is the mask of a and 'mask' is the mask of b.
int32_t BN_CopyWithMask(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b,
BN_UINT mask)
{
if (r == NULL || a == NULL || b == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if ((a->room != r->room) || (b->room != r->room)) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_MASKCOPY_LEN);
return CRYPT_BN_ERR_MASKCOPY_LEN;
}
BN_UINT rmask = ~mask;
uint32_t len = r->room;
BN_UINT *dst = r->data;
BN_UINT *srcA = a->data;
BN_UINT *srcB = b->data;
for (uint32_t i = 0; i < len; i++) {
dst[i] = (srcA[i] & rmask) ^ (srcB[i] & mask);
}
r->sign = (mask != 0) ? (a->sign) : (b->sign);
r->size = (a->size & (uint32_t)rmask) ^ (b->size & (uint32_t)mask);
return CRYPT_SUCCESS;
}
#endif
#if defined(HITLS_CRYPTO_ECC) && defined(HITLS_CRYPTO_CURVE_MONT)
/* Invoked by the ECC module and the sign can be ignored.
* if mask = BN_MASK, a, b --> b, a
* if mask = 0, a, b --> a, b
*/
int32_t BN_SwapWithMask(BN_BigNum *a, BN_BigNum *b, BN_UINT mask)
{
if (a == NULL || b == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (a->room != b->room) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_SWAP_LEN);
return CRYPT_BN_ERR_SWAP_LEN;
}
BN_UINT rmask = ~mask;
BN_UINT *srcA = a->data;
BN_UINT *srcB = b->data;
BN_UINT tmp1;
BN_UINT tmp2;
for (uint32_t i = 0; i < a->room; i++) {
tmp1 = srcA[i];
tmp2 = srcB[i];
srcA[i] = (tmp1 & rmask) | (tmp2 & mask);
srcB[i] = (tmp2 & rmask) | (tmp1 & mask);
}
tmp1 = a->size;
tmp2 = b->size;
a->size = (tmp1 & (uint32_t)rmask) | (tmp2 & (uint32_t)mask);
b->size = (tmp2 & (uint32_t)rmask) | (tmp1 & (uint32_t)mask);
return CRYPT_SUCCESS;
}
#endif // HITLS_CRYPTO_ECC and HITLS_CRYPTO_CURVE_MONT
#endif /* HITLS_CRYPTO_BN */
|
2301_79861745/bench_create
|
crypto/bn/src/bn_operation.c
|
C
|
unknown
| 29,125
|
/*
* 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_BN
#include <stdint.h>
#include <string.h>
#include "securec.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "bn_optimizer.h"
BN_Optimizer *BN_OptimizerCreate(void)
{
BN_Optimizer *opt = BSL_SAL_Calloc(1u, sizeof(BN_Optimizer));
if (opt == NULL) {
return NULL;
}
opt->curChunk = BSL_SAL_Calloc(1u, sizeof(Chunk));
if (opt->curChunk == NULL) {
BSL_SAL_FREE(opt);
return NULL;
}
return opt;
}
void BN_OptimizerSetLibCtx(void *libCtx, BN_Optimizer *opt)
{
opt->libCtx = libCtx;
}
void *BN_OptimizerGetLibCtx(BN_Optimizer *opt)
{
return opt->libCtx;
}
void BN_OptimizerDestroy(BN_Optimizer *opt)
{
if (opt == NULL) {
return;
}
Chunk *curChunk = opt->curChunk;
Chunk *nextChunk = curChunk->next;
Chunk *prevChunk = curChunk->prev;
while (nextChunk != NULL) {
for (uint32_t i = 0; i < HITLS_CRYPT_OPTIMIZER_BN_NUM; i++) {
BSL_SAL_CleanseData((void *)(nextChunk->bigNums[i].data), nextChunk->bigNums[i].size * sizeof(BN_UINT));
BSL_SAL_FREE(nextChunk->bigNums[i].data);
}
Chunk *tmp = nextChunk->next;
BSL_SAL_Free(nextChunk);
nextChunk = tmp;
}
while (prevChunk != NULL) {
for (uint32_t i = 0; i < HITLS_CRYPT_OPTIMIZER_BN_NUM; i++) {
BSL_SAL_CleanseData((void *)(prevChunk->bigNums[i].data), prevChunk->bigNums[i].size * sizeof(BN_UINT));
BSL_SAL_FREE(prevChunk->bigNums[i].data);
}
Chunk *tmp = prevChunk->prev;
BSL_SAL_Free(prevChunk);
prevChunk = tmp;
}
// curChunk != NULL
for (uint32_t i = 0; i < HITLS_CRYPT_OPTIMIZER_BN_NUM; i++) {
BSL_SAL_CleanseData((void *)(curChunk->bigNums[i].data), curChunk->bigNums[i].size * sizeof(BN_UINT));
BSL_SAL_FREE(curChunk->bigNums[i].data);
}
BSL_SAL_Free(curChunk);
BSL_SAL_Free(opt);
}
int32_t OptimizerStart(BN_Optimizer *opt)
{
if (opt->deep != CRYPT_OPTIMIZER_MAXDEEP) {
opt->deep++;
return CRYPT_SUCCESS;
}
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_STACK_FULL);
return CRYPT_BN_OPTIMIZER_STACK_FULL;
}
/* create a new room that has not been initialized */
static BN_BigNum *GetPresetBn(BN_Optimizer *opt, Chunk *curChunk)
{
if (curChunk->occupied != HITLS_CRYPT_OPTIMIZER_BN_NUM) {
curChunk->occupied++;
return &curChunk->bigNums[curChunk->occupied - 1];
}
if (curChunk->prev != NULL) {
opt->curChunk = curChunk->prev;
opt->curChunk->occupied++; // new chunk and occupied = 0;
return &opt->curChunk->bigNums[opt->curChunk->occupied - 1];
}
// We has used all chunks.
Chunk *newChunk = BSL_SAL_Calloc(1u, sizeof(Chunk));
if (newChunk == NULL) {
return NULL;
}
newChunk->next = curChunk;
curChunk->prev = newChunk;
opt->curChunk = newChunk;
newChunk->occupied++;
return &newChunk->bigNums[newChunk->occupied - 1];
}
static int32_t BnMake(BN_BigNum *r, uint32_t room)
{
if (r->room < room) {
if (room > BITS_TO_BN_UNIT(BN_MAX_BITS)) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_BITS_TOO_MAX);
return CRYPT_BN_BITS_TOO_MAX;
}
BN_UINT *tmp = (BN_UINT *)BSL_SAL_Calloc(1u, room * sizeof(BN_UINT));
if (tmp == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
if (r->size > 0) {
BSL_SAL_CleanseData(r->data, r->size * sizeof(BN_UINT));
}
BSL_SAL_FREE(r->data);
r->data = tmp;
r->room = room;
} else {
(void)memset_s(r->data, r->room * sizeof(BN_UINT), 0, r->room * sizeof(BN_UINT));
}
r->size = 0;
r->sign = false;
r->flag |= CRYPT_BN_FLAG_OPTIMIZER;
return CRYPT_SUCCESS;
}
/* create a BigNum and initialize to 0 */
BN_BigNum *OptimizerGetBn(BN_Optimizer *opt, uint32_t room)
{
if (opt->deep == 0) {
return NULL;
}
if ((opt->used[opt->deep - 1] + 1) < opt->used[opt->deep - 1]) {
// Avoid overflow
return NULL;
}
BN_BigNum *tmp = GetPresetBn(opt, opt->curChunk);
if (tmp == NULL) {
return NULL;
}
if (BnMake(tmp, room) != CRYPT_SUCCESS) {
return NULL;
}
opt->used[opt->deep - 1]++;
return tmp;
}
void OptimizerEnd(BN_Optimizer *opt)
{
if (opt->deep == 0) {
return;
}
opt->deep--;
uint32_t usedNum = opt->used[opt->deep];
opt->used[opt->deep] = 0;
Chunk *curChunk = opt->curChunk;
if (usedNum <= curChunk->occupied) {
curChunk->occupied -= usedNum;
return;
}
usedNum -= curChunk->occupied;
curChunk->occupied = 0;
while (usedNum >= HITLS_CRYPT_OPTIMIZER_BN_NUM) {
curChunk = curChunk->next;
curChunk->occupied = 0;
usedNum -= HITLS_CRYPT_OPTIMIZER_BN_NUM;
}
if (usedNum != 0) {
curChunk = curChunk->next;
curChunk->occupied = HITLS_CRYPT_OPTIMIZER_BN_NUM - usedNum;
}
opt->curChunk = curChunk;
return;
}
#endif /* HITLS_CRYPTO_BN */
|
2301_79861745/bench_create
|
crypto/bn/src/bn_optimizer.c
|
C
|
unknown
| 5,708
|
/*
* 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 BN_OPTIMIZER_H
#define BN_OPTIMIZER_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_BN
#include "bn_basic.h"
#ifdef __cplusplus
extern "c" {
#endif
#define CRYPT_OPTIMIZER_MAXDEEP 10
/*
* Peak memory usage of the bn process during RSA key generation. BN_NUM stands for HITLS_CRYPT_OPTIMIZER_BN_NUM.
* |----------------------------+--------+--------+--------+--------+--------|
* | key bits\memory(Kb)\BN_NUM | 16 | 24 | 32 | 48 | 64 |
* |----------------------------+--------+--------+--------+--------+--------|
* | rsa1024 | 9.0 | 9.7 | 9.7 | 10.8 | 12.0 |
* | rsa2048 | 20.4 | 21.0 | 21.1 | 22.6 | 22.6 |
* | rsa3072 | 37.8 | 38.3 | 38.5 | 40.0 | 40.0 |
* | rsa4096 | 73.5 | 73.5 | 74.2 | 75.7 | 75.7 |
* |----------------------------+--------+--------+--------+--------+--------|
*
* The number of chunk during RSA key generation. BN_NUM stands for HITLS_CRYPT_OPTIMIZER_BN_NUM.
* |----------------------------+--------+--------+--------+--------+--------|
* |key bits\chunk number\BN_NUM| 16 | 24 | 32 | 48 | 64 |
* |----------------------------+--------+--------+--------+--------+--------|
* | rsa1024 | 352 | 352 | 193 | 193 | 193 |
* | rsa2048 | 1325 | 1035 | 745 | 745 | 455 |
* | rsa3072 | 1597 | 1227 | 857 | 857 | 487 |
* | rsa4096 | 2522 | 1967 | 1412 | 1412 | 857 |
* |----------------------------+--------+--------+--------+--------+--------|
*/
#ifndef HITLS_CRYPT_OPTIMIZER_BN_NUM
#define HITLS_CRYPT_OPTIMIZER_BN_NUM 32
#endif
typedef struct ChunkStruct {
uint32_t occupied; /** < occupied of current chunk */
BN_BigNum bigNums[HITLS_CRYPT_OPTIMIZER_BN_NUM]; /** < preset BN_BigNums */
struct ChunkStruct *prev; /** < prev optimizer node */
struct ChunkStruct *next; /** < prev optimizer node */
} Chunk;
struct BnOptimizer {
uint32_t deep; /* depth of stack */
uint32_t used[CRYPT_OPTIMIZER_MAXDEEP]; /* size of the used stack */
Chunk *curChunk; /** < chunk, the last point*/
void *libCtx;
};
#ifdef __cplusplus
}
#endif
#endif /* HITLS_CRYPTO_BN */
#endif
|
2301_79861745/bench_create
|
crypto/bn/src/bn_optimizer.h
|
C
|
unknown
| 2,911
|
/*
* 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_BN_PRIME
#include <stdint.h>
#include "securec.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "bn_bincal.h"
#include "bn_optimizer.h"
/*
* Differential table of adjacent prime numbers, size = 1024
* The times of trial division will affect whether the number enters the Miller-rabin test.
* We consider common prime lengths: 1024, 2048, 4096, 8192 bits.
* 1024 bits: we choose 128 try times, ref the paper of 'A Performant, Misuse-Resistant API for Primality Testing'.
* 2048 bits: 128 try times: 1 (performance baseline)
* 384 try times: +0.15
* 512 try times: +0.03
* 1024 try times: +0.16
* 4096 bits: 1024 try times: 0.04 tps
* 2048 try times: 0.02 tps
* 8192 bits: 1024 try times: 0.02 tps
* 2048 try times: 0.02 tps
*/
static const uint8_t PRIME_DIFF_TABLE[1024] = {
0, 1, 2, 2, 4, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6,
6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4, 2, 4, 14, 4,
6, 2, 10, 2, 6, 6, 4, 6, 6, 2, 10, 2, 4, 2, 12, 12,
4, 2, 4, 6, 2, 10, 6, 6, 6, 2, 6, 4, 2, 10, 14, 4,
2, 4, 14, 6, 10, 2, 4, 6, 8, 6, 6, 4, 6, 8, 4, 8,
10, 2, 10, 2, 6, 4, 6, 8, 4, 2, 4, 12, 8, 4, 8, 4,
6, 12, 2, 18, 6, 10, 6, 6, 2, 6, 10, 6, 6, 2, 6, 6,
4, 2, 12, 10, 2, 4, 6, 6, 2, 12, 4, 6, 8, 10, 8, 10,
8, 6, 6, 4, 8, 6, 4, 8, 4, 14, 10, 12, 2, 10, 2, 4,
2, 10, 14, 4, 2, 4, 14, 4, 2, 4, 20, 4, 8, 10, 8, 4,
6, 6, 14, 4, 6, 6, 8, 6, 12, 4, 6, 2, 10, 2, 6, 10,
2, 10, 2, 6, 18, 4, 2, 4, 6, 6, 8, 6, 6, 22, 2, 10,
8, 10, 6, 6, 8, 12, 4, 6, 6, 2, 6, 12, 10, 18, 2, 4,
6, 2, 6, 4, 2, 4, 12, 2, 6, 34, 6, 6, 8, 18, 10, 14,
4, 2, 4, 6, 8, 4, 2, 6, 12, 10, 2, 4, 2, 4, 6, 12,
12, 8, 12, 6, 4, 6, 8, 4, 8, 4, 14, 4, 6, 2, 4, 6,
2, 6, 10, 20, 6, 4, 2, 24, 4, 2, 10, 12, 2, 10, 8, 6,
6, 6, 18, 6, 4, 2, 12, 10, 12, 8, 16, 14, 6, 4, 2, 4,
2, 10, 12, 6, 6, 18, 2, 16, 2, 22, 6, 8, 6, 4, 2, 4,
8, 6, 10, 2, 10, 14, 10, 6, 12, 2, 4, 2, 10, 12, 2, 16,
2, 6, 4, 2, 10, 8, 18, 24, 4, 6, 8, 16, 2, 4, 8, 16,
2, 4, 8, 6, 6, 4, 12, 2, 22, 6, 2, 6, 4, 6, 14, 6,
4, 2, 6, 4, 6, 12, 6, 6, 14, 4, 6, 12, 8, 6, 4, 26,
18, 10, 8, 4, 6, 2, 6, 22, 12, 2, 16, 8, 4, 12, 14, 10,
2, 4, 8, 6, 6, 4, 2, 4, 6, 8, 4, 2, 6, 10, 2, 10,
8, 4, 14, 10, 12, 2, 6, 4, 2, 16, 14, 4, 6, 8, 6, 4,
18, 8, 10, 6, 6, 8, 10, 12, 14, 4, 6, 6, 2, 28, 2, 10,
8, 4, 14, 4, 8, 12, 6, 12, 4, 6, 20, 10, 2, 16, 26, 4,
2, 12, 6, 4, 12, 6, 8, 4, 8, 22, 2, 4, 2, 12, 28, 2,
6, 6, 6, 4, 6, 2, 12, 4, 12, 2, 10, 2, 16, 2, 16, 6,
20, 16, 8, 4, 2, 4, 2, 22, 8, 12, 6, 10, 2, 4, 6, 2,
6, 10, 2, 12, 10, 2, 10, 14, 6, 4, 6, 8, 6, 6, 16, 12,
2, 4, 14, 6, 4, 8, 10, 8, 6, 6, 22, 6, 2, 10, 14, 4,
6, 18, 2, 10, 14, 4, 2, 10, 14, 4, 8, 18, 4, 6, 2, 4,
6, 2, 12, 4, 20, 22, 12, 2, 4, 6, 6, 2, 6, 22, 2, 6,
16, 6, 12, 2, 6, 12, 16, 2, 4, 6, 14, 4, 2, 18, 24, 10,
6, 2, 10, 2, 10, 2, 10, 6, 2, 10, 2, 10, 6, 8, 30, 10,
2, 10, 8, 6, 10, 18, 6, 12, 12, 2, 18, 6, 4, 6, 6, 18,
2, 10, 14, 6, 4, 2, 4, 24, 2, 12, 6, 16, 8, 6, 6, 18,
16, 2, 4, 6, 2, 6, 6, 10, 6, 12, 12, 18, 2, 6, 4, 18,
8, 24, 4, 2, 4, 6, 2, 12, 4, 14, 30, 10, 6, 12, 14, 6,
10, 12, 2, 4, 6, 8, 6, 10, 2, 4, 14, 6, 6, 4, 6, 2,
10, 2, 16, 12, 8, 18, 4, 6, 12, 2, 6, 6, 6, 28, 6, 14,
4, 8, 10, 8, 12, 18, 4, 2, 4, 24, 12, 6, 2, 16, 6, 6,
14, 10, 14, 4, 30, 6, 6, 6, 8, 6, 4, 2, 12, 6, 4, 2,
6, 22, 6, 2, 4, 18, 2, 4, 12, 2, 6, 4, 26, 6, 6, 4,
8, 10, 32, 16, 2, 6, 4, 2, 4, 2, 10, 14, 6, 4, 8, 10,
6, 20, 4, 2, 6, 30, 4, 8, 10, 6, 6, 8, 6, 12, 4, 6,
2, 6, 4, 6, 2, 10, 2, 16, 6, 20, 4, 12, 14, 28, 6, 20,
4, 18, 8, 6, 4, 6, 14, 6, 6, 10, 2, 10, 12, 8, 10, 2,
10, 8, 12, 10, 24, 2, 4, 8, 6, 4, 8, 18, 10, 6, 6, 2,
6, 10, 12, 2, 10, 6, 6, 6, 8, 6, 10, 6, 2, 6, 6, 6,
10, 8, 24, 6, 22, 2, 18, 4, 8, 10, 30, 8, 18, 4, 2, 10,
6, 2, 6, 4, 18, 8, 12, 18, 16, 6, 2, 12, 6, 10, 2, 10,
2, 6, 10, 14, 4, 24, 2, 16, 2, 10, 2, 10, 20, 4, 2, 4,
8, 16, 6, 6, 2, 12, 16, 8, 4, 6, 30, 2, 10, 2, 6, 4,
6, 6, 8, 6, 4, 12, 6, 8, 12, 4, 14, 12, 10, 24, 6, 12,
6, 2, 22, 8, 18, 10, 6, 14, 4, 2, 6, 10, 8, 6, 4, 6,
30, 14, 10, 2, 12, 10, 2, 16, 2, 18, 24, 18, 6, 16, 18, 6,
2, 18, 4, 6, 2, 10, 8, 10, 6, 6, 8, 4, 6, 2, 10, 2,
12, 4, 6, 6, 2, 12, 4, 14, 18, 4, 6, 20, 4, 8, 6, 4,
8, 4, 14, 6, 4, 14, 12, 4, 2, 30, 4, 24, 6, 6, 12, 12,
14, 6, 4, 2, 4, 18, 6, 12, 8, 6, 4, 12, 2, 12, 30, 16,
2, 6, 22, 14, 6, 10, 12, 6, 2, 4, 8, 10, 6, 6, 24, 14
};
/* Times of trial division. */
static uint32_t DivisorsCnt(uint32_t bits)
{
if (bits <= 1024) { /* 1024bit */
return 128; /* 128 times check */
}
return 1024; /* 1024 times check */
}
// Minimum times of checking for Miller-Rabin.
// The probability of errors in a check is one quarter. After 64 rounds of check, the error rate is 2 ^ - 128.
static uint32_t MinChecks(uint32_t bits)
{
if (bits >= 2048) { /* 2048bit */
return 128; /* 128 rounds of verification */
}
return 64; /* 64 rounds of verification */
}
/* A BigNum mod a limb, limb < (1 << (BN_UINT_BITS >> 1)) */
static BN_UINT ModLimbHalf(const BN_BigNum *a, BN_UINT w)
{
BN_UINT rem = 0;
uint32_t i;
for (i = a->size; i > 0; i--) {
MOD_HALF(rem, rem, a->data[i - 1], w);
}
return rem;
}
static int32_t LimbCheck(const BN_BigNum *bn)
{
uint32_t bits = BN_Bits(bn);
uint32_t cnt = DivisorsCnt(bits);
int32_t ret = CRYPT_SUCCESS;
BN_UINT littlePrime = 2;
for (uint32_t i = 0; i < cnt; i++) {
// Try division. Large prime numbers do not divide small prime numbers.
littlePrime += PRIME_DIFF_TABLE[i];
BN_UINT mod = ModLimbHalf(bn, littlePrime);
if (mod == 0) {
if (BN_IsLimb(bn, littlePrime) == false) { // small prime judgement
ret = CRYPT_BN_NOR_CHECK_PRIME;
}
break;
}
}
return ret;
}
/* The random number increases by 2 each time, and added for n times,
so that it is mutually primed to all data in the prime table. */
static int32_t FillUp(BN_BigNum *rnd, const BN_UINT *mods, uint32_t modsLen)
{
uint32_t i;
uint32_t complete = 0;
uint32_t bits = BN_Bits(rnd);
uint32_t cnt = modsLen;
BN_UINT inc = 0;
while (complete == 0) {
BN_UINT littlePrime = 2; // the minimum prime = 2
for (i = 1; i < cnt; i++) {
/* check */
littlePrime += PRIME_DIFF_TABLE[i];
if ((mods[i] + inc) % littlePrime == 0) {
inc += 2; // inc increases by 2 each time
break;
}
if (i == cnt - 1) { // end and exit
complete = 1;
}
}
if (inc + 2 == 0) { // inc increases by 2 each time. Check whether the inc may overflow.
BSL_ERR_PUSH_ERROR(CRYPT_BN_NOR_CHECK_PRIME);
return CRYPT_BN_NOR_CHECK_PRIME;
}
}
int32_t ret = BN_AddLimb(rnd, rnd, inc);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// If the random number length of a prime number is incorrect, generate a new random number.
if (BN_Bits(rnd) != bits) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_NOR_CHECK_PRIME);
return CRYPT_BN_NOR_CHECK_PRIME;
}
return CRYPT_SUCCESS;
}
/* Generate random numbers that can be mutually primed with the data in the small prime number table. */
static int32_t ProbablePrime(BN_BigNum *rnd, BN_BigNum *e, uint32_t bits, bool half, BN_Optimizer *opt)
{
const int32_t maxCnt = 100; /* try 100 times */
int32_t tryCnt = 0;
uint32_t i;
int32_t ret;
uint32_t cnt = DivisorsCnt(bits);
ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
return ret;
}
BN_BigNum *mods = OptimizerGetBn(opt, cnt);
if (mods == NULL) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
uint32_t top = ((half == true) ? BN_RAND_TOP_TWOBIT : BN_RAND_TOP_ONEBIT);
do {
tryCnt++;
if (tryCnt > maxCnt) {
/* If it cannot be generated after loop 100 times, a failure message is returned. */
OptimizerEnd(opt);
/* In this case, the random number may be incorrect. Keep the error information. */
BSL_ERR_PUSH_ERROR(CRYPT_BN_NOR_GEN_PRIME);
return CRYPT_BN_NOR_GEN_PRIME;
}
// 'top' can control whether to set the most two significant bits to 1.
// RSA key generation usually focuses on this parameter to ensure the length of p*q.
ret = BN_RandEx(opt->libCtx, rnd, bits, top, BN_RAND_BOTTOM_ONEBIT);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
OptimizerEnd(opt);
return ret;
}
BN_UINT littlePrime = 2; // the minimum prime = 2
// Random number rnd divided by the prime number in the table of small prime numbers, modulo mods.
for (i = 1; i < cnt; i++) {
littlePrime += PRIME_DIFF_TABLE[i];
mods->data[i] = ModLimbHalf(rnd, littlePrime);
}
// Check the mods and supplement the rnd.
ret = FillUp(rnd, mods->data, cnt);
if (ret != CRYPT_BN_NOR_CHECK_PRIME && ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
OptimizerEnd(opt);
return ret;
}
if (ret != CRYPT_BN_NOR_CHECK_PRIME && e != NULL) {
// check if rnd-1 and e are coprime
// reference: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-5.pdf A.1.3
BN_BigNum *rnd1 = OptimizerGetBn(opt, BITS_TO_BN_UNIT(bits));
BN_BigNum *inv = OptimizerGetBn(opt, e->size);
if (rnd1 == NULL || inv == NULL) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
ret = BN_SubLimb(rnd1, rnd, 1);
if (ret != CRYPT_SUCCESS) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = BN_ModInv(inv, rnd1, e, opt);
}
} while (ret == CRYPT_BN_NOR_CHECK_PRIME);
OptimizerEnd(opt);
return ret;
}
static int32_t BnCheck(const BN_BigNum *bnSubOne, const BN_BigNum *bnSubThree,
const BN_BigNum *divisor, const BN_BigNum *rnd, const BN_Mont *mont)
{
if (bnSubOne == NULL || bnSubThree == NULL || divisor == NULL || rnd == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
if (mont == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
return CRYPT_SUCCESS;
}
static int32_t GenRnd(void *libCtx, BN_BigNum *rnd, const BN_BigNum *bnSubThree)
{
int32_t ret = BN_RandRangeEx(libCtx, rnd, bnSubThree);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
return BN_AddLimb(rnd, rnd, 2); /* bn - 3 + 2 = bn - 1 */
}
static bool SumCorrect(BN_BigNum *sum, const BN_BigNum *bnSubOne)
{
if (BN_IsOne(sum) || BN_Cmp(sum, bnSubOne) == 0) {
(void)BN_SetLimb(sum, 1);
return true;
}
return false;
}
int32_t MillerRabinCheckCore(const BN_BigNum *bn, BN_Mont *mont, BN_BigNum *rnd,
const BN_BigNum *divisor, const BN_BigNum *bnSubOne, const BN_BigNum *bnSubThree,
uint32_t p, uint32_t checkTimes, BN_Optimizer *opt, BN_CbCtx *cb)
{
uint32_t i, j;
int32_t ret = CRYPT_SUCCESS;
uint32_t checks = (checkTimes == 0) ? MinChecks(BN_Bits(bn)) : checkTimes;
BN_BigNum *sum = rnd;
for (i = 0; i < checks; i++) {
// 3.1 Generate a random number rnd, 2 < rnd < n-1
ret = GenRnd(opt->libCtx, rnd, bnSubThree);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// 3.2 Calculate base = rnd^divisor mod bn
ret = BN_MontExp(sum, rnd, divisor, mont, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
for (j = 0; j < p; j++) {
// If sum is equal to 1 or bn-1, the modulus square result must be 1. Exit directly.
if (SumCorrect(sum, bnSubOne)) {
break;
}
// sum < bn
ret = MontSqrCore(sum, sum, mont, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// Inverse negation of Miller Rabin's theorem, if equal to 1, bn is not a prime number.
if (BN_IsOne(sum)) {
ret = CRYPT_BN_NOR_CHECK_PRIME;
return ret;
}
}
// 3.4 Fermat's little theorem inverse negation if sum = rnd^(bn -1) != 1 mod bn, bn is not a prime number.
if (!BN_IsOne(sum)) {
ret = CRYPT_BN_NOR_CHECK_PRIME;
return ret;
}
#ifdef HITLS_CRYPTO_BN_CB
ret = BN_CbCtxCall(cb, 0, 0);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
#else
(void)cb;
#endif
}
return ret;
}
static int32_t BnSubGet(BN_BigNum *bnSubOne, BN_BigNum *bnSubThree, const BN_BigNum *bn)
{
int32_t ret = BN_SubLimb(bnSubOne, bn, 1); /* bn - 1 */
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
return BN_SubLimb(bnSubThree, bn, 3); /* bn - 3 */
}
static int32_t PrimeLimbCheck(const BN_BigNum *bn)
{
if (BN_IsLimb(bn, 2) || BN_IsLimb(bn, 3)) { /* 2 and 3 directly determine that the number is a prime number. */
return CRYPT_SUCCESS;
}
BSL_ERR_PUSH_ERROR(CRYPT_BN_NOR_CHECK_PRIME);
return CRYPT_BN_NOR_CHECK_PRIME;
}
static uint32_t GetP(const BN_BigNum *bn)
{
uint32_t p = 0;
while (!BN_GetBit(bn, p)) {
p++;
}
return p;
}
// CRYPT_SUCCESS is returned for a prime number,
// and CRYPT_BN_NOR_CHECK_PRIME is returned for a non-prime number. Other error codes are returned.
static int32_t MillerRabinPrimeVerify(const BN_BigNum *bn, uint32_t checkTimes, BN_Optimizer *opt, BN_CbCtx *cb)
{
int32_t ret = CRYPT_SUCCESS;
uint32_t p;
if (PrimeLimbCheck(bn) == CRYPT_SUCCESS) { /* 2 and 3 directly determine that the number is a prime number. */
return CRYPT_SUCCESS;
}
if (!BN_GetBit(bn, 0)) { // even
BSL_ERR_PUSH_ERROR(CRYPT_BN_NOR_CHECK_PRIME);
return CRYPT_BN_NOR_CHECK_PRIME;
}
ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
return ret;
}
BN_BigNum *bnSubOne = OptimizerGetBn(opt, bn->size); // bnSubOne = bn - 1
BN_BigNum *bnSubThree = OptimizerGetBn(opt, bn->size); // bnSubThree = bn - 3
BN_BigNum *divisor = OptimizerGetBn(opt, bn->size); // divisor = bnSubOne / 2^p
BN_BigNum *rnd = OptimizerGetBn(opt, bn->size); // rnd to verify bn
BN_Mont *mont = BN_MontCreate(bn);
ret = BnCheck(bnSubOne, bnSubThree, divisor, rnd, mont);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto err;
}
ret = BnSubGet(bnSubOne, bnSubThree, bn);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto err;
}
// 1. Extract the power p of factor 2 in bnSubOne.
p = GetP(bnSubOne);
// 2. Number after factor 2 is extracted by bnSubOne. divisor = (bn - 1) / 2^p
ret = BN_Rshift(divisor, bnSubOne, p);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto err;
}
ret = MillerRabinCheckCore(bn, mont, rnd, divisor, bnSubOne, bnSubThree, p, checkTimes, opt, cb);
err:
BN_MontDestroy(mont);
OptimizerEnd(opt);
return ret;
}
// CRYPT_SUCCESS is returned for a prime number,
// and CRYPT_BN_NOR_CHECK_PRIME is returned for a non-prime number. Other error codes are returned.
int32_t BN_PrimeCheck(const BN_BigNum *bn, uint32_t checkTimes, BN_Optimizer *opt, BN_CbCtx *cb)
{
if (bn == NULL || opt == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret;
// Check whether the value is 0 or 1.
if (BN_IsZero(bn) || BN_IsOne(bn)) {
return CRYPT_BN_NOR_CHECK_PRIME;
}
// Check whether the number is negative.
if (bn->sign == 1) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_NOR_CHECK_PRIME);
return CRYPT_BN_NOR_CHECK_PRIME;
}
ret = LimbCheck(bn);
if (ret != CRYPT_SUCCESS) {
return ret;
}
#ifdef HITLS_CRYPTO_BN_CB
ret = BN_CbCtxCall(cb, 0, 0);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
#endif
return MillerRabinPrimeVerify(bn, checkTimes, opt, cb);
}
static int32_t GenPrimeLimb(BN_BigNum *bn, uint32_t bits, bool half, BN_Optimizer *opt)
{
const BN_UINT baseAll[11] = {0, 2, 4, 6, 11, 18, 31, 54, 97, 172, 309};
const BN_UINT cntAll[11] = {2, 2, 2, 5, 7, 13, 23, 43, 75, 137, 255};
const BN_UINT baseHalf[11] = {1, 3, 5, 9, 15, 24, 43, 76, 135, 242, 439};
const BN_UINT cntHalf[11] = {1, 1, 1, 2, 3, 7, 11, 21, 37, 67, 125};
const BN_UINT *base = baseAll;
const BN_UINT *cnt = cntAll;
if (half == true) {
base = baseHalf;
cnt = cntHalf;
}
int32_t ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BN_BigNum *bnCnt = OptimizerGetBn(opt, BITS_TO_BN_UNIT(bits));
BN_BigNum *bnRnd = OptimizerGetBn(opt, BITS_TO_BN_UNIT(bits));
if (bnCnt == NULL || bnRnd == NULL) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
(void)BN_SetLimb(bnCnt, cnt[bits - 2]); /* offset, the minimum bit of the interface is 2. */
ret = BN_RandRangeEx(opt->libCtx, bnRnd, bnCnt);
if (ret != CRYPT_SUCCESS) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BN_UINT rnd = bnRnd->data[0] + base[bits - 2]; /* offset, the minimum bit of the interface is 2. */
OptimizerEnd(opt);
BN_UINT littlePrime = 2;
for (BN_UINT i = 1; i <= rnd; i++) {
littlePrime += PRIME_DIFF_TABLE[i];
}
return BN_SetLimb(bn, littlePrime);
}
static int32_t GenCheck(BN_BigNum *bn, uint32_t bits, const BN_Optimizer *opt)
{
if (bn == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (opt == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (bits < 2) { // The number of bits less than 2 can only be 0 or 1. The prime number cannot be generated.
BSL_ERR_PUSH_ERROR(CRYPT_BN_NOR_CHECK_PRIME);
return CRYPT_BN_NOR_CHECK_PRIME;
}
return BnExtend(bn, BITS_TO_BN_UNIT(bits));
}
// If the prime number r is generated successfully, CRYPT_SUCCESS is returned.
// If the prime number r fails to be generated, CRYPT_BN_NOR_GEN_PRIME is returned. Other error codes are returned.
// If half is 1, the prime number whose two most significant bits are 1 is generated.
int32_t BN_GenPrime(BN_BigNum *r, BN_BigNum *e, uint32_t bits, bool half, BN_Optimizer *opt, BN_CbCtx *cb)
{
int32_t time = 0;
#ifndef HITLS_CRYPTO_BN_CB
(void)cb;
const int32_t maxTime = 256; /* The maximum number of cycles is 256. If no prime number is generated after the
* maximum number of cycles, the operation fails. */
#endif
int32_t ret = GenCheck(r, bits, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (bits < 13) { // < 13 is limited by the small prime table of 1024 size.
return GenPrimeLimb(r, bits, half, opt);
}
ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
/* To preventing insufficient space in addition operations when the rnd is constructed. */
BN_BigNum *rnd = OptimizerGetBn(opt, BITS_TO_BN_UNIT(bits) + 1);
if (rnd == NULL) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
return CRYPT_BN_OPTIMIZER_GET_FAIL;
}
do {
#ifdef HITLS_CRYPTO_BN_CB
if (BN_CbCtxCall(cb, time, 0) != CRYPT_SUCCESS) {
#else
if (time == maxTime) {
#endif
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(CRYPT_BN_NOR_GEN_PRIME);
return CRYPT_BN_NOR_GEN_PRIME;
}
// Generate a random number bn that may be a prime.
ret = ProbablePrime(rnd, e, bits, half, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
OptimizerEnd(opt);
return ret;
}
ret = MillerRabinPrimeVerify(rnd, 0, opt, cb);
time++;
} while (ret != CRYPT_SUCCESS);
OptimizerEnd(opt);
return BN_Copy(r, rnd);
}
#endif /* HITLS_CRYPTO_BN_PRIME */
|
2301_79861745/bench_create
|
crypto/bn/src/bn_prime.c
|
C
|
unknown
| 22,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"
#ifdef HITLS_CRYPTO_BN_RAND
#include <stdint.h>
#include "securec.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "bn_basic.h"
#include "bn_bincal.h"
#include "crypt_util_rand.h"
static int32_t RandGenerate(void *libCtx, BN_BigNum *r, uint32_t bits)
{
int32_t ret;
uint32_t room = BITS_TO_BN_UNIT(bits);
BN_UINT mask;
// Maxbits = (1 << 29) --> MaxBytes = (1 << 26), hence BN_BITS_TO_BYTES(bits) will not exceed the upper limit.
uint32_t byteSize = BN_BITS_TO_BYTES(bits);
uint8_t *buf = BSL_SAL_Malloc(byteSize);
if (buf == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
ret = CRYPT_RandEx(libCtx, buf, byteSize);
if (ret == CRYPT_NO_REGIST_RAND) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_RAND_GEN_FAIL);
ret = CRYPT_BN_RAND_GEN_FAIL;
goto ERR;
}
ret = BN_Bin2Bn(r, buf, byteSize);
BSL_SAL_CleanseData(buf, byteSize);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
mask = (BN_UINT)(-1) >> ((BN_UINT_BITS - bits % BN_UINT_BITS) % BN_UINT_BITS);
r->data[room - 1] &= mask;
r->size = BinFixSize(r->data, room);
ERR:
BSL_SAL_FREE(buf);
return ret;
}
static int32_t CheckTopAndBottom(uint32_t bits, uint32_t top, uint32_t bottom)
{
if (top > BN_RAND_TOP_TWOBIT) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_RAND_TOP_BOTTOM);
return CRYPT_BN_ERR_RAND_TOP_BOTTOM;
}
if (bottom > BN_RAND_BOTTOM_TWOBIT) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_RAND_TOP_BOTTOM);
return CRYPT_BN_ERR_RAND_TOP_BOTTOM;
}
if (top > bits || bottom > bits) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_RAND_BITS_NOT_ENOUGH);
return CRYPT_BN_ERR_RAND_BITS_NOT_ENOUGH;
}
return CRYPT_SUCCESS;
}
int32_t BN_Rand(BN_BigNum *r, uint32_t bits, uint32_t top, uint32_t bottom)
{
return BN_RandEx(NULL, r, bits, top, bottom);
}
int32_t BN_RandEx(void *libCtx, BN_BigNum *r, uint32_t bits, uint32_t top, uint32_t bottom)
{
if (r == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret = CheckTopAndBottom(bits, top, bottom);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (bits == 0) {
return BN_Zeroize(r);
}
if (bits > BN_MAX_BITS) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_BITS_TOO_MAX);
return CRYPT_BN_BITS_TOO_MAX;
}
ret = BnExtend(r, BITS_TO_BN_UNIT(bits));
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = RandGenerate(libCtx, r, bits);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
r->data[0] |= (bottom == BN_RAND_BOTTOM_TWOBIT) ? 0x3 : (BN_UINT)bottom; // CheckTopAndBottom ensure that bottom>0
if (top == BN_RAND_TOP_ONEBIT) {
(void)BN_SetBit(r, bits - 1);
} else if (top == BN_RAND_TOP_TWOBIT) {
(void)BN_SetBit(r, bits - 1);
(void)BN_SetBit(r, bits - 2); /* the most significant 2 bits are 1 */
}
r->size = BinFixSize(r->data, r->room);
return ret;
}
static int32_t InputCheck(BN_BigNum *r, const BN_BigNum *p)
{
if (r == NULL || p == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (BN_IsZero(p)) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_RAND_ZERO);
return CRYPT_BN_ERR_RAND_ZERO;
}
if (p->sign == true) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_RAND_NEGATIVE);
return CRYPT_BN_ERR_RAND_NEGATIVE;
}
return BnExtend(r, p->size);
}
int32_t BN_RandRange(BN_BigNum *r, const BN_BigNum *p)
{
return BN_RandRangeEx(NULL, r, p);
}
int32_t BN_RandRangeEx(void *libCtx, BN_BigNum *r, const BN_BigNum *p)
{
const int32_t maxCnt = 100; /* try 100 times */
int32_t tryCnt = 0;
int32_t ret;
ret = InputCheck(r, p);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = BN_Zeroize(r);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if (BN_IsOne(p)) {
return CRYPT_SUCCESS;
}
uint32_t bits = BN_Bits(p);
do {
tryCnt++;
if (tryCnt > maxCnt) {
/* The success rate is more than 50%. */
/* Return a failure if failed to generated after try 100 times */
BSL_ERR_PUSH_ERROR(CRYPT_BN_RAND_GEN_FAIL);
return CRYPT_BN_RAND_GEN_FAIL;
}
ret = RandGenerate(libCtx, r, bits);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
} while (BinCmp(r->data, r->size, p->data, p->size) >= 0);
return ret;
}
#endif /* HITLS_CRYPTO_BN_RAND */
|
2301_79861745/bench_create
|
crypto/bn/src/bn_rand.c
|
C
|
unknown
| 5,406
|
/*
* 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_ECC
#include <stdint.h>
#include <stdbool.h>
#include "securec.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "crypt_utils.h"
#include "bn_optimizer.h"
#include "crypt_bn.h"
static uint32_t GetExp(const BN_BigNum *bn)
{
uint32_t s = 0;
while (!BN_GetBit(bn, s)) {
s++;
}
return s;
}
// p does not perform prime number check, but performs parity check.
static int32_t CheckParam(const BN_BigNum *a, const BN_BigNum *p)
{
if (BN_IsZero(p) || BN_IsOne(p)) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_SQRT_PARA);
return CRYPT_BN_ERR_SQRT_PARA;
}
if (!BN_GetBit(p, 0)) { // p must be odd prime
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_SQRT_PARA);
return CRYPT_BN_ERR_SQRT_PARA;
}
if (p->sign || a->sign) { // p、a must be positive
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_SQRT_PARA);
return CRYPT_BN_ERR_SQRT_PARA;
}
if (BN_Cmp(p, a) <= 0) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_SQRT_PARA);
return CRYPT_BN_ERR_SQRT_PARA;
}
return CRYPT_SUCCESS;
}
// r = +- a^((p + 1)/4)
static int32_t CalculationRoot(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *p, BN_Mont *mont, BN_Optimizer *opt)
{
int32_t ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BN_BigNum *temp = OptimizerGetBn(opt, p->size);
if (temp == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
ret = CRYPT_MEM_ALLOC_FAIL;
goto ERR;
}
GOTO_ERR_IF_EX(BN_AddLimb(temp, p, 1), ret); // p + 1
GOTO_ERR_IF_EX(BN_Rshift(temp, temp, 2), ret); // (p + 1) / 4 = (p + 1) >> 2
GOTO_ERR_IF(BN_MontExp(r, a, temp, mont, opt), ret);
ERR:
OptimizerEnd(opt);
return ret;
}
static int32_t LegendreFastTempDataCheck(const BN_BigNum *a, const BN_BigNum *pp)
{
if (a == NULL || pp == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
return CRYPT_SUCCESS;
}
int32_t LegendreFast(BN_BigNum *z, const BN_BigNum *p, int32_t *legendre, BN_Optimizer *opt)
{
int32_t l = 1;
BN_BigNum *temp = NULL;
int32_t ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BN_BigNum *a = OptimizerGetBn(opt, p->size); // The variable has been checked for NULL in BN_Copy.
BN_BigNum *pp = OptimizerGetBn(opt, p->size);
GOTO_ERR_IF(LegendreFastTempDataCheck(a, pp), ret);
if (BN_IsOne(z)) {
*legendre = 1;
goto ERR;
}
if (BN_IsZero(z)) {
*legendre = 0;
goto ERR;
}
GOTO_ERR_IF_EX(BN_Copy(a, z), ret);
GOTO_ERR_IF_EX(BN_Copy(pp, p), ret);
while (true) {
if (BN_IsZero(a)) {
*legendre = BN_IsOne(pp) ? l : 0;
break;
}
// Theorem: p is an odd prime number, a and b are numbers that are not divisible by p. (a|p)(b|p) = (ab|p)
// a = aa * 2^exp
// (a|pp) = (2|pp)^exp * (aa|pp)
// If exp is an even number, (a|pp) = (aa|pp)
uint32_t exp = GetExp(a);
GOTO_ERR_IF_EX(BN_Rshift(a, a, exp), ret);
if ((exp & 1) != 0) {
// pp = +- 1 mod 8, 2 is its quadratic remainder. pp = +-3 mod 8, 2 is its non-quadric remainder.
if ((pp->data[0] & 1) != 0) {
// pp->data[0] % 8 = pp->data[0] & 7
// pp = +- 1 mod 8 = 7 or 1 mod
l = ((pp->data[0] & 7) == 1 || (pp->data[0] & 7) == 7) ? l : -l;
} else {
l = 0;
}
}
// pp->data[0] % 4 = pp->data[0] & 3
// K(a|pp) = K(pp|a) * (-1)^((a-1)*(pp-1)/4)
// (a-1)*(pp-1)/4 is an even number only when at least one of A and P mod 4 = 1;
// if both A and P mod 4 = 3, (a-1)*(pp-1)/4 is an odd number.
if (((pp->data[0] & 3) == 3) && ((a->data[0] & 3) == 3)) {
l = -l;
}
// K(pp|a) = K(pp%a|a), swap(a,pp)
GOTO_ERR_IF_EX(BN_Div(NULL, pp, pp, a, opt), ret);
temp = a;
a = pp;
pp = temp;
}
ret = CRYPT_SUCCESS;
ERR:
OptimizerEnd(opt);
return ret;
}
// Find z so that legendre(z / p) = z^((p-1)/2) mod p != 1
static int32_t GetLegendreZ(BN_BigNum *z, const BN_BigNum *p, BN_Optimizer *opt)
{
uint32_t maxCnt = 50; // A random number can be generated cyclically for a maximum of 50 times.
int32_t ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
int32_t legendre;
BN_BigNum *exp = OptimizerGetBn(opt, p->size); // exp = (p - 1) / 2
if (exp == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
ret = CRYPT_MEM_ALLOC_FAIL;
goto ERR;
}
GOTO_ERR_IF_EX(BN_SubLimb(exp, p, 1), ret);
GOTO_ERR_IF_EX(BN_Rshift(exp, exp, 1), ret);
while (maxCnt > 0) {
GOTO_ERR_IF_EX(BN_RandRangeEx(opt->libCtx, z, p), ret);
maxCnt--;
if (BN_IsZero(z)) {
continue;
}
GOTO_ERR_IF_EX(LegendreFast(z, p, &legendre, opt), ret);
if (legendre == -1) {
ret = CRYPT_SUCCESS;
goto ERR;
}
}
ret = CRYPT_BN_ERR_LEGENDE_DATA;
ERR:
OptimizerEnd(opt);
return ret;
}
static int32_t SetParaR(BN_BigNum *r, BN_BigNum *q, const BN_BigNum *a, BN_Mont *mont, BN_Optimizer *opt)
{
int32_t ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BN_BigNum *temp = OptimizerGetBn(opt, q->size);
if (temp == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
ret = CRYPT_MEM_ALLOC_FAIL;
goto ERR;
}
GOTO_ERR_IF_EX(BN_AddLimb(temp, q, 1), ret); // q + 1
GOTO_ERR_IF_EX(BN_Rshift(temp, temp, 1), ret); // (p + 1) / 2
GOTO_ERR_IF(BN_MontExp(r, a, temp, mont, opt), ret); // r = a^((q+1)/2) mod p
ERR:
OptimizerEnd(opt);
return ret;
}
static int32_t TonelliShanksCalculation(BN_BigNum *r, BN_BigNum *c, BN_BigNum *t,
uint32_t s, const BN_BigNum *p, BN_Optimizer *opt)
{
uint32_t m = s;
uint32_t i, j;
int32_t ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BN_BigNum *b = OptimizerGetBn(opt, p->size);
BN_BigNum *tempT = OptimizerGetBn(opt, p->size);
if (b == NULL || tempT == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
ret = CRYPT_MEM_ALLOC_FAIL;
goto ERR;
}
while (!BN_IsOne(t)) {
// Find an i (0 < i < s) so that t^(2^i) = 1
i = 1;
// repeat modulus square
GOTO_ERR_IF_EX(BN_ModSqr(tempT, t, p, opt), ret);
while (!BN_IsOne(tempT)) {
i++;
if (i >= m) {
ret = CRYPT_BN_ERR_NO_SQUARE_ROOT;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
GOTO_ERR_IF_EX(BN_ModSqr(tempT, tempT, p, opt), ret);
}
// b = c^(2^(m-i-1)), if m-i-1 == 0, b = c
GOTO_ERR_IF_EX(BN_Copy(b, c), ret);
for (j = m - i - 1; j > 0; j--) {
GOTO_ERR_IF_EX(BN_ModSqr(b, b, p, opt), ret);
}
GOTO_ERR_IF_EX(BN_ModMul(r, r, b, p, opt), ret); // r = r * b
GOTO_ERR_IF_EX(BN_ModSqr(c, b, p, opt), ret); // c = b*b
GOTO_ERR_IF_EX(BN_ModMul(t, t, c, p, opt), ret); // t = t * b * b = t * c
m = i;
}
ret = CRYPT_SUCCESS;
ERR:
OptimizerEnd(opt);
return ret;
}
static int32_t SqrtVerify(
BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *p, BN_Optimizer *opt)
{
int32_t ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BN_BigNum *square = OptimizerGetBn(opt, p->size);
if (square == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
ret = CRYPT_MEM_ALLOC_FAIL;
goto ERR;
}
GOTO_ERR_IF_EX(BN_ModSqr(square, r, p, opt), ret);
if (BN_Cmp(square, a) != 0) {
ret = CRYPT_BN_ERR_NO_SQUARE_ROOT;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
ERR:
OptimizerEnd(opt);
return ret;
}
static int32_t BN_ModSqrtTempDataCheck(const BN_BigNum *pSubOne, const BN_BigNum *q,
const BN_BigNum *z, const BN_BigNum *c, const BN_BigNum *t)
{
if (pSubOne == NULL || q == NULL || z == NULL || c == NULL || t == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
return CRYPT_SUCCESS;
}
/* 1. Input parameters a and p. p is an odd prime number, and a is an integer (0 <= a <= p-1)
2. For P-1 processing, let p-1 = q * 2^s
3. If s=1,r = a^((p + 1)/4)
4. Randomly select z (1<= z <= p-1) so that the Legendre symbol of z to p equals -1. (z, p) = 1, (z/p) = a^((p-1)/2)
5. Setting c = z^q, r = a^((q+1)/2), t = a^q, m = s
6. Circulation
1) If t = 1, return r.
2) Find an i (0 < i < m) so that t^(2^i) = 1.
3) b = c^(2^(m-i-1)), r = r * b, t = t*b*b, c = b*b, m = i
7. Verification */
int32_t BN_ModSqrt(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *p, BN_Optimizer *opt)
{
if (r == NULL || a == NULL || p == NULL || opt == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret = OptimizerStart(opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
uint32_t s = 0;
BN_Mont *mont = NULL;
BN_BigNum *pSubOne = OptimizerGetBn(opt, p->size);
BN_BigNum *q = OptimizerGetBn(opt, p->size);
BN_BigNum *z = OptimizerGetBn(opt, p->size);
BN_BigNum *c = OptimizerGetBn(opt, p->size);
BN_BigNum *t = OptimizerGetBn(opt, p->size);
GOTO_ERR_IF(BN_ModSqrtTempDataCheck(pSubOne, q, z, c, t), ret);
GOTO_ERR_IF_EX(CheckParam(a, p), ret);
if (BN_IsZero(a) || BN_IsOne(a)) {
GOTO_ERR_IF_EX(BN_Copy(r, a), ret);
goto VERIFY;
}
mont = BN_MontCreate(p);
if (mont == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
GOTO_ERR_IF_EX(BN_SubLimb(pSubOne, p, 1), ret);
s = GetExp(pSubOne); // Obtains the power s of factor 2 in p-1.
GOTO_ERR_IF_EX(BN_Rshift(q, pSubOne, s), ret); // p - 1 = q * 2^s
if (s == 1) {
// s==1,r = +- n^((p + 1)/4)
GOTO_ERR_IF_EX(CalculationRoot(r, a, p, mont, opt), ret);
goto VERIFY;
}
// Randomly select z(1<= z <= p-1), so that the Legendre symbol of z to p equals -1. (z, p) = 1, (z/p) = a^((p-1)/2)
GOTO_ERR_IF(GetLegendreZ(z, p, opt), ret);
GOTO_ERR_IF(BN_MontExp(c, z, q, mont, opt), ret); // c = z^q mod p
GOTO_ERR_IF(BN_MontExp(t, a, q, mont, opt), ret); // t = a^q mod p
GOTO_ERR_IF_EX(SetParaR(r, q, a, mont, opt), ret); // r = a^((q+1)/2) mod p
// Circulation
// 1) If t = 1, return r.
// 2) Find an i (0 < i < m) so that t^(2^i) = 1
// 3) b = c^(2^(m-i-1)), r = r * b, t = t*b*b, c = b*b, m = i
GOTO_ERR_IF_EX(TonelliShanksCalculation(r, c, t, s, p, opt), ret);
VERIFY:
GOTO_ERR_IF_EX(SqrtVerify(r, a, p, opt), ret);
ERR:
OptimizerEnd(opt);
BN_MontDestroy(mont);
return ret;
}
#endif /* HITLS_CRYPTO_ECC */
|
2301_79861745/bench_create
|
crypto/bn/src/bn_sqrt.c
|
C
|
unknown
| 11,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"
#ifdef HITLS_CRYPTO_BN
#include "securec.h"
#include "bn_bincal.h"
#include "crypt_errno.h"
#include "bsl_err_internal.h"
/* the user should guaranteed a.size >= b.size */
int32_t USub(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b)
{
uint32_t maxSize = a->size;
uint32_t minSize = b->size;
// Ensure that r is sufficient.
int32_t ret = BnExtend(r, maxSize);
if (ret != CRYPT_SUCCESS) {
return ret;
}
BN_UINT *rr = r->data;
const BN_UINT *aa = a->data;
const BN_UINT *bb = b->data;
BN_UINT borrow = BinSub(rr, aa, bb, minSize);
rr += minSize;
aa += minSize;
uint32_t diff = maxSize - minSize;
while (diff > 0) {
BN_UINT t = *aa;
aa++;
*rr = t - borrow;
rr++;
borrow = t < borrow;
diff--;
}
while (maxSize != 0) {
rr--;
if (*rr != 0) {
break;
}
maxSize--;
}
r->size = maxSize;
return CRYPT_SUCCESS;
}
void UDec(BN_BigNum *r, const BN_BigNum *a, BN_UINT w)
{
uint32_t size = a->size;
// the user should guaranteed size > 1, the return value must be 0 thus the return value is ignored
(void)BinDec(r->data, a->data, size, w);
r->size = BinFixSize(r->data, size);
}
int32_t UAdd(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b)
{
const BN_BigNum *max = (a->size < b->size) ? b : a;
const BN_BigNum *min = (a->size < b->size) ? a : b;
uint32_t maxSize = max->size;
uint32_t minSize = min->size;
// Ensure that r is sufficient to carry the sum.
int32_t ret = BnExtend(r, maxSize + 1);
if (ret != CRYPT_SUCCESS) {
return ret;
}
r->size = maxSize;
BN_UINT *rr = r->data;
const BN_UINT *aa = max->data;
const BN_UINT *bb = min->data;
BN_UINT carry = BinAdd(rr, aa, bb, minSize);
rr += minSize;
aa += minSize;
uint32_t diff = maxSize - minSize;
while (diff > 0) {
ADD_AB(carry, *rr, *aa, carry);
aa++, rr++, diff--;
}
if (carry != 0) {
*rr = carry;
r->size += 1;
}
return CRYPT_SUCCESS;
}
#endif /* HITLS_CRYPTO_BN */
|
2301_79861745/bench_create
|
crypto/bn/src/bn_ucal.c
|
C
|
unknown
| 2,714
|
/*
* 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 BN_UCAL_H
#define BN_UCAL_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_BN
#include "bn_basic.h"
#ifdef __cplusplus
extern "C" {
#endif
/* unsigned BigNum subtraction, caution: The input parameter validity must be ensured during external invoking. */
int32_t USub(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b);
/* unsigned BigNum add fraction, caution: The input parameter validity must be ensured during external invoking. */
void UDec(BN_BigNum *r, const BN_BigNum *a, BN_UINT w);
/* unsigned BigNum addition, caution: The input parameter validity must be ensured during external invoking. */
int32_t UAdd(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b);
#ifdef __cplusplus
}
#endif
#endif /* HITLS_CRYPTO_BN */
#endif
|
2301_79861745/bench_create
|
crypto/bn/src/bn_ucal.h
|
C
|
unknown
| 1,296
|
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_BN
#include "securec.h"
#include "bsl_err_internal.h"
#include "crypt_errno.h"
#include "bn_basic.h"
#include "bn_bincal.h"
#include "bsl_sal.h"
int32_t BN_Bin2Bn(BN_BigNum *r, const uint8_t *bin, uint32_t binLen)
{
if (r == NULL || bin == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
(void)BN_Zeroize(r);
uint32_t zeroNum = 0;
for (; zeroNum < binLen; zeroNum++) {
if (bin[zeroNum] != 0) {
break;
}
}
if (zeroNum == binLen) {
// All data is 0.
return CRYPT_SUCCESS;
}
const uint8_t *base = bin + zeroNum;
uint32_t left = binLen - zeroNum;
uint32_t needRooms = (left % sizeof(BN_UINT) == 0) ? left / sizeof(BN_UINT)
: (left / sizeof(BN_UINT)) + 1;
int32_t ret = BnExtend(r, needRooms);
if (ret != CRYPT_SUCCESS) {
return ret;
}
uint32_t offset = 0;
while (left > 0) {
BN_UINT num = 0; // single number
uint32_t m = (left >= sizeof(BN_UINT)) ? sizeof(BN_UINT) : left;
uint32_t i;
for (i = m; i > 0; i--) { // big-endian
num = (num << 8) | base[left - i]; // 8: indicates the number of bits in a byte.
}
r->data[offset++] = num;
left -= m;
}
r->size = BinFixSize(r->data, offset);
return CRYPT_SUCCESS;
}
/* convert BN_UINT to bin */
static inline void Limb2Bin(uint8_t *bin, BN_UINT num)
{
// convert BN_UINT to bin: buff[0] is the most significant bit.
uint32_t i;
for (i = 0; i < sizeof(BN_UINT); i++) { // big-endian
bin[sizeof(BN_UINT) - i - 1] = (uint8_t)(num >> (8 * i)); // 8: indicates the number of bits in a byte.
}
}
int32_t BN_Bn2Bin(const BN_BigNum *a, uint8_t *bin, uint32_t *binLen)
{
if (a == NULL || bin == NULL || binLen == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
uint32_t bytes = BN_Bytes(a);
bytes = (bytes == 0) ? 1 : bytes; // If bytes is 0, 1 byte 0 data needs to be output.
if (*binLen < bytes) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_BUFF_LEN_NOT_ENOUGH);
return CRYPT_BN_BUFF_LEN_NOT_ENOUGH;
}
int32_t ret = BN_Bn2BinFixZero(a, bin, bytes);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
*binLen = bytes;
return ret;
}
void BN_FixSize(BN_BigNum *a)
{
if (a == NULL) {
return;
}
a->size = BinFixSize(a->data, a->size);
}
int32_t BN_Extend(BN_BigNum *a, uint32_t words)
{
return BnExtend(a, words);
}
// Padded 0s before bin to obtain the output data whose length is binLen.
int32_t BN_Bn2BinFixZero(const BN_BigNum *a, uint8_t *bin, uint32_t binLen)
{
if (a == NULL || bin == NULL || binLen == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
uint32_t bytes = BN_Bytes(a);
if (binLen < bytes) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_BUFF_LEN_NOT_ENOUGH);
return CRYPT_BN_BUFF_LEN_NOT_ENOUGH;
}
uint32_t fixLen = binLen - bytes;
uint8_t *base = bin + fixLen;
(void)memset_s(bin, binLen, 0, fixLen);
if (bytes == 0) {
return CRYPT_SUCCESS;
}
uint32_t index = a->size - 1;
uint32_t left = bytes % sizeof(BN_UINT); // High-order non-integrated data
uint32_t offset = 0;
while (left != 0) {
base[offset] = (uint8_t)((a->data[index] >> (8 * (left - 1))) & 0xFF); // 1byte = 8bit
left--;
offset++;
}
if (offset != 0) {
index--;
}
uint32_t num = bytes / sizeof(BN_UINT); // High-order non-integrated data
// Cyclically parse the entire data block.
for (uint32_t i = 0; i < num; i++) {
Limb2Bin(base + offset, a->data[index]);
index--;
offset += sizeof(BN_UINT);
}
return CRYPT_SUCCESS;
}
#if defined(HITLS_CRYPTO_CURVE_SM2_ASM) || \
((defined(HITLS_CRYPTO_CURVE_NISTP521) || defined(HITLS_CRYPTO_CURVE_NISTP384_ASM)) && \
defined(HITLS_CRYPTO_NIST_USE_ACCEL))
/* Convert BigNum to a 64-bit array in little-endian order. */
int32_t BN_Bn2U64Array(const BN_BigNum *a, uint64_t *array, uint32_t *len)
{
// Number of BN_UINTs that can be accommodated
const uint64_t capacity = ((uint64_t)(*len)) * (sizeof(uint64_t) / sizeof(BN_UINT));
if (a->size > capacity || *len == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_SPACE_NOT_ENOUGH);
return CRYPT_BN_SPACE_NOT_ENOUGH;
}
if (BN_IsZero(a)) {
*len = 1;
array[0] = 0;
return CRYPT_SUCCESS;
}
// BN_UINT is 64-bit or 32-bit. Select one during compilation.
if (sizeof(BN_UINT) == sizeof(uint64_t)) {
uint32_t i = 0;
for (; i < a->size; i++) {
array[i] = a->data[i];
}
*len = i;
}
if (sizeof(BN_UINT) == sizeof(uint32_t)) {
uint32_t i = 0;
uint32_t j = 0;
for (; i < a->size - 1; i += 2) { // processes 2 BN_UINT each time. Here, a->size >= 1
array[j] = a->data[i];
array[j] |= ((uint64_t)a->data[i + 1]) << 32; // in the upper 32 bits
j++;
}
// When a->size is an odd number, process the tail.
if (i < a->size) {
array[j++] = a->data[i];
}
*len = j;
}
return CRYPT_SUCCESS;
}
/* Convert a 64-bit array in little-endian order to a BigNum. */
int32_t BN_U64Array2Bn(BN_BigNum *r, const uint64_t *array, uint32_t len)
{
const uint64_t needRoom = ((uint64_t)len) * sizeof(uint64_t) / sizeof(BN_UINT);
if (r == NULL || array == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (needRoom > UINT32_MAX) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_BITS_TOO_MAX);
return CRYPT_BN_BITS_TOO_MAX;
}
int32_t ret = BnExtend(r, (uint32_t)needRoom);
if (ret != CRYPT_SUCCESS) {
return ret;
}
(void)BN_Zeroize(r);
// BN_UINT is 64-bit or 32-bit. Select one during compilation.
if (sizeof(BN_UINT) == sizeof(uint64_t)) {
for (uint32_t i = 0; i < needRoom; i++) {
r->data[i] = array[i];
}
}
if (sizeof(BN_UINT) == sizeof(uint32_t)) {
for (uint64_t i = 0; i < len; i++) {
r->data[i * 2] = (BN_UINT)array[i]; // uint64_t is twice the width of uint32_t.
// obtain the upper 32 bits, uint64_t is twice the width of uint32_t.
r->data[i * 2 + 1] = (BN_UINT)(array[i] >> 32);
}
}
// can be forcibly converted to 32 bits because needRoom <= r->room
r->size = BinFixSize(r->data, (uint32_t)needRoom);
return CRYPT_SUCCESS;
}
#endif
#if defined(HITLS_CRYPTO_CURVE_SM2_ASM) || (defined(HITLS_CRYPTO_CURVE_NISTP256_ASM) && \
defined(HITLS_CRYPTO_NIST_USE_ACCEL))
int32_t BN_BN2Array(const BN_BigNum *src, BN_UINT *dst, uint32_t size)
{
if (size < src->size) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_BUFF_LEN_NOT_ENOUGH);
return CRYPT_BN_BUFF_LEN_NOT_ENOUGH;
}
(void)memset_s(dst, size * sizeof(BN_UINT), 0, size * sizeof(BN_UINT));
for (uint32_t i = 0; i < src->size; i++) {
dst[i] = src->data[i];
}
return CRYPT_SUCCESS;
}
int32_t BN_Array2BN(BN_BigNum *dst, const BN_UINT *src, const uint32_t size)
{
int32_t ret = BnExtend(dst, size);
if (ret != CRYPT_SUCCESS) {
return ret;
}
// No error code is returned because the src has been checked NULL.
(void)BN_Zeroize(dst);
for (uint32_t i = 0; i < size; i++) {
dst->data[i] = src[i];
}
dst->size = BinFixSize(dst->data, size);
return CRYPT_SUCCESS;
}
#endif
#ifdef HITLS_CRYPTO_BN_STR_CONV
static const char HEX_MAP[] = "0123456789ABCDEF"; // Hexadecimal value corresponding to 0-15
#define BITS_OF_NUM 4
#define BITS_OF_BYTE 8
static bool IsXdigit(const char str, bool isHex)
{
if ((str >= '0') && (str <= '9')) {
return true;
}
if (isHex) {
if ((str >= 'A') && (str <= 'F')) {
return true;
}
if ((str >= 'a') && (str <= 'f')) {
return true;
}
}
return false;
}
static unsigned char StrToHex(char str)
{
if ((str >= '0') && (str <= '9')) {
return (unsigned char)(str - '0');
}
if ((str >= 'A') && (str <= 'F')) {
return (unsigned char)(str - 'A' + 10); // Hexadecimal. A~F offset 10
}
if ((str >= 'a') && (str <= 'f')) {
return (unsigned char)(str - 'a' + 10); // Hexadecimal. a~f offset 10
}
return 0x00; // Unexpected character string, which is processed as 0.
}
static int32_t CheckInputStr(int32_t *outLen, const char *str, int32_t *negtive, bool isHex)
{
int32_t len = 0;
int32_t strMax = BN_MAX_BITS / BITS_OF_NUM; // BigNum storage limit: 2^29 bits
const char *inputStr = str;
if (str[0] == '\0') {
BSL_ERR_PUSH_ERROR(CRYPT_BN_CONVERT_INPUT_INVALID);
return CRYPT_BN_CONVERT_INPUT_INVALID;
}
if (str[0] == '-') {
*negtive = 1;
inputStr++;
}
int32_t initStrLen = strlen(inputStr);
if (initStrLen == 0 || initStrLen > strMax) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_CONVERT_INPUT_INVALID);
return CRYPT_BN_CONVERT_INPUT_INVALID;
}
while (len < initStrLen) {
if (!IsXdigit(inputStr[len++], isHex)) { // requires that the entire content of a character string must be valid
BSL_ERR_PUSH_ERROR(CRYPT_BN_CONVERT_INPUT_INVALID);
return CRYPT_BN_CONVERT_INPUT_INVALID;
}
}
*outLen = len;
return CRYPT_SUCCESS;
}
static int32_t OutputCheck(BN_BigNum **r, int32_t num)
{
uint32_t needBits = (uint32_t)num * BITS_OF_NUM;
if (*r == NULL) {
*r = BN_Create(needBits);
if (*r == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
} else {
int32_t ret = BnExtend(*r, BITS_TO_BN_UNIT(needBits));
if (ret != CRYPT_SUCCESS) {
return ret;
}
(void)BN_Zeroize(*r);
}
return CRYPT_SUCCESS;
}
int32_t BN_Hex2Bn(BN_BigNum **r, const char *str)
{
int32_t ret;
int32_t len;
int32_t negtive = 0;
if (r == NULL || str == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
const char *inputStr = str;
ret = CheckInputStr(&len, inputStr, &negtive, true);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = OutputCheck(r, len);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BN_UINT *p = (*r)->data;
if (negtive != 0) {
inputStr++;
}
int32_t unitBytes;
uint32_t tmpval = 0;
uint32_t size = 0; // Record the size that r will use.
int32_t bytes = sizeof(BN_UINT);
BN_UINT unitValue;
while (len > 0) {
unitBytes = (bytes * 2 <= len) ? bytes * 2 : len; // Prevents the number of char left being less than bytes *2
unitValue = 0;
for (; unitBytes > 0; unitBytes--) {
// interface ensures that all characters are valid at the begining
tmpval = StrToHex(inputStr[len - unitBytes]);
unitValue = (unitValue << 4) | tmpval; // The upper bits are shifted rightwards by 4 bits each time.
}
p[size++] = unitValue;
len -= bytes * 2; // Length of the character stream processed each time = Number of bytes x 2
}
(*r)->size = BinFixSize(p, size);
if (!BN_IsZero(*r)) {
(*r)->sign = negtive;
}
return CRYPT_SUCCESS;
}
char *BN_Bn2Hex(const BN_BigNum *a)
{
uint32_t bytes = sizeof(BN_UINT);
if (a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return NULL;
}
// output character stream = Number of bytes x 2 + minus sign + terminator
char *ret = (char *)BSL_SAL_Malloc(a->size * bytes * 2 + 2);
if (ret == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
char *p = ret;
if (BN_IsZero(a)) {
*p++ = '0';
*p++ = '\0';
return ret;
}
if (a->sign) {
*p++ = '-';
}
bool leadingZeros = true;
for (int32_t i = a->size - 1; i >= 0; i--) {
// processes data in a group of 8 bits
for (int32_t j = (int32_t)(bytes * BITS_OF_BYTE - BITS_OF_BYTE); j >= 0; j -= 8) {
uint32_t chars = (uint32_t)((a->data[i] >> (uint32_t)j) & 0xFF); // Take the last eight bits.
if (leadingZeros && (chars == 0)) {
continue;
}
*p++ = HEX_MAP[chars >> 4]; // Higher 4 bits
*p++ = HEX_MAP[chars & 0x0F]; // Lower 4 bits
leadingZeros = false;
}
}
*p = '\0';
return ret;
}
static int32_t CalBnData(BN_BigNum **r, int32_t num, const char *inputStr)
{
int32_t ret = CRYPT_INVALID_ARG;
int32_t optTimes;
int32_t len = num;
const char *p = inputStr;
BN_UINT unitValue = 0;
/*
* Processes decimal strings in groups of BN_DEC_LEN.
* If the length of a string is not a multiple of BN_DEC_LEN, then in the first round of string processing,
handle according to the actual length of less than BN_DEC_LEN
*/
optTimes = (len % BN_DEC_LEN == 0) ? 0 : (BN_DEC_LEN - len % BN_DEC_LEN);
while (len > 0) {
// keep the upper limit of each round of traversal as BN_DEC_LEN
for (; optTimes < BN_DEC_LEN; optTimes++, len--) {
unitValue *= 10; // A decimal number is multiplied by 10 and then added.
unitValue += *p - '0';
p++;
}
ret = BN_MulLimb(*r, *r, BN_DEC_VAL);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
ret = BN_AddLimb(*r, *r, unitValue);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
unitValue = 0;
optTimes = 0;
}
ERR:
return ret;
}
int32_t BN_Dec2Bn(BN_BigNum **r, const char *str)
{
int32_t ret;
int32_t num;
int32_t negtive = 0;
if (r == NULL || str == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
const char *inputStr = str;
ret = CheckInputStr(&num, inputStr, &negtive, false);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = OutputCheck(r, num);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (negtive != 0) {
inputStr++;
}
ret = CalBnData(r, num, inputStr);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (!BN_IsZero(*r)) {
(*r)->sign = negtive;
}
return ret;
}
static int32_t CalDecStr(const BN_BigNum *a, BN_UINT *bnInit, uint32_t unitNum, uint32_t *step)
{
int32_t ret = CRYPT_INVALID_ARG;
BN_UINT *valNow = bnInit;
uint32_t index = 0;
BN_BigNum *bnDup = BN_Dup(a);
if (bnDup == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
goto ERR;
}
while (!BN_IsZero(bnDup)) {
BN_UINT rem;
// index records the amount of BN_UINT offset, cannot exceed the maximum value unitNum
if (index == unitNum) {
ret = CRYPT_SECUREC_FAIL;
goto ERR;
}
ret = BN_DivLimb(bnDup, &rem, bnDup, BN_DEC_VAL);
if (ret != CRYPT_SUCCESS) {
goto ERR;
}
valNow[index++] = rem;
}
(*step) = index - 1;
ERR:
BN_Destroy(bnDup);
return ret;
}
static int32_t NumToStr(char *output, uint32_t *restLen, BN_UINT valNow, bool isNeedPad, uint32_t *printNum)
{
BN_UINT num = valNow;
char *target = output;
uint32_t len = 0;
do {
if (*restLen < len + 1) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_BUFF_LEN_NOT_ENOUGH);
return CRYPT_BN_BUFF_LEN_NOT_ENOUGH;
}
// The ASCII code of 0 to 9 is [48, 57]
target[len++] = num % 10 + 48; // Take last num by mod 10, and convet to 'char'.
num /= 10; // for taken the last digit by dividing 10
} while (num != 0);
if (isNeedPad) {
if (*restLen < BN_DEC_LEN) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_BUFF_LEN_NOT_ENOUGH);
return CRYPT_BN_BUFF_LEN_NOT_ENOUGH;
}
while (len < BN_DEC_LEN) {
target[len++] = '0';
}
}
// Symmetrically swapped values at both ends, needs len / 2 times.
for (uint32_t j = 0; j < len / 2; j++) {
char t = target[j];
target[j] = target[len - 1 - j];
target[len - 1 - j] = t;
}
*restLen -= len;
*printNum = len;
return CRYPT_SUCCESS;
}
static int32_t FmtDecOutput(char *output, uint32_t outLen, const BN_UINT *bnInit, uint32_t steps)
{
uint32_t cpyNum = 0;
char *outputPtr = output;
uint32_t index = steps;
uint32_t restLen = outLen - 1; // Reserve the position of the terminator.
int32_t ret = NumToStr(outputPtr, &restLen, *(bnInit + index), false, &cpyNum);
if (ret != CRYPT_SUCCESS) {
return ret;
}
outputPtr += cpyNum;
while (index-- != 0) {
ret = NumToStr(outputPtr, &restLen, *(bnInit + index), true, &cpyNum);
if (ret != CRYPT_SUCCESS) {
return ret;
}
outputPtr += cpyNum;
}
*outputPtr = '\0';
return CRYPT_SUCCESS;
}
char *BN_Bn2Dec(const BN_BigNum *a)
{
if (a == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return NULL;
}
int32_t ret;
char *p = NULL;
uint32_t steps = 0;
/*
* Estimate the maximum length of a decimal BigNum
* x <= 10 ^ y < 2 ^ (bit + 1)
* y < lg_(2) ( 2 ^ (bit + 1))
* y < (bit + 1) * lg2 -- (lg_2 = 0.30102999566...)
* y < (bit + 1) * 0.303
* y < 3 * bit * 0.001 + 3 * bit * 0.100 + 1
*/
uint32_t numLen = (BN_Bits(a) * 3) / 10 + (BN_Bits(a) * 3) / 1000 + 1;
uint32_t outLen = numLen + 3; // Add the sign, end symbol, and buffer space.
uint32_t unitNum = (numLen / BN_DEC_LEN) + 1;
char *result = BSL_SAL_Malloc(outLen);
BN_UINT *bnInit = (BN_UINT *)BSL_SAL_Malloc(unitNum * sizeof(BN_UINT));
if (result == NULL || bnInit == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
goto ERR;
}
p = result;
if (BN_IsZero(a)) {
*p++ = '0';
*p++ = '\0';
ret = CRYPT_SUCCESS;
goto ERR;
}
if (a->sign) {
*p++ = '-';
outLen--;
}
ret = CalDecStr(a, bnInit, unitNum, &steps);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
ret = FmtDecOutput(p, outLen, bnInit, steps);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
ERR:
BSL_SAL_FREE(bnInit);
if (ret == CRYPT_SUCCESS) {
return result;
}
BSL_SAL_FREE(result);
return NULL;
}
#endif /* HITLS_CRYPTO_BN_STR_CONV */
#endif /* HITLS_CRYPTO_BN */
|
2301_79861745/bench_create
|
crypto/bn/src/bn_utils.c
|
C
|
unknown
| 19,706
|
/*
* 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_BN
#include <stdint.h>
#include "bn_bincal.h"
/* r = a + b, the length of r, a and b array is n. The return value is the carry. */
BN_UINT BinAdd(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t n)
{
BN_UINT carry = 0;
uint32_t nn = n;
const BN_UINT *aa = a;
const BN_UINT *bb = b;
BN_UINT *rr = r;
#ifndef HITLS_CRYPTO_BN_SMALL_MEM
while (nn >= 4) { /* Process 4 groups in batches. */
ADD_ABC(carry, rr[0], aa[0], bb[0], carry); /* offset 0 */
ADD_ABC(carry, rr[1], aa[1], bb[1], carry); /* offset 1 */
ADD_ABC(carry, rr[2], aa[2], bb[2], carry); /* offset 2 */
ADD_ABC(carry, rr[3], aa[3], bb[3], carry); /* offset 3 */
rr += 4; /* a group of 4 */
aa += 4; /* a group of 4 */
bb += 4; /* a group of 4 */
nn -= 4; /* a group of 4 */
}
#endif
uint32_t i = 0;
for (; i < nn; i++) {
ADD_ABC(carry, rr[i], aa[i], bb[i], carry);
}
return carry;
}
/* r = a - b, the length of r, a and b array is n. The return value is the borrow-digit. */
BN_UINT BinSub(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t n)
{
BN_UINT borrow = 0;
uint32_t nn = n;
const BN_UINT *aa = a;
const BN_UINT *bb = b;
BN_UINT *rr = r;
#ifndef HITLS_CRYPTO_BN_SMALL_MEM
while (nn >= 4) { /* Process 4 groups in batches. */
SUB_ABC(borrow, rr[0], aa[0], bb[0], borrow); /* offset 0 */
SUB_ABC(borrow, rr[1], aa[1], bb[1], borrow); /* offset 1 */
SUB_ABC(borrow, rr[2], aa[2], bb[2], borrow); /* offset 2 */
SUB_ABC(borrow, rr[3], aa[3], bb[3], borrow); /* offset 3 */
rr += 4; /* a group of 4 */
aa += 4; /* a group of 4 */
bb += 4; /* a group of 4 */
nn -= 4; /* a group of 4 */
}
#endif
uint32_t i = 0;
for (; i < nn; i++) {
SUB_ABC(borrow, rr[i], aa[i], bb[i], borrow);
}
return borrow;
}
/* Obtains the number of 0s in the first x most significant bits of data. */
uint32_t GetZeroBitsUint(BN_UINT x)
{
BN_UINT iter;
BN_UINT tmp = x;
uint32_t bits = BN_UNIT_BITS;
uint32_t base = BN_UNIT_BITS >> 1;
do {
iter = tmp >> base;
if (iter != 0) {
tmp = iter;
bits -= base;
}
base = base >> 1;
} while (base != 0);
return (uint32_t)(bits - tmp);
}
/* Multiply and then subtract. The return value is borrow digit. */
BN_UINT BinSubMul(BN_UINT *r, const BN_UINT *a, BN_UINT aSize, BN_UINT m)
{
BN_UINT borrow = 0;
uint32_t i;
for (i = 0; i < aSize; i++) {
BN_UINT ah, al;
MUL_AB(ah, al, a[i], m);
SUB_ABC(borrow, r[i], r[i], al, borrow);
borrow += ah;
}
return borrow;
}
#endif /* HITLS_CRYPTO_BN */
|
2301_79861745/bench_create
|
crypto/bn/src/noasm_bn_bincal.c
|
C
|
unknown
| 3,341
|
/*
* 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_BN
#include <stdint.h>
#include <stdbool.h>
#include "bn_bincal.h"
/* reduce(r * r) */
int32_t MontSqrBin(BN_UINT *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime)
{
return MontSqrBinCore(r, mont, opt, consttime);
}
int32_t MontMulBin(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, BN_Mont *mont,
BN_Optimizer *opt, bool consttime)
{
return MontMulBinCore(r, a, b, mont, opt, consttime);
}
int32_t MontEncBin(BN_UINT *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime)
{
return MontEncBinCore(r, mont, opt, consttime);
}
void Reduce(BN_UINT *r, BN_UINT *x, const BN_UINT *one, const BN_UINT *m, uint32_t mSize, BN_UINT m0)
{
(void)one;
ReduceCore(r, x, m, mSize, m0);
}
#endif /* HITLS_CRYPTO_BN */
|
2301_79861745/bench_create
|
crypto/bn/src/noasm_bn_mont.c
|
C
|
unknown
| 1,325
|
/*
* 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_BN
#include <stdint.h>
#include "bn_bincal.h"
#ifndef HITLS_SIXTY_FOUR_BITS
#error Bn binical x8664 optimizer must open BN-64.
#endif
// r = a + b, len = n, return carry
BN_UINT BinAdd(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t n)
{
if (n == 0) {
return 0;
}
BN_UINT ret = n;
asm volatile (
".p2align 4 \n"
" mov %0, %%rcx \n"
" and $3, %%rcx \n" // will clear CF
" shr $2, %0 \n"
" clc \n"
" jz aone \n" // n / 4 > = 0 , goto step 4
"4: movq 0(%2), %%r8 \n"
" movq 8(%2), %%r9 \n"
" movq 16(%2), %%r10 \n"
" movq 24(%2), %%r11 \n"
" adcq 0(%3), %%r8 \n"
" adcq 8(%3), %%r9 \n"
" adcq 16(%3), %%r10 \n"
" adcq 24(%3), %%r11 \n"
" movq %%r8, 0(%1) \n"
" movq %%r9, 8(%1) \n"
" movq %%r10, 16(%1) \n"
" movq %%r11, 24(%1) \n"
" lea 32(%1), %1 \n"
" lea 32(%2), %2 \n"
" lea 32(%3), %3 \n"
" dec %0 \n"
" jnz 4b \n"
"aone: jrcxz eadd \n" // n % 4 == 0, goto end
"1: movq (%2,%0,8), %%r8 \n"
" adcq (%3,%0,8), %%r8 \n"
" movq %%r8, (%1,%0,8) \n"
" inc %0 \n"
" dec %%rcx \n"
" jnz 1b \n"
"eadd: sbbq %0, %0 \n"
:"+&r" (ret)
:"r"(r), "r"(a), "r"(b)
:"r8", "r9", "r10", "r11", "rcx", "cc", "memory");
return ret & 1;
}
// r = a - b, len = n, return carry
BN_UINT BinSub(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t n)
{
if (n == 0) {
return 0;
}
BN_UINT res = n;
asm volatile (
".p2align 4 \n"
" mov %0, %%rcx \n"
" and $3, %%rcx \n"
" shr $2, %0 \n"
" clc \n"
" jz sone \n" // n / 4 > = 0 , goto step 4
"4: movq 0(%2), %%r8 \n"
" movq 8(%2), %%r9 \n"
" movq 16(%2), %%r10 \n"
" movq 24(%2), %%r11 \n"
" sbbq 0(%3), %%r8 \n"
" sbbq 8(%3), %%r9 \n"
" sbbq 16(%3), %%r10 \n"
" sbbq 24(%3), %%r11 \n"
" movq %%r8, 0(%1) \n"
" movq %%r9, 8(%1) \n"
" movq %%r10, 16(%1) \n"
" movq %%r11, 24(%1) \n"
" lea 32(%1), %1 \n"
" lea 32(%2), %2 \n"
" lea 32(%3), %3 \n"
" dec %0 \n"
" jnz 4b \n"
"sone: jrcxz esub \n" // n % 4 == 0, goto end
"1: movq (%2,%0,8), %%r8 \n"
" sbbq (%3,%0,8), %%r8 \n"
" movq %%r8, (%1,%0,8) \n"
" inc %0 \n"
" dec %%rcx \n"
" jnz 1b \n"
"esub: sbbq %0, %0 \n"
:"+&r" (res)
:"r"(r), "r"(a), "r"(b)
:"r8", "r9", "r10", "r11", "rcx", "cc", "memory");
return res & 1;
}
// r = r - a * m, return the carry;
BN_UINT BinSubMul(BN_UINT *r, const BN_UINT *a, BN_UINT aSize, BN_UINT m)
{
BN_UINT borrow = 0;
BN_UINT i = 0;
asm volatile (
".p2align 4 \n"
"endy: movq %5, %%rax \n" // rax = m
" mulq (%4,%1,8) \n" // rax -> al, rdx -> ah
" addq %0, %%rax \n" // rax = al + borrow
" adcq $0, %%rdx \n" // if has carry, rdx++
" subq %%rax, (%3,%1,8) \n" // r[i] = r[i] - (al + borrow)
" adcq $0, %%rdx \n" // if has carry, borrow++
" movq %%rdx, %0 \n"
" inc %1 \n"
" dec %2 \n"
" jnz endy \n"
:"+&r" (borrow), "+r"(i), "+r"(aSize)
:"r"(r), "r"(a), "r"(m)
:"rax", "rdx", "cc", "memory");
return borrow;
}
/* Obtains the number of 0s in the first x most significant bits of data. */
uint32_t GetZeroBitsUint(BN_UINT x)
{
BN_UINT iter;
BN_UINT tmp = x;
uint32_t bits = BN_UNIT_BITS;
uint32_t base = BN_UNIT_BITS >> 1;
do {
iter = tmp >> base;
if (iter != 0) {
tmp = iter;
bits -= base;
}
base = base >> 1;
} while (base != 0);
return bits - tmp;
}
#endif /* HITLS_CRYPTO_BN */
|
2301_79861745/bench_create
|
crypto/bn/src/x8664_bn_bincal.c
|
C
|
unknown
| 6,809
|
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef CRYPT_CHACHA20_H
#define CRYPT_CHACHA20_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_CHACHA20
#include <stdint.h>
#include "crypt_types.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
#define CHACHA20_STATESIZE 16
#define CHACHA20_STATEBYTES (CHACHA20_STATESIZE * sizeof(uint32_t))
#define CHACHA20_KEYLEN 32
#define CHACHA20_NONCELEN 12
typedef struct {
uint32_t state[CHACHA20_STATESIZE]; // state RFC 7539
union {
uint32_t c[CHACHA20_STATESIZE];
uint8_t u[CHACHA20_STATEBYTES];
} last; // save the last data
uint32_t lastLen; // remaining length of the last data in bytes
uint8_t set; // indicates whether the key and nonce are set
} CRYPT_CHACHA20_Ctx;
int32_t CRYPT_CHACHA20_SetKey(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *key, uint32_t keyLen);
int32_t CRYPT_CHACHA20_Update(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len);
int32_t CRYPT_CHACHA20_Ctrl(CRYPT_CHACHA20_Ctx *ctx, int32_t opt, void *val, uint32_t len);
void CRYPT_CHACHA20_Clean(CRYPT_CHACHA20_Ctx *ctx);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // HITLS_CRYPTO_CHACHA20
#endif // CRYPT_CHACHA20_H
|
2301_79861745/bench_create
|
crypto/chacha20/include/crypt_chacha20.h
|
C
|
unknown
| 1,710
|
/*
* 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_CHACHA20
.text
.macro CHA256_SET_VDATA
mov VREG01.16b, VSIGMA.16b
mov VREG11.16b, VSIGMA.16b
mov VREG21.16b, VSIGMA.16b
mov VREG02.16b, VKEY01.16b
mov VREG12.16b, VKEY01.16b
mov VREG22.16b, VKEY01.16b
mov VREG03.16b, VKEY02.16b
mov VREG13.16b, VKEY02.16b
mov VREG23.16b, VKEY02.16b
mov VREG04.16b, VREG52.16b // 1
mov VREG14.16b, VREG53.16b // 2
mov VREG24.16b, VREG54.16b // 3
.endm
.macro CHA256_ROUND_A
add WINPUT0, WINPUT0, WINPUT4 // A+B
add VREG01.4s, VREG01.4s, VREG02.4s
add WINPUT1, WINPUT1, WINPUT5 // A+B
add VREG11.4s, VREG11.4s, VREG12.4s
add WINPUT2, WINPUT2, WINPUT6 // A+B
add VREG21.4s, VREG21.4s, VREG22.4s
add WINPUT3, WINPUT3, WINPUT7 // A+B
eor VREG04.16b, VREG04.16b, VREG01.16b
eor WINPUT12, WINPUT12, WINPUT0 // D^A
eor VREG14.16b, VREG14.16b, VREG11.16b
eor WINPUT13, WINPUT13, WINPUT1 // D^A
eor VREG24.16b, VREG24.16b, VREG21.16b
eor WINPUT14, WINPUT14, WINPUT2 // D^A
rev32 VREG04.8h, VREG04.8h
eor WINPUT15, WINPUT15, WINPUT3 // D^A
rev32 VREG14.8h, VREG14.8h
ror WINPUT12, WINPUT12, #16 // D>>>16
rev32 VREG24.8h, VREG24.8h
ror WINPUT13, WINPUT13, #16 // D>>>16
add VREG03.4s, VREG03.4s, VREG04.4s
ror WINPUT14, WINPUT14, #16 // D>>>16
add VREG13.4s, VREG13.4s, VREG14.4s
ror WINPUT15, WINPUT15, #16 // D>>>16
add VREG23.4s, VREG23.4s, VREG24.4s
add WINPUT8, WINPUT8, WINPUT12 // C+D
eor VREG41.16b, VREG03.16b, VREG02.16b
add WINPUT9, WINPUT9, WINPUT13 // C+D
eor VREG42.16b, VREG13.16b, VREG12.16b
add WINPUT10, WINPUT10, WINPUT14 // C+D
eor VREG43.16b, VREG23.16b, VREG22.16b
add WINPUT11, WINPUT11, WINPUT15 // C+D
ushr VREG02.4s, VREG41.4s, #20
eor WINPUT4, WINPUT4, WINPUT8 // B^C
ushr VREG12.4s, VREG42.4s, #20
eor WINPUT5, WINPUT5, WINPUT9 // B^C
ushr VREG22.4s, VREG43.4s, #20
eor WINPUT6, WINPUT6, WINPUT10 // B^C
sli VREG02.4s, VREG41.4s, #12
eor WINPUT7, WINPUT7, WINPUT11 // B^C
sli VREG12.4s, VREG42.4s, #12
ror WINPUT4, WINPUT4, #20 // B>>>20
sli VREG22.4s, VREG43.4s, #12
ror WINPUT5, WINPUT5, #20 // B>>>20
add VREG01.4s, VREG01.4s, VREG02.4s
ror WINPUT6, WINPUT6, #20 // B>>>20
add VREG11.4s, VREG11.4s, VREG12.4s
ror WINPUT7, WINPUT7, #20 // B>>>20
add VREG21.4s, VREG21.4s, VREG22.4s
add WINPUT0, WINPUT0, WINPUT4 // A+B
eor VREG41.16b, VREG04.16b, VREG01.16b
add WINPUT1, WINPUT1, WINPUT5 // A+B
eor VREG42.16b, VREG14.16b, VREG11.16b
add WINPUT2, WINPUT2, WINPUT6 // A+B
eor VREG43.16b, VREG24.16b, VREG21.16b
add WINPUT3, WINPUT3, WINPUT7 // A+B
ushr VREG04.4s, VREG41.4s, #24
eor WINPUT12, WINPUT12, WINPUT0 // D^A
ushr VREG14.4s, VREG42.4s, #24
eor WINPUT13, WINPUT13, WINPUT1 // D^A
ushr VREG24.4s, VREG43.4s, #24
eor WINPUT14, WINPUT14, WINPUT2 // D^A
sli VREG04.4s, VREG41.4s, #8
eor WINPUT15, WINPUT15, WINPUT3 // D^A
sli VREG14.4s, VREG42.4s, #8
ror WINPUT12, WINPUT12, #24 // D>>>24
sli VREG24.4s, VREG43.4s, #8
ror WINPUT13, WINPUT13, #24 // D>>>24
add VREG03.4s, VREG03.4s, VREG04.4s
ror WINPUT14, WINPUT14, #24 // D>>>24
add VREG13.4s, VREG13.4s, VREG14.4s
ror WINPUT15, WINPUT15, #24 // D>>>24
add VREG23.4s, VREG23.4s, VREG24.4s
add WINPUT8, WINPUT8, WINPUT12 // C+D
eor VREG41.16b, VREG03.16b, VREG02.16b
add WINPUT9, WINPUT9, WINPUT13 // C+D
eor VREG42.16b, VREG13.16b, VREG12.16b
add WINPUT10, WINPUT10, WINPUT14 // C+D
eor VREG43.16b, VREG23.16b, VREG22.16b
add WINPUT11, WINPUT11, WINPUT15 // C+D
ushr VREG02.4s, VREG41.4s, #25
eor WINPUT4, WINPUT4, WINPUT8 // B^C
ushr VREG12.4s, VREG42.4s, #25
eor WINPUT5, WINPUT5, WINPUT9 // B^C
ushr VREG22.4s, VREG43.4s, #25
eor WINPUT6, WINPUT6, WINPUT10 // B^C
sli VREG02.4s, VREG41.4s, #7
eor WINPUT7, WINPUT7, WINPUT11 // B^C
sli VREG12.4s, VREG42.4s, #7
ror WINPUT4, WINPUT4, #25 // B>>>25
sli VREG22.4s, VREG43.4s, #7
ror WINPUT5, WINPUT5, #25 // B>>>25
ext VREG03.16b, VREG03.16b, VREG03.16b, #8
ror WINPUT6, WINPUT6, #25 // B>>>25
ext VREG13.16b, VREG13.16b, VREG13.16b, #8
ror WINPUT7, WINPUT7, #25 // B>>>25
ext VREG23.16b, VREG23.16b, VREG23.16b, #8
.endm
.macro CHA256_ROUND_B
add WINPUT0, WINPUT0, WINPUT5 // A+B
add VREG01.4s, VREG01.4s, VREG02.4s
add WINPUT1, WINPUT1, WINPUT6 // A+B
add VREG11.4s, VREG11.4s, VREG12.4s
add WINPUT2, WINPUT2, WINPUT7 // A+B
add VREG21.4s, VREG21.4s, VREG22.4s
add WINPUT3, WINPUT3, WINPUT4 // A+B
eor VREG04.16b, VREG04.16b, VREG01.16b
eor WINPUT15, WINPUT15, WINPUT0 // D^A
eor VREG14.16b, VREG14.16b, VREG11.16b
eor WINPUT12, WINPUT12, WINPUT1 // D^A
eor VREG24.16b, VREG24.16b, VREG21.16b
eor WINPUT13, WINPUT13, WINPUT2 // D^A
rev32 VREG04.8h, VREG04.8h
eor WINPUT14, WINPUT14, WINPUT3 // D^A
rev32 VREG14.8h, VREG14.8h
ror WINPUT12, WINPUT12, #16 // D>>>16
rev32 VREG24.8h, VREG24.8h
ror WINPUT13, WINPUT13, #16 // D>>>16
add VREG03.4s, VREG03.4s, VREG04.4s
ror WINPUT14, WINPUT14, #16 // D>>>16
add VREG13.4s, VREG13.4s, VREG14.4s
ror WINPUT15, WINPUT15, #16 // D>>>16
add VREG23.4s, VREG23.4s, VREG24.4s
add WINPUT10, WINPUT10, WINPUT15 // C+D
eor VREG41.16b, VREG03.16b, VREG02.16b
add WINPUT11, WINPUT11, WINPUT12 // C+D
eor VREG42.16b, VREG13.16b, VREG12.16b
add WINPUT8, WINPUT8, WINPUT13 // C+D
eor VREG43.16b, VREG23.16b, VREG22.16b
add WINPUT9, WINPUT9, WINPUT14 // C+D
ushr VREG02.4s, VREG41.4s, #20
eor WINPUT5, WINPUT5, WINPUT10 // B^C
ushr VREG12.4s, VREG42.4s, #20
eor WINPUT6, WINPUT6, WINPUT11 // B^C
ushr VREG22.4s, VREG43.4s, #20
eor WINPUT7, WINPUT7, WINPUT8 // B^C
sli VREG02.4s, VREG41.4s, #12
eor WINPUT4, WINPUT4, WINPUT9 // B^C
sli VREG12.4s, VREG42.4s, #12
ror WINPUT4, WINPUT4, #20 // B>>>20
sli VREG22.4s, VREG43.4s, #12
ror WINPUT5, WINPUT5, #20 // B>>>20
add VREG01.4s, VREG01.4s, VREG02.4s
ror WINPUT6, WINPUT6, #20 // B>>>20
add VREG11.4s, VREG11.4s, VREG12.4s
ror WINPUT7, WINPUT7, #20 // B>>>20
add VREG21.4s, VREG21.4s, VREG22.4s
add WINPUT0, WINPUT0, WINPUT5 // A+B
eor VREG41.16b, VREG04.16b, VREG01.16b
add WINPUT1, WINPUT1, WINPUT6 // A+B
eor VREG42.16b, VREG14.16b, VREG11.16b
add WINPUT2, WINPUT2, WINPUT7 // A+B
eor VREG43.16b, VREG24.16b, VREG21.16b
add WINPUT3, WINPUT3, WINPUT4 // A+B
ushr VREG04.4s, VREG41.4s, #24
eor WINPUT15, WINPUT15, WINPUT0 // D^A
ushr VREG14.4s, VREG42.4s, #24
eor WINPUT12, WINPUT12, WINPUT1 // D^A
ushr VREG24.4s, VREG43.4s, #24
eor WINPUT13, WINPUT13, WINPUT2 // D^A
sli VREG04.4s, VREG41.4s, #8
eor WINPUT14, WINPUT14, WINPUT3 // D^A
sli VREG14.4s, VREG42.4s, #8
ror WINPUT12, WINPUT12, #24 // D>>>24
sli VREG24.4s, VREG43.4s, #8
ror WINPUT13, WINPUT13, #24
add VREG03.4s, VREG03.4s, VREG04.4s
ror WINPUT14, WINPUT14, #24
add VREG13.4s, VREG13.4s, VREG14.4s
ror WINPUT15, WINPUT15, #24
add VREG23.4s, VREG23.4s, VREG24.4s
add WINPUT10, WINPUT10, WINPUT15 // C+D
eor VREG41.16b, VREG03.16b, VREG02.16b
add WINPUT11, WINPUT11, WINPUT12 // C+D
eor VREG42.16b, VREG13.16b, VREG12.16b
add WINPUT8, WINPUT8, WINPUT13 // C+D
eor VREG43.16b, VREG23.16b, VREG22.16b
add WINPUT9, WINPUT9, WINPUT14 // C+D
ushr VREG02.4s, VREG41.4s, #25
eor WINPUT5, WINPUT5, WINPUT10 // B^C
ushr VREG12.4s, VREG42.4s, #25
eor WINPUT6, WINPUT6, WINPUT11
ushr VREG22.4s, VREG43.4s, #25
eor WINPUT7, WINPUT7, WINPUT8
sli VREG02.4s, VREG41.4s, #7
eor WINPUT4, WINPUT4, WINPUT9
sli VREG12.4s, VREG42.4s, #7
ror WINPUT4, WINPUT4, #25 // B>>>25
sli VREG22.4s, VREG43.4s, #7
ror WINPUT5, WINPUT5, #25
ext VREG03.16b, VREG03.16b, VREG03.16b, #8
ror WINPUT6, WINPUT6, #25
ext VREG13.16b, VREG13.16b, VREG13.16b, #8
ror WINPUT7, WINPUT7, #25
ext VREG23.16b, VREG23.16b, VREG23.16b, #8
.endm
.macro CHA256_ROUND_END
add VREG01.4s, VREG01.4s, VSIGMA.4s // After the cycle is complete, add input.
add VREG11.4s, VREG11.4s, VSIGMA.4s
add VREG21.4s, VREG21.4s, VSIGMA.4s
add VREG02.4s, VREG02.4s, VKEY01.4s // After the cycle is complete, add input.
add VREG12.4s, VREG12.4s, VKEY01.4s
add VREG22.4s, VREG22.4s, VKEY01.4s
add VREG03.4s, VREG03.4s, VKEY02.4s // After the cycle is complete, add input.
add VREG13.4s, VREG13.4s, VKEY02.4s
add VREG23.4s, VREG23.4s, VKEY02.4s
add VREG04.4s, VREG04.4s, VREG52.4s // 0
add VREG14.4s, VREG14.4s, VREG53.4s // 1
add VREG24.4s, VREG24.4s, VREG54.4s // 2
.endm
.macro CHA256_WRITE_BACK
ld1 {VREG41.16b, VREG42.16b, VREG43.16b, VREG44.16b}, [REGINC], #64 // Load 64 bytes.
eor XINPUT0, XINPUT0, XINPUT1
eor XINPUT2, XINPUT2, XINPUT3
eor XINPUT4, XINPUT4, XINPUT5
eor XINPUT6, XINPUT6, XINPUT7
eor XINPUT8, XINPUT8, XINPUT9
stp XINPUT0, XINPUT2, [REGOUT], #16 // Write data.
eor VREG01.16b, VREG01.16b, VREG41.16b
stp XINPUT4, XINPUT6, [REGOUT], #16
eor XINPUT10, XINPUT10, XINPUT11
eor VREG02.16b, VREG02.16b, VREG42.16b
eor XINPUT12, XINPUT12, XINPUT13
eor VREG03.16b, VREG03.16b, VREG43.16b
eor XINPUT14, XINPUT14, XINPUT15
stp XINPUT8, XINPUT10, [REGOUT], #16
eor VREG04.16b, VREG04.16b, VREG44.16b
ld1 {VREG41.16b, VREG42.16b, VREG43.16b, VREG44.16b}, [REGINC], #64 // Load 64 bytes.
stp XINPUT12, XINPUT14, [REGOUT], #16
eor VREG11.16b, VREG11.16b, VREG41.16b
eor VREG12.16b, VREG12.16b, VREG42.16b
st1 {VREG01.16b, VREG02.16b, VREG03.16b, VREG04.16b}, [REGOUT], #64 // Write 64 bytes.
eor VREG13.16b, VREG13.16b, VREG43.16b
eor VREG14.16b, VREG14.16b, VREG44.16b
ld1 {VREG01.16b, VREG02.16b, VREG03.16b, VREG04.16b}, [REGINC], #64 // Load 64 bytes.
st1 {VREG11.16b, VREG12.16b, VREG13.16b, VREG14.16b}, [REGOUT], #64 // Write 64 bytes.
eor VREG21.16b, VREG21.16b, VREG01.16b
eor VREG22.16b, VREG22.16b, VREG02.16b
eor VREG23.16b, VREG23.16b, VREG03.16b
eor VREG24.16b, VREG24.16b, VREG04.16b
st1 {VREG21.16b, VREG22.16b, VREG23.16b, VREG24.16b}, [REGOUT], #64 // Write 64 bytes.
.endm
.macro CHA256_WRITE_BACKB src1, src2, src3, src4
ld1 {VREG41.16b, VREG42.16b, VREG43.16b, VREG44.16b}, [REGINC], #64 // Load 64 bytes.
eor \src1, \src1, VREG41.16b
eor \src2, \src2, VREG42.16b
eor \src3, \src3, VREG43.16b
eor \src4, \src4, VREG44.16b
st1 {\src1, \src2, \src3, \src4}, [REGOUT], #64 // Write 64 bytes.
.endm
#endif
|
2301_79861745/bench_create
|
crypto/chacha20/src/asm/chacha20_256block_aarch64.S
|
Unix Assembly
|
unknown
| 12,601
|
/*
* 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_CHACHA20
.text
.macro CHA512_EXTA
VEXT2 VREG04.16b, VREG14.16b, #12
VEXT2 VREG24.16b, VREG34.16b, #12
VEXT2 VREG44.16b, VREG54.16b, #12
VEXT2 VREG02.16b, VREG12.16b, #4
VEXT2 VREG22.16b, VREG32.16b, #4
VEXT2 VREG42.16b, VREG52.16b, #4
.endm
.macro CHA512_EXTB
VEXT2 VREG04.16b, VREG14.16b, #4
VEXT2 VREG24.16b, VREG34.16b, #4
VEXT2 VREG44.16b, VREG54.16b, #4
VEXT2 VREG02.16b, VREG12.16b, #12
VEXT2 VREG22.16b, VREG32.16b, #12
VEXT2 VREG42.16b, VREG52.16b, #12
.endm
.macro CHA512_SET_VDATA
mov VREG01.16b, VSIGMA.16b
mov VREG11.16b, VSIGMA.16b
mov VREG21.16b, VSIGMA.16b
mov VREG31.16b, VSIGMA.16b
mov VREG41.16b, VSIGMA.16b
mov VREG51.16b, VSIGMA.16b
mov VREG02.16b, VKEY01.16b
mov VREG12.16b, VKEY01.16b
mov VREG22.16b, VKEY01.16b
mov VREG32.16b, VKEY01.16b
mov VREG42.16b, VKEY01.16b
mov VREG52.16b, VKEY01.16b
mov VREG03.16b, VKEY02.16b
mov VREG13.16b, VKEY02.16b
mov VREG23.16b, VKEY02.16b
mov VREG33.16b, VKEY02.16b
mov VREG43.16b, VKEY02.16b
mov VREG53.16b, VKEY02.16b
mov VREG04.16b, VCUR01.16b // Counter + 2
mov VREG14.16b, VCUR02.16b // Counter + 3
mov VREG24.16b, VCUR03.16b // Counter + 4
mov VREG34.16b, VCUR04.16b // Counter + 5
add VREG44.4s, VREG04.4s, VADDER.4s // Counter + 6 = 4 + 2
add VREG54.4s, VREG14.4s, VADDER.4s // Counter + 7 = 4 + 3
.endm
.macro CHA512_ROUND_END
add VREG01.4s, VREG01.4s, VSIGMA.4s // After the loop is complete, add input.
add VREG11.4s, VREG11.4s, VSIGMA.4s
add VREG21.4s, VREG21.4s, VSIGMA.4s
add VREG31.4s, VREG31.4s, VSIGMA.4s
add VREG41.4s, VREG41.4s, VSIGMA.4s
add VREG51.4s, VREG51.4s, VSIGMA.4s
add VREG02.4s, VREG02.4s, VKEY01.4s // After the loop is complete, add input.
add VREG12.4s, VREG12.4s, VKEY01.4s
add VREG22.4s, VREG22.4s, VKEY01.4s
add VREG32.4s, VREG32.4s, VKEY01.4s
add VREG42.4s, VREG42.4s, VKEY01.4s
add VREG52.4s, VREG52.4s, VKEY01.4s
add VREG03.4s, VREG03.4s, VKEY02.4s // After the loop is complete, add input.
add VREG13.4s, VREG13.4s, VKEY02.4s
add VREG23.4s, VREG23.4s, VKEY02.4s
add VREG33.4s, VREG33.4s, VKEY02.4s
add VREG43.4s, VREG43.4s, VKEY02.4s
add VREG53.4s, VREG53.4s, VKEY02.4s
add VREG44.4s, VREG44.4s, VCUR01.4s // 2
add VREG54.4s, VREG54.4s, VCUR02.4s // 3
add VREG04.4s, VREG04.4s, VCUR01.4s // 2
add VREG14.4s, VREG14.4s, VCUR02.4s // 3
add VREG24.4s, VREG24.4s, VCUR03.4s // 4
add VREG34.4s, VREG34.4s, VCUR04.4s // 5
add VREG44.4s, VREG44.4s, VADDER.4s // 4 + 2
add VREG54.4s, VREG54.4s, VADDER.4s // 4 + 3
.endm
.macro CHA512_WRITE_BACK
ld1 {VCUR01.16b, VCUR02.16b, VCUR03.16b, VCUR04.16b}, [REGINC], #64 // Load 64 bytes.
eor VREG01.16b, VREG01.16b, VCUR01.16b
eor VREG02.16b, VREG02.16b, VCUR02.16b
eor VREG03.16b, VREG03.16b, VCUR03.16b
eor VREG04.16b, VREG04.16b, VCUR04.16b
ld1 {VCUR01.16b, VCUR02.16b, VCUR03.16b, VCUR04.16b}, [REGINC], #64 // Load 64 bytes.
st1 {VREG01.16b, VREG02.16b, VREG03.16b, VREG04.16b}, [REGOUT], #64 // Write 64 bytes.
eor VREG11.16b, VREG11.16b, VCUR01.16b
eor VREG12.16b, VREG12.16b, VCUR02.16b
eor VREG13.16b, VREG13.16b, VCUR03.16b
eor VREG14.16b, VREG14.16b, VCUR04.16b
ld1 {VREG01.16b, VREG02.16b, VREG03.16b, VREG04.16b}, [REGINC], #64 // Load 64 bytes.
st1 {VREG11.16b, VREG12.16b, VREG13.16b, VREG14.16b}, [REGOUT], #64 // Write 64 bytes.
eor VREG21.16b, VREG21.16b, VREG01.16b
eor VREG22.16b, VREG22.16b, VREG02.16b
eor VREG23.16b, VREG23.16b, VREG03.16b
eor VREG24.16b, VREG24.16b, VREG04.16b
ld1 {VREG11.16b, VREG12.16b, VREG13.16b, VREG14.16b}, [REGINC], #64 // Load 64 bytes.
st1 {VREG21.16b, VREG22.16b, VREG23.16b, VREG24.16b}, [REGOUT], #64 // Write 64 bytes.
eor VREG31.16b, VREG31.16b, VREG11.16b
eor VREG32.16b, VREG32.16b, VREG12.16b
eor VREG33.16b, VREG33.16b, VREG13.16b
eor VREG34.16b, VREG34.16b, VREG14.16b
ld1 {VREG01.16b, VREG02.16b, VREG03.16b, VREG04.16b}, [REGINC], #64 // Load 64 bytes.
st1 {VREG31.16b, VREG32.16b, VREG33.16b, VREG34.16b}, [REGOUT], #64 // Write 64 bytes.
shl VREG21.4s, VADDER.4s, #1 // 4 -> 8
eor VREG41.16b, VREG41.16b, VREG01.16b
eor VREG42.16b, VREG42.16b, VREG02.16b
eor VREG43.16b, VREG43.16b, VREG03.16b
eor VREG44.16b, VREG44.16b, VREG04.16b
ld1 {VREG11.16b, VREG12.16b, VREG13.16b, VREG14.16b}, [REGINC], #64 // Load 64 bytes.
st1 {VREG41.16b, VREG42.16b, VREG43.16b, VREG44.16b}, [REGOUT], #64 // Write 64 bytes.
ldp QCUR01, QCUR02, [sp, #32] // restore counter 0 1 2 4
ldp QCUR03, QCUR04, [sp, #64]
eor VREG51.16b, VREG51.16b, VREG11.16b
eor VREG52.16b, VREG52.16b, VREG12.16b
eor VREG53.16b, VREG53.16b, VREG13.16b
eor VREG54.16b, VREG54.16b, VREG14.16b
st1 {VREG51.16b, VREG52.16b, VREG53.16b, VREG54.16b}, [REGOUT], #64 // Write 64 bytes.
add VCUR01.4s, VCUR01.4s, VREG21.4s
add VCUR02.4s, VCUR02.4s, VREG21.4s
add VCUR03.4s, VCUR03.4s, VREG21.4s
add VCUR04.4s, VCUR04.4s, VREG21.4s
.endm
.macro CHA512_ROUND
WCHA_ADD_A_B // a += b
VADD2 VREG02.4s, VREG01.4s, VREG12.4s, VREG11.4s // a[0,1,2,3] += b[4,5,6,7]
VADD2 VREG22.4s, VREG21.4s, VREG32.4s, VREG31.4s
WCHA_EOR_D_A // d ^= a
VADD2 VREG42.4s, VREG41.4s, VREG52.4s, VREG51.4s
VEOR2 VREG01.16b, VREG04.16b, VREG11.16b, VREG14.16b // d[12,13,14,15] ^= a[0,1,2,3]
WCHA_ROR_D #16 // d <<<= 16 ror Cyclic shift right by 16 bits.
VEOR2 VREG21.16b, VREG24.16b, VREG31.16b, VREG34.16b
VEOR2 VREG41.16b, VREG44.16b, VREG51.16b, VREG54.16b
WCHA_ADD_C_D // c += d
VREV322 VREG04.8h, VREG14.8h // d[12,13,14,15] (#16 inverse).
VREV322 VREG24.8h, VREG34.8h
WCHA_EOR_B_C
VREV322 VREG44.8h, VREG54.8h
VADD2 VREG04.4s, VREG03.4s, VREG14.4s, VREG13.4s // c[8,9,10,11] += d[12,13,14,15]
WCHA_ROR_B #20
VADD2 VREG24.4s, VREG23.4s, VREG34.4s, VREG33.4s
VADD2 VREG44.4s, VREG43.4s, VREG54.4s, VREG53.4s
WCHA_ADD_A_B // a += b
VEORX VREG03.16b, VREG02.16b, VCUR01.16b, VREG13.16b, VREG12.16b, VCUR02.16b // m = b[4,5,6,7] ^ c[8,9,10,11]
VEORX VREG23.16b, VREG22.16b, VCUR03.16b, VREG33.16b, VREG32.16b, VCUR04.16b
WCHA_EOR_D_A
VEORX VREG43.16b, VREG42.16b, VCUR05.16b, VREG53.16b, VREG52.16b, VCUR06.16b
VUSHR2 VCUR01.4s, VREG02.4s, VCUR02.4s, VREG12.4s, #20 // b[4,5,6,7] = m << 20
WCHA_ROR_D #24
VUSHR2 VCUR03.4s, VREG22.4s, VCUR04.4s, VREG32.4s, #20
VUSHR2 VCUR05.4s, VREG42.4s, VCUR06.4s, VREG52.4s, #20
WCHA_ADD_C_D // c += d
VSLI2 VCUR01.4s, VREG02.4s, VCUR02.4s, VREG12.4s, #12 // b[4,5,6,7] = m >> 12
VSLI2 VCUR03.4s, VREG22.4s, VCUR04.4s, VREG32.4s, #12
WCHA_EOR_B_C
VSLI2 VCUR05.4s, VREG42.4s, VCUR06.4s, VREG52.4s, #12
VADD2 VREG02.4s, VREG01.4s, VREG12.4s, VREG11.4s // a[0,1,2,3] += b[4,5,6,7]
WCHA_ROR_B #25
VADD2 VREG22.4s, VREG21.4s, VREG32.4s, VREG31.4s
VADD2 VREG42.4s, VREG41.4s, VREG52.4s, VREG51.4s
WCHA_ADD2_A_B
VEORX VREG04.16b, VREG01.16b, VCUR01.16b, VREG14.16b, VREG11.16b, VCUR02.16b // m = d[12,13,14,15] ^ a[0,1,2,3]
VEORX VREG24.16b, VREG21.16b, VCUR03.16b, VREG34.16b, VREG31.16b, VCUR04.16b
WCHA_EOR2_D_A
VEORX VREG44.16b, VREG41.16b, VCUR05.16b, VREG54.16b, VREG51.16b, VCUR06.16b
VUSHR2 VCUR01.4s, VREG04.4s, VCUR02.4s, VREG14.4s, #24 // d[12,13,14,15] = m << 24
WCHA_ROR_D #16
VUSHR2 VCUR03.4s, VREG24.4s, VCUR04.4s, VREG34.4s, #24
VUSHR2 VCUR05.4s, VREG44.4s, VCUR06.4s, VREG54.4s, #24
WCHA_ADD2_C_D
VSLI2 VCUR01.4s, VREG04.4s, VCUR02.4s, VREG14.4s, #8 // d[12,13,14,15] = m >> 8
VSLI2 VCUR03.4s, VREG24.4s, VCUR04.4s, VREG34.4s, #8
WCHA_EOR2_B_C
VSLI2 VCUR05.4s, VREG44.4s, VCUR06.4s, VREG54.4s, #8
VADD2 VREG04.4s, VREG03.4s, VREG14.4s, VREG13.4s // c[8,9,10,11] += d[12,13,14,15]
WCHA_ROR_B #20
VADD2 VREG24.4s, VREG23.4s, VREG34.4s, VREG33.4s
VADD2 VREG44.4s, VREG43.4s, VREG54.4s, VREG53.4s
WCHA_ADD2_A_B
VEORX VREG03.16b, VREG02.16b, VCUR01.16b, VREG13.16b, VREG12.16b, VCUR02.16b // m = b[4,5,6,7] ^ c[8,9,10,11]
VEORX VREG23.16b, VREG22.16b, VCUR03.16b, VREG33.16b, VREG32.16b, VCUR04.16b
WCHA_EOR2_D_A
VEORX VREG43.16b, VREG42.16b, VCUR05.16b, VREG53.16b, VREG52.16b, VCUR06.16b
VUSHR2 VCUR01.4s, VREG02.4s, VCUR02.4s, VREG12.4s, #25 // b[4,5,6,7] = m << 25
WCHA_ROR_D #24
VUSHR2 VCUR03.4s, VREG22.4s, VCUR04.4s, VREG32.4s, #25
VUSHR2 VCUR05.4s, VREG42.4s, VCUR06.4s, VREG52.4s, #25
WCHA_ADD2_C_D
VSLI2 VCUR01.4s, VREG02.4s, VCUR02.4s, VREG12.4s, #7 // b[4,5,6,7] = m >> 7
VSLI2 VCUR03.4s, VREG22.4s, VCUR04.4s, VREG32.4s, #7
WCHA_EOR2_B_C
VSLI2 VCUR05.4s, VREG42.4s, VCUR06.4s, VREG52.4s, #7
VEXT2 VREG03.16b, VREG13.16b, #8
WCHA_ROR_B #25
VEXT2 VREG23.16b, VREG33.16b, #8
VEXT2 VREG43.16b, VREG53.16b, #8
.endm
#endif
|
2301_79861745/bench_create
|
crypto/chacha20/src/asm/chacha20_512block_aarch64.S
|
Unix Assembly
|
unknown
| 10,013
|
/*
* 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_CHACHA20
.text
.macro CHA64_SET_WDATA
mov WINPUT0, WSIG01
lsr XINPUT1, XSIG01, #32
mov WINPUT2, WSIG02
lsr XINPUT3, XSIG02, #32
mov WINPUT4, WKEY01
lsr XINPUT5, XKEY01, #32
mov WINPUT6, WKEY02
lsr XINPUT7, XKEY02, #32
mov WINPUT8, WKEY03
lsr XINPUT9, XKEY03, #32
mov WINPUT10, WKEY04
lsr XINPUT11, XKEY04, #32
mov WINPUT12, WCOUN1
lsr XINPUT13, XCOUN1, #32 // 0
mov WINPUT14, WCOUN2
lsr XINPUT15, XCOUN2, #32
.endm
.macro CHA64_ROUND_END
add WINPUT0, WINPUT0, WSIG01 // Sum of the upper 32 bits and lower 32 bits.
add XINPUT1, XINPUT1, XSIG01, lsr#32
add WINPUT2, WINPUT2, WSIG02
add XINPUT3, XINPUT3, XSIG02, lsr#32
add WINPUT4, WINPUT4, WKEY01
add XINPUT5, XINPUT5, XKEY01, lsr#32
add WINPUT6, WINPUT6, WKEY02
add XINPUT7, XINPUT7, XKEY02, lsr#32
add WINPUT8, WINPUT8, WKEY03
add XINPUT9, XINPUT9, XKEY03, lsr#32
add WINPUT10, WINPUT10, WKEY04
add XINPUT11, XINPUT11, XKEY04, lsr#32
add WINPUT12, WINPUT12, WCOUN1
add XINPUT13, XINPUT13, XCOUN1, lsr#32
add WINPUT14, WINPUT14, WCOUN2
add XINPUT15, XINPUT15, XCOUN2, lsr#32
add XINPUT0, XINPUT0, XINPUT1, lsl#32 // Combination of upper 32 bits and lower 32 bits.
add XINPUT2, XINPUT2, XINPUT3, lsl#32 // Combination of upper 32 bits and lower 32 bits.
ldp XINPUT1, XINPUT3, [REGINC], #16 // Load input.
add XINPUT4, XINPUT4, XINPUT5, lsl#32 // Combination of upper 32 bits and lower 32 bits.
add XINPUT6, XINPUT6, XINPUT7, lsl#32 // Combination of upper 32 bits and lower 32 bits.
ldp XINPUT5, XINPUT7, [REGINC], #16 // Load input.
add XINPUT8, XINPUT8, XINPUT9, lsl#32 // Combination of upper 32 bits and lower 32 bits.
add XINPUT10, XINPUT10, XINPUT11, lsl#32 // Combination of upper 32 bits and lower 32 bits.
ldp XINPUT9, XINPUT11, [REGINC], #16 // Load input.
add XINPUT12, XINPUT12, XINPUT13, lsl#32 // Combination of upper 32 bits and lower 32 bits.
add XINPUT14, XINPUT14, XINPUT15, lsl#32 // Combination of upper 32 bits and lower 32 bits.
ldp XINPUT13, XINPUT15, [REGINC], #16 // Load input.
#ifdef HITLS_BIG_ENDIAN // Special processing is required in big-endian mode.
rev XINPUT0, XINPUT0
rev XINPUT2, XINPUT2
rev XINPUT4, XINPUT4
rev XINPUT6, XINPUT6
rev XINPUT8, XINPUT8
rev XINPUT10, XINPUT10
rev XINPUT12, XINPUT12
rev XINPUT14, XINPUT14
#endif
.endm
.macro CHA64_WRITE_BACK
eor XINPUT0, XINPUT0, XINPUT1
eor XINPUT2, XINPUT2, XINPUT3
eor XINPUT4, XINPUT4, XINPUT5
eor XINPUT6, XINPUT6, XINPUT7
eor XINPUT8, XINPUT8, XINPUT9
stp XINPUT0, XINPUT2, [REGOUT], #16 // Write data.
eor XINPUT10, XINPUT10, XINPUT11
stp XINPUT4, XINPUT6, [REGOUT], #16
eor XINPUT12, XINPUT12, XINPUT13
eor XINPUT14, XINPUT14, XINPUT15
stp XINPUT8, XINPUT10, [REGOUT], #16
stp XINPUT12, XINPUT14, [REGOUT], #16
.endm
#endif
|
2301_79861745/bench_create
|
crypto/chacha20/src/asm/chacha20_64block_aarch64.S
|
Unix Assembly
|
unknown
| 3,649
|
/*
* 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_CHACHA20
#include "crypt_arm.h"
#include "chacha20_common_aarch64.S"
#include "chacha20_64block_aarch64.S"
#include "chacha20_256block_aarch64.S"
#include "chacha20_512block_aarch64.S"
.section .rodata
.ADD_LONG:
.long 1,0,0,0
/**
* @Interconnection with the C interface:void CHACHA20_Update(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len);
* @brief Chacha20 algorithm
* @param ctx [IN] Algorithm context, which is set by the C interface and transferred.
* @param in [IN] Data to be encrypted
* @param out [OUT] Data after encryption
* @param len [IN] Encrypted length
*/
.text
.globl CHACHA20_Update
.type CHACHA20_Update,%function
.align 4
CHACHA20_Update:
AARCH64_PACIASP
lsr REGLEN, REGLEN, #6 // Divided by 64 to calculate how many blocks.
stp x29, x30, [sp, #-96]! // x29 x30 store sp -96 address sp -=96.
add x29, sp, #0 // x29 = sp
stp x19, x20, [sp, #80] // x19 x20 store sp, sp +=16.
stp x21, x22, [sp, #64]
cmp REGLEN, #1 // 1
stp x23, x24, [sp, #48]
stp x25, x26, [sp, #32]
stp x27, x28, [sp, #16]
sub sp, sp, #128+64 // sp -= 192
b.lo .Lchacha_end // Less than 1 block.
b.eq .Lchacha64 // Equals 1 block.
adrp x5, .ADD_LONG
add x5, x5, :lo12:.ADD_LONG // load(1, 0, 0, 0)
cmp REGLEN, #8 // >= 512(64*8)
#ifdef HITLS_BIG_ENDIAN
ldp XSIG01, XSIG02, [x0]
ld1 {VSIGMA.4s}, [x0], #16 // {sima0, sima1, key0, key1, key3, key4, counter1, counter2}
ldp XKEY01, XKEY02, [x0]
ldp XKEY03, XKEY04, [x0, #16]
ld1 {VKEY01.4s, VKEY02.4s}, [x0], #32
ldp XCOUN1, XCOUN2, [x0]
ld1 {VCOUN0.4s}, [x0]
// Processing when the big-endian machine is loaded.
ror XCOUN1, XCOUN1, #32
ror XCOUN2, XCOUN2, #32
ror XSIG01, XSIG01, #32
ror XSIG02, XSIG02, #32
add WINPUT2, WCOUN1, w3
ror XKEY01, XKEY01, #32
ror XKEY02, XKEY02, #32
ror XKEY03, XKEY03, #32
ror XKEY04, XKEY04, #32
str WINPUT2, [x0]
#else
ldp XSIG01, XSIG02, [x0]
ld1 {VSIGMA.4s}, [x0], #16 // {sima0, sima1, key0, key1, key3, key4, counter1, counter2}
ldp XKEY01, XKEY02, [x0]
ldp XKEY03, XKEY04, [x0, #16]
ld1 {VKEY01.4s, VKEY02.4s}, [x0], #32
ldp XCOUN1, XCOUN2, [x0]
ld1 {VCOUN0.4s}, [x0]
add x6, XCOUN1, REGLEN
str x6, [x0] // Write back the counter.
#endif
b.lo .Lchacha256 // < 512
stp QCUR05, QCUR06, [sp, #0] // Write sigma key1 to SP.
ld1 {VADDER.4s}, [x5] // Load ADDR.
add VCUR01.4s, VCOUN0.4s, VADDER.4s // 0
add VCUR01.4s, VCUR01.4s, VADDER.4s // +2
add VCUR02.4s, VCUR01.4s, VADDER.4s // +3
add VCUR03.4s, VCUR02.4s, VADDER.4s // +4
add VCUR04.4s, VCUR03.4s, VADDER.4s // +5
shl VADDER.4s, VADDER.4s, #2 // 4
stp d8, d9,[sp,#128+0] // Meet ABI requirements.
stp d10, d11,[sp,#128+16]
stp d12, d13,[sp,#128+32]
stp d14, d15,[sp,#128+48]
// 8 block
.Loop_512_start:
cmp REGLEN, #8
b.lo .L512ToChacha256 // Less than 512.
CHA64_SET_WDATA // General-purpose register 1 x 64 bytes.
CHA512_SET_VDATA // Wide register 6 x 64 bytes.
stp QCUR01, QCUR02, [sp, #32] // Write counter 0, 1, 2 3 to sp.
stp QCUR03, QCUR04, [sp, #64]
mov x4, #5
sub REGLEN, REGLEN, #8 // Process 512 at a time.
.Loop_512_a_run:
sub x4, x4, #1
CHA512_ROUND
CHA512_EXTA
CHA512_ROUND
CHA512_EXTB
cbnz x4, .Loop_512_a_run
CHA64_ROUND_END // Add to input after the loop is complete.
CHA64_WRITE_BACK // 512 Write 64 bytes in the first half round.
add XCOUN1, XCOUN1, #1 // +1
CHA64_SET_WDATA // Resetting.
mov x4, #5
.Loop_512_b_run:
sub x4, x4, #1
CHA512_ROUND
CHA512_EXTA
CHA512_ROUND
CHA512_EXTB
cbnz x4, .Loop_512_b_run
CHA64_ROUND_END // Add to input after the loop is complete.
CHA64_WRITE_BACK // 512 Write 64 bytes in the first half round.
add XCOUN1, XCOUN1, #7 // +7
ldp QCUR05, QCUR06, [sp, #0] // Restore sigma and key1.
ldp QCUR01, QCUR02, [sp, #32] // Restore counter 0 1 2 4.
ldp QCUR03, QCUR04, [sp, #64]
CHA512_ROUND_END // Add to input after the loop is complete.
CHA512_WRITE_BACK // Write back data.
b .Loop_512_start // return start.
// 1 block
.Lchacha64:
#ifdef HITLS_BIG_ENDIAN
ldp XCOUN1, XCOUN2, [x0, #48]
ldp XSIG01, XSIG02, [x0]
ldp XKEY01, XKEY02, [x0, #16]
// Processing when the big-endian machine is loaded
ror XCOUN1, XCOUN1, #32
ror XCOUN2, XCOUN2, #32
ror XSIG01, XSIG01, #32
ror XSIG02, XSIG02, #32
ldp XKEY03, XKEY04, [x0, #32]
add WINPUT0, WCOUN1, w3
ror XKEY01, XKEY01, #32
ror XKEY02, XKEY02, #32
ror XKEY03, XKEY03, #32
ror XKEY04, XKEY04, #32
str WINPUT0, [x0, #48]
#else
ldp XCOUN1, XCOUN2, [x0, #48]
ldp XSIG01, XSIG02, [x0]
ldp XKEY01, XKEY02, [x0, #16]
add XINPUT0, XCOUN1, REGLEN
ldp XKEY03, XKEY04, [x0, #32]
str XINPUT0, [x0, #48] // Write data.
#endif
.Loop_64_start:
CHA64_SET_WDATA // General-purpose register, 1x64byte.
mov x4, #10
.Loop_64_run:
sub x4, x4, #1
WCHA_ADD_A_B // a += b
WCHA_EOR_D_A // d ^= a
WCHA_ROR_D #16 // d <<<= 16 ror Cyclic shift right by 16 bits.
WCHA_ADD_C_D // c += d
WCHA_EOR_B_C
WCHA_ROR_B #20
WCHA_ADD_A_B // a += b
WCHA_EOR_D_A
WCHA_ROR_D #24
WCHA_ADD_C_D // c += d
WCHA_EOR_B_C
WCHA_ROR_B #25
WCHA_ADD2_A_B
WCHA_EOR2_D_A
WCHA_ROR_D #16
WCHA_ADD2_C_D
WCHA_EOR2_B_C
WCHA_ROR_B #20
WCHA_ADD2_A_B
WCHA_EOR2_D_A
WCHA_ROR_D #24
WCHA_ADD2_C_D
WCHA_EOR2_B_C
WCHA_ROR_B #25
cbnz x4, .Loop_64_run
CHA64_ROUND_END // Add to input after the loop is complete.
subs REGLEN, REGLEN, #1
CHA64_WRITE_BACK // Write 64 bytes.
add XCOUN1, XCOUN1, #1
b.le .Lchacha_end
b .Loop_64_start
.L512ToChacha256:
ldp d8,d9,[sp,#128+0] // Meet ABI requirements.
ldp d10,d11,[sp,#128+16]
ldp d12,d13,[sp,#128+32]
ldp d14,d15,[sp,#128+48]
cbz REGLEN, .Lchacha_end // The length is 0.
ushr VADDER.4s, VADDER.4s, #2 // 4->1
sub VREG52.4s, VCUR01.4s, VADDER.4s // 10-1 = 9 8
sub VREG53.4s, VCUR02.4s, VADDER.4s // 11-1 = 10
sub VREG54.4s, VCUR03.4s, VADDER.4s // 12-1 = 11
shl VCUR01.4s, VADDER.4s, #2 // 2 -> 4
b .Loop_256_start
// 4 block
.Lchacha256:
ld1 {VADDER.4s}, [x5] // Load ADDR.
mov VREG51.16b, VCOUN0.16b // 0
add VREG52.4s, VCOUN0.4s, VADDER.4s // 1
add VREG53.4s, VREG52.4s, VADDER.4s // 2
add VREG54.4s, VREG53.4s, VADDER.4s // 3
shl VCUR01.4s, VADDER.4s, #2 // 4
.Loop_256_start:
CHA64_SET_WDATA // General-purpose register 16 byte.
CHA256_SET_VDATA // Neon register 3 * 48 byte.
mov x4, #10
.Loop_256_run:
sub x4, x4, #1
CHA256_ROUND_A
VEXT2 VREG04.16b, VREG14.16b, #12
VEXT2 VREG24.16b, VREG34.16b, #12
VEXT2 VREG02.16b, VREG12.16b, #4
VEXT2 VREG22.16b, VREG32.16b, #4
CHA256_ROUND_B
VEXT2 VREG04.16b, VREG14.16b, #4
VEXT2 VREG24.16b, VREG34.16b, #4
VEXT2 VREG02.16b, VREG12.16b, #12
VEXT2 VREG22.16b, VREG32.16b, #12
cbnz x4, .Loop_256_run
subs REGLEN, REGLEN, #4 // One-time processing 256.
CHA256_ROUND_END
b.lo .Lchacha_less_than_256 // < 0
CHA64_ROUND_END
CHA256_WRITE_BACK // Write back data.
b.le .Lchacha_end // = 0
add XCOUN1, XCOUN1, #4 // Counter+4.
add VREG52.4s, VREG52.4s, VCUR01.4s // Counter+4.
add VREG53.4s, VREG53.4s, VCUR01.4s
add VREG54.4s, VREG54.4s, VCUR01.4s
b .Loop_256_start
.Lchacha_less_than_256:
add REGLEN, REGLEN, #4
cmp REGLEN, #1
b.lo .Lchacha_end // <= 64 byte.
CHA64_ROUND_END
CHA64_WRITE_BACK
sub REGLEN, REGLEN, #1
cmp REGLEN, #1
b.lo .Lchacha_end
CHA256_WRITE_BACKB VREG01.16b, VREG02.16b, VREG03.16b, VREG04.16b
sub REGLEN, REGLEN, #1
cmp REGLEN, #1
b.lo .Lchacha_end
CHA256_WRITE_BACKB VREG11.16b, VREG12.16b, VREG13.16b, VREG14.16b
.Lchacha_end:
eor XKEY01, XKEY01, XKEY01
eor XKEY02, XKEY02, XKEY02
eor XKEY03, XKEY03, XKEY03
eor XKEY04, XKEY04, XKEY04
eor XKEY04, XKEY04, XKEY04
eor XCOUN2, XCOUN2, XCOUN2
eor VKEY01.16b, VKEY01.16b, VKEY01.16b
eor VKEY02.16b, VKEY02.16b, VKEY02.16b
eor VCUR01.16b, VCUR01.16b, VCUR01.16b
ldp x19, x20, [x29, #80]
add sp, sp, #128+64
ldp x21, x22, [x29, #64]
ldp x23, x24, [x29, #48]
ldp x25, x26, [x29, #32]
ldp x27, x28, [x29, #16]
ldp x29, x30, [sp], #96
.Labort:
AARCH64_AUTIASP
ret
.size CHACHA20_Update,.-CHACHA20_Update
#endif
|
2301_79861745/bench_create
|
crypto/chacha20/src/asm/chacha20_aarch64.S
|
Unix Assembly
|
unknown
| 10,460
|
/*
* 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_CHACHA20
.text
// Input ctx、in、out、len.
REGCTX .req x0
REGINC .req x1
REGOUT .req x2
REGLEN .req x3
// 64-byte input, temporarily loaded register(0 ~ 15).
WINPUT0 .req w5
XINPUT0 .req x5
WINPUT1 .req w6
XINPUT1 .req x6
WINPUT2 .req w7
XINPUT2 .req x7
WINPUT3 .req w8
XINPUT3 .req x8
WINPUT4 .req w9
XINPUT4 .req x9
WINPUT5 .req w10
XINPUT5 .req x10
WINPUT6 .req w11
XINPUT6 .req x11
WINPUT7 .req w12
XINPUT7 .req x12
WINPUT8 .req w13
XINPUT8 .req x13
WINPUT9 .req w14
XINPUT9 .req x14
WINPUT10 .req w15
XINPUT10 .req x15
WINPUT11 .req w16
XINPUT11 .req x16
WINPUT12 .req w17
XINPUT12 .req x17
WINPUT13 .req w19
XINPUT13 .req x19
WINPUT14 .req w20
XINPUT14 .req x20
WINPUT15 .req w21
XINPUT15 .req x21
// 8 blocks in parallel, 6 blocks of 64-byte data in 8 blocks of 512 bytes.
VREG01 .req v0
VREG02 .req v1
VREG03 .req v2
VREG04 .req v3
VREG11 .req v4
VREG12 .req v5
VREG13 .req v6
VREG14 .req v7
VREG21 .req v8
VREG22 .req v9
VREG23 .req v10
VREG24 .req v11
VREG31 .req v12
VREG32 .req v13
VREG33 .req v14
VREG34 .req v15
VREG41 .req v16
VREG42 .req v17
VREG43 .req v18
VREG44 .req v19
VREG51 .req v20
VREG52 .req v21
VREG53 .req v22
VREG54 .req v23
// Public register, used for temporary calculation.
VCUR01 .req v24
QCUR01 .req q24
VCUR02 .req v25
QCUR02 .req q25
VCUR03 .req v26
QCUR03 .req q26
VCUR04 .req v27
QCUR04 .req q27
VCUR05 .req v28
QCUR05 .req q28
VCUR06 .req v29
QCUR06 .req q29
// Counter、sigma、key、adder register.
VCOUN0 .req v27
VSIGMA .req v28
VKEY01 .req v29
VKEY02 .req v30
VADDER .req v31
// Counter、sigma、key、adder register.
WSIG01 .req w22
XSIG01 .req x22
WSIG02 .req w23
XSIG02 .req x23
WKEY01 .req w24
XKEY01 .req x24
WKEY02 .req w25
XKEY02 .req x25
WKEY03 .req w26
XKEY03 .req x26
WKEY04 .req w27
XKEY04 .req x27
WCOUN1 .req w28
XCOUN1 .req x28
WCOUN2 .req w30
XCOUN2 .req x30
.macro VADD2 src, dest, src2, dest2
add \dest, \dest, \src
add \dest2, \dest2, \src2
.endm
.macro VEOR2 src, dest, src2, dest2
eor \dest, \dest, \src
eor \dest2, \dest2, \src2
.endm
.macro VEORX srca, srcb, dest, srca2, srcb2, dest2
eor \dest, \srcb, \srca
eor \dest2, \srcb2, \srca2
.endm
.macro VREV322 dest, dest2
rev32 \dest, \dest
rev32 \dest2, \dest2
.endm
.macro VUSHR2 src, dest, src2, dest2, count
ushr \dest, \src, \count
ushr \dest2, \src2, \count
.endm
.macro VSLI2 src, dest, src2, dest2, count
sli \dest, \src, \count
sli \dest2, \src2, \count
.endm
.macro VEXT2 src, src2, count
ext \src, \src, \src, \count
ext \src2, \src2, \src2, \count
.endm
.macro WCHA_ADD_A_B
add WINPUT0, WINPUT0, WINPUT4
add WINPUT1, WINPUT1, WINPUT5
add WINPUT2, WINPUT2, WINPUT6
add WINPUT3, WINPUT3, WINPUT7
.endm
.macro WCHA_EOR_D_A
eor WINPUT12, WINPUT12, WINPUT0
eor WINPUT13, WINPUT13, WINPUT1
eor WINPUT14, WINPUT14, WINPUT2
eor WINPUT15, WINPUT15, WINPUT3
.endm
.macro WCHA_ROR_D count
ror WINPUT12, WINPUT12, \count
ror WINPUT13, WINPUT13, \count
ror WINPUT14, WINPUT14, \count
ror WINPUT15, WINPUT15, \count
.endm
.macro WCHA_ADD_C_D
add WINPUT8, WINPUT8, WINPUT12
add WINPUT9, WINPUT9, WINPUT13
add WINPUT10, WINPUT10, WINPUT14
add WINPUT11, WINPUT11, WINPUT15
.endm
.macro WCHA_EOR_B_C
eor WINPUT4, WINPUT4, WINPUT8
eor WINPUT5, WINPUT5, WINPUT9
eor WINPUT6, WINPUT6, WINPUT10
eor WINPUT7, WINPUT7, WINPUT11
.endm
.macro WCHA_ROR_B count
ror WINPUT4, WINPUT4, \count
ror WINPUT5, WINPUT5, \count
ror WINPUT6, WINPUT6, \count
ror WINPUT7, WINPUT7, \count
.endm
.macro WCHA_ADD2_A_B
add WINPUT0, WINPUT0, WINPUT5
add WINPUT1, WINPUT1, WINPUT6
add WINPUT2, WINPUT2, WINPUT7
add WINPUT3, WINPUT3, WINPUT4
.endm
.macro WCHA_EOR2_D_A
eor WINPUT15, WINPUT15, WINPUT0
eor WINPUT12, WINPUT12, WINPUT1
eor WINPUT13, WINPUT13, WINPUT2
eor WINPUT14, WINPUT14, WINPUT3
.endm
.macro WCHA_ADD2_C_D
add WINPUT10, WINPUT10, WINPUT15
add WINPUT11, WINPUT11, WINPUT12
add WINPUT8, WINPUT8, WINPUT13
add WINPUT9, WINPUT9, WINPUT14
.endm
.macro WCHA_EOR2_B_C
eor WINPUT5, WINPUT5, WINPUT10
eor WINPUT6, WINPUT6, WINPUT11
eor WINPUT7, WINPUT7, WINPUT8
eor WINPUT4, WINPUT4, WINPUT9
.endm
#endif
|
2301_79861745/bench_create
|
crypto/chacha20/src/asm/chacha20_common_aarch64.S
|
Motorola 68K Assembly
|
unknown
| 4,831
|
/*
* 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_CHACHA20
/* --------------AVX2 Overall design-----------------
* 64->%xmm0-%xmm7 No need to use stack memory
* 128->%xmm0-%xmm11 No need to use stack memory
* 256->%xmm0-%xmm15 Use 256 + 64 bytes of stack memory
* 512->%ymm0-%ymm15 Use 512 + 128 bytes of stack memory
*
--------------AVX512 Overall design-----------------
* 64->%xmm0-%xmm7 No need to use stack memory
* 128->%xmm0-%xmm11 No need to use stack memory
* 256->%xmm0-%xmm31 Use 64-byte stack memory
* 512->%ymm0-%ymm31 Use 128-byte stack memory
* 1024->%zmm0-%zmm31 Use 256-byte stack memory
*/
/*************************************************************************************
* AVX2/AVX512 Generic Instruction Set Using Macros
*************************************************************************************/
/* %xmm0-15 load STATE Macro. */
.macro LOAD_STATE s0 s1 s2 s3 adr
vmovdqu (\adr), \s0 // state[0-3]
vmovdqu 16(\adr), \s1 // state[4-7]
vmovdqu 32(\adr), \s2 // state[8-11]
vmovdqu 48(\adr), \s3 // state[12-15]
.endm
/* %ymm0-15 load STATE Macro. */
.macro LOAD_512_STATE s0 s1 s2 s3 adr
vbroadcasti128 (\adr), \s0 // state[0-3]
vbroadcasti128 16(\adr), \s1 // state[4-7]
vbroadcasti128 32(\adr), \s2 // state[8-11]
vbroadcasti128 48(\adr), \s3 // state[12-15]
.endm
/*
* %xmm0-15, %ymm0-15 MATRIX TO STATE
* IN: s0 s1 s2 s3 cur1 cur2
* OUT: s0 s3 cur1 cur2
* xmm:
* {A0 B0 C0 D0} => {A0 A1 A2 A3}
* {A1 B1 C1 D1} {B0 B1 B2 B3}
* {A2 B2 C2 D2} {C0 C1 C2 C3}
* {A3 B3 C3 D3} {D0 D1 D2 D3}
* ymm:
* {A0 B0 C0 D0 E0 F0 G0 H0} => {A0 A1 A2 A3 E0 E1 E2 E3}
* {A1 B1 C1 D1 E1 F1 G1 H1} {B0 B1 B2 B3 F0 F1 F2 F3}
* {A2 B2 C2 D2 E2 F2 G2 H2} {C0 C1 C2 C3 G0 G1 G2 G3}
* {A3 B3 C3 D3 E3 F3 G3 H3} {D0 D1 D2 D3 H0 H1 H2 H3}
* zmm:
* {A0 B0 C0 D0 E0 F0 G0 H0 I0 J0 K0 L0 M0 N0 O0 P0} => {A0 A1 A2 A3 E0 E1 E2 E3 I0 I1 I2 I3 M0 M1 M2 M3}
* {A1 B1 C1 D1 E1 F1 G1 H1 I1 J1 K1 L1 M1 N1 O1 P1} {B0 B1 B2 B3 F0 F1 F2 F3 J0 J1 J2 J3 N0 N1 N2 N3}
* {A2 B2 C2 D2 E2 F2 G2 H2 I2 J2 K2 L2 M2 N2 O2 P2} {C0 C1 C2 C3 G0 G1 G2 G3 K0 K1 K2 K3 O0 O1 O2 O3}
* {A3 B3 C3 D3 E3 F3 G3 H3 I3 J3 K3 L3 M3 N3 O3 P3} {D0 D1 D2 D3 H0 H1 H2 H3 L0 L1 L2 L3 P0 P1 P2 P3}
*/
.macro MATRIX_TO_STATE s0 s1 s2 s3 cur1 cur2
vpunpckldq \s1, \s0, \cur1
vpunpckldq \s3, \s2, \cur2
vpunpckhdq \s1, \s0, \s1
vpunpckhdq \s3, \s2, \s2
vpunpcklqdq \cur2, \cur1, \s0
vpunpckhqdq \cur2, \cur1, \s3
vpunpcklqdq \s2, \s1, \cur1
vpunpckhqdq \s2, \s1, \cur2
.endm
/*************************************************************************************
* AVX2 instruction set use macros
*************************************************************************************/
.macro WRITEBACK_64_AVX2 inpos outpos s0 s1 s2 s3
vpxor (\inpos), \s0, \s0
vpxor 16(\inpos), \s1, \s1
vpxor 32(\inpos), \s2, \s2
vpxor 48(\inpos), \s3, \s3
vmovdqu \s0, (\outpos) // write back output
vmovdqu \s1, 16(\outpos)
vmovdqu \s2, 32(\outpos)
vmovdqu \s3, 48(\outpos)
add $64, \inpos
add $64, \outpos
.endm
/*
* Converts a state into a matrix.
* %xmm0-15 %ymm0-15 STATE TO MATRIX
* s0-s15:Corresponding to 16 wide-bit registers,adr:counter Settings; base:address of the data storage stack;
* per:Register bit width,Byte representation(16、32)
*/
.macro STATE_TO_MATRIX s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15 base per adr
vpshufd $0b00000000, \s3, \s12
vpshufd $0b01010101, \s3, \s13
vpaddd \adr, \s12, \s12 // 0, 1, 2, 3, 4, 5, 6 ,7
vmovdqa \s12, \base+12*\per(%rsp)
vpshufd $0b10101010, \s3, \s14
vmovdqa \s13, \base+13*\per(%rsp)
vpshufd $0b11111111, \s3, \s15
vmovdqa \s14, \base+14*\per(%rsp)
vpshufd $0b00000000, \s2, \s8
vmovdqa \s15, \base+15*\per(%rsp)
vpshufd $0b01010101, \s2, \s9
vmovdqa \s8, \base+8*\per(%rsp)
vpshufd $0b10101010, \s2, \s10
vmovdqa \s9, \base+9*\per(%rsp)
vpshufd $0b11111111, \s2, \s11
vmovdqa \s10, \base+10*\per(%rsp)
vpshufd $0b00000000, \s1, \s4
vmovdqa \s11, \base+11*\per(%rsp)
vpshufd $0b01010101, \s1, \s5
vmovdqa \s4, \base+4*\per(%rsp)
vpshufd $0b10101010, \s1, \s6
vmovdqa \s5, \base+5*\per(%rsp)
vpshufd $0b11111111, \s1, \s7
vmovdqa \s6, \base+6*\per(%rsp)
vpshufd $0b11111111, \s0, \s3
vmovdqa \s7, \base+7*\per(%rsp)
vpshufd $0b10101010, \s0, \s2
vmovdqa \s3, \base+3*\per(%rsp)
vpshufd $0b01010101, \s0, \s1
vmovdqa \s2, \base+2*\per(%rsp)
vpshufd $0b00000000, \s0, \s0
vmovdqa \s1, \base+1*\per(%rsp)
vmovdqa \s0, \base(%rsp)
.endm
/*
* %xmm0-15 %ymm0-15 LOAD MATRIX
*/
.macro LOAD_MATRIX s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15 base per adr
vmovdqa \base(%rsp), \s0
vmovdqa \base+1*\per(%rsp), \s1
vmovdqa \base+2*\per(%rsp), \s2
vmovdqa \base+3*\per(%rsp), \s3
vmovdqa \base+4*\per(%rsp), \s4
vmovdqa \base+5*\per(%rsp), \s5
vmovdqa \base+6*\per(%rsp), \s6
vmovdqa \base+7*\per(%rsp), \s7
vmovdqa \base+8*\per(%rsp), \s8
vmovdqa \base+9*\per(%rsp), \s9
vmovdqa \base+10*\per(%rsp), \s10
vmovdqa \base+11*\per(%rsp), \s11
vmovdqa \base+12*\per(%rsp), \s12
vmovdqa \base+13*\per(%rsp), \s13
vpaddd \adr, \s12, \s12 // add 8, 8, 8, 8, 8, 8, 8, 8 or 4, 4, 4, 4
vmovdqa \base+14*\per(%rsp), \s14
vmovdqa \base+15*\per(%rsp), \s15
vmovdqa \s12, \base+12*\per(%rsp)
.endm
/*
* %xmm0-15(256) %ymm0-15(512) Loop
*/
.macro CHACHA20_LOOP s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15 base per A8 ror16 ror8
/* 0 = 0 + 4, 12 = (12 ^ 0) >>> 16 | 8 = 8 + 12, 4 = (4 ^ 8) >>> 12 |
* 0 = 0 + 4, 12 = (12 ^ 0) >>> 8 | 8 = 8 + 12, 4 = (4 ^ 8) >>> 7
* 1 = 1 + 5, 13 = (13 ^ 1) >>> 16 | 9 = 9 + 13, 5 = (5 ^ 9) >>> 12 |
* 1 = 1 + 5, 13 = (13 ^ 1) >>> 8 | 9 = 9 + 13, 5 = (5 ^ 9) >>> 7
*/
COLUM_QUARTER_AVX_0 \s0 \s4 \s12 \s1 \s5 \s13 (\ror16)
COLUM_QUARTER_AVX_1 \s8 \s12 \s4 \s9 \s13 \s5 \s10 \s11 $20 $12
COLUM_QUARTER_AVX_0 \s0 \s4 \s12 \s1 \s5 \s13 (\ror8)
COLUM_QUARTER_AVX_1 \s8 \s12 \s4 \s9 \s13 \s5 \s10 \s11 $25 $7
vmovdqa \s8, \base(\A8)
vmovdqa \s9, \base+\per(\A8)
vmovdqa \base+2*\per(\A8), \s10
vmovdqa \base+3*\per(\A8), \s11
/* 2 = 2 + 6, 14 = (14 ^ 2) >>> 16 | 10 = 10 + 14, 6 = (6 ^ 10)>>> 12 |
* 2 = 2 + 6, 14 = (14 ^ 2) >>> 8 | 10 = 10 + 14, 6 = (6 ^ 10)>>> 7
* 3 = 3 + 7, 15 = (15 ^ 3) >>> 16 | 11 = 11 + 15, 7 = (7 ^ 11)>>> 12 |
* 3 = 3 + 7, 15 = (15 ^ 3) >>> 8 | 11 = 11 + 15, 7 = (7 ^ 11)>>> 7
*/
COLUM_QUARTER_AVX_0 \s2 \s6 \s14 \s3 \s7 \s15 (\ror16)
COLUM_QUARTER_AVX_1 \s10 \s14 \s6 \s11 \s15 \s7 \s8 \s9 $20 $12
COLUM_QUARTER_AVX_0 \s2 \s6 \s14 \s3 \s7 \s15 (\ror8)
COLUM_QUARTER_AVX_1 \s10 \s14 \s6 \s11 \s15 \s7 \s8 \s9 $25 $7
/* 0 = 0 + 5, 15 = (15 ^ 0) >>> 16 | 10 = 10 + 15, 5 = (5 ^ 10) >>> 12 |
* 0 = 0 + 5, 15 = (15 ^ 0) >>> 8 | 10 = 10 + 15, 5 = (5 ^ 10) >>> 7
* 1 = 1 + 6, 12 = (12 ^ 1) >>> 16 | 11 = 11 + 12, 6 = (6 ^ 11) >>> 12 |
* 1 = 1 + 6, 12 = (12 ^ 1) >>> 8 | 11 = 11 + 12, 6 = (6 ^ 11) >>> 7
*/
COLUM_QUARTER_AVX_0 \s0 \s5 \s15 \s1 \s6 \s12 (\ror16)
COLUM_QUARTER_AVX_1 \s10 \s15 \s5 \s11 \s12 \s6 \s8 \s9 $20 $12
COLUM_QUARTER_AVX_0 \s0 \s5 \s15 \s1 \s6 \s12 (\ror8)
COLUM_QUARTER_AVX_1 \s10 \s15 \s5 \s11 \s12 \s6 \s8 \s9 $25 $7
vmovdqa \s10, \base+2*\per(\A8)
vmovdqa \s11, \base+3*\per(\A8)
vmovdqa \base(\A8), \s8
vmovdqa \base+\per(\A8), \s9
/* 2 = 2 + 7, 13 = (13 ^ 2) >>> 16 | 8 = 8 + 13, 7 = (7 ^ 8)>>> 12 |
* 2 = 2 + 7, 13 = (13 ^ 2) >>> 8 | 8 = 8 + 13, 7 = (7 ^ 8)>>> 7
* 3 = 3 + 4, 14 = (14 ^ 3) >>> 16 | 9 = 9 + 14, 4 = (4 ^ 9)>>> 12 |
* 3 = 3 + 4, 14 = (14 ^ 3) >>> 8 | 9 = 9 + 14, 4 = (4 ^ 9)>>> 7
*/
COLUM_QUARTER_AVX_0 \s2 \s7 \s13 \s3 \s4 \s14 (\ror16)
COLUM_QUARTER_AVX_1 \s8 \s13 \s7 \s9 \s14 \s4 \s10 \s11 $20 $12
COLUM_QUARTER_AVX_0 \s2 \s7 \s13 \s3 \s4 \s14 (\ror8)
COLUM_QUARTER_AVX_1 \s8 \s13 \s7 \s9 \s14 \s4 \s10 \s11 $25 $7
.endm
/*
* %xmm0-15 %ymm0-15 QUARTER macro(used when cyclically moving right by 16 or 8)
*/
.macro COLUM_QUARTER_AVX_0 a0 a1 a2 b0 b1 b2 ror
vpaddd \a1, \a0, \a0
vpaddd \b1, \b0, \b0
vpxor \a0, \a2, \a2
vpxor \b0, \b2, \b2
vpshufb \ror, \a2, \a2
vpshufb \ror, \b2, \b2
.endm
/*
* %xmm0-15 %ymm0-15 QUARTER macro(used when cyclically moving right by 12 or 7)
*/
.macro COLUM_QUARTER_AVX_1 a0 a1 a2 b0 b1 b2 cur1 cur2 psr psl
vpaddd \a1, \a0, \a0
vpaddd \b1, \b0, \b0
vpxor \a0, \a2, \a2
vpxor \b0, \b2, \b2
vpsrld \psr, \a2, \cur1
vpsrld \psr, \b2, \cur2
vpslld \psl, \a2, \a2
vpslld \psl, \b2, \b2
vpor \cur1, \a2, \a2
vpor \cur2, \b2, \b2
.endm
/*************************************************************************************
* AVX512 generic instruction set using macros.
*************************************************************************************/
/* %zmm0-15 LOAD STATE MACRO. */
.macro LOAD_1024_STATE s0 s1 s2 s3 adr
vbroadcasti32x4 (\adr), \s0 // state[0-3]
vbroadcasti32x4 16(\adr), \s1 // state[4-7]
vbroadcasti32x4 32(\adr), \s2 // state[8-11]
vbroadcasti32x4 48(\adr), \s3 // state[12-15]
.endm
.macro WRITEBACK_64_AVX512 inpos outpos s0 s1 s2 s3
vpxord (\inpos), \s0, \s0
vpxord 16(\inpos), \s1, \s1
vpxord 32(\inpos), \s2, \s2
vpxord 48(\inpos), \s3, \s3
vmovdqu32 \s0, (\outpos) // Write back output.
vmovdqu32 \s1, 16(\outpos)
vmovdqu32 \s2, 32(\outpos)
vmovdqu32 \s3, 48(\outpos)
add $64, \inpos
add $64, \outpos
.endm
/*
* %zmm0-15 STATE TO MATRIX
*/
.macro STATE_TO_MATRIX_Z_AVX512 in out0 out1 out2 out3
// {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} .... {15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15}
vpshufd $0b00000000, \in, \out0
vpshufd $0b01010101, \in, \out1
vpshufd $0b10101010, \in, \out2
vpshufd $0b11111111, \in, \out3
.endm
/* AVX512 instruction set
* %zmm0-31(1024) QUARTER
*/
.macro COLUM_QUARTER_AVX512_4 s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 ror
vpaddd \s4, \s0, \s0
vpaddd \s5, \s1, \s1
vpaddd \s6, \s2, \s2
vpaddd \s7, \s3, \s3
vpxord \s0, \s8, \s8
vpxord \s1, \s9, \s9
vpxord \s2, \s10, \s10
vpxord \s3, \s11, \s11
vprold \ror, \s8, \s8
vprold \ror, \s9, \s9
vprold \ror, \s10, \s10
vprold \ror, \s11, \s11
.endm
/* AVX512 instruction set
* %xmm0-15(256) %ymm0-15(512) %zmm0-31(1024) Loop
*/
.macro CHACHA20_LOOP_AVX512 s00 s01 s02 s03 s04 s05 s06 s07 s08 s09 s10 s11 s12 s13 s14 s15
/* 0 = 0 + 4, 12 = (12 ^ 0) >>> 16 | 8 = 8 + 12, 4 = (4 ^ 8) >>> 12 |
* 0 = 0 + 4, 12 = (12 ^ 0) >>> 8 | 8 = 8 + 12, 4 = (4 ^ 8) >>> 7
* 1 = 1 + 5, 13 = (13 ^ 1) >>> 16 | 9 = 9 + 13, 5 = (5 ^ 9) >>> 12 |
* 1 = 1 + 5, 13 = (13 ^ 1) >>> 8 | 9 = 9 + 13, 5 = (5 ^ 9) >>> 7
* 2 = 2 + 6, 14 = (14 ^ 2) >>> 16 | 10 = 10 + 14, 6 = (6 ^ 10)>>> 12 |
* 2 = 2 + 6, 14 = (14 ^ 2) >>> 8 | 10 = 10 + 14, 6 = (6 ^ 10)>>> 7
* 3 = 3 + 7, 15 = (15 ^ 3) >>> 16 | 11 = 11 + 15, 7 = (7 ^ 11)>>> 12 |
* 3 = 3 + 7, 15 = (15 ^ 3) >>> 8 | 11 = 11 + 15, 7 = (7 ^ 11)>>> 7
*/
COLUM_QUARTER_AVX512_4 \s00 \s01 \s02 \s03 \s04 \s05 \s06 \s07 \s12 \s13 \s14 \s15 $16
COLUM_QUARTER_AVX512_4 \s08 \s09 \s10 \s11 \s12 \s13 \s14 \s15 \s04 \s05 \s06 \s07 $12
COLUM_QUARTER_AVX512_4 \s00 \s01 \s02 \s03 \s04 \s05 \s06 \s07 \s12 \s13 \s14 \s15 $8
COLUM_QUARTER_AVX512_4 \s08 \s09 \s10 \s11 \s12 \s13 \s14 \s15 \s04 \s05 \s06 \s07 $7
/* 0 = 0 + 5, 15 = (15 ^ 0) >>> 16 | 10 = 10 + 15, 5 = (5 ^ 10) >>> 12 |
* 0 = 0 + 5, 15 = (15 ^ 0) >>> 8 | 10 = 10 + 15, 5 = (5 ^ 10) >>> 7
* 1 = 1 + 6, 12 = (12 ^ 1) >>> 16 | 11 = 11 + 12, 6 = (6 ^ 11) >>> 12 |
* 1 = 1 + 6, 12 = (12 ^ 1) >>> 8 | 11 = 11 + 12, 6 = (6 ^ 11) >>> 7
* 2 = 2 + 7, 13 = (13 ^ 2) >>> 16 | 8 = 8 + 13, 7 = (7 ^ 8)>>> 12 |
* 2 = 2 + 7, 13 = (13 ^ 2) >>> 8 | 8 = 8 + 13, 7 = (7 ^ 8)>>> 7
* 3 = 3 + 4, 14 = (14 ^ 3) >>> 16 | 9 = 9 + 14, 4 = (4 ^ 9)>>> 12 |
* 3 = 3 + 4, 14 = (14 ^ 3) >>> 8 | 9 = 9 + 14, 4 = (4 ^ 9)>>> 7
*/
COLUM_QUARTER_AVX512_4 \s00 \s01 \s02 \s03 \s05 \s06 \s07 \s04 \s15 \s12 \s13 \s14 $16
COLUM_QUARTER_AVX512_4 \s10 \s11 \s08 \s09 \s15 \s12 \s13 \s14 \s05 \s06 \s07 \s04 $12
COLUM_QUARTER_AVX512_4 \s00 \s01 \s02 \s03 \s05 \s06 \s07 \s04 \s15 \s12 \s13 \s14 $8
COLUM_QUARTER_AVX512_4 \s10 \s11 \s08 \s09 \s15 \s12 \s13 \s14 \s05 \s06 \s07 \s04 $7
.endm
#endif
|
2301_79861745/bench_create
|
crypto/chacha20/src/asm/chacha20_x8664_common.S
|
Unix Assembly
|
unknown
| 13,328
|
/*
* 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_CHACHA20
#include "chacha20_x8664_common.S"
.text
.align 64
g_ror16_128:
.byte 0x2,0x3,0x0,0x1, 0x6,0x7,0x4,0x5, 0xa,0xb,0x8,0x9, 0xe,0xf,0xc,0xd, \
0x2,0x3,0x0,0x1, 0x6,0x7,0x4,0x5, 0xa,0xb,0x8,0x9, 0xe,0xf,0xc,0xd
.size g_ror16_128, .-g_ror16_128
.align 64
g_ror8_128:
.byte 0x3,0x0,0x1,0x2, 0x7,0x4,0x5,0x6, 0xb,0x8,0x9,0xa, 0xf,0xc,0xd,0xe, \
0x3,0x0,0x1,0x2, 0x7,0x4,0x5,0x6, 0xb,0x8,0x9,0xa, 0xf,0xc,0xd,0xe
.size g_ror8_128, .-g_ror8_128
.align 64
g_ror16:
.byte 0x2,0x3,0x0,0x1, 0x6,0x7,0x4,0x5, 0xa,0xb,0x8,0x9, 0xe,0xf,0xc,0xd
.size g_ror16, .-g_ror16
.align 64
g_ror8:
.byte 0x3,0x0,0x1,0x2, 0x7,0x4,0x5,0x6, 0xb,0x8,0x9,0xa, 0xf,0xc,0xd,0xe
.size g_ror8, .-g_ror8
.align 64
g_ror16_512:
.byte 0x2,0x3,0x0,0x1, 0x6,0x7,0x4,0x5, 0xa,0xb,0x8,0x9, 0xe,0xf,0xc,0xd, \
0x2,0x3,0x0,0x1, 0x6,0x7,0x4,0x5, 0xa,0xb,0x8,0x9, 0xe,0xf,0xc,0xd
.size g_ror16_512, .-g_ror16_512
.align 64
g_ror8_512:
.byte 0x3,0x0,0x1,0x2, 0x7,0x4,0x5,0x6, 0xb,0x8,0x9,0xa, 0xf,0xc,0xd,0xe, \
0x3,0x0,0x1,0x2, 0x7,0x4,0x5,0x6, 0xb,0x8,0x9,0xa, 0xf,0xc,0xd,0xe
.size g_ror8_512, .-g_ror8_512
.align 64
g_add4block:
.long 0, 1, 2, 3
.size g_add4block, .-g_add4block
.align 64
g_addsecond4block:
.long 4, 4, 4, 4
.size g_addsecond4block, .-g_addsecond4block
.align 64
g_add8block:
.long 0, 1, 2, 3, 4, 5, 6, 7
.size g_add8block, .-g_add8block
.align 64
g_addsecond8block:
.long 8, 8, 8, 8, 8, 8, 8, 8
.size g_addsecond8block, .-g_addsecond8block
.align 64
g_addOne:
.long 0, 0, 0, 0, 1, 0, 0, 0
.size g_addOne, .-g_addOne
.set IN, %rsi
.set OUT, %rdx
/* QUARTERROUND for one state */
.macro CHACHA20_ROUND s0 s1 s2 s3 cur ror16 ror8
vpaddd \s1, \s0, \s0
vpxor \s0, \s3, \s3
vpshufb (\ror16), \s3, \s3
vpaddd \s3, \s2, \s2
vpxor \s2, \s1, \s1
vmovdqa \s1, \cur
vpsrld $20, \s1, \s1
vpslld $12, \cur, \cur
vpor \cur, \s1, \s1
vpaddd \s1, \s0, \s0
vpxor \s0, \s3, \s3
vpshufb (\ror8), \s3, \s3
vpaddd \s3, \s2, \s2
vpxor \s2, \s1, \s1
vmovdqa \s1, \cur
vpsrld $25, \s1, \s1
vpslld $7, \cur, \cur
vpor \cur, \s1, \s1
.endm
/* QUARTERROUND for two states */
.macro CHACHA20_2_ROUND s0 s1 s2 s3 cur s4 s5 s6 s7 cur1 ror16 ror8
vpaddd \s1, \s0, \s0
vpxor \s0, \s3, \s3
vpshufb (\ror16), \s3, \s3
vpaddd \s3, \s2, \s2
vpxor \s2, \s1, \s1
vmovdqa \s1, \cur
vpsrld $20, \s1, \s1
vpslld $12, \cur, \cur
vpor \cur, \s1, \s1
vpaddd \s1, \s0, \s0
vpxor \s0, \s3, \s3
vpshufb (\ror8), \s3, \s3
vpaddd \s3, \s2, \s2
vpxor \s2, \s1, \s1
vmovdqa \s1, \cur
vpsrld $25, \s1, \s1
vpslld $7, \cur, \cur
vpor \cur, \s1, \s1
vpaddd \s5, \s4, \s4
vpxor \s4, \s7, \s7
vpshufb (\ror16), \s7, \s7
vpaddd \s7, \s6, \s6
vpxor \s6, \s5, \s5
vmovdqa \s5, \cur1
vpsrld $20, \s5, \s5
vpslld $12, \cur1, \cur1
vpor \cur1, \s5, \s5
vpaddd \s5, \s4, \s4
vpxor \s4, \s7, \s7
vpshufb (\ror8), \s7, \s7
vpaddd \s7, \s6, \s6
vpxor \s6, \s5, \s5
vmovdqa \s5, \cur1
vpsrld $25, \s5, \s5
vpslld $7, \cur1, \cur1
vpor \cur1, \s5, \s5
.endm
/* current matrix add original matrix */
.macro LASTADD_MATRIX S0 S1 S2 S3 S4 S5 S6 S7 S8 S9 S10 S11 S12 S13 S14 S15 PER
vpaddd (%rsp), \S0, \S0
vpaddd 1*\PER(%rsp), \S1, \S1
vpaddd 2*\PER(%rsp), \S2, \S2
vpaddd 3*\PER(%rsp), \S3, \S3
vpaddd 4*\PER(%rsp), \S4, \S4
vpaddd 5*\PER(%rsp), \S5, \S5
vpaddd 6*\PER(%rsp), \S6, \S6
vpaddd 7*\PER(%rsp), \S7, \S7
vpaddd 8*\PER(%rsp), \S8, \S8
vpaddd 9*\PER(%rsp), \S9, \S9
vpaddd 10*\PER(%rsp), \S10, \S10
vpaddd 11*\PER(%rsp), \S11, \S11
vpaddd 12*\PER(%rsp), \S12, \S12
vpaddd 13*\PER(%rsp), \S13, \S13
vpaddd 14*\PER(%rsp), \S14, \S14
vpaddd 15*\PER(%rsp), \S15, \S15
.endm
/* write output for left part of 512 bytes (ymm) */
.macro WRITE_BACK_512_L inpos outpos s0 s1 s2 s3 s4 s5 s6 s7 out0 out1 out2 out3
/* {A0 B0 C0 D0 E0 F0 G0 H0} {A1 B1 C1 D1 E1 F1 G1 H1} => {A0 B0 C0 D0 A1 B1 C1 D1} */
vperm2i128 $0x20, \s1, \s0, \out0
vpxor (\inpos), \out0, \out0
vmovdqu \out0, (\outpos) // write back output
vperm2i128 $0x20, \s3, \s2, \out1
vpxor 32(\inpos), \out1, \out1
vmovdqu \out1, 32(\outpos)
vperm2i128 $0x20, \s5, \s4, \out2
vpxor 64(\inpos), \out2, \out2 // write back output
vmovdqu \out2, 64(\outpos)
vperm2i128 $0x20, \s7, \s6, \out3
vpxor 96(\inpos), \out3, \out3
vmovdqu \out3, 96(\outpos)
.endm
/* write output for right part of 512 bytes (ymm) */
.macro WRITE_BACK_512_R inpos outpos s0 s1 s2 s3 s4 s5 s6 s7
/* {A0 B0 C0 D0 E0 F0 G0 H0} {A1 B1 C1 D1 E1 F1 G1 H1} => {E0 F0 G0 H0 E1 F1 G1 H1} */
vperm2i128 $0x31, \s1, \s0, \s1
vpxor (\inpos), \s1, \s1
vmovdqu \s1, (\outpos) // write back output
vperm2i128 $0x31, \s3, \s2, \s3
vpxor 32(\inpos), \s3, \s3
vmovdqu \s3, 32(\outpos)
vperm2i128 $0x31, \s5, \s4, \s5
vpxor 64(\inpos), \s5, \s5
vmovdqu \s5, 64(\outpos) // write back output
vperm2i128 $0x31, \s7, \s6, \s7
vpxor 96(\inpos), \s7, \s7
vmovdqu \s7, 96(\outpos)
.endm
/*
* Processing 64 bytes: 4 xmm registers
* xmm0 ~ xmm3:
* xmm0 {0, 1, 2, 3}
* xmm1 {4, 5, 6, 7}
* xmm2 {8, 9, 10, 11}
* xmm3 {12, 13, 14, 15}
*
* Processing 128 bytes: 8 xmm registers
* xmm0 ~ xmm8:
* xmm0 {0, 1, 2, 3} xmm5 {0, 1, 2, 3}
* xmm1 {4, 5, 6, 7} xmm6 {4, 5, 6, 7}
* xmm2 {8, 9, 10, 11} xmm7 {8, 9, 10, 11}
* xmm3 {12, 13, 14, 15} xmm8 {12, 13, 14, 15}
*
* Processing 256 bytes: 16 xmm registers
* xmm0 ~ xmm15:
* xmm0 {0, 0, 0, 0}
* xmm1 {1, 2, 2, 2}
* xmm2 {3, 3, 3, 3}
* xmm3 {4, 4, 4, 4}
* ...
* xmm15 {15, 15, 15, 15}
*
* Processing 512 bytes: 16 xmm registers
* ymm0 ~ ymm15:
* ymm0 {0, 0, 0, 0}
* ymm1 {1, 2, 2, 2}
* ymm2 {3, 3, 3, 3}
* ymm3 {4, 4, 4, 4}
* ...
* ymm15 {15, 15, 15, 15}
*
*/
/*
* @Interconnection with the C interface:void CHACHA20_Update(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len);
* @brief chacha20 algorithm
* @param ctx [IN] Algorithm context, which is set by the C interface and transferred.
* @param in [IN] Data to be encrypted
* @param out [OUT] Data after encryption
* @param len [IN] Encrypted length
* esp cannot use 15 available ctx in out len
* 16 registers are needed in one cycle, then
* {0, 1, 4, 5, 8, 9, 12, 13}
* {2, 3, 6, 7, 10, 11, 14, 15}
*/
.globl CHACHA20_Update
.type CHACHA20_Update,%function
.align 64
CHACHA20_Update:
.cfi_startproc
mov 48(%rdi), %r11d
mov %rsp, %rax
subq $1024,%rsp
andq $-512,%rsp
.Lchacha20_start:
cmp $512, %rcx
jae .Lchacha20_512_start
cmp $256, %rcx
jae .Lchacha20_256_start
cmp $128, %rcx
jae .Lchacha20_128_start
cmp $64, %rcx
jae .Lchacha20_64_start
jmp .Lchacha20_end
.Lchacha20_64_start:
LOAD_STATE %xmm0, %xmm1, %xmm2, %xmm3, %rdi
vmovdqa %xmm0, %xmm10
vmovdqa %xmm1, %xmm11
vmovdqa %xmm2, %xmm12
vmovdqa %xmm3, %xmm13
leaq g_ror16(%rip), %r9
leaq g_ror8(%rip), %r10
mov $10, %r8
.Lchacha20_64_loop:
/* 0 = 0 + 4, 12 = (12 ^ 0) >>> 16 | 8 = 8 + 12, 4 = (4 ^ 8) >>> 12 |
* 0 = 0 + 4, 12 = (12 ^ 0) >>> 8 | 8 = 8 + 12, 4 = (4 ^ 8) >>> 7
* 1 = 1 + 5, 13 = (13 ^ 1) >>> 16 | 9 = 9 + 13, 5 = (5 ^ 9) >>> 12 |
* 1 = 1 + 5, 13 = (13 ^ 1) >>> 8 | 9 = 9 + 13, 5 = (5 ^ 9) >>> 7
* 2 = 2 + 6, 14 = (14 ^ 2) >>> 16 | 10 = 10 + 14, 6 = (6 ^ 10)>>> 12 |
* 2 = 2 + 6, 14 = (14 ^ 2) >>> 8 | 10 = 10 + 14, 6 = (6 ^ 10)>>> 7
* 3 = 3 + 7, 15 = (15 ^ 3) >>> 16 | 11 = 11 + 15, 7 = (7 ^ 11)>>> 12 |
* 3 = 3 + 7 ,15 = (15 ^ 3) >>> 8 | 11 = 11 + 15, 7 = (7 ^ 11)>>> 7
*/
CHACHA20_ROUND %xmm0, %xmm1, %xmm2, %xmm3, %xmm4, %r9, %r10
vpshufd $78, %xmm2, %xmm2 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10
vpshufd $57, %xmm1, %xmm1 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01
vpshufd $147, %xmm3, %xmm3 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11
/* 0 = 0 + 5 , 15 = (15 ^ 0) >>> 16 | 10 = 10 + 15, 5 = (5 ^ 10) >>> 12 |
* 0 = 0 + 5, 15 = (15 ^ 0) >>> 8 | 10 = 10 + 15, 5 = (5 ^ 10) >>> 7
* 1 = 1 + 6 , 12 = (12 ^ 1) >>> 16 | 11 = 11 + 12, 6 = (6 ^ 11) >>> 12 |
* 1 = 1 + 6, 12 = (12 ^ 1) >>> 8 | 11 = 11 + 12, 6 = (6 ^ 11) >>> 7
* 2 = 2 + 7 , 13 = (13 ^ 2) >>> 16 | 8 = 8 + 13, 7 = (7 ^ 8)>>> 12 |
* 2 = 2 + 7, 13 = (13 ^ 2) >>> 8 | 8 = 8 + 13, 7 = (7 ^ 8)>>> 7
* 3 = 3 + 4 , 14 = (14 ^ 3) >>> 16 | 9 = 9 + 14, 4 = (4 ^ 9)>>> 12 |
* 3 = 3 + 4, 14 = (14 ^ 3) >>> 8 | 9 = 9 + 14, 4 = (4 ^ 9)>>> 7
*/
CHACHA20_ROUND %xmm0, %xmm1, %xmm2, %xmm3, %xmm4, %r9, %r10
vpshufd $78, %xmm2, %xmm2 // {10 11 8 9} ==> {8 9 10 11} 01 00 11 10
vpshufd $147, %xmm1, %xmm1 // {5 6 7 4} ==> {4 5 6 7} 00 11 10 01
vpshufd $57, %xmm3, %xmm3 // {15 12 13 14} ==> {12 13 14 15} 10 01 00 11
decq %r8
jnz .Lchacha20_64_loop
vpaddd %xmm10, %xmm0, %xmm0
vpaddd %xmm11, %xmm1, %xmm1
vpaddd %xmm12, %xmm2, %xmm2
vpaddd %xmm13, %xmm3, %xmm3
add $1, %r11d
vpxor 0(IN), %xmm0, %xmm4
vpxor 16(IN), %xmm1, %xmm5
vpxor 32(IN), %xmm2, %xmm6
vpxor 48(IN), %xmm3, %xmm7
vmovdqu %xmm4, 0(OUT)
vmovdqu %xmm5, 16(OUT)
vmovdqu %xmm6, 32(OUT)
vmovdqu %xmm7, 48(OUT)
add $64, IN
add $64, OUT
mov %r11d, 48(%rdi)
jmp .Lchacha20_end
.Lchacha20_128_start:
vbroadcasti128 (%rdi), %ymm0 // {0 1 2 3 0 1 2 3}
vbroadcasti128 16(%rdi), %ymm1 // {4 5 6 7 4 5 6 7}
vbroadcasti128 32(%rdi), %ymm2 // {8 9 10 11 8 9 10 11}
vbroadcasti128 48(%rdi), %ymm3 // {12 13 14 15 12 13 14 15}
vpaddd g_addOne(%rip), %ymm3, %ymm3
vmovdqa %ymm0, %ymm12
vmovdqa %ymm1, %ymm13
vmovdqa %ymm2, %ymm14
vmovdqa %ymm3, %ymm15
leaq g_ror16_128(%rip), %r9
leaq g_ror8_128(%rip), %r10
mov $10, %r8
.Lchacha20_128_loop:
CHACHA20_ROUND %ymm0, %ymm1, %ymm2, %ymm3, %ymm4, %r9, %r10
vpshufd $78, %ymm2, %ymm2 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10
vpshufd $57, %ymm1, %ymm1 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01
vpshufd $147, %ymm3, %ymm3 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11
CHACHA20_ROUND %ymm0, %ymm1, %ymm2, %ymm3, %ymm4, %r9, %r10
vpshufd $78, %ymm2, %ymm2 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10
vpshufd $147, %ymm1, %ymm1 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01
vpshufd $57, %ymm3, %ymm3 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11
decq %r8
jnz .Lchacha20_128_loop
vpaddd %ymm12, %ymm0, %ymm0
vpaddd %ymm13, %ymm1, %ymm1
vpaddd %ymm14, %ymm2, %ymm2
vpaddd %ymm15, %ymm3, %ymm3
vextracti128 $1, %ymm0, %xmm4 // ymm0 => {xmm0 xmm5}
vextracti128 $1, %ymm1, %xmm5 // ymm1 => {xmm1 xmm6}
vextracti128 $1, %ymm2, %xmm6 // ymm2 => {xmm2 xmm7}
vextracti128 $1, %ymm3, %xmm7 // ymm3 => {xmm3 xmm8}
WRITEBACK_64_AVX2 IN, OUT, %xmm0, %xmm1, %xmm2, %xmm3
add $2, %r11d
WRITEBACK_64_AVX2 IN, OUT, %xmm4, %xmm5, %xmm6, %xmm7
mov %r11d, 48(%rdi)
sub $128, %rcx
jz .Lchacha20_end
jmp .Lchacha20_start
.Lchacha20_256_start:
LOAD_STATE %xmm0, %xmm1, %xmm2, %xmm3, %rdi
STATE_TO_MATRIX %xmm0, %xmm1, %xmm2, %xmm3, %xmm4, %xmm5, %xmm6, %xmm7, %xmm8, %xmm9, %xmm10, \
%xmm11, %xmm12, %xmm13, %xmm14, %xmm15, 0, 16, g_add4block(%rip)
/* move xmm8~11 into stack for CHACHA20_LOOP encryption */
vmovdqa %xmm8, 256(%rsp)
vmovdqa %xmm9, 256+16(%rsp)
vmovdqa %xmm10, 256+32(%rsp)
vmovdqa %xmm11, 256+48(%rsp)
leaq g_ror16(%rip), %r9
leaq g_ror8(%rip), %r10
mov $10, %r8
.Lchacha20_256_loop:
CHACHA20_LOOP %xmm0, %xmm1, %xmm2, %xmm3, %xmm4, %xmm5, %xmm6, %xmm7, %xmm8, %xmm9, %xmm10 \
%xmm11, %xmm12, %xmm13, %xmm14, %xmm15, 256, 16, %rsp, %r9, %r10
decq %r8
jnz .Lchacha20_256_loop
/* xmm0~15: encrypt matrix 0 ~ 15*/
vmovdqa 256+32(%rsp), %xmm10 // rsp32: encrypt matrix xmm10
vmovdqa 256+48(%rsp), %xmm11
LASTADD_MATRIX %xmm0, %xmm1, %xmm2, %xmm3, %xmm4, %xmm5, %xmm6, %xmm7, %xmm8, %xmm9, %xmm10 \
%xmm11, %xmm12, %xmm13, %xmm14, %xmm15, 16
/* store xmm9, 10, 13, 14 in stack */
vmovdqa %xmm9, 256(%rsp) // rsp 0: encrypt matrix xmm9
vmovdqa %xmm10, 256+32(%rsp) // rsp32: encrypt matrix xmm9
vmovdqa %xmm13, 256+16(%rsp) // rsp16: encrypt matrix xmm13
vmovdqa %xmm14, 256+48(%rsp) // rsp48: encrypt matrix xmm14
MATRIX_TO_STATE %xmm0, %xmm1, %xmm2, %xmm3, %xmm9, %xmm10 // set state 0, 3, 9, 10
MATRIX_TO_STATE %xmm4, %xmm5, %xmm6, %xmm7, %xmm13, %xmm14 // set state 4, 7, 13, 14
vmovdqa 256(%rsp), %xmm5
vmovdqa 256+32(%rsp), %xmm6
vmovdqa %xmm9, 256(%rsp)
vmovdqa %xmm10, 256+32(%rsp)
MATRIX_TO_STATE %xmm8, %xmm5, %xmm6, %xmm11, %xmm1, %xmm2 // set state 8, 11, 1, 2
vmovdqa 256+16(%rsp), %xmm9
vmovdqa 256+48(%rsp), %xmm10
vmovdqa %xmm13, 256+16(%rsp)
vmovdqa %xmm14, 256+48(%rsp)
MATRIX_TO_STATE %xmm12, %xmm9, %xmm10, %xmm15, %xmm5, %xmm6 // set state 12, 15, 5, 6
vmovdqa 256(%rsp), %xmm9 // rsp 0: state 9
vmovdqa 256+32(%rsp), %xmm10 // rsp32: state 10
vmovdqa 256+16(%rsp), %xmm13 // rsp16: state 13
vmovdqa 256+48(%rsp), %xmm14 // rsp48: state 14
/* finish state calculation, now write result to output */
WRITEBACK_64_AVX2 IN, OUT, %xmm0, %xmm4, %xmm8, %xmm12
WRITEBACK_64_AVX2 IN, OUT, %xmm3, %xmm7, %xmm11, %xmm15
WRITEBACK_64_AVX2 IN, OUT, %xmm9, %xmm13, %xmm1, %xmm5
WRITEBACK_64_AVX2 IN, OUT, %xmm10, %xmm14, %xmm2, %xmm6
add $4, %r11d
sub $256, %rcx
mov %r11d, 48(%rdi)
cmp $256, %rcx
jz .Lchacha20_end
jmp .Lchacha20_start
.Lchacha20_512_start:
LOAD_512_STATE %ymm0 %ymm1 %ymm2 %ymm3 %rdi
STATE_TO_MATRIX %ymm0, %ymm1, %ymm2, %ymm3, %ymm4, %ymm5, %ymm6, %ymm7, %ymm8, %ymm9, \
%ymm10, %ymm11, %ymm12, %ymm13, %ymm14, %ymm15, 0, 32, g_add8block(%rip)
jmp .Lchacha20_512_run
.Lchacha20_512_start_cont:
LOAD_MATRIX %ymm0, %ymm1, %ymm2, %ymm3, %ymm4, %ymm5, %ymm6, %ymm7, %ymm8, %ymm9, \
%ymm10, %ymm11, %ymm12, %ymm13, %ymm14, %ymm15, 0, 32, g_addsecond8block(%rip)
.Lchacha20_512_run:
/* move ymm8~11 into stack for CHACHA20_LOOP encryption */
vmovdqa %ymm8, 512(%rsp)
vmovdqa %ymm9, 512+32(%rsp)
vmovdqa %ymm10, 512+64(%rsp)
vmovdqa %ymm11, 512+96(%rsp)
leaq g_ror16_512(%rip), %r9
leaq g_ror8_512(%rip), %r10
mov $10, %r8
.align 32
.Lchacha20_512_loop:
CHACHA20_LOOP %ymm0, %ymm1, %ymm2, %ymm3, %ymm4, %ymm5, %ymm6, %ymm7, %ymm8, %ymm9, %ymm10 \
%ymm11, %ymm12, %ymm13, %ymm14, %ymm15, 512, 32, %rsp, %r9, %r10
decq %r8
jnz .Lchacha20_512_loop
/* ymm0~15: encrypt matrix 0 ~ 15*/
vmovdqa 512+64(%rsp), %ymm10 // rsp64: encrypt matrix ymm10
vmovdqu 512+96(%rsp), %ymm11
LASTADD_MATRIX %ymm0, %ymm1, %ymm2, %ymm3, %ymm4, %ymm5, %ymm6, %ymm7, %ymm8, %ymm9, %ymm10 \
%ymm11, %ymm12, %ymm13, %ymm14, %ymm15, 32
/* store matrix ymm9, 10, 13, 14 in stack */
vmovdqa %ymm9, 512(%rsp) // rsp 0: encrypt matrix ymm9
vmovdqu %ymm10, 512+32(%rsp) // rsp32: encrypt matrix ymm10
vmovdqa %ymm13, 512+64(%rsp) // rsp64: encrypt matrix ymm13
vmovdqu %ymm14, 512+96(%rsp) // rsp96: encrypt matrix ymm14
MATRIX_TO_STATE %ymm0, %ymm1, %ymm2, %ymm3, %ymm9, %ymm10 // set state 0, 3, 9, 10
MATRIX_TO_STATE %ymm4, %ymm5, %ymm6, %ymm7, %ymm13, %ymm14 // set state 4, 7, 13, 14
vmovdqu 512(%rsp), %ymm5
vmovdqa 512+32(%rsp), %ymm6
vmovdqu %ymm9, 512(%rsp)
vmovdqa %ymm10, 512+32(%rsp)
MATRIX_TO_STATE %ymm8, %ymm5, %ymm6, %ymm11, %ymm1, %ymm2 // set state 8, 11, 1, 2
vmovdqa 512+64(%rsp), %ymm9
vmovdqu 512+96(%rsp), %ymm10
vmovdqa %ymm13, 512+64(%rsp)
vmovdqu %ymm14, 512+96(%rsp)
MATRIX_TO_STATE %ymm12, %ymm9, %ymm10, %ymm15, %ymm5, %ymm6 // set state 12, 15, 5, 6
/*
* {A0 A1 A2 A3 E0 E1 E2 E3}
* {B0 B1 B2 B3 F0 F1 F2 F3}
* {C0 C1 C2 C3 G0 G1 G2 G3}
* {D0 D1 D2 D3 H0 H1 H2 H3}
* ...
* =>
* {A0 A1 A2 A3 B0 B1 B2 B3}
* {C0 C1 C2 C3 D0 D1 D2 D3}
* ....
*/
/* left half of ymm registers */
WRITE_BACK_512_L IN, OUT, %ymm0, %ymm4, %ymm8, %ymm12, %ymm3, %ymm7, %ymm11, %ymm15, %ymm9, %ymm10, %ymm13, %ymm14
add $256, IN
add $256, OUT
/* right half of ymm registers */
WRITE_BACK_512_R IN, OUT, %ymm0, %ymm4, %ymm8, %ymm12, %ymm3, %ymm7, %ymm11, %ymm15
sub $128, IN
sub $128, OUT
vmovdqa 512(%rsp), %ymm9
vmovdqu 512+32(%rsp), %ymm10
vmovdqa 512+64(%rsp), %ymm13
vmovdqu 512+96(%rsp), %ymm14
/* second left half of ymm registers */
WRITE_BACK_512_L IN, OUT, %ymm9, %ymm13, %ymm1, %ymm5, %ymm10, %ymm14, %ymm2, %ymm6, %ymm0, %ymm4, %ymm8, %ymm12
add $256, IN
add $256, OUT
/* second right half of ymm registers */
WRITE_BACK_512_R IN, OUT, %ymm9, %ymm13, %ymm1, %ymm5, %ymm10, %ymm14, %ymm2, %ymm6
add $128, IN
add $128, OUT
add $8, %r11d
sub $512, %rcx
mov %r11d, 48(%rdi)
jz .Lchacha20_end
cmp $512, %rcx
jae .Lchacha20_512_start_cont
jmp .Lchacha20_start
.Lchacha20_end:
/* clear sensitive info in stack */
vpxor %ymm0, %ymm0, %ymm0
xor %r11d, %r11d
vmovdqa %ymm0, (%rsp)
vmovdqa %ymm0, 32(%rsp)
vmovdqa %ymm0, 64(%rsp)
vmovdqa %ymm0, 96(%rsp)
vmovdqa %ymm0, 128(%rsp)
vmovdqa %ymm0, 160(%rsp)
vmovdqa %ymm0, 192(%rsp)
vmovdqa %ymm0, 224(%rsp)
vmovdqa %ymm0, 256(%rsp)
vmovdqa %ymm0, 288(%rsp)
vmovdqa %ymm0, 320(%rsp)
vmovdqa %ymm0, 352(%rsp)
vmovdqa %ymm0, 384(%rsp)
vmovdqa %ymm0, 416(%rsp)
vmovdqa %ymm0, 448(%rsp)
vmovdqa %ymm0, 480(%rsp)
vmovdqa %ymm0, 512(%rsp)
vmovdqa %ymm0, 512+32(%rsp)
vmovdqa %ymm0, 512+64(%rsp)
vmovdqa %ymm0, 512+96(%rsp)
mov %rax, %rsp
.cfi_endproc
ret
.size CHACHA20_Update,.-CHACHA20_Update
#endif
|
2301_79861745/bench_create
|
crypto/chacha20/src/asm/chacha20block_x8664_avx2.S
|
Unix Assembly
|
unknown
| 20,876
|
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_CHACHA20
#include "chacha20_x8664_common.S"
.text
.align 64
g_ror16:
.byte 0x2,0x3,0x0,0x1, 0x6,0x7,0x4,0x5, 0xa,0xb,0x8,0x9, 0xe,0xf,0xc,0xd
.size g_ror16, .-g_ror16
.align 64
g_ror8:
.byte 0x3,0x0,0x1,0x2, 0x7,0x4,0x5,0x6, 0xb,0x8,0x9,0xa, 0xf,0xc,0xd,0xe
.size g_ror8, .-g_ror8
.align 64
g_ror16_128:
.byte 0x2,0x3,0x0,0x1, 0x6,0x7,0x4,0x5, 0xa,0xb,0x8,0x9, 0xe,0xf,0xc,0xd, \
0x2,0x3,0x0,0x1, 0x6,0x7,0x4,0x5, 0xa,0xb,0x8,0x9, 0xe,0xf,0xc,0xd
.size g_ror16_128, .-g_ror16_128
.align 64
g_ror8_128:
.byte 0x3,0x0,0x1,0x2, 0x7,0x4,0x5,0x6, 0xb,0x8,0x9,0xa, 0xf,0xc,0xd,0xe, \
0x3,0x0,0x1,0x2, 0x7,0x4,0x5,0x6, 0xb,0x8,0x9,0xa, 0xf,0xc,0xd,0xe
.size g_ror8_128, .-g_ror8_128
.align 64
g_addOne:
.long 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0
.size g_addOne, .-g_addOne
.align 64
g_add4block:
.long 0, 1, 2, 3
.size g_add4block, .-g_add4block
.align 64
g_addsecond4block:
.long 4, 4, 4, 4
.size g_addsecond4block, .-g_addsecond4block
.align 64
g_add8block:
.long 0, 1, 2, 3, 4, 5, 6, 7
.size g_add8block, .-g_add8block
.align 64
g_addsecond8block:
.long 8, 8, 8, 8, 8, 8, 8, 8
.size g_addsecond8block, .-g_addsecond8block
.align 64
g_add16block:
.long 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
.size g_add16block, .-g_add16block
.align 64
g_addsecond16block:
.long 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16
.size g_addsecond16block, .-g_addsecond16block
.set IN, %rsi
.set OUT, %rdx
/*
* Processing 64 bytes: 4 x registers, number of instructions in a single loop: 21*2 = 42
* xmm0 ~ xmm3:
* xmm0 {0, 1, 2, 3}
* xmm1 {4, 5, 6, 7}
* xmm2 {8, 9, 10, 11}
* xmm3 {12, 13, 14, 15}
*
* Processing 128-256 bytes: 4 x registers, number of instructions in a single loop:30
* ymm0 ~ ymm3:
* ymm0 {0, 1, 2, 3, 0, 1, 2, 3 }
* ymm1 {4, 5, 6, 7, 4, 5, 6, 7 }
* ymm2 {8, 9, 10, 11, 8, 9, 10, 11}
* ymm3 {12, 13, 14, 15, 12, 13, 14, 15}
*
* Processing 512 bytes: y registers 0-15, 128 stack space and y registers 16-31,number of instructions
*in a single loop:12*8 = 96
* Processing 1024 bytes: z registers 0-15, 256 stack space and z registers 16-31, number of instructions
* in a single loop:12*8 = 96
* ymm0 ~ ymm15:
* ymm0 {0, 0, 0, 0, 0, 0, 0, 0}
* ymm1 {1, 1, 1, 1, 1, 1, 1, 1}
* ymm2 {2, 2, 2, 2, 2, 2, 2, 2}
* ymm3 {3, 3, 3, 3, 3, 3, 3, 3}
* ......
* ymm15 {15, 15, 15, 15, 15, 15, 15, 15}
*
* zmm0 ~ zmm31:
* zmm0 {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
* zmm1 {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
* zmm2 {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}
* zmm3 {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}
* ...
* zmm15 {15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15}
*/
.macro CHACHA20_ROUND s0 s1 s2 s3
vpaddd \s1, \s0, \s0
vpxord \s0, \s3, \s3
vprold $16, \s3, \s3
vpaddd \s3, \s2, \s2
vpxord \s2, \s1, \s1
vprold $12, \s1, \s1
vpaddd \s1, \s0, \s0
vpxord \s0, \s3, \s3
vprold $8, \s3, \s3
vpaddd \s3, \s2, \s2
vpxord \s2, \s1, \s1
vprold $7, \s1, \s1
.endm
/* convert y registers and write back */
.macro CONVERT_Y s0 s1 pos inpos outpos
/* ymm16 => {xmm16, xmm17} */
vextracti32x4 \pos, \s0, %xmm16
vextracti32x4 \pos, \s1, %xmm17
vinserti32x4 $1, %xmm17, %ymm16, %ymm16
vpxord (IN), %ymm16, %ymm16
vmovdqu64 %ymm16, (OUT)
add $32, \inpos
add $32, \outpos
.endm
/* convert z registers and write back */
.macro CONVERT_Z s0 s1 s2 s3 pos inpos outpos
/* zmm16 => {xmm16, xmm17, xmm18, xmm19} */
vextracti64x2 \pos, \s0, %xmm16
vextracti64x2 \pos, \s1, %xmm17
vextracti64x2 \pos, \s2, %xmm18
vextracti64x2 \pos, \s3, %xmm19
vinserti64x2 $1, %xmm17, %zmm16, %zmm16
vinserti64x2 $2, %xmm18, %zmm16, %zmm16
vinserti64x2 $3, %xmm19, %zmm16, %zmm16
vpxord (IN), %zmm16, %zmm16
vmovdqu64 %zmm16, (OUT)
add $64, \inpos
add $64, \outpos
.endm
/**
* @Interconnection with the C interface:void CHACHA20_Update(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len);
* @brief chacha20 algorithm
* @param ctx [IN] Algorithm context, which is set by the C interface and transferred.
* @param in [IN] Data to be encrypted
* @param out [OUT] Data after encryption
* @param len [IN] Encrypted length
* esp cannot use 15 available ctx in out len
* 16 registers are needed in one cycle, then
* {0, 1, 4, 5, 8, 9, 12, 13}
* {2, 3, 6, 7, 10, 11, 14, 15}
**/
.globl CHACHA20_Update
.type CHACHA20_Update,%function
.align 64
CHACHA20_Update:
.cfi_startproc
mov 48(%rdi), %r11d
mov %rsp, %r9
subq $2048,%rsp
andq $-1024,%rsp
.Lchacha20_start:
cmp $1024, %rcx
jae .Lchacha20_1024_start
cmp $512, %rcx
jae .Lchacha20_512_start
cmp $256, %rcx
jae .Lchacha20_256_start
cmp $128, %rcx
jae .Lchacha20_128_start
cmp $64, %rcx
jae .Lchacha20_64_start
jmp .Lchacha20_end
.Lchacha20_64_start:
LOAD_STATE %xmm0, %xmm1, %xmm2, %xmm3, %rdi
vmovdqa %xmm0, %xmm10
vmovdqa %xmm1, %xmm11
vmovdqa %xmm2, %xmm12
vmovdqa %xmm3, %xmm13
mov $10, %r8
.Lchacha20_64_loop:
/* 0 = 0 + 4, 12 = (12 ^ 0) >>> 16 | 8 = 8 + 12, 4 = (4 ^ 8) >>> 12 |
* 0 = 0 + 4, 12 = (12 ^ 0) >>> 8 | 8 = 8 + 12, 4 = (4 ^ 8) >>> 7
* 1 = 1 + 5, 13 = (13 ^ 1) >>> 16 | 9 = 9 + 13, 5 = (5 ^ 9) >>> 12 |
* 1 = 1 + 5, 13 = (13 ^ 1) >>> 8 | 9 = 9 + 13, 5 = (5 ^ 9) >>> 7
* 2 = 2 + 6, 14 = (14 ^ 2) >>> 16 | 10 = 10 + 14, 6 = (6 ^ 10)>>> 12 |
* 2 = 2 + 6, 14 = (14 ^ 2) >>> 8 | 10 = 10 + 14, 6 = (6 ^ 10)>>> 7
* 3 = 3 + 7, 15 = (15 ^ 3) >>> 16 | 11 = 11 + 15, 7 = (7 ^ 11)>>> 12 |
* 3 = 3 + 7 ,15 = (15 ^ 3) >>> 8 | 11 = 11 + 15, 7 = (7 ^ 11)>>> 7
*/
CHACHA20_ROUND %xmm0, %xmm1, %xmm2, %xmm3
vpshufd $78, %xmm2, %xmm2 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10
vpshufd $57, %xmm1, %xmm1 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01
vpshufd $147, %xmm3, %xmm3 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11
/* 0 = 0 + 5 , 15 = (15 ^ 0) >>> 16 | 10 = 10 + 15, 5 = (5 ^ 10) >>> 12 |
* 0 = 0 + 5, 15 = (15 ^ 0) >>> 8 | 10 = 10 + 15, 5 = (5 ^ 10) >>> 7
* 1 = 1 + 6 , 12 = (12 ^ 1) >>> 16 | 11 = 11 + 12, 6 = (6 ^ 11) >>> 12 |
* 1 = 1 + 6, 12 = (12 ^ 1) >>> 8 | 11 = 11 + 12, 6 = (6 ^ 11) >>> 7
* 2 = 2 + 7 , 13 = (13 ^ 2) >>> 16 | 8 = 8 + 13, 7 = (7 ^ 8)>>> 12 |
* 2 = 2 + 7, 13 = (13 ^ 2) >>> 8 | 8 = 8 + 13, 7 = (7 ^ 8)>>> 7
* 3 = 3 + 4 , 14 = (14 ^ 3) >>> 16 | 9 = 9 + 14, 4 = (4 ^ 9)>>> 12 |
* 3 = 3 + 4, 14 = (14 ^ 3) >>> 8 | 9 = 9 + 14, 4 = (4 ^ 9)>>> 7
*/
CHACHA20_ROUND %xmm0, %xmm1, %xmm2, %xmm3
vpshufd $78, %xmm2, %xmm2 // {10 11 8 9} ==> {8 9 10 11} 01 00 11 10
vpshufd $147, %xmm1, %xmm1 // {5 6 7 4} ==> {4 5 6 7} 00 11 10 01
vpshufd $57, %xmm3, %xmm3 // {15 12 13 14} ==> {12 13 14 15} 10 01 00 11
decq %r8
jnz .Lchacha20_64_loop
vpaddd %xmm10, %xmm0, %xmm0
vpaddd %xmm11, %xmm1, %xmm1
vpaddd %xmm12, %xmm2, %xmm2
vpaddd %xmm13, %xmm3, %xmm3
add $1, %r11d
WRITEBACK_64_AVX512 IN, OUT, %xmm0, %xmm1, %xmm2, %xmm3
mov %r11d, 48(%rdi)
jmp .Lchacha20_end
.Lchacha20_128_start:
vbroadcasti128 (%rdi), %ymm0 // {0 1 2 3 0 1 2 3}
vbroadcasti128 16(%rdi), %ymm1 // {4 5 6 7 4 5 6 7}
vbroadcasti128 32(%rdi), %ymm2 // {8 9 10 11 8 9 10 11}
vbroadcasti128 48(%rdi), %ymm3 // {12 13 14 15 12 13 14 15}
vpaddd g_addOne(%rip), %ymm3, %ymm3
vmovdqa32 %ymm0, %ymm16
vmovdqa32 %ymm1, %ymm17
vmovdqa32 %ymm2, %ymm18
vmovdqa32 %ymm3, %ymm19
mov $10, %r8
.Lchacha20_128_loop:
CHACHA20_ROUND %ymm0, %ymm1, %ymm2, %ymm3
vpshufd $78, %ymm2, %ymm2 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10
vpshufd $57, %ymm1, %ymm1 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01
vpshufd $147, %ymm3, %ymm3 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11
CHACHA20_ROUND %ymm0, %ymm1, %ymm2, %ymm3
vpshufd $78, %ymm2, %ymm2 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10
vpshufd $147, %ymm1, %ymm1 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01
vpshufd $57, %ymm3, %ymm3 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11
decq %r8
jnz .Lchacha20_128_loop
vpaddd %ymm16, %ymm0, %ymm0
vpaddd %ymm17, %ymm1, %ymm1
vpaddd %ymm18, %ymm2, %ymm2
vpaddd %ymm19, %ymm3, %ymm3
vextracti32x4 $1, %ymm0, %xmm5 // ymm0 => {xmm0 xmm5}
vextracti32x4 $1, %ymm1, %xmm6 // ymm1 => {xmm1 xmm6}
vextracti32x4 $1, %ymm2, %xmm7 // ymm2 => {xmm2 xmm7}
vextracti32x4 $1, %ymm3, %xmm8 // ymm3 => {xmm3 xmm8}
WRITEBACK_64_AVX512 IN, OUT, %xmm0, %xmm1, %xmm2, %xmm3
WRITEBACK_64_AVX512 IN, OUT, %xmm5, %xmm6, %xmm7, %xmm8
add $2, %r11d
sub $128, %rcx
mov %r11d, 48(%rdi)
jz .Lchacha20_end
jmp .Lchacha20_start
.Lchacha20_256_start:
LOAD_1024_STATE %zmm0 %zmm1 %zmm2 %zmm3 %rdi
vpaddd g_addOne(%rip), %zmm3, %zmm3
vmovdqa64 %zmm0, %zmm16
vmovdqa64 %zmm1, %zmm17
vmovdqa64 %zmm2, %zmm18
vmovdqa64 %zmm3, %zmm19
mov $10, %r8
.Lchacha20_256_loop:
CHACHA20_ROUND %zmm0, %zmm1, %zmm2, %zmm3
vpshufd $78, %zmm2, %zmm2 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10
vpshufd $57, %zmm1, %zmm1 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01
vpshufd $147, %zmm3, %zmm3 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11
CHACHA20_ROUND %zmm0, %zmm1, %zmm2, %zmm3
vpshufd $78, %zmm2, %zmm2 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10
vpshufd $147, %zmm1, %zmm1 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01
vpshufd $57, %zmm3, %zmm3 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11
decq %r8
jnz .Lchacha20_256_loop
vpaddd %zmm16, %zmm0, %zmm0
vpaddd %zmm17, %zmm1, %zmm1
vpaddd %zmm18, %zmm2, %zmm2
vpaddd %zmm19, %zmm3, %zmm3
vextracti64x2 $1, %zmm0, %xmm4
vextracti64x2 $1, %zmm1, %xmm5
vextracti64x2 $1, %zmm2, %xmm6
vextracti64x2 $1, %zmm3, %xmm7
vextracti64x2 $2, %zmm0, %xmm8
vextracti64x2 $2, %zmm1, %xmm9
vextracti64x2 $2, %zmm2, %xmm10
vextracti64x2 $2, %zmm3, %xmm11
vextracti64x2 $3, %zmm0, %xmm12
vextracti64x2 $3, %zmm1, %xmm13
vextracti64x2 $3, %zmm2, %xmm14
vextracti64x2 $3, %zmm3, %xmm15
WRITEBACK_64_AVX512 IN, OUT, %xmm0, %xmm1, %xmm2, %xmm3
WRITEBACK_64_AVX512 IN, OUT, %xmm4, %xmm5, %xmm6, %xmm7
WRITEBACK_64_AVX512 IN, OUT, %xmm8, %xmm9, %xmm10, %xmm11
WRITEBACK_64_AVX512 IN, OUT, %xmm12, %xmm13, %xmm14, %xmm15
add $4, %r11d
sub $256, %rcx
mov %r11d, 48(%rdi)
jz .Lchacha20_end
jmp .Lchacha20_start
.Lchacha20_512_start:
LOAD_512_STATE %ymm0, %ymm1, %ymm2, %ymm3, %rdi
vpshufd $0b00000000, %ymm3, %ymm12
vpshufd $0b01010101, %ymm3, %ymm13
vpaddd g_add8block(%rip), %ymm12, %ymm12 // 0, 1, 2, 3, 4, 5, 6 ,7
vmovdqa32 %ymm12, %ymm28
vpshufd $0b10101010, %ymm3, %ymm14
vmovdqa32 %ymm13, %ymm29
vpshufd $0b11111111, %ymm3, %ymm15
vmovdqa32 %ymm14, %ymm30
vpshufd $0b00000000, %ymm2, %ymm8
vmovdqa32 %ymm15, %ymm31
vpshufd $0b01010101, %ymm2, %ymm9
vmovdqa32 %ymm8, %ymm24
vpshufd $0b10101010, %ymm2, %ymm10
vmovdqa32 %ymm9, %ymm25
vpshufd $0b11111111, %ymm2, %ymm11
vmovdqa32 %ymm10, %ymm26
vpshufd $0b00000000, %ymm1, %ymm4
vmovdqa32 %ymm11, %ymm27
vpshufd $0b01010101, %ymm1, %ymm5
vmovdqa32 %ymm4, %ymm20
vpshufd $0b10101010, %ymm1, %ymm6
vmovdqa32 %ymm5, %ymm21
vpshufd $0b11111111, %ymm1, %ymm7
vmovdqa32 %ymm6, %ymm22
vpshufd $0b11111111, %ymm0, %ymm3
vmovdqa32 %ymm7, %ymm23
vpshufd $0b10101010, %ymm0, %ymm2
vmovdqa32 %ymm3, %ymm19
vpshufd $0b01010101, %ymm0, %ymm1
vmovdqa32 %ymm2, %ymm18
vpshufd $0b00000000, %ymm0, %ymm0
vmovdqa32 %ymm1, %ymm17
vmovdqa32 %ymm0, %ymm16
mov $10, %r8
.Lchacha20_512_loop:
CHACHA20_LOOP_AVX512 %ymm0, %ymm1, %ymm2, %ymm3, %ymm4, %ymm5, %ymm6, %ymm7, %ymm8, %ymm9, \
%ymm10, %ymm11, %ymm12, %ymm13, %ymm14, %ymm15
decq %r8
jnz .Lchacha20_512_loop
/* ymm16~31: original matrix */
vpaddd %ymm16, %ymm0, %ymm0
vpaddd %ymm17, %ymm1, %ymm1
vpaddd %ymm18, %ymm2, %ymm2
vpaddd %ymm19, %ymm3, %ymm3
vpaddd %ymm20, %ymm4, %ymm4
vpaddd %ymm21, %ymm5, %ymm5
vpaddd %ymm22, %ymm6, %ymm6
vpaddd %ymm23, %ymm7, %ymm7
vpaddd %ymm24, %ymm8, %ymm8
vpaddd %ymm25, %ymm9, %ymm9
vpaddd %ymm26, %ymm10, %ymm10
vpaddd %ymm27, %ymm11, %ymm11
vpaddd %ymm28, %ymm12, %ymm12
vpaddd %ymm29, %ymm13, %ymm13
vpaddd %ymm30, %ymm14, %ymm14
vpaddd %ymm31, %ymm15, %ymm15
MATRIX_TO_STATE %ymm0, %ymm1, %ymm2, %ymm3, %ymm20, %ymm21 // set state 0, 3, 9, 10
MATRIX_TO_STATE %ymm4, %ymm5, %ymm6, %ymm7, %ymm22, %ymm23 // set state 4, 7, 13, 14
MATRIX_TO_STATE %ymm8, %ymm9, %ymm10, %ymm11, %ymm1, %ymm2 // set state 8, 11, 1, 2
MATRIX_TO_STATE %ymm12, %ymm13, %ymm14, %ymm15, %ymm5, %ymm6 // set state 12, 15, 5, 6
/*
* {A0 A1 A2 A3 E0 E1 E2 E3}
* {B0 B1 B2 B3 F0 F1 F2 F3}
* {C0 C1 C2 C3 G0 G1 G2 G3}
* {D0 D1 D2 D3 H0 H1 H2 H3}
* ...
* =>
* {A0 A1 A2 A3 B0 B1 B2 B3}
* {C0 C1 C2 C3 D0 D1 D2 D3}
* ....
*/
CONVERT_Y %ymm0, %ymm4, $0 IN OUT
CONVERT_Y %ymm8, %ymm12, $0 IN OUT
CONVERT_Y %ymm3, %ymm7, $0 IN OUT
CONVERT_Y %ymm11, %ymm15, $0 IN OUT
CONVERT_Y %ymm20, %ymm22, $0 IN OUT
CONVERT_Y %ymm1, %ymm5, $0 IN OUT
CONVERT_Y %ymm21, %ymm23, $0 IN OUT
CONVERT_Y %ymm2, %ymm6, $0 IN OUT
CONVERT_Y %ymm0, %ymm4, $1 IN OUT
CONVERT_Y %ymm8, %ymm12, $1 IN OUT
CONVERT_Y %ymm3, %ymm7, $1 IN OUT
CONVERT_Y %ymm11, %ymm15, $1 IN OUT
CONVERT_Y %ymm20, %ymm22, $1 IN OUT
CONVERT_Y %ymm1, %ymm5, $1 IN OUT
CONVERT_Y %ymm21, %ymm23, $1 IN OUT
CONVERT_Y %ymm2, %ymm6, $1 IN OUT
add $8, %r11d
sub $512, %rcx
mov %r11d, 48(%rdi)
jz .Lchacha20_end
jmp .Lchacha20_start
.Lchacha20_1024_start:
LOAD_1024_STATE %zmm0 %zmm1 %zmm2 %zmm3 %rdi
STATE_TO_MATRIX_Z_AVX512 %zmm0, %zmm16, %zmm17, %zmm18, %zmm19
STATE_TO_MATRIX_Z_AVX512 %zmm1, %zmm20, %zmm21, %zmm22, %zmm23
STATE_TO_MATRIX_Z_AVX512 %zmm2, %zmm24, %zmm25, %zmm26, %zmm27
STATE_TO_MATRIX_Z_AVX512 %zmm3, %zmm28, %zmm29, %zmm30, %zmm31
vpaddd g_add16block(%rip), %zmm28, %zmm28
vmovdqa64 %zmm16, %zmm0
vmovdqa64 %zmm17, %zmm1
vmovdqa64 %zmm18, %zmm2
vmovdqa64 %zmm19, %zmm3
vmovdqa64 %zmm20, %zmm4
vmovdqa64 %zmm21, %zmm5
vmovdqa64 %zmm22, %zmm6
vmovdqa64 %zmm23, %zmm7
vmovdqa64 %zmm24, %zmm8
vmovdqa64 %zmm25, %zmm9
vmovdqa64 %zmm26, %zmm10
vmovdqa64 %zmm27, %zmm11
vmovdqa64 %zmm28, %zmm12
vmovdqa64 %zmm29, %zmm13
vmovdqa64 %zmm30, %zmm14
vmovdqa64 %zmm31, %zmm15
mov $10, %r8
jmp .Lchacha20_1024_loop
.Lchacha20_1024_start_cont:
vmovdqa32 %zmm16, %zmm0
vmovdqa32 %zmm17, %zmm1
vmovdqa32 %zmm18, %zmm2
vmovdqa32 %zmm19, %zmm3
vmovdqa32 %zmm20, %zmm4
vmovdqa32 %zmm21, %zmm5
vmovdqa32 %zmm22, %zmm6
vmovdqa32 %zmm23, %zmm7
vmovdqa32 %zmm24, %zmm8
vmovdqa32 %zmm25, %zmm9
vmovdqa32 %zmm26, %zmm10
vmovdqa32 %zmm27, %zmm11
vmovdqa32 %zmm28, %zmm12
vmovdqa32 %zmm29, %zmm13
vpaddd g_addsecond16block(%rip), %zmm12, %zmm12 // add 8, 8, 8, 8, 8, 8, 8, 8 or 4, 4, 4, 4
vmovdqa32 %zmm30, %zmm14
vmovdqa32 %zmm31, %zmm15
vmovdqa32 %zmm12, %zmm28
mov $10, %r8
.Lchacha20_1024_loop:
CHACHA20_LOOP_AVX512 %zmm0, %zmm1, %zmm2, %zmm3, %zmm4, %zmm5, %zmm6, %zmm7, %zmm8, %zmm9, \
%zmm10, %zmm11, %zmm12, %zmm13, %zmm14, %zmm15
decq %r8
jnz .Lchacha20_1024_loop
vpaddd %zmm16, %zmm0, %zmm0
vpaddd %zmm17, %zmm1, %zmm1
vpaddd %zmm18, %zmm2, %zmm2
vpaddd %zmm19, %zmm3, %zmm3
vpaddd %zmm20, %zmm4, %zmm4
vpaddd %zmm21, %zmm5, %zmm5
vpaddd %zmm22, %zmm6, %zmm6
vpaddd %zmm23, %zmm7, %zmm7
vpaddd %zmm24, %zmm8, %zmm8
vpaddd %zmm25, %zmm9, %zmm9
vpaddd %zmm26, %zmm10, %zmm10
vpaddd %zmm27, %zmm11, %zmm11
vpaddd %zmm28, %zmm12, %zmm12
vpaddd %zmm29, %zmm13, %zmm13
vpaddd %zmm30, %zmm14, %zmm14
vpaddd %zmm31, %zmm15, %zmm15
/* store matrix 16, 17, 18, 19 in stack */
vmovdqa64 %zmm16, (%rsp)
vmovdqa64 %zmm17, 64(%rsp)
vmovdqa64 %zmm18, 128(%rsp)
vmovdqa64 %zmm19, 192(%rsp)
/* store matrix 9, 10, 13, 14 in zmm16, 17, 18, 19 */
vmovdqa64 %zmm9, %zmm16 // zmm16: encrypt matrix zmm9
vmovdqa64 %zmm10, %zmm17 // zmm17: encrypt matrix zmm10
vmovdqa64 %zmm13, %zmm18 // zmm18: encrypt matrix zmm13
vmovdqa64 %zmm14, %zmm19 // zmm19: encrypt matrix zmm14
/* zmm0~15: encrypt matrix 0 ~ 15*/
MATRIX_TO_STATE %zmm0, %zmm1, %zmm2, %zmm3, %zmm9, %zmm10 // set state 0, 3, 9, 10
MATRIX_TO_STATE %zmm4, %zmm5, %zmm6, %zmm7, %zmm13, %zmm14 // set state 4, 7, 13, 14
MATRIX_TO_STATE %zmm8, %zmm16, %zmm17, %zmm11, %zmm1, %zmm2 // set state 8, 11, 1, 2
MATRIX_TO_STATE %zmm12, %zmm18, %zmm19, %zmm15, %zmm5, %zmm6 // set state 12, 15, 5, 6
/*
* {A0 A1 A2 A3 E0 E1 E2 E3 I0 I1 I2 I3 M0 M1 M2 M3}
* {B0 B1 B2 B3 F0 F1 F2 F3 J0 J1 J2 J3 N0 N1 N2 N3}
* {C0 C1 C2 C3 G0 G1 G2 G3 K0 K1 K2 K3 O0 O1 O2 O3}
* {D0 D1 D2 D3 H0 H1 H2 H3 L0 L1 L2 L3 P0 P1 P2 P3}
* ...
* =>
* {A0 A1 A2 A3 B0 B1 B2 B3 C0 C1 C2 C3 D0 D1 D2 D3}
* {E0 E1 E2 E3 F0 F1 F2 F3 G0 G1 G2 G3 H0 H1 H2 H3}
* {I0 I1 I2 I3 J0 J1 J2 J3 K0 K1 K2 K3 L0 L1 L2 L3}
* ....
*/
CONVERT_Z %zmm0, %zmm4, %zmm8, %zmm12, $0 IN OUT
CONVERT_Z %zmm3, %zmm7, %zmm11, %zmm15, $0 IN OUT
CONVERT_Z %zmm9, %zmm13, %zmm1, %zmm5, $0 IN OUT
CONVERT_Z %zmm10, %zmm14, %zmm2, %zmm6, $0 IN OUT
CONVERT_Z %zmm0, %zmm4, %zmm8, %zmm12, $1 IN OUT
CONVERT_Z %zmm3, %zmm7, %zmm11, %zmm15, $1 IN OUT
CONVERT_Z %zmm9, %zmm13, %zmm1, %zmm5, $1 IN OUT
CONVERT_Z %zmm10, %zmm14, %zmm2, %zmm6, $1 IN OUT
CONVERT_Z %zmm0, %zmm4, %zmm8, %zmm12, $2 IN OUT
CONVERT_Z %zmm3, %zmm7, %zmm11, %zmm15, $2 IN OUT
CONVERT_Z %zmm9, %zmm13, %zmm1, %zmm5, $2 IN OUT
CONVERT_Z %zmm10, %zmm14, %zmm2, %zmm6, $2 IN OUT
CONVERT_Z %zmm0, %zmm4, %zmm8, %zmm12, $3 IN OUT
CONVERT_Z %zmm3, %zmm7, %zmm11, %zmm15, $3 IN OUT
CONVERT_Z %zmm9, %zmm13, %zmm1, %zmm5, $3 IN OUT
CONVERT_Z %zmm10, %zmm14, %zmm2, %zmm6, $3 IN OUT
/* store zmm16~19 in stack */
vmovdqa64 (%rsp), %zmm16
vmovdqa64 64(%rsp), %zmm17
vmovdqa64 128(%rsp), %zmm18
vmovdqa64 192(%rsp), %zmm19
add $16, %r11d
sub $1024, %rcx
mov %r11d, 48(%rdi)
jz .Lchacha20_clear
cmp $1024, %rcx
jae .Lchacha20_1024_start_cont
jmp .Lchacha20_start
.Lchacha20_clear:
/* clear sensitive info in stack */
vpxord %zmm0, %zmm0, %zmm0
vmovdqa64 %zmm0, (%rsp)
vmovdqa64 %zmm0, 64(%rsp)
vmovdqa64 %zmm0, 128(%rsp)
vmovdqa64 %zmm0, 192(%rsp)
.Lchacha20_end:
xor %r11d, %r11d
mov %r9, %rsp
.cfi_endproc
ret
.size CHACHA20_Update,.-CHACHA20_Update
#endif
|
2301_79861745/bench_create
|
crypto/chacha20/src/asm/chacha20block_x8664_avx512.S
|
Unix Assembly
|
unknown
| 21,249
|
/*
* 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_CHACHA20
.text
.LAndBlock:
.long 1, 0, 0, 0
.LRor16:
.byte 0x2,0x3,0x0,0x1, 0x6,0x7,0x4,0x5, 0xa,0xb,0x8,0x9, 0xe,0xf,0xc,0xd
.LRor8:
.byte 0x3,0x0,0x1,0x2, 0x7,0x4,0x5,0x6, 0xb,0x8,0x9,0xa, 0xf,0xc,0xd,0xe
.set IN, %r9
.set OUT, %r10
/* Original State */
.set O00, %xmm12
.set O01, %xmm13
.set O02, %xmm14
.set O03, %xmm15
/* State 0 */
.set S00, %xmm0 // LINE 0 STATE 0
.set S01, %xmm1 // LINE 1 STATE 0
.set S02, %xmm2 // LINE 2 STATE 0
.set S03, %xmm3 // LINE 3 STATE 0
/* State 1 */
.set S10, %xmm5 // LINE 0 STATE 1
.set S11, %xmm6 // LINE 1 STATE 1
.set S12, %xmm7 // LINE 2 STATE 1
.set S13, %xmm8 // LINE 3 STATE 1
.macro CHACHA20_ROUND S0 S1 S2 S3 CUR
paddd \S1, \S0
pxor \S0, \S3
pshufb .LRor16(%rip), \S3
paddd \S3, \S2
pxor \S2, \S1
movdqa \S1, \CUR
psrld $20, \S1
pslld $12, \CUR
por \CUR, \S1
paddd \S1, \S0
pxor \S0, \S3
pshufb .LRor8(%rip), \S3
paddd \S3, \S2
pxor \S2, \S1
movdqa \S1, \CUR
psrld $25, \S1
pslld $7, \CUR
por \CUR, \S1
.endm
/* QUARTERROUND for two states */
.macro CHACHA20_2_ROUND S0 S1 S2 S3 CUR S4 S5 S6 S7 CUR1
paddd \S1, \S0
pxor \S0, \S3
pshufb .LRor16(%rip), \S3
paddd \S3, \S2
pxor \S2, \S1
movdqa \S1, \CUR
psrld $20, \S1
pslld $12, \CUR
por \CUR, \S1
paddd \S1, \S0
pxor \S0, \S3
pshufb .LRor8(%rip), \S3
paddd \S3, \S2
pxor \S2, \S1
movdqa \S1, \CUR
psrld $25, \S1
pslld $7, \CUR
por \CUR, \S1
paddd \S5, \S4
pxor \S4, \S7
pshufb .LRor16(%rip), \S7
paddd \S7, \S6
pxor \S6, \S5
movdqa \S5, \CUR1
psrld $20, \S5
pslld $12, \CUR1
por \CUR1, \S5
paddd \S5, \S4
pxor \S4, \S7
pshufb .LRor8(%rip), \S7
paddd \S7, \S6
pxor \S6, \S5
movdqa \S5, \CUR1
psrld $25, \S5
pslld $7, \CUR1
por \CUR1, \S5
.endm
/* final add & xor for 64 bytes */
.macro WRITE_BACK_64 IN_POS OUT_POS
paddd O00, S00
paddd O01, S01
paddd O02, S02
paddd O03, S03
movdqu (\IN_POS), %xmm4 // get input
movdqu 16(\IN_POS), %xmm9
movdqu 32(\IN_POS), %xmm10
movdqu 48(\IN_POS), %xmm11
pxor %xmm4, S00
pxor %xmm9, S01
pxor %xmm10, S02
pxor %xmm11, S03
movdqu S00, (\OUT_POS) // write back output
movdqu S01, 16(\OUT_POS)
movdqu S02, 32(\OUT_POS)
movdqu S03, 48(\OUT_POS)
.endm
/* final add & xor for 128 bytes */
.macro WRITE_BACK_128 IN_POS OUT_POS
paddd O00, S00 // state 0 + origin state 0
paddd O01, S01
paddd O02, S02
paddd O03, S03
pinsrd $0, %r11d, O03 // change Original state 0 to Original state 1
paddd O00, S10 // state 1 + origin state 1
paddd O01, S11
paddd O02, S12
paddd O03, S13
movdqu (\IN_POS), %xmm4 // get input 0
movdqu 16(\IN_POS), %xmm9
movdqu 32(\IN_POS), %xmm10
movdqu 48(\IN_POS), %xmm11
pxor %xmm4, S00 // input 0 ^ state 0
pxor %xmm9, S01
pxor %xmm10, S02
pxor %xmm11, S03
movdqu S00, (\OUT_POS) // write back to output 0
movdqu S01, 16(\OUT_POS)
movdqu S02, 32(\OUT_POS)
movdqu S03, 48(\OUT_POS)
movdqu 64(\IN_POS), %xmm4 // get input 1
movdqu 80(\IN_POS), %xmm9
movdqu 96(\IN_POS), %xmm10
movdqu 112(\IN_POS), %xmm11
pxor %xmm4, S10 // input 1 ^ state 1
pxor %xmm9, S11
pxor %xmm10, S12
pxor %xmm11, S13
movdqu S10, 64(\OUT_POS) // write back to output 1
movdqu S11, 80(\OUT_POS)
movdqu S12, 96(\OUT_POS)
movdqu S13, 112(\OUT_POS)
.endm
.macro GENERATE_1_STATE
add $1, %r11d
pinsrd $0, %r11d, O03
movdqu O00, S00 // set state 0
movdqu O01, S01
movdqu O02, S02
movdqu O03, S03
.endm
.macro GENERATE_2_STATE
add $1, %r11d
pinsrd $0, %r11d, O03
movdqu O00, S00 // set state 0
movdqu O01, S01
movdqu O02, S02
movdqu O03, S03
movdqu O00, S10 // set state 1
movdqu O01, S11
movdqu O02, S12
movdqu O03, S13
add $1, %r11d
pinsrd $0, %r11d, S13
.endm
/*
* Processing 64 bytes: 4 xmm registers
* xmm0 ~ xmm3:
* xmm0 {0, 1, 2, 3}
* xmm1 {4, 5, 6, 7}
* xmm2 {8, 9, 10, 11}
* xmm3 {12, 13, 14, 15}
*
* Processing 128 bytes: 8 xmm registers
* xmm0 ~ xmm8:
* xmm0 {0, 1, 2, 3} xmm5 {0, 1, 2, 3}
* xmm1 {4, 5, 6, 7} xmm6 {4, 5, 6, 7}
* xmm2 {8, 9, 10, 11} xmm7 {8, 9, 10, 11}
* xmm3 {12, 13, 14, 15} xmm8 {12, 13, 14, 15}
*
* Processing 256 bytes: 16 xmm registers
* xmm0 ~ xmm15:
* xmm0 {0, 0, 0, 0}
* xmm1 {1, 2, 2, 2}
* xmm2 {3, 3, 3, 3}
* xmm3 {4, 4, 4, 4}
* ...
* xmm15 {15, 15, 15, 15}
*
* Processing 512 bytes: 16 xmm registers
* ymm0 ~ ymm15:
* ymm0 {0, 0, 0, 0}
* ymm1 {1, 2, 2, 2}
* ymm2 {3, 3, 3, 3}
* ymm3 {4, 4, 4, 4}
* ...
* ymm15 {15, 15, 15, 15}
*
*/
/**
* @Interconnection with the C interface:void CHACHA20_Update(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len);
* @brief chacha20 algorithm
* @param ctx [IN] Algorithm context, which is set by the C interface and transferred.
* @param in [IN] Data to be encrypted
* @param out [OUT] Data after encryption
* @param len [IN] Encrypted length
* esp cannot use 15 available ctx in out len
* 16 registers are needed in one cycle, then
* {0, 1, 4, 5, 8, 9, 12, 13}
* {2, 3, 6, 7, 10, 11, 14, 15}
**/
.globl CHACHA20_Update
.type CHACHA20_Update,%function
.align 64
CHACHA20_Update:
.cfi_startproc
push %r12
mov %rcx, %r12
mov 48(%rdi), %r11d
mov %rsi, IN
mov %rdx, OUT
movdqu (%rdi), O00 // state[0-3]
movdqu 16(%rdi), O01 // state[4-7]
movdqu 32(%rdi), O02 // state[8-11]
movdqu 48(%rdi), O03 // state[12-15]
sub $1, %r11d
.LChaCha20_start:
cmp $128, %r12
jae .LChaCha20_128_start
cmp $64, %r12
jae .LChaCha20_64_start
jmp .LChaCha20_end
.LChaCha20_64_start:
GENERATE_1_STATE
mov $10, %r8
.LChaCha20_64_loop:
sub $1, %r8
/* 0 = 0 + 4, 12 = (12 ^ 0) >>> 16 | 8 = 8 + 12, 4 = (4 ^ 8) >>> 12 | 0 = 0 + 4, 12 = (12 ^ 0) >>> 8 | 8 = 8 + 12, 4 = (4 ^ 8) >>> 7 */
/* 1 = 1 + 5, 13 = (13 ^ 1) >>> 16 | 9 = 9 + 13, 5 = (5 ^ 9) >>> 12 | 1 = 1 + 5, 13 = (13 ^ 1) >>> 8 | 9 = 9 + 13, 5 = (5 ^ 9) >>> 7 */
/* 2 = 2 + 6, 14 = (14 ^ 2) >>> 16 | 10 = 10 + 14, 6 = (6 ^ 10)>>> 12 | 2 = 2 + 6, 14 = (14 ^ 2) >>> 8 | 10 =10+ 14, 6 = (6 ^ 10)>>> 7 */
/* 3 = 3 + 7, 15 = (15 ^ 3) >>> 16 | 11 = 11 + 15, 7 = (7 ^ 11)>>> 12 | 3 = 3 + 7 ,15 = (15 ^ 3) >>> 8 | 11 =11+ 15, 7 = (7 ^ 11)>>> 7 */
CHACHA20_ROUND S00 S01 S02 S03 %xmm4
pshufd $78, S02, S02 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10
pshufd $57, S01, S01 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01
pshufd $147, S03, S03 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11
/* 0 = 0 + 5 , 15 = (15 ^ 0) >>> 16 | 10 = 10 + 15, 5 = (5 ^ 10) >>> 12 | 0 = 0 + 5, 15 = (15 ^ 0) >>> 8 | 10 = 10 + 15, 5 = (5 ^ 10) >>> 7 */
/* 1 = 1 + 6 , 12 = (12 ^ 1) >>> 16 | 11 = 11 + 12, 6 = (6 ^ 11) >>> 12 | 1 = 1 + 6, 12 = (12 ^ 1) >>> 8 | 11 = 11 + 12, 6 = (6 ^ 11) >>> 7 */
/* 2 = 2 + 7 , 13 = (13 ^ 2) >>> 16 | 8 = 8 + 13, 7 = (7 ^ 8)>>> 12 | 2 = 2 + 7, 13 = (13 ^ 2) >>> 8 | 8 = 8 + 13, 7 = (7 ^ 8)>>> 7 */
/* 3 = 3 + 4 , 14 = (14 ^ 3) >>> 16 | 9 = 9 + 14, 4 = (4 ^ 9)>>> 12 | 3 = 3 + 4, 14 = (14 ^ 3) >>> 8 | 9 = 9 + 14, 4 = (4 ^ 9)>>> 7 */
CHACHA20_ROUND S00 S01 S02 S03 %xmm4
pshufd $78, S02, S02 // {10 11 8 9} ==> {8 9 10 11} 01 00 11 10
pshufd $147, S01, S01 // {5 6 7 4} ==> {4 5 6 7} 00 11 10 01
pshufd $57, S03, S03 // {15 12 13 14} ==> {12 13 14 15} 10 01 00 11
jnz .LChaCha20_64_loop
WRITE_BACK_64 IN OUT
add $64, IN
add $64, OUT
sub $64, %r12
jmp .LChaCha20_start
.LChaCha20_128_start:
GENERATE_2_STATE
mov $10, %r8
.LChaCha20_128_loop:
CHACHA20_2_ROUND S00 S01 S02 S03 %xmm4 S10 S11 S12 S13 %xmm9
pshufd $78, S02, S02 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10
pshufd $57, S01, S01 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01
pshufd $147, S03, S03 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11
pshufd $78, S12, S12 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10
pshufd $57, S11, S11 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01
pshufd $147, S13, S13 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11
CHACHA20_2_ROUND S00 S01 S02 S03 %xmm4 S10 S11 S12 S13 %xmm9
pshufd $78, S02, S02 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10
pshufd $147, S01, S01 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01
pshufd $57, S03, S03 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11
pshufd $78, S12, S12 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10
pshufd $147, S11, S11 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01
pshufd $57, S13, S13 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11
sub $1, %r8
jnz .LChaCha20_128_loop
WRITE_BACK_128 IN OUT
add $128, IN
add $128, OUT
sub $128, %r12
jmp .LChaCha20_start
.LChaCha20_end:
add $1, %r11d
mov %r11d, 48(%rdi)
pop %r12
ret
.cfi_endproc
.size CHACHA20_Update,.-CHACHA20_Update
#endif
|
2301_79861745/bench_create
|
crypto/chacha20/src/asm/chachablock_x86_AVX2.S
|
Unix Assembly
|
unknown
| 10,613
|
/*
* 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_CHACHA20
#include "securec.h"
#include "bsl_err_internal.h"
#include "crypt_utils.h"
#include "crypt_errno.h"
#include "crypt_chacha20.h"
#include "chacha20_local.h"
#define KEYSET 0x01
#define NONCESET 0x02
// RFC7539-2.1
#define QUARTER(a, b, c, d) \
do { \
(a) += (b); (d) ^= (a); (d) = ROTL32((d), 16); \
(c) += (d); (b) ^= (c); (b) = ROTL32((b), 12); \
(a) += (b); (d) ^= (a); (d) = ROTL32((d), 8); \
(c) += (d); (b) ^= (c); (b) = ROTL32((b), 7); \
} while (0)
#define QUARTERROUND(state, a, b, c, d) QUARTER((state)[(a)], (state)[(b)], (state)[(c)], (state)[(d)])
int32_t CRYPT_CHACHA20_SetKey(CRYPT_CHACHA20_Ctx *ctx, const 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 (keyLen != CHACHA20_KEYLEN) {
BSL_ERR_PUSH_ERROR(CRYPT_CHACHA20_KEYLEN_ERROR);
return CRYPT_CHACHA20_KEYLEN_ERROR;
}
/**
* RFC7539-2.3
* cccccccc cccccccc cccccccc cccccccc
* kkkkkkkk kkkkkkkk kkkkkkkk kkkkkkkk
* kkkkkkkk kkkkkkkk kkkkkkkk kkkkkkkk
* bbbbbbbb nnnnnnnn nnnnnnnn nnnnnnnn
*/
// The first four words (0-3) are constants: 0x61707865, 0x3320646e, 0x79622d32, 0x6b206574
ctx->state[0] = 0x61707865;
ctx->state[1] = 0x3320646e;
ctx->state[2] = 0x79622d32;
ctx->state[3] = 0x6b206574;
/**
* The next eight words (4-11) are taken from the 256-bit key by
* reading the bytes in little-endian order, in 4-byte chunks.
*/
ctx->state[4] = GET_UINT32_LE(key, 0);
ctx->state[5] = GET_UINT32_LE(key, 4);
ctx->state[6] = GET_UINT32_LE(key, 8);
ctx->state[7] = GET_UINT32_LE(key, 12);
ctx->state[8] = GET_UINT32_LE(key, 16);
ctx->state[9] = GET_UINT32_LE(key, 20);
ctx->state[10] = GET_UINT32_LE(key, 24);
ctx->state[11] = GET_UINT32_LE(key, 28);
// Word 12 is a block counter
// RFC7539-2.4: It makes sense to use one if we use the zero block
ctx->state[12] = 1;
ctx->set |= KEYSET;
ctx->lastLen = 0;
return CRYPT_SUCCESS;
}
static int32_t CRYPT_CHACHA20_SetNonce(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *nonce, uint32_t nonceLen)
{
// RFC7539-2.3
if (ctx == NULL || nonce == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (nonceLen != CHACHA20_NONCELEN) {
BSL_ERR_PUSH_ERROR(CRYPT_CHACHA20_NONCELEN_ERROR);
return CRYPT_CHACHA20_NONCELEN_ERROR;
}
/**
* Words 13-15 are a nonce, which should not be repeated for the same
* key. The 13th word is the first 32 bits of the input nonce taken
* as a little-endian integer, while the 15th word is the last 32
* bits.
*/
ctx->state[13] = GET_UINT32_LE(nonce, 0);
ctx->state[14] = GET_UINT32_LE(nonce, 4);
ctx->state[15] = GET_UINT32_LE(nonce, 8);
ctx->set |= NONCESET;
ctx->lastLen = 0;
return CRYPT_SUCCESS;
}
// Little-endian data input
static int32_t CRYPT_CHACHA20_SetCount(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *cnt, uint32_t cntLen)
{
if (ctx == NULL || cnt == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (cntLen != sizeof(uint32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_CHACHA20_COUNTLEN_ERROR);
return CRYPT_CHACHA20_COUNTLEN_ERROR;
}
/**
* RFC7539-2.4
* This can be set to any number, but will
* usually be zero or one. It makes sense to use one if we use the
* zero block for something else, such as generating a one-time
* authenticator key as part of an AEAD algorithm
*/
ctx->state[12] = GET_UINT32_LE((uintptr_t)cnt, 0);
ctx->lastLen = 0;
return CRYPT_SUCCESS;
}
void CHACHA20_Block(CRYPT_CHACHA20_Ctx *ctx)
{
uint32_t i;
// The length defined by ctx->last.c is the same as that defined by ctx->state.
// Therefore, the returned value is not out of range.
(void)memcpy_s(ctx->last.c, CHACHA20_STATEBYTES, ctx->state, sizeof(ctx->state));
/* RFC7539-2.3 These are 20 round in this function */
for (i = 0; i < 10; i++) {
/* column round */
QUARTERROUND(ctx->last.c, 0, 4, 8, 12);
QUARTERROUND(ctx->last.c, 1, 5, 9, 13);
QUARTERROUND(ctx->last.c, 2, 6, 10, 14);
QUARTERROUND(ctx->last.c, 3, 7, 11, 15);
/* diagonal round */
QUARTERROUND(ctx->last.c, 0, 5, 10, 15);
QUARTERROUND(ctx->last.c, 1, 6, 11, 12);
QUARTERROUND(ctx->last.c, 2, 7, 8, 13);
QUARTERROUND(ctx->last.c, 3, 4, 9, 14);
}
/* Reference from rfc 7539, At the end of 20 rounds (or 10 iterations of the above list),
* we add the original input words to the output words
*/
for (i = 0; i < CHACHA20_STATESIZE; i++) {
ctx->last.c[i] += ctx->state[i];
ctx->last.c[i] = CRYPT_HTOLE32(ctx->last.c[i]);
}
ctx->state[12]++;
}
int32_t CRYPT_CHACHA20_Update(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len)
{
if (ctx == NULL || out == NULL || in == NULL || len == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if ((ctx->set & KEYSET) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_CHACHA20_NO_KEYINFO);
return CRYPT_CHACHA20_NO_KEYINFO;
}
if ((ctx->set & NONCESET) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_CHACHA20_NO_NONCEINFO);
return CRYPT_CHACHA20_NO_NONCEINFO;
}
uint32_t i;
const uint8_t *offIn = in;
uint8_t *offOut = out;
uint32_t tLen = len;
if (ctx->lastLen != 0) { // has remaining data during the last processing
uint32_t num = (tLen < ctx->lastLen) ? tLen : ctx->lastLen;
uint8_t *tLast = ctx->last.u + CHACHA20_STATEBYTES - ctx->lastLen; // offset
for (i = 0; i < num; i++) {
offOut[i] = tLast[i] ^ offIn[i];
}
offIn += num;
offOut += num;
tLen -= num;
ctx->lastLen -= num;
}
if (tLen >= CHACHA20_STATEBYTES) { // which is greater than or equal to an integer multiple of 64 bytes
CHACHA20_Update(ctx, offIn, offOut, tLen); // processes data that is an integer multiple of 64 bytes
uint32_t vLen = tLen - (tLen & 0x3f); // 0x3f = %CHACHA20_STATEBYTES
offIn += vLen;
offOut += vLen;
tLen -= vLen;
}
// Process the remaining data
if (tLen > 0) {
CHACHA20_Block(ctx);
uint32_t t = tLen & 0xf8; // processing length is a multiple of 8
if (t != 0) {
DATA64_XOR(ctx->last.u, offIn, offOut, t);
}
for (i = t; i < tLen; i++) {
offOut[i] = ctx->last.u[i] ^ offIn[i];
}
ctx->lastLen = CHACHA20_STATEBYTES - tLen;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_CHACHA20_Ctrl(CRYPT_CHACHA20_Ctx *ctx, int32_t opt, void *val, uint32_t len)
{
switch (opt) {
case CRYPT_CTRL_SET_IV: // in chacha20_poly1305 mode, the configured IV is the nonce of chacha20.
/**
* RFC_7539-2.8.1
* chacha20_aead_encrypt(aad, key, iv, constant, plaintext):
* nonce = constant | iv
*/
return CRYPT_CHACHA20_SetNonce(ctx, val, len);
case CRYPT_CTRL_SET_COUNT:
return CRYPT_CHACHA20_SetCount(ctx, val, len);
default:
BSL_ERR_PUSH_ERROR(CRYPT_CHACHA20_CTRLTYPE_ERROR);
return CRYPT_CHACHA20_CTRLTYPE_ERROR;
}
}
void CRYPT_CHACHA20_Clean(CRYPT_CHACHA20_Ctx *ctx)
{
if (ctx == NULL) {
return;
}
(void)memset_s(ctx, sizeof(CRYPT_CHACHA20_Ctx), 0, sizeof(CRYPT_CHACHA20_Ctx));
}
#endif // HITLS_CRYPTO_CHACHA20
|
2301_79861745/bench_create
|
crypto/chacha20/src/chacha20.c
|
C
|
unknown
| 8,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 CHACHA20_LOCAL_H
#define CHACHA20_LOCAL_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_CHACHA20
#include "crypt_chacha20.h"
void CHACHA20_Block(CRYPT_CHACHA20_Ctx *ctx);
void CHACHA20_Update(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *in,
uint8_t *out, uint32_t len);
#endif // HITLS_CRYPTO_CHACHA20
#endif // CHACHA20_LOCAL_H
|
2301_79861745/bench_create
|
crypto/chacha20/src/chacha20_local.h
|
C
|
unknown
| 885
|
/*
* 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_CHACHA20
#include "crypt_utils.h"
#include "chacha20_local.h"
void CHACHA20_Update(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *in,
uint8_t *out, uint32_t len)
{
const uint8_t *offIn = in;
uint8_t *offOut = out;
uint32_t tLen = len;
// one block is processed each time
while (tLen >= CHACHA20_STATEBYTES) {
CHACHA20_Block(ctx);
// Process 64 bits at a time
DATA64_XOR(ctx->last.u, offIn, offOut, CHACHA20_STATEBYTES);
offIn += CHACHA20_STATEBYTES;
offOut += CHACHA20_STATEBYTES;
tLen -= CHACHA20_STATEBYTES;
}
}
#endif // HITLS_CRYPTO_CHACHA20
|
2301_79861745/bench_create
|
crypto/chacha20/src/chacha20block.c
|
C
|
unknown
| 1,206
|
/*
* 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_CBC_MAC_H
#define CRYPT_CBC_MAC_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_CBC_MAC
#include <stdint.h>
#include "crypt_types.h"
#include "crypt_cmac.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
typedef struct CBC_MAC_Ctx CRYPT_CBC_MAC_Ctx;
#define CRYPT_CBC_MAC_SetParam NULL
/**
* @brief Create a new CBC_MAC context.
* @param id [IN] CBC_MAC algorithm ID
* @return Pointer to the CBC_MAC context
*/
CRYPT_CBC_MAC_Ctx *CRYPT_CBC_MAC_NewCtx(CRYPT_MAC_AlgId id);
/**
* @brief Create a new CBC_MAC context with external library context.
* @param libCtx [in] External library context
* @param id [in] CBC_MAC algorithm ID
* @return Pointer to the CBC_MAC context
*/
CRYPT_CBC_MAC_Ctx *CRYPT_CBC_MAC_NewCtxEx(void *libCtx, CRYPT_MAC_AlgId id);
/**
* @brief Use the key passed by the user to initialize the algorithm context.
* @param ctx [IN] CBC_MAC context
* @param key [in] symmetric algorithm key
* @param len [in] Key length
* @param param [in] param
* @retval #CRYPT_SUCCESS Succeeded.
* @retval #CRYPT_NULL_INPUT The input parameter is NULL.
* For other error codes, see crypt_errno.h.
*/
int32_t CRYPT_CBC_MAC_Init(CRYPT_CBC_MAC_Ctx *ctx, const uint8_t *key, uint32_t len, void *param);
/**
* @brief Enter the data to be calculated and update the context.
* @param ctx [IN] CBC_MAC 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.
* @retval #CRYPT_NULL_INPUT The input parameter is NULL.
* For other error codes, see crypt_errno.h.
*/
int32_t CRYPT_CBC_MAC_Update(CRYPT_CBC_MAC_Ctx *ctx, const uint8_t *in, uint32_t len);
/**
* @brief Output the cmac calculation result.
* @param ctx [IN] CBC_MAC context
* @param out [OUT] Output data. Sufficient memory must be allocated to store CBC_MAC results and cannot be null.
* @param len [IN/OUT] Output data length
* @retval #CRYPT_SUCCESS Succeeded.
* @retval #CRYPT_NULL_INPUT The input parameter is NULL.
* @retval #CRYPT_EAL_BUFF_LEN_NOT_ENOUGH The length of the output buffer is insufficient.
* For other error codes, see crypt_errno.h.
*/
int32_t CRYPT_CBC_MAC_Final(CRYPT_CBC_MAC_Ctx *ctx, uint8_t *out, uint32_t *len);
/**
* @brief Re-initialize using the information retained in the ctx. Do not need to invoke the init again.
* This function is equivalent to the combination of deinit and init interfaces.
* @param ctx [IN] CBC_MAC context
*/
int32_t CRYPT_CBC_MAC_Reinit(CRYPT_CBC_MAC_Ctx *ctx);
/**
* @brief Deinitialization function.
* If calculation is required after this function is invoked, it needs to be initialized again.
* @param ctx [IN] CBC_MAC context
*/
int32_t CRYPT_CBC_MAC_Deinit(CRYPT_CBC_MAC_Ctx *ctx);
/**
* @brief CBC_MAC control function to set some information
* @param ctx [IN] CBC_MAC context
* @param opt [IN] option
* @param val [IN] value
* @param len [IN] the length of value
* @return See crypt_errno.h.
*/
int32_t CRYPT_CBC_MAC_Ctrl(CRYPT_CBC_MAC_Ctx *ctx, uint32_t opt, void *val, uint32_t len);
/**
* @brief Free the CBC_MAC context.
* @param ctx [IN] CBC_MAC context
*/
void CRYPT_CBC_MAC_FreeCtx(CRYPT_CBC_MAC_Ctx *ctx);
#ifdef __cplusplus
}
#endif /* __cpluscplus */
#endif
#endif
|
2301_79861745/bench_create
|
crypto/cmac/include/crypt_cbc_mac.h
|
C
|
unknown
| 4,037
|
/*
* 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_CMAC_H
#define CRYPT_CMAC_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_CMAC
#include <stdint.h>
#include "crypt_types.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
typedef struct Cipher_MAC_Ctx CRYPT_CMAC_Ctx;
#define CRYPT_CMAC_SetParam NULL
/**
* @brief Create a new CMAC context.
* @param id [in] Symmetric encryption and decryption algorithm ID
* @return CMAC context
*/
CRYPT_CMAC_Ctx *CRYPT_CMAC_NewCtx(CRYPT_MAC_AlgId id);
/**
* @brief Create a new CMAC context with external library context.
* @param libCtx [in] External library context
* @param id [in] Symmetric encryption and decryption algorithm ID
* @return CMAC context
*/
CRYPT_CMAC_Ctx *CRYPT_CMAC_NewCtxEx(void *libCtx, CRYPT_MAC_AlgId id);
/**
* @brief Use the key passed by the user to initialize the algorithm context.
* @param ctx [IN] CMAC context
* @param key [in] symmetric algorithm key
* @param len [in] Key length
* @param param [in] param
* @retval #CRYPT_SUCCESS Succeeded.
* @retval #CRYPT_NULL_INPUT The input parameter is NULL.
* For other error codes, see crypt_errno.h.
*/
int32_t CRYPT_CMAC_Init(CRYPT_CMAC_Ctx *ctx, const uint8_t *key, uint32_t len, void *param);
/**
* @brief Enter the data to be calculated and update the context.
* @param ctx [IN] CMAC 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.
* @retval #CRYPT_NULL_INPUT The input parameter is NULL.
* For other error codes, see crypt_errno.h.
*/
int32_t CRYPT_CMAC_Update(CRYPT_CMAC_Ctx *ctx, const uint8_t *in, uint32_t len);
/**
* @brief Output the cmac calculation result.
* @param ctx [IN] CMAC context
* @param out [OUT] Output data. Sufficient memory must be allocated to store CMAC results and cannot be null.
* @param len [IN/OUT] Output data length
* @retval #CRYPT_SUCCESS Succeeded.
* @retval #CRYPT_NULL_INPUT The input parameter is NULL.
* @retval #CRYPT_EAL_BUFF_LEN_NOT_ENOUGH The length of the output buffer is insufficient.
* For other error codes, see crypt_errno.h.
*/
int32_t CRYPT_CMAC_Final(CRYPT_CMAC_Ctx *ctx, uint8_t *out, uint32_t *len);
/**
* @brief Re-initialize using the information retained in the ctx. Do not need to invoke the init again.
* This function is equivalent to the combination of deinit and init interfaces.
* @param ctx [IN] CMAC context
* @retval #CRYPT_SUCCESS Succeeded.
* @retval #CRYPT_NULL_INPUT The input parameter is NULL.
* For other error codes, see crypt_errno.h.
*/
int32_t CRYPT_CMAC_Reinit(CRYPT_CMAC_Ctx *ctx);
/**
* @brief Deinitialization function.
* If calculation is required after this function is invoked, it needs to be initialized again.
* @param ctx [IN] CMAC context
* @retval #CRYPT_SUCCESS Succeeded.
* @retval #CRYPT_NULL_INPUT The input parameter is NULL.
* For other error codes, see crypt_errno.h.
*/
int32_t CRYPT_CMAC_Deinit(CRYPT_CMAC_Ctx *ctx);
/**
* @brief Control function for CMAC.
* @param ctx [IN] CMAC context
* @param opt [IN] Control option
* @param val [IN]/[OUT] Control value
* @param len [IN] Control value length
* @retval #CRYPT_SUCCESS Succeeded.
* @retval #CRYPT_NULL_INPUT The input parameter is NULL.
* For other error codes, see crypt_errno.h.
*/
int32_t CRYPT_CMAC_Ctrl(CRYPT_CMAC_Ctx *ctx, uint32_t opt, void *val, uint32_t len);
/**
* @brief Free the CMAC context.
* @param ctx [IN] CMAC context
*/
void CRYPT_CMAC_FreeCtx(CRYPT_CMAC_Ctx *ctx);
#ifdef __cplusplus
}
#endif /* __cpluscplus */
#endif
#endif
|
2301_79861745/bench_create
|
crypto/cmac/include/crypt_cmac.h
|
C
|
unknown
| 4,258
|
/*
* 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_CBC_MAC
#include <stdint.h>
#include "bsl_sal.h"
#include "crypt_types.h"
#include "crypt_utils.h"
#include "bsl_err_internal.h"
#include "cipher_mac_common.h"
#include "crypt_errno.h"
#include "crypt_cbc_mac.h"
#include "eal_mac_local.h"
CRYPT_CBC_MAC_Ctx *CRYPT_CBC_MAC_NewCtx(CRYPT_MAC_AlgId id)
{
int32_t ret;
EAL_MacDepMethod method = {0};
ret = EAL_MacFindDepMethod(id, NULL, NULL, &method, NULL, false);
if (ret != CRYPT_SUCCESS) {
return NULL;
}
CRYPT_CBC_MAC_Ctx *ctx = BSL_SAL_Calloc(1, sizeof(CRYPT_CBC_MAC_Ctx));
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
ret = CipherMacInitCtx(&ctx->common, method.method.sym);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_Free(ctx);
return NULL;
}
ctx->paddingType = CRYPT_PADDING_MAX_COUNT;
return ctx;
}
CRYPT_CBC_MAC_Ctx *CRYPT_CBC_MAC_NewCtxEx(void *libCtx, CRYPT_MAC_AlgId id)
{
(void)libCtx;
return CRYPT_CBC_MAC_NewCtx(id);
}
int32_t CRYPT_CBC_MAC_Init(CRYPT_CBC_MAC_Ctx *ctx, const uint8_t *key, uint32_t len, void *param)
{
(void)param;
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
return CipherMacInit(&ctx->common, key, len);
}
int32_t CRYPT_CBC_MAC_Update(CRYPT_CBC_MAC_Ctx *ctx, const uint8_t *in, uint32_t len)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->paddingType == CRYPT_PADDING_MAX_COUNT) {
BSL_ERR_PUSH_ERROR(CRYPT_CBC_MAC_PADDING_NOT_SET);
return CRYPT_CBC_MAC_PADDING_NOT_SET;
}
return CipherMacUpdate(&ctx->common, in, len);
}
static int32_t CbcMacPadding(CRYPT_CBC_MAC_Ctx *ctx)
{
const EAL_SymMethod *method = ctx->common.method;
uint32_t length = ctx->common.len;
uint32_t padLen = method->blockSize - length;
switch (ctx->paddingType) {
case CRYPT_PADDING_ZEROS:
for (uint32_t i = 0; i < padLen; i++) {
ctx->common.left[length++] = 0;
}
ctx->common.len = length;
return CRYPT_SUCCESS;
default:
BSL_ERR_PUSH_ERROR(CRYPT_CBC_MAC_PADDING_NOT_SUPPORT);
return CRYPT_CBC_MAC_PADDING_NOT_SUPPORT;
}
}
int32_t CRYPT_CBC_MAC_Final(CRYPT_CBC_MAC_Ctx *ctx, uint8_t *out, uint32_t *len)
{
if (ctx == NULL || ctx->common.method == NULL || len == NULL || out == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
const EAL_SymMethod *method = ctx->common.method;
uint32_t blockSize = method->blockSize;
if (*len < blockSize) {
BSL_ERR_PUSH_ERROR(CRYPT_CBC_MAC_OUT_BUFF_LEN_NOT_ENOUGH);
return CRYPT_CBC_MAC_OUT_BUFF_LEN_NOT_ENOUGH;
}
int32_t ret = CbcMacPadding(ctx);
if (ret != CRYPT_SUCCESS) {
return ret;
}
DATA_XOR(ctx->common.left, ctx->common.data, ctx->common.left, blockSize);
ret = method->encryptBlock(ctx->common.key, ctx->common.left, out, blockSize);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
*len = blockSize;
return CRYPT_SUCCESS;
}
int32_t CRYPT_CBC_MAC_Reinit(CRYPT_CBC_MAC_Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
return CipherMacReinit(&ctx->common);
}
int32_t CRYPT_CBC_MAC_Deinit(CRYPT_CBC_MAC_Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
return CipherMacDeinit(&ctx->common);
}
int32_t CRYPT_CBC_MAC_Ctrl(CRYPT_CBC_MAC_Ctx *ctx, uint32_t 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_SET_CBC_MAC_PADDING:
if (len != sizeof(CRYPT_PaddingType)) {
BSL_ERR_PUSH_ERROR(CRYPT_CBC_MAC_ERR_CTRL_LEN);
return CRYPT_CBC_MAC_ERR_CTRL_LEN;
}
ctx->paddingType = *(CRYPT_PaddingType*)val;
return CRYPT_SUCCESS;
case CRYPT_CTRL_GET_MACLEN:
return CipherMacGetMacLen(&ctx->common, val, len);
default:
BSL_ERR_PUSH_ERROR(CRYPT_CBC_MAC_ERR_UNSUPPORTED_CTRL_OPTION);
return CRYPT_CBC_MAC_ERR_UNSUPPORTED_CTRL_OPTION;
}
}
void CRYPT_CBC_MAC_FreeCtx(CRYPT_CBC_MAC_Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return;
}
CipherMacDeinitCtx(&ctx->common);
BSL_SAL_Free(ctx);
}
#endif
|
2301_79861745/bench_create
|
crypto/cmac/src/cbc_mac.c
|
C
|
unknown
| 5,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.
*/
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_CBC_MAC) || defined(HITLS_CRYPTO_CMAC)
#include <stdlib.h>
#include "securec.h"
#include "bsl_sal.h"
#include "crypt_utils.h"
#include "crypt_errno.h"
#include "bsl_err_internal.h"
#include "crypt_local_types.h"
#include "cipher_mac_common.h"
int32_t CipherMacInitCtx(Cipher_MAC_Common_Ctx *ctx, const EAL_SymMethod *method)
{
if (ctx == NULL || method == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
void *key = (void *)BSL_SAL_Calloc(1u, method->ctxSize);
if (key == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
// set key and set method
ctx->key = key;
ctx->method = method;
return CRYPT_SUCCESS;
}
void CipherMacDeinitCtx(Cipher_MAC_Common_Ctx *ctx)
{
if (ctx == NULL || ctx->method == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return;
}
const EAL_SymMethod *method = ctx->method;
BSL_SAL_CleanseData((void *)(ctx->key), method->ctxSize);
BSL_SAL_FREE(ctx->key);
}
int32_t CipherMacInit(Cipher_MAC_Common_Ctx *ctx, const uint8_t *key, uint32_t len)
{
if (ctx == NULL || ctx->method == NULL || (key == NULL && len != 0)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret = ctx->method->setEncryptKey(ctx->key, key, len);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
(void)memset_s(ctx->data, CIPHER_MAC_MAXBLOCKSIZE, 0, CIPHER_MAC_MAXBLOCKSIZE);
ctx->len = 0;
return CRYPT_SUCCESS;
}
int32_t CipherMacUpdate(Cipher_MAC_Common_Ctx *ctx, const uint8_t *in, uint32_t len)
{
if (ctx == NULL || ctx->method == NULL || (in == NULL && len != 0)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
const EAL_SymMethod *method = ctx->method;
int32_t ret;
uint32_t blockSize = method->blockSize;
const uint8_t *inTmp = in;
uint32_t lenTmp = len;
if (ctx->len > 0) {
if (ctx->len > (UINT32_MAX - lenTmp)) {
BSL_ERR_PUSH_ERROR(CRYPT_CMAC_INPUT_OVERFLOW);
return CRYPT_CMAC_INPUT_OVERFLOW;
}
uint32_t end = (ctx->len + lenTmp) > (blockSize) ? (blockSize) : (ctx->len + lenTmp);
for (uint32_t i = ctx->len; i < end; i++) {
ctx->left[i] = (*inTmp);
inTmp++;
}
lenTmp -= (end - ctx->len);
if (lenTmp == 0) {
ctx->len = end;
return CRYPT_SUCCESS;
}
DATA_XOR(ctx->left, ctx->data, ctx->left, blockSize);
ret = method->encryptBlock(ctx->key, ctx->left, ctx->data, blockSize);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
while (lenTmp > blockSize) {
DATA_XOR(inTmp, ctx->data, ctx->left, blockSize);
ret = method->encryptBlock(ctx->key, ctx->left, ctx->data, blockSize);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
lenTmp -= blockSize;
inTmp += blockSize;
}
for (uint32_t i = 0; i < lenTmp; i++) {
ctx->left[i] = inTmp[i];
}
ctx->len = lenTmp;
return CRYPT_SUCCESS;
}
int32_t CipherMacReinit(Cipher_MAC_Common_Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
(void)memset_s(ctx->data, CIPHER_MAC_MAXBLOCKSIZE, 0, CIPHER_MAC_MAXBLOCKSIZE);
ctx->len = 0;
return CRYPT_SUCCESS;
}
int32_t CipherMacDeinit(Cipher_MAC_Common_Ctx *ctx)
{
if (ctx == NULL || ctx->method == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
const uint32_t ctxSize = ctx->method->ctxSize;
BSL_SAL_CleanseData(ctx->key, ctxSize);
(void)memset_s(ctx->data, CIPHER_MAC_MAXBLOCKSIZE, 0, CIPHER_MAC_MAXBLOCKSIZE);
(void)memset_s(ctx->left, CIPHER_MAC_MAXBLOCKSIZE, 0, CIPHER_MAC_MAXBLOCKSIZE);
ctx->len = 0;
return CRYPT_SUCCESS;
}
int32_t CipherMacGetMacLen(const Cipher_MAC_Common_Ctx *ctx, void *val, uint32_t len)
{
if (ctx == NULL || ctx->method == NULL || val == NULL || len != sizeof(uint32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
*(uint32_t *)val = ctx->method->blockSize;
return CRYPT_SUCCESS;
}
#endif // #if defined(HITLS_CRYPTO_CBC_MAC) || defined(HITLS_CRYPTO_CMAC)
|
2301_79861745/bench_create
|
crypto/cmac/src/cipher_mac_common.c
|
C
|
unknown
| 5,210
|
/*
* 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 CIPHER_MAC_COMMON_H
#define CIPHER_MAC_COMMON_H
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_CBC_MAC) || defined(HITLS_CRYPTO_CMAC)
#include <stdint.h>
#include "crypt_local_types.h"
#include "crypt_cmac.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
#define CIPHER_MAC_MAXBLOCKSIZE 16
struct Cipher_MAC_Ctx {
const EAL_SymMethod *method;
void *key;
/* Stores the intermediate process data of CBC_MAC. The length is the block size. */
uint8_t data[CIPHER_MAC_MAXBLOCKSIZE];
uint8_t left[CIPHER_MAC_MAXBLOCKSIZE];
uint32_t len; /* Length of a non-integral data block */
};
typedef struct Cipher_MAC_Ctx Cipher_MAC_Common_Ctx;
#ifdef HITLS_CRYPTO_CBC_MAC
struct CBC_MAC_Ctx {
Cipher_MAC_Common_Ctx common;
CRYPT_PaddingType paddingType;
};
#endif
int32_t CipherMacInitCtx(Cipher_MAC_Common_Ctx *ctx, const EAL_SymMethod *method);
void CipherMacDeinitCtx(Cipher_MAC_Common_Ctx *ctx);
int32_t CipherMacInit(Cipher_MAC_Common_Ctx *ctx, const uint8_t *key, uint32_t len);
int32_t CipherMacUpdate(Cipher_MAC_Common_Ctx *ctx, const uint8_t *in, uint32_t len);
int32_t CipherMacReinit(Cipher_MAC_Common_Ctx *ctx);
int32_t CipherMacDeinit(Cipher_MAC_Common_Ctx *ctx);
int32_t CipherMacGetMacLen(const Cipher_MAC_Common_Ctx *ctx, void *val, uint32_t len);
#ifdef __cplusplus
}
#endif /* __cpluscplus */
#endif // #if defined(HITLS_CRYPTO_CBC_MAC) || defined(HITLS_CRYPTO_CMAC)
#endif // CIPHER_MAC_COMMON_H
|
2301_79861745/bench_create
|
crypto/cmac/src/cipher_mac_common.h
|
C
|
unknown
| 2,084
|
/*
* 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_CMAC
#include <stdlib.h>
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "crypt_utils.h"
#include "bsl_err_internal.h"
#include "cipher_mac_common.h"
#include "crypt_cmac.h"
#include "eal_mac_local.h"
CRYPT_CMAC_Ctx *CRYPT_CMAC_NewCtx(CRYPT_MAC_AlgId id)
{
int32_t ret;
EAL_MacDepMethod method = {0};
ret = EAL_MacFindDepMethod(id, NULL, NULL, &method, NULL, false);
if (ret != CRYPT_SUCCESS) {
return NULL;
}
CRYPT_CMAC_Ctx *ctx = BSL_SAL_Calloc(1, sizeof(CRYPT_CMAC_Ctx));
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
ret = CipherMacInitCtx(ctx, method.method.sym);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_Free(ctx);
return NULL;
}
return ctx;
}
CRYPT_CMAC_Ctx *CRYPT_CMAC_NewCtxEx(void *libCtx, CRYPT_MAC_AlgId id)
{
(void)libCtx;
return CRYPT_CMAC_NewCtx(id);
}
int32_t CRYPT_CMAC_Init(CRYPT_CMAC_Ctx *ctx, const uint8_t *key, uint32_t len, void *param)
{
(void)param;
return CipherMacInit((Cipher_MAC_Common_Ctx *)ctx, key, len);
}
int32_t CRYPT_CMAC_Update(CRYPT_CMAC_Ctx *ctx, const uint8_t *in, uint32_t len)
{
return CipherMacUpdate((Cipher_MAC_Common_Ctx *)ctx, in, len);
}
static inline void LeftShiftOneBit(const uint8_t *in, uint32_t len, uint8_t *out)
{
uint32_t i = len - 1;
out[i] = (in[i] << 1) | 0;
do {
i--;
out[i] = (in[i] << 1) | (in[i + 1] >> 7); // 7 is used to obtain the most significant bit of the 8-bit data.
} while (i != 0);
}
static void CMAC_Final(CRYPT_CMAC_Ctx *ctx)
{
const uint8_t z[CIPHER_MAC_MAXBLOCKSIZE] = {0};
uint8_t rb;
uint8_t l[CIPHER_MAC_MAXBLOCKSIZE];
uint8_t k1[CIPHER_MAC_MAXBLOCKSIZE];
const EAL_SymMethod *method = ctx->method;
uint32_t blockSize = method->blockSize;
int32_t ret;
ret = method->encryptBlock(ctx->key, z, l, blockSize);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return;
}
LeftShiftOneBit(l, blockSize, k1);
if (blockSize == CIPHER_MAC_MAXBLOCKSIZE) {
rb = 0x87; /* When the AES algorithm is used and the blocksize is 128 bits, rb uses 0x87. */
} else {
rb = 0x1B; /* When the DES and TDES algorithms are used and blocksize is 64 bits, rb uses 0x1B. */
}
if ((l[0] & 0x80) != 0) {
k1[blockSize - 1] ^= rb;
}
uint32_t length = ctx->len;
if (length == blockSize) { // When the message length is an integer multiple of blockSize, use K1
DATA_XOR(ctx->left, k1, ctx->left, blockSize);
} else { // The message length is not an integer multiple of blockSize. Use K2 after padding.
/* padding */
ctx->left[length++] = 0x80; // 0x80 indicates that the first bit of the data is added with 1.
while (length < blockSize) {
ctx->left[length++] = 0;
}
uint8_t k2[CIPHER_MAC_MAXBLOCKSIZE];
LeftShiftOneBit(k1, blockSize, k2);
if ((k1[0] & 0x80) != 0) {
k2[blockSize - 1] ^= rb;
}
DATA_XOR(ctx->left, k2, ctx->left, blockSize);
ctx->len = blockSize;
}
}
int32_t CRYPT_CMAC_Final(CRYPT_CMAC_Ctx *ctx, uint8_t *out, uint32_t *len)
{
if (ctx == NULL || ctx->method == NULL || len == NULL || out == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
const EAL_SymMethod *method = ctx->method;
uint32_t blockSize = method->blockSize;
if (*len < blockSize) {
BSL_ERR_PUSH_ERROR(CRYPT_CMAC_OUT_BUFF_LEN_NOT_ENOUGH);
return CRYPT_CMAC_OUT_BUFF_LEN_NOT_ENOUGH;
}
CMAC_Final(ctx);
DATA_XOR(ctx->left, ctx->data, ctx->left, blockSize);
int32_t ret = method->encryptBlock(ctx->key, ctx->left, out, blockSize);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
*len = blockSize;
return CRYPT_SUCCESS;
}
int32_t CRYPT_CMAC_Reinit(CRYPT_CMAC_Ctx *ctx)
{
return CipherMacReinit((Cipher_MAC_Common_Ctx *)ctx);
}
int32_t CRYPT_CMAC_Deinit(CRYPT_CMAC_Ctx *ctx)
{
return CipherMacDeinit((Cipher_MAC_Common_Ctx *)ctx);
}
int32_t CRYPT_CMAC_Ctrl(CRYPT_CMAC_Ctx *ctx, uint32_t opt, void *val, uint32_t len)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
switch (opt) {
case CRYPT_CTRL_GET_MACLEN:
return CipherMacGetMacLen(ctx, val, len);
default:
break;
}
BSL_ERR_PUSH_ERROR(CRYPT_CMAC_ERR_UNSUPPORTED_CTRL_OPTION);
return CRYPT_CMAC_ERR_UNSUPPORTED_CTRL_OPTION;
}
void CRYPT_CMAC_FreeCtx(CRYPT_CMAC_Ctx *ctx)
{
CipherMacDeinitCtx(ctx);
BSL_SAL_Free(ctx);
}
#endif /* HITLS_CRYPTO_CMAC */
|
2301_79861745/bench_create
|
crypto/cmac/src/cmac.c
|
C
|
unknown
| 5,318
|
/*
* 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_DECODE_KEY_IMPL_H
#define CRYPT_DECODE_KEY_IMPL_H
#ifdef __cplusplus
extern "C" {
#endif
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_CODECSKEY
#include <stdint.h>
#include "bsl_params.h"
typedef struct {
const char *outFormat;
const char *outType;
} DECODER_CommonCtx;
int32_t DECODER_CommonGetParam(const DECODER_CommonCtx *commonCtx, BSL_Param *param);
void *DECODER_EPKI2PKI_NewCtx(void *provCtx);
int32_t DECODER_EPKI2PKI_GetParam(void *ctx, BSL_Param *param);
int32_t DECODER_EPKI2PKI_SetParam(void *ctx, const BSL_Param *param);
int32_t DECODER_EPKI2PKI_Decode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam);
void DECODER_EPKI2PKI_FreeOutData(void *ctx, BSL_Param *outParam);
void DECODER_EPKI2PKI_FreeCtx(void *ctx);
int32_t DECODER_DER2KEY_GetParam(void *ctx, BSL_Param *param);
int32_t DECODER_DER2KEY_SetParam(void *ctx, const BSL_Param *param);
void DECODER_DER2KEY_FreeOutData(void *ctx, BSL_Param *outParam);
void DECODER_DER2KEY_FreeCtx(void *ctx);
#ifdef HITLS_CRYPTO_RSA
void *DECODER_RsaDer2KeyNewCtx(void *provCtx);
int32_t DECODER_RsaPrvKeyDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam);
int32_t DECODER_RsaPubKeyDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam);
int32_t DECODER_RsaSubPubKeyDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam);
int32_t DECODER_RsaSubPubKeyWithOutSeqDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam);
int32_t DECODER_RsaPkcs8Der2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam);
#endif
#ifdef HITLS_CRYPTO_ECDSA
void *DECODER_EcdsaDer2KeyNewCtx(void *provCtx);
int32_t DECODER_EcdsaPrvKeyDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam);
int32_t DECODER_EcdsaSubPubKeyDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam);
int32_t DECODER_EcdsaSubPubKeyWithOutSeqDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam);
int32_t DECODER_EcdsaPkcs8Der2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam);
#endif
#ifdef HITLS_CRYPTO_SM2
void *DECODER_Sm2Der2KeyNewCtx(void *provCtx);
int32_t DECODER_Sm2PrvKeyDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam);
int32_t DECODER_Sm2SubPubKeyDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam);
int32_t DECODER_Sm2SubPubKeyWithOutSeqDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam);
int32_t DECODER_Sm2Pkcs8Der2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam);
#endif
#ifdef HITLS_CRYPTO_ED25519
void *DECODER_Ed25519Der2KeyNewCtx(void *provCtx);
int32_t DECODER_Ed25519SubPubKeyDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam);
int32_t DECODER_Ed25519SubPubKeyWithOutSeqDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam);
int32_t DECODER_Ed25519Pkcs8Der2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam);
#endif
#ifdef HITLS_BSL_PEM
void *DECODER_Pem2DerNewCtx(void *provCtx);
int32_t DECODER_Pem2DerGetParam(void *ctx, BSL_Param *param);
int32_t DECODER_Pem2DerSetParam(void *ctx, const BSL_Param *param);
int32_t DECODER_Pem2DerDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam);
void DECODER_Pem2DerFreeOutData(void *ctx, BSL_Param *outParam);
void DECODER_Pem2DerFreeCtx(void *ctx);
#endif
void *DECODER_LowKeyObject2PkeyObjectNewCtx(void *provCtx);
int32_t DECODER_LowKeyObject2PkeyObjectSetParam(void *ctx, const BSL_Param *param);
int32_t DECODER_LowKeyObject2PkeyObjectGetParam(void *ctx, BSL_Param *param);
int32_t DECODER_LowKeyObject2PkeyObjectDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam);
void DECODER_LowKeyObject2PkeyObjectFreeOutData(void *ctx, BSL_Param *outParam);
void DECODER_LowKeyObject2PkeyObjectFreeCtx(void *ctx);
#endif /* HITLS_CRYPTO_CODECSKEY */
#ifdef __cplusplus
}
#endif
#endif /* CRYPT_DECODE_KEY_IMPL_H */
|
2301_79861745/bench_create
|
crypto/codecskey/include/crypt_decode_key_impl.h
|
C
|
unknown
| 4,509
|
/*
* 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_DECODE_KEY_H
#define CRYPT_ENCODE_DECODE_KEY_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_CODECSKEY
#include "bsl_types.h"
#include "bsl_asn1_internal.h"
#include "crypt_eal_pkey.h"
#ifdef HITLS_CRYPTO_KEY_INFO
#include "bsl_uio.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
typedef struct {
int32_t version;
BslCid keyType;
BSL_ASN1_Buffer keyParam;
uint8_t *pkeyRawKey;
uint32_t pkeyRawKeyLen;
void *attrs; // HITLS_X509_Attrs *
} CRYPT_ENCODE_DECODE_Pk8PrikeyInfo;
#ifdef HITLS_CRYPTO_KEY_DECODE
typedef struct {
BslCid keyType;
BSL_ASN1_Buffer keyParam;
BSL_ASN1_BitString pubKey;
} CRYPT_DECODE_SubPubkeyInfo;
int32_t CRYPT_DECODE_SubPubkey(uint8_t *buff, uint32_t buffLen, BSL_ASN1_DecTemplCallBack keyInfoCb,
CRYPT_DECODE_SubPubkeyInfo *subPubkeyInfo, bool isComplete);
int32_t CRYPT_DECODE_Pkcs8Info(uint8_t *buff, uint32_t buffLen, BSL_ASN1_DecTemplCallBack keyInfoCb,
CRYPT_ENCODE_DECODE_Pk8PrikeyInfo *pk8PrikeyInfo);
int32_t CRYPT_EAL_ParseRsaPssAlgParam(BSL_ASN1_Buffer *param, CRYPT_RSA_PssPara *para);
int32_t CRYPT_EAL_PriKeyParseFile(BSL_ParseFormat format, int32_t type,
const char *path, const BSL_Buffer *pwd, CRYPT_EAL_PkeyCtx **ealPriKey);
#endif // HITLS_CRYPTO_KEY_DECODE
#ifdef HITLS_CRYPTO_KEY_ENCODE
int32_t CRYPT_ENCODE_Pkcs8Info(CRYPT_ENCODE_DECODE_Pk8PrikeyInfo *pk8PrikeyInfo, BSL_Buffer *asn1);
int32_t CRYPT_EAL_EncodePubKeyBuffInternal(CRYPT_EAL_PkeyCtx *ealPubKey,
BSL_ParseFormat format, int32_t type, bool isComplete, BSL_Buffer *encode);
#ifdef HITLS_CRYPTO_RSA
int32_t CRYPT_EAL_EncodeRsaPssAlgParam(const CRYPT_RSA_PssPara *rsaPssParam, uint8_t **buf, uint32_t *bufLen);
#endif
#endif // HITLS_CRYPTO_KEY_ENCODE
#if defined(HITLS_CRYPTO_RSA) && (defined(HITLS_CRYPTO_KEY_ENCODE) || defined(HITLS_CRYPTO_KEY_INFO))
int32_t CRYPT_EAL_InitRsaPrv(const CRYPT_EAL_PkeyCtx *ealPriKey, CRYPT_PKEY_AlgId cid, CRYPT_EAL_PkeyPrv *rsaPrv);
void CRYPT_EAL_DeinitRsaPrv(CRYPT_EAL_PkeyPrv *rsaPrv);
int32_t CRYPT_EAL_GetRsaPssPara(CRYPT_EAL_PkeyCtx *ealPriKey, CRYPT_RSA_PssPara *rsaPssParam);
#endif
#ifdef HITLS_PKI_PKCS12_PARSE
// parse PKCS7-EncryptData:only support PBES2 + PBKDF2.
int32_t CRYPT_EAL_ParseAsn1PKCS7EncryptedData(CRYPT_EAL_LibCtx *libCtx, const char *attrName, BSL_Buffer *encode,
const uint8_t *pwd, uint32_t pwdlen, BSL_Buffer *output);
#endif
#ifdef HITLS_PKI_PKCS12_GEN
// encode PKCS7-EncryptData:only support PBES2 + PBKDF2.
int32_t CRYPT_EAL_EncodePKCS7EncryptDataBuff(CRYPT_EAL_LibCtx *libCtx, const char *attrName, BSL_Buffer *data,
const void *encodeParam, BSL_Buffer *encode);
#endif
#ifdef HITLS_CRYPTO_KEY_INFO
int32_t CRYPT_EAL_PrintPubkey(uint32_t layer, CRYPT_EAL_PkeyCtx *pkey, BSL_UIO *uio);
int32_t CRYPT_EAL_PrintPrikey(uint32_t layer, CRYPT_EAL_PkeyCtx *pkey, BSL_UIO *uio);
#ifdef HITLS_CRYPTO_RSA
int32_t CRYPT_EAL_PrintRsaPssPara(uint32_t layer, CRYPT_RSA_PssPara *para, BSL_UIO *uio);
#endif
#endif // HITLS_CRYPTO_KEY_INFO
int32_t CRYPT_EAL_GetEncodeFormat(const char *format);
int32_t CRYPT_EAL_GetEncodeType(const char *type);
#ifdef __cplusplus
}
#endif
#endif // HITLS_CRYPTO_CODECSKEY
#endif // CRYPT_ENCODE_DECODE_KEY_H
|
2301_79861745/bench_create
|
crypto/codecskey/include/crypt_encode_decode_key.h
|
C
|
unknown
| 3,777
|
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_CODECSKEY) && defined(HITLS_CRYPTO_PROVIDER)
#include <string.h>
#include <stdbool.h>
#include "crypt_eal_implprovider.h"
#include "crypt_eal_pkey.h"
#include "crypt_default_provderimpl.h"
#include "crypt_algid.h"
#ifdef HITLS_CRYPTO_RSA
#include "crypt_rsa.h"
#endif
#ifdef HITLS_CRYPTO_ECDSA
#include "crypt_ecdsa.h"
#endif
#ifdef HITLS_CRYPTO_SM2
#include "crypt_sm2.h"
#endif
#ifdef HITLS_CRYPTO_ED25519
#include "crypt_curve25519.h"
#endif
#include "eal_pkey.h"
#include "crypt_provider_local.h"
#include "crypt_errno.h"
#include "bsl_sal.h"
#include "bsl_obj.h"
#include "bsl_err_internal.h"
#include "crypt_encode_decode_local.h"
#include "crypt_decode_key_impl.h"
#define PKEY_MAX_PARAM_NUM 20
#if defined(HITLS_CRYPTO_RSA) || defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2) || \
defined(HITLS_CRYPTO_ED25519)
typedef struct {
CRYPT_EAL_ProvMgrCtx *provMgrCtx;
EAL_PkeyUnitaryMethod *method;
int32_t keyAlgId;
const char *outFormat;
const char *outType;
} DECODER_Der2KeyCtx;
DECODER_Der2KeyCtx *DECODER_DER2KEY_NewCtx(void *provCtx)
{
(void)provCtx;
DECODER_Der2KeyCtx *ctx = (DECODER_Der2KeyCtx *)BSL_SAL_Calloc(1, sizeof(DECODER_Der2KeyCtx));
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
ctx->outFormat = "OBJECT";
ctx->outType = "LOW_KEY";
return ctx;
}
#define DECODER_DEFINE_DER2KEY_NEW_CTX(keyType, keyId, keyMethod, asyCipherMethod, exchMethod, signMethod, kemMethod) \
void *DECODER_##keyType##Der2KeyNewCtx(void *provCtx) \
{ \
DECODER_Der2KeyCtx *ctx = DECODER_DER2KEY_NewCtx(provCtx); \
if (ctx == NULL) { \
return NULL; \
} \
int32_t ret = CRYPT_EAL_SetPkeyMethod(&ctx->method, keyMethod, asyCipherMethod, exchMethod, signMethod, \
kemMethod); \
if (ret != CRYPT_SUCCESS) { \
BSL_SAL_Free(ctx); \
return NULL; \
} \
ctx->keyAlgId = keyId; \
return ctx; \
}
int32_t DECODER_CommonGetParam(const DECODER_CommonCtx *commonCtx, BSL_Param *param)
{
if (commonCtx == NULL || param == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
BSL_Param *param1 = BSL_PARAM_FindParam(param, CRYPT_PARAM_DECODE_OUTPUT_TYPE);
if (param1 != NULL) {
if (param1->valueType != BSL_PARAM_TYPE_OCTETS_PTR) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
param1->value = (void *)(uintptr_t)commonCtx->outType;
}
BSL_Param *param2 = BSL_PARAM_FindParam(param, CRYPT_PARAM_DECODE_OUTPUT_FORMAT);
if (param2 != NULL) {
if (param2->valueType != BSL_PARAM_TYPE_OCTETS_PTR) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
param2->value = (void *)(uintptr_t)commonCtx->outFormat;
}
return CRYPT_SUCCESS;
}
int32_t DECODER_DER2KEY_GetParam(void *ctx, BSL_Param *param)
{
DECODER_Der2KeyCtx *decoderCtx = (DECODER_Der2KeyCtx *)ctx;
if (decoderCtx == NULL || param == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
DECODER_CommonCtx commonCtx = {
.outFormat = decoderCtx->outFormat,
.outType = decoderCtx->outType
};
return DECODER_CommonGetParam(&commonCtx, param);
}
int32_t DECODER_DER2KEY_SetParam(void *ctx, const BSL_Param *param)
{
DECODER_Der2KeyCtx *decoderCtx = (DECODER_Der2KeyCtx *)ctx;
if (decoderCtx == NULL || param == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
const BSL_Param *input = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_DECODE_PROVIDER_CTX);
if (input != NULL) {
if (input->valueType != BSL_PARAM_TYPE_CTX_PTR || input->value == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
decoderCtx->provMgrCtx = (CRYPT_EAL_ProvMgrCtx *)(uintptr_t)input->value;
}
return CRYPT_SUCCESS;
}
static int32_t CheckParams(DECODER_Der2KeyCtx *decoderCtx, const BSL_Param *inParam, BSL_Param **outParam,
BSL_Buffer *asn1Encode)
{
if (decoderCtx == NULL || inParam == NULL || outParam == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
const BSL_Param *input = BSL_PARAM_FindConstParam(inParam, CRYPT_PARAM_DECODE_BUFFER_DATA);
if (input == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (input->value == NULL || input->valueLen == 0 || input->valueType != BSL_PARAM_TYPE_OCTETS) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
asn1Encode->data = (uint8_t *)(uintptr_t)input->value;
asn1Encode->dataLen = input->valueLen;
return CRYPT_SUCCESS;
}
#define DECODER_CHECK_PARAMS(ctx, inParam, outParam) \
void *key = NULL; \
BSL_Buffer asn1Encode = {0}; \
DECODER_Der2KeyCtx *decoderCtx = (DECODER_Der2KeyCtx *)ctx; \
int32_t ret = CheckParams(decoderCtx, inParam, outParam, &asn1Encode); \
if (ret != CRYPT_SUCCESS) { \
BSL_ERR_PUSH_ERROR(ret); \
return ret; \
}
static int32_t ConstructOutputParams(DECODER_Der2KeyCtx *decoderCtx, void *key, BSL_Param **outParam)
{
BSL_Param *result = BSL_SAL_Calloc(7, sizeof(BSL_Param));
if (result == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
int32_t ret = BSL_PARAM_InitValue(&result[0], CRYPT_PARAM_DECODE_OBJECT_DATA, BSL_PARAM_TYPE_CTX_PTR, key, 0);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BSL_PARAM_InitValue(&result[1], CRYPT_PARAM_DECODE_OBJECT_TYPE, BSL_PARAM_TYPE_INT32, &decoderCtx->keyAlgId,
sizeof(int32_t));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BSL_PARAM_InitValue(&result[2], CRYPT_PARAM_DECODE_PKEY_EXPORT_METHOD_FUNC, BSL_PARAM_TYPE_FUNC_PTR,
decoderCtx->method->export, 0);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BSL_PARAM_InitValue(&result[3], CRYPT_PARAM_DECODE_PKEY_FREE_METHOD_FUNC, BSL_PARAM_TYPE_FUNC_PTR,
decoderCtx->method->freeCtx, 0);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BSL_PARAM_InitValue(&result[4], CRYPT_PARAM_DECODE_PKEY_DUP_METHOD_FUNC, BSL_PARAM_TYPE_FUNC_PTR,
decoderCtx->method->dupCtx, 0);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BSL_PARAM_InitValue(&result[5], CRYPT_PARAM_DECODE_PROVIDER_CTX, BSL_PARAM_TYPE_CTX_PTR,
decoderCtx->provMgrCtx, 0);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
*outParam = result;
return CRYPT_SUCCESS;
EXIT:
if (decoderCtx->method != NULL && decoderCtx->method->freeCtx != NULL) {
decoderCtx->method->freeCtx(key);
}
BSL_SAL_Free(result);
return ret;
}
#define DECODER_DEFINE_PRVKEY_DER2KEY_DECODE(keyType, keyStructName, parseFunc) \
int32_t DECODER_##keyType##PrvKeyDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam) \
{ \
DECODER_CHECK_PARAMS(ctx, inParam, outParam); \
ret = parseFunc(decoderCtx->provMgrCtx->libCtx, asn1Encode.data, asn1Encode.dataLen, NULL, \
(keyStructName **)&key); \
if (ret != CRYPT_SUCCESS) { \
BSL_ERR_PUSH_ERROR(ret); \
return ret; \
} \
return ConstructOutputParams(decoderCtx, key, outParam); \
}
#define DECODER_DEFINE_PUBKEY_DER2KEY_DECODE(keyType, keyStructName, parseFunc) \
int32_t DECODER_##keyType##PubKeyDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam) \
{ \
DECODER_CHECK_PARAMS(ctx, inParam, outParam); \
ret = parseFunc(decoderCtx->provMgrCtx->libCtx, asn1Encode.data, asn1Encode.dataLen, NULL, \
(keyStructName **)&key, BSL_CID_UNKNOWN); \
if (ret != CRYPT_SUCCESS) { \
BSL_ERR_PUSH_ERROR(ret); \
return ret; \
} \
return ConstructOutputParams(decoderCtx, key, outParam); \
}
#define DECODER_DEFINE_SUBPUBKEY_DER2KEY_DECODE(keyType, keyStructName, parseFunc) \
int32_t DECODER_##keyType##SubPubKeyDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam) \
{ \
DECODER_CHECK_PARAMS(ctx, inParam, outParam) \
ret = parseFunc(decoderCtx->provMgrCtx->libCtx, asn1Encode.data, asn1Encode.dataLen, \
(keyStructName **)&key, true); \
if (ret != CRYPT_SUCCESS) { \
BSL_ERR_PUSH_ERROR(ret); \
return ret; \
} \
return ConstructOutputParams(decoderCtx, key, outParam); \
}
#define DECODER_DEFINE_SUBPUBKEY_WITHOUT_SEQ_DER2KEY_DECODE(keyType, keyStructName, parseFunc) \
int32_t DECODER_##keyType##SubPubKeyWithOutSeqDer2KeyDecode(void *ctx, const BSL_Param *inParam, \
BSL_Param **outParam) \
{ \
DECODER_CHECK_PARAMS(ctx, inParam, outParam) \
ret = parseFunc(decoderCtx->provMgrCtx->libCtx, asn1Encode.data, asn1Encode.dataLen, (keyStructName **)&key, \
false); \
if (ret != CRYPT_SUCCESS) { \
BSL_ERR_PUSH_ERROR(ret); \
return ret; \
} \
return ConstructOutputParams(decoderCtx, key, outParam); \
}
#define DECODER_DEFINE_PKCS8_DECODE(keyType, keyStructName, parseFunc) \
int32_t DECODER_##keyType##Pkcs8Der2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam) \
{ \
DECODER_CHECK_PARAMS(ctx, inParam, outParam) \
ret = parseFunc(decoderCtx->provMgrCtx->libCtx, asn1Encode.data, asn1Encode.dataLen, (keyStructName **)&key); \
if (ret != CRYPT_SUCCESS) { \
BSL_ERR_PUSH_ERROR(ret); \
return ret; \
} \
return ConstructOutputParams(decoderCtx, key, outParam); \
}
void DECODER_DER2KEY_FreeOutData(void *ctx, BSL_Param *outParam)
{
DECODER_Der2KeyCtx *decoderCtx = ctx;
if (decoderCtx == NULL || outParam == NULL) {
return;
}
if (decoderCtx->method == NULL || decoderCtx->method->freeCtx == NULL) {
return;
}
BSL_Param *outKey = BSL_PARAM_FindParam(outParam, CRYPT_PARAM_DECODE_OBJECT_DATA);
if (outKey == NULL) {
return;
}
decoderCtx->method->freeCtx(outKey->value);
BSL_SAL_Free(outParam);
}
void DECODER_DER2KEY_FreeCtx(void *ctx)
{
if (ctx == NULL) {
return;
}
DECODER_Der2KeyCtx *decoderCtx = (DECODER_Der2KeyCtx *)ctx;
if (decoderCtx->method != NULL) {
BSL_SAL_Free(decoderCtx->method);
}
BSL_SAL_Free(decoderCtx);
}
#endif
#ifdef HITLS_CRYPTO_RSA
DECODER_DEFINE_DER2KEY_NEW_CTX(Rsa, CRYPT_PKEY_RSA, g_defEalKeyMgmtRsa, g_defEalAsymCipherRsa, NULL, \
g_defEalSignRsa, NULL)
#endif
#ifdef HITLS_CRYPTO_ECDSA
DECODER_DEFINE_DER2KEY_NEW_CTX(Ecdsa, CRYPT_PKEY_ECDSA, g_defEalKeyMgmtEcdsa, NULL, NULL, \
g_defEalSignEcdsa, NULL)
#endif
#ifdef HITLS_CRYPTO_SM2
DECODER_DEFINE_DER2KEY_NEW_CTX(Sm2, CRYPT_PKEY_SM2, g_defEalKeyMgmtSm2, g_defEalAsymCipherSm2, g_defEalExchSm2, \
g_defEalSignSm2, NULL)
#endif
#ifdef HITLS_CRYPTO_ED25519
DECODER_DEFINE_DER2KEY_NEW_CTX(Ed25519, CRYPT_PKEY_ED25519, g_defEalKeyMgmtEd25519, NULL, NULL, \
g_defEalSignEd25519, NULL)
#endif
#ifdef HITLS_CRYPTO_RSA
DECODER_DEFINE_PRVKEY_DER2KEY_DECODE(Rsa, CRYPT_RSA_Ctx, CRYPT_RSA_ParsePrikeyAsn1Buff)
DECODER_DEFINE_PUBKEY_DER2KEY_DECODE(Rsa, CRYPT_RSA_Ctx, CRYPT_RSA_ParsePubkeyAsn1Buff)
DECODER_DEFINE_SUBPUBKEY_DER2KEY_DECODE(Rsa, CRYPT_RSA_Ctx, CRYPT_RSA_ParseSubPubkeyAsn1Buff)
DECODER_DEFINE_SUBPUBKEY_WITHOUT_SEQ_DER2KEY_DECODE(Rsa, CRYPT_RSA_Ctx, CRYPT_RSA_ParseSubPubkeyAsn1Buff)
DECODER_DEFINE_PKCS8_DECODE(Rsa, CRYPT_RSA_Ctx, CRYPT_RSA_ParsePkcs8Key)
#endif
#ifdef HITLS_CRYPTO_ECDSA
DECODER_DEFINE_PRVKEY_DER2KEY_DECODE(Ecdsa, void, CRYPT_ECC_ParsePrikeyAsn1Buff)
DECODER_DEFINE_SUBPUBKEY_DER2KEY_DECODE(Ecdsa, void, CRYPT_ECC_ParseSubPubkeyAsn1Buff)
DECODER_DEFINE_SUBPUBKEY_WITHOUT_SEQ_DER2KEY_DECODE(Ecdsa, void, CRYPT_ECC_ParseSubPubkeyAsn1Buff)
DECODER_DEFINE_PKCS8_DECODE(Ecdsa, void, CRYPT_ECC_ParsePkcs8Key)
#endif
#ifdef HITLS_CRYPTO_SM2
DECODER_DEFINE_PRVKEY_DER2KEY_DECODE(Sm2, CRYPT_SM2_Ctx, CRYPT_SM2_ParsePrikeyAsn1Buff)
DECODER_DEFINE_SUBPUBKEY_DER2KEY_DECODE(Sm2, CRYPT_SM2_Ctx, CRYPT_SM2_ParseSubPubkeyAsn1Buff)
DECODER_DEFINE_SUBPUBKEY_WITHOUT_SEQ_DER2KEY_DECODE(Sm2, CRYPT_SM2_Ctx,CRYPT_SM2_ParseSubPubkeyAsn1Buff)
DECODER_DEFINE_PKCS8_DECODE(Sm2, CRYPT_SM2_Ctx, CRYPT_SM2_ParsePkcs8Key)
#endif
#ifdef HITLS_CRYPTO_ED25519
DECODER_DEFINE_SUBPUBKEY_DER2KEY_DECODE(Ed25519, CRYPT_CURVE25519_Ctx, CRYPT_ED25519_ParseSubPubkeyAsn1Buff)
DECODER_DEFINE_SUBPUBKEY_WITHOUT_SEQ_DER2KEY_DECODE(Ed25519, CRYPT_CURVE25519_Ctx, CRYPT_ED25519_ParseSubPubkeyAsn1Buff)
DECODER_DEFINE_PKCS8_DECODE(Ed25519, CRYPT_CURVE25519_Ctx, CRYPT_ED25519_ParsePkcs8Key)
#endif
#endif /* HITLS_CRYPTO_CODECSKEY && defined(HITLS_CRYPTO_PROVIDER) */
|
2301_79861745/bench_create
|
crypto/codecskey/src/crypt_decode_der2key.c
|
C
|
unknown
| 13,506
|
/*
* 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_KEY_DECODE
#include "crypt_ecc.h"
#ifdef HITLS_CRYPTO_ECDSA
#include "crypt_ecdsa.h"
#endif
#ifdef HITLS_CRYPTO_SM2
#include "crypt_sm2.h"
#endif
#ifdef HITLS_CRYPTO_ED25519
#include "crypt_curve25519.h"
#endif
#include "crypt_params_key.h"
#include "bsl_asn1_internal.h"
#include "bsl_params.h"
#include "bsl_obj_internal.h"
#include "bsl_err_internal.h"
#include "crypt_errno.h"
#include "crypt_encode_decode_local.h"
#include "crypt_encode_decode_key.h"
#if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2)
typedef struct {
int32_t version;
BSL_ASN1_Buffer param;
BSL_ASN1_Buffer prikey;
BSL_ASN1_Buffer pubkey;
} CRYPT_DECODE_EccPrikeyInfo;
static int32_t GetParaId(uint8_t *octs, uint32_t octsLen)
{
BslOidString oidStr = {octsLen, (char *)octs, 0};
BslCid cid = BSL_OBJ_GetCID(&oidStr);
if (cid == BSL_CID_UNKNOWN) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_ALGID);
return CRYPT_PKEY_PARAID_MAX;
}
return (int32_t)cid;
}
static int32_t ParsePrikeyAsn1Info(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *pk8AlgoParam,
CRYPT_DECODE_EccPrikeyInfo *eccPrvInfo)
{
BSL_ASN1_Buffer asn1[CRYPT_ECPRIKEY_PUBKEY_IDX + 1] = {0};
int32_t ret = CRYPT_DECODE_PrikeyAsn1Buff(buff, buffLen, asn1, CRYPT_ECPRIKEY_PUBKEY_IDX + 1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
int32_t version;
BSL_ASN1_Buffer *prikey = &asn1[CRYPT_ECPRIKEY_PRIKEY_IDX]; // the ECC OID
BSL_ASN1_Buffer *ecParamOid = &asn1[CRYPT_ECPRIKEY_PARAM_IDX]; // the parameters OID
BSL_ASN1_Buffer *pubkey = &asn1[CRYPT_ECPRIKEY_PUBKEY_IDX]; // the ECC OID
BSL_ASN1_Buffer *param = pk8AlgoParam;
if (ecParamOid->len != 0) {
// has a valid Algorithm param
param = ecParamOid;
} else {
if (param == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (param->len == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PKCS8_INVALID_ALGO_PARAM);
return CRYPT_DECODE_PKCS8_INVALID_ALGO_PARAM;
}
}
if (pubkey->len == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ASN1_BUFF_FAILED);
return CRYPT_DECODE_ASN1_BUFF_FAILED;
}
ret = BSL_ASN1_DecodePrimitiveItem(&asn1[CRYPT_ECPRIKEY_VERSION_IDX], &version);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
eccPrvInfo->version = version;
eccPrvInfo->param = *param;
eccPrvInfo->prikey = *prikey;
eccPrvInfo->pubkey = *pubkey;
return CRYPT_SUCCESS;
}
#endif // HITLS_CRYPTO_ECDSA || HITLS_CRYPTO_SM2
#ifdef HITLS_CRYPTO_ECDSA
// ecdh is not considered, and it will be improved in the future
static int32_t EccKeyNew(void *libCtx, BSL_ASN1_Buffer *ecParamOid, void **ecKey)
{
int32_t paraId = GetParaId(ecParamOid->buff, ecParamOid->len);
if (!IsEcdsaEcParaId(paraId)) {
return CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH;
}
CRYPT_ECDSA_Ctx *key = CRYPT_ECDSA_NewCtxEx(libCtx);
if (key == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
int32_t ret = ECC_SetPara(key, ECC_NewPara(paraId));
if (ret != CRYPT_SUCCESS) {
ECC_FreeCtx(key);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
*ecKey = (void *)key;
return CRYPT_SUCCESS;
}
int32_t CRYPT_ECC_ParseSubPubkeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, void **pubKey, bool isComplete)
{
if (buff == NULL || buffLen == 0 || pubKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_DECODE_SubPubkeyInfo subPubkeyInfo = {0};
void *pctx = NULL;
int32_t ret = CRYPT_DECODE_SubPubkey(buff, buffLen, NULL, &subPubkeyInfo, isComplete);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (subPubkeyInfo.keyType != BSL_CID_EC_PUBLICKEY) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH);
return CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH;
}
ret = EccKeyNew(libCtx, &subPubkeyInfo.keyParam, &pctx);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BSL_Param pubParam[2] = {
{CRYPT_PARAM_EC_PUBKEY, BSL_PARAM_TYPE_OCTETS, subPubkeyInfo.pubKey.buff,
subPubkeyInfo.pubKey.len, 0},
BSL_PARAM_END
};
ret = ECC_PkeySetPubKeyEx(pctx, pubParam);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
ECC_FreeCtx(pctx);
return ret;
}
*pubKey = (void *)pctx;
return ret;
}
int32_t CRYPT_ECC_ParsePrikeyAsn1Buff(void *libCtx, uint8_t *buffer, uint32_t bufferLen, BSL_ASN1_Buffer *pk8AlgoParam,
void **ecPriKey)
{
if (buffer == NULL || bufferLen == 0 || ecPriKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_DECODE_EccPrikeyInfo eccPrvInfo = {0};
int32_t ret = ParsePrikeyAsn1Info(buffer, bufferLen, pk8AlgoParam, &eccPrvInfo);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
void *pctx = NULL;
ret = EccKeyNew(libCtx, &eccPrvInfo.param, &pctx);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BSL_Param pubParam[2] = {
{CRYPT_PARAM_EC_PUBKEY, BSL_PARAM_TYPE_OCTETS, (eccPrvInfo.pubkey.buff + 1),
eccPrvInfo.pubkey.len - 1, 0},
BSL_PARAM_END
};
ret = ECC_PkeySetPubKeyEx(pctx, pubParam);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
BSL_Param prvParam[2] = {
{CRYPT_PARAM_EC_PRVKEY, BSL_PARAM_TYPE_OCTETS, eccPrvInfo.prikey.buff, eccPrvInfo.prikey.len, 0},
BSL_PARAM_END
};
ret = ECC_PkeySetPrvKeyEx(pctx, prvParam);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
*ecPriKey = pctx;
return ret;
ERR:
ECC_FreeCtx(pctx);
return ret;
}
int32_t CRYPT_ECC_ParsePkcs8Key(void *libCtx, uint8_t *buff, uint32_t buffLen, void **ecdsaPriKey)
{
CRYPT_ENCODE_DECODE_Pk8PrikeyInfo pk8PrikeyInfo = {0};
int32_t ret = CRYPT_DECODE_Pkcs8Info(buff, buffLen, NULL, &pk8PrikeyInfo);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (pk8PrikeyInfo.keyType != BSL_CID_EC_PUBLICKEY) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH);
return CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH;
}
ret = CRYPT_ECC_ParsePrikeyAsn1Buff(libCtx, pk8PrikeyInfo.pkeyRawKey, pk8PrikeyInfo.pkeyRawKeyLen,
&pk8PrikeyInfo.keyParam, ecdsaPriKey);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
#endif // HITLS_CRYPTO_ECDSA
#ifdef HITLS_CRYPTO_SM2
static int32_t Sm2KeyNew(void *libCtx, BSL_ASN1_Buffer *ecParamOid, CRYPT_SM2_Ctx **ecKey)
{
CRYPT_SM2_Ctx *key = NULL;
int32_t paraId = GetParaId(ecParamOid->buff, ecParamOid->len);
if (paraId != CRYPT_ECC_SM2) {
return CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH;
}
key = CRYPT_SM2_NewCtxEx(libCtx);
if (key == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
*ecKey = key;
return CRYPT_SUCCESS;
}
int32_t CRYPT_SM2_ParseSubPubkeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, CRYPT_SM2_Ctx **pubKey,
bool isComplete)
{
if (buff == NULL || buffLen == 0 || pubKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_DECODE_SubPubkeyInfo subPubkeyInfo = {0};
CRYPT_SM2_Ctx *pctx = NULL;
int32_t ret = CRYPT_DECODE_SubPubkey(buff, buffLen, NULL, &subPubkeyInfo, isComplete);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (subPubkeyInfo.keyType != BSL_CID_EC_PUBLICKEY && subPubkeyInfo.keyType != BSL_CID_SM2PRIME256) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH);
return CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH;
}
ret = Sm2KeyNew(libCtx, &subPubkeyInfo.keyParam, &pctx);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BSL_Param pubParam[2] = {
{CRYPT_PARAM_EC_PUBKEY, BSL_PARAM_TYPE_OCTETS, subPubkeyInfo.pubKey.buff,
subPubkeyInfo.pubKey.len, 0},
BSL_PARAM_END
};
ret = CRYPT_SM2_SetPubKeyEx(pctx, pubParam);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
CRYPT_SM2_FreeCtx(pctx);
return ret;
}
*pubKey = pctx;
return ret;
}
int32_t CRYPT_SM2_ParsePrikeyAsn1Buff(void *libCtx, uint8_t *buffer, uint32_t bufferLen, BSL_ASN1_Buffer *pk8AlgoParam,
CRYPT_SM2_Ctx **sm2PriKey)
{
CRYPT_DECODE_EccPrikeyInfo eccPrvInfo = {0};
int32_t ret = ParsePrikeyAsn1Info(buffer, bufferLen, pk8AlgoParam, &eccPrvInfo);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
CRYPT_SM2_Ctx *pctx = NULL;
ret = Sm2KeyNew(libCtx, &eccPrvInfo.param, &pctx);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BSL_Param pubParam[2] = {
{CRYPT_PARAM_EC_PUBKEY, BSL_PARAM_TYPE_OCTETS, eccPrvInfo.pubkey.buff + 1,
eccPrvInfo.pubkey.len - 1, 0},
BSL_PARAM_END
};
ret = CRYPT_SM2_SetPubKeyEx(pctx, pubParam);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
BSL_Param prvParam[2] = {
{CRYPT_PARAM_EC_PRVKEY, BSL_PARAM_TYPE_OCTETS, eccPrvInfo.prikey.buff, eccPrvInfo.prikey.len, 0},
BSL_PARAM_END
};
ret = CRYPT_SM2_SetPrvKeyEx(pctx, prvParam);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
*sm2PriKey = pctx;
return ret;
ERR:
CRYPT_SM2_FreeCtx(pctx);
return ret;
}
int32_t CRYPT_SM2_ParsePkcs8Key(void *libCtx, uint8_t *buff, uint32_t buffLen, CRYPT_SM2_Ctx **sm2PriKey)
{
CRYPT_ENCODE_DECODE_Pk8PrikeyInfo pk8PrikeyInfo = {0};
int32_t ret = CRYPT_DECODE_Pkcs8Info(buff, buffLen, NULL, &pk8PrikeyInfo);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (pk8PrikeyInfo.keyType != BSL_CID_EC_PUBLICKEY) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH);
return CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH;
}
ret = CRYPT_SM2_ParsePrikeyAsn1Buff(libCtx, pk8PrikeyInfo.pkeyRawKey, pk8PrikeyInfo.pkeyRawKeyLen,
&pk8PrikeyInfo.keyParam, sm2PriKey);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
#endif // HITLS_CRYPTO_SM2
#ifdef HITLS_CRYPTO_ED25519
static int32_t ParseEd25519PrikeyAsn1Buff(void *libCtx, uint8_t *buffer, uint32_t bufferLen,
CRYPT_CURVE25519_Ctx **ed25519PriKey)
{
uint8_t *tmpBuff = buffer;
uint32_t tmpBuffLen = bufferLen;
int32_t ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_OCTETSTRING, &tmpBuff, &tmpBuffLen, &tmpBuffLen);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
CRYPT_CURVE25519_Ctx *pctx = CRYPT_ED25519_NewCtxEx(libCtx);
if (pctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
BSL_Param prvParam[2] = {
{CRYPT_PARAM_CURVE25519_PRVKEY, BSL_PARAM_TYPE_OCTETS, tmpBuff, tmpBuffLen, 0},
BSL_PARAM_END
};
ret = CRYPT_CURVE25519_SetPrvKeyEx(pctx, prvParam);
if (ret != CRYPT_SUCCESS) {
CRYPT_CURVE25519_FreeCtx(pctx);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
*ed25519PriKey = pctx;
return CRYPT_SUCCESS;
}
int32_t CRYPT_ED25519_ParsePkcs8Key(void *libCtx, uint8_t *buffer, uint32_t bufferLen,
CRYPT_CURVE25519_Ctx **ed25519PriKey)
{
CRYPT_ENCODE_DECODE_Pk8PrikeyInfo pk8PrikeyInfo = {0};
int32_t ret = CRYPT_DECODE_Pkcs8Info(buffer, bufferLen, NULL, &pk8PrikeyInfo);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (pk8PrikeyInfo.keyType != BSL_CID_ED25519) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH);
return CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH;
}
return ParseEd25519PrikeyAsn1Buff(libCtx, pk8PrikeyInfo.pkeyRawKey, pk8PrikeyInfo.pkeyRawKeyLen, ed25519PriKey);
}
int32_t CRYPT_ED25519_ParseSubPubkeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen,
CRYPT_CURVE25519_Ctx **pubKey, bool isComplete)
{
if (buff == NULL || buffLen == 0 || pubKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_DECODE_SubPubkeyInfo subPubkeyInfo = {0};
int32_t ret = CRYPT_DECODE_SubPubkey(buff, buffLen, NULL, &subPubkeyInfo, isComplete);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (subPubkeyInfo.keyType != BSL_CID_ED25519) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH);
return CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH;
}
CRYPT_CURVE25519_Ctx *pctx = CRYPT_ED25519_NewCtxEx(libCtx);
if (pctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
BSL_Param pubParam[2] = {
{CRYPT_PARAM_CURVE25519_PUBKEY, BSL_PARAM_TYPE_OCTETS, subPubkeyInfo.pubKey.buff, subPubkeyInfo.pubKey.len, 0},
BSL_PARAM_END
};
ret = CRYPT_CURVE25519_SetPubKeyEx(pctx, pubParam);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
CRYPT_CURVE25519_FreeCtx(pctx);
return ret;
}
*pubKey = pctx;
return ret;
}
#endif // HITLS_CRYPTO_ED25519
#endif // HITLS_CRYPTO_KEY_DECODE
|
2301_79861745/bench_create
|
crypto/codecskey/src/crypt_decode_ecc.c
|
C
|
unknown
| 14,282
|
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_CODECSKEY) && defined(HITLS_CRYPTO_KEY_EPKI) && defined(HITLS_CRYPTO_PROVIDER)
#include <string.h>
#include "crypt_eal_implprovider.h"
#include "crypt_params_key.h"
#include "crypt_errno.h"
#include "bsl_types.h"
#include "bsl_params.h"
#include "bsl_err_internal.h"
#include "crypt_encode_decode_local.h"
#include "crypt_decode_key_impl.h"
typedef struct DECODER_EPki2PkiCtx {
CRYPT_EAL_LibCtx *libCtx;
const char *attrName;
const char *outFormat;
const char *outType;
} DECODER_EPki2PkiCtx;
void *DECODER_EPKI2PKI_NewCtx(void *provCtx)
{
(void)provCtx;
DECODER_EPki2PkiCtx *ctx = (DECODER_EPki2PkiCtx *)BSL_SAL_Calloc(1, sizeof(DECODER_EPki2PkiCtx));
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
ctx->outFormat = "ASN1";
ctx->outType = "PRIKEY_PKCS8_UNENCRYPT";
return ctx;
}
int32_t DECODER_EPKI2PKI_GetParam(void *ctx, BSL_Param *param)
{
DECODER_EPki2PkiCtx *decoderCtx = (DECODER_EPki2PkiCtx *)ctx;
if (decoderCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
DECODER_CommonCtx commonCtx = {
.outFormat = decoderCtx->outFormat,
.outType = decoderCtx->outType
};
return DECODER_CommonGetParam(&commonCtx, param);
}
int32_t DECODER_EPKI2PKI_SetParam(void *ctx, const BSL_Param *param)
{
DECODER_EPki2PkiCtx *decoderCtx = (DECODER_EPki2PkiCtx *)ctx;
if (decoderCtx == NULL || param == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
const BSL_Param *attrNameParam = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_DECODE_TARGET_ATTR_NAME);
if (attrNameParam != NULL) {
if (attrNameParam->valueType != BSL_PARAM_TYPE_OCTETS_PTR) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
decoderCtx->attrName = (const char *)attrNameParam->value;
}
const BSL_Param *libCtxParam = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_DECODE_LIB_CTX);
if (libCtxParam != NULL) {
if (libCtxParam->valueType != BSL_PARAM_TYPE_CTX_PTR) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
decoderCtx->libCtx = (CRYPT_EAL_LibCtx *)(uintptr_t)libCtxParam->value;
}
return CRYPT_SUCCESS;
}
int32_t DECODER_EPKI2PKI_Decode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam)
{
DECODER_EPki2PkiCtx *decoderCtx = (DECODER_EPki2PkiCtx *)ctx;
if (decoderCtx == NULL || inParam == NULL || outParam == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
const BSL_Param *inputParam = BSL_PARAM_FindConstParam(inParam, CRYPT_PARAM_DECODE_BUFFER_DATA);
if (inputParam == NULL || inputParam->value == NULL || inputParam->valueType != BSL_PARAM_TYPE_OCTETS) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
const BSL_Param *passParam = BSL_PARAM_FindConstParam(inParam, CRYPT_PARAM_DECODE_PASSWORD);
if (passParam == NULL || passParam->valueType != BSL_PARAM_TYPE_OCTETS) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
BSL_Buffer input = {(uint8_t *)(uintptr_t)inputParam->value, inputParam->valueLen};
BSL_Buffer pwdBuff = {(uint8_t *)(uintptr_t)passParam->value, passParam->valueLen};
BSL_Buffer decode = {NULL, 0};
int32_t ret = CRYPT_DECODE_Pkcs8PrvDecrypt(decoderCtx->libCtx, decoderCtx->attrName, &input,
&pwdBuff, NULL, &decode);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
return CRYPT_DECODE_ConstructBufferOutParam(outParam, decode.data, decode.dataLen);
}
void DECODER_EPKI2PKI_FreeCtx(void *ctx)
{
if (ctx == NULL) {
return;
}
BSL_SAL_Free(ctx);
}
void DECODER_EPKI2PKI_FreeOutData(void *ctx, BSL_Param *outParam)
{
(void)ctx;
if (outParam == NULL) {
return;
}
BSL_Param *dataParam = BSL_PARAM_FindParam(outParam, CRYPT_PARAM_DECODE_BUFFER_DATA);
if (dataParam == NULL) {
return;
}
BSL_SAL_ClearFree(dataParam->value, dataParam->valueLen);
BSL_SAL_Free(outParam);
}
#endif /* HITLS_CRYPTO_CODECSKEY && HITLS_CRYPTO_EPKI2PKI && HITLS_CRYPTO_PROVIDER */
|
2301_79861745/bench_create
|
crypto/codecskey/src/crypt_decode_epki2pki.c
|
C
|
unknown
| 4,914
|
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_CODECSKEY) && defined(HITLS_CRYPTO_PROVIDER)
#include "crypt_eal_implprovider.h"
#include "crypt_eal_pkey.h"
#include "crypt_provider.h"
#include "crypt_params_key.h"
#include "crypt_types.h"
#include "crypt_errno.h"
#include "crypt_utils.h"
#include "eal_pkey.h"
#include "crypt_decode_key_impl.h"
#include "bsl_err_internal.h"
typedef struct {
CRYPT_EAL_LibCtx *libCtx;
const char *targetAttrName;
const char *outFormat;
const char *outType;
} DECODER_Lowkey2PkeyCtx;
void *DECODER_LowKeyObject2PkeyObjectNewCtx(void *provCtx)
{
(void)provCtx;
DECODER_Lowkey2PkeyCtx *ctx = (DECODER_Lowkey2PkeyCtx *)BSL_SAL_Calloc(1, sizeof(DECODER_Lowkey2PkeyCtx));
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
ctx->outFormat = "OBJECT";
ctx->outType = "HIGH_KEY";
return (void *)ctx;
}
int32_t DECODER_LowKeyObject2PkeyObjectSetParam(void *ctx, const BSL_Param *param)
{
DECODER_Lowkey2PkeyCtx *decoderCtx = (DECODER_Lowkey2PkeyCtx *)ctx;
if (decoderCtx == NULL || param == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
const BSL_Param *libCtxParam = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_DECODE_LIB_CTX);
if (libCtxParam != NULL) {
if (libCtxParam->valueType != BSL_PARAM_TYPE_CTX_PTR) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
decoderCtx->libCtx = (CRYPT_EAL_LibCtx *)(uintptr_t)libCtxParam->value;
}
const BSL_Param *targetAttrNameParam = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_DECODE_TARGET_ATTR_NAME);
if (targetAttrNameParam != NULL) {
if (targetAttrNameParam->valueType != BSL_PARAM_TYPE_OCTETS_PTR) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
decoderCtx->targetAttrName = (const char *)(uintptr_t)targetAttrNameParam->value;
}
return CRYPT_SUCCESS;
}
int32_t DECODER_LowKeyObject2PkeyObjectGetParam(void *ctx, BSL_Param *param)
{
DECODER_Lowkey2PkeyCtx *decoderCtx = (DECODER_Lowkey2PkeyCtx *)ctx;
if (decoderCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
DECODER_CommonCtx commonCtx = {
.outFormat = decoderCtx->outFormat,
.outType = decoderCtx->outType
};
return DECODER_CommonGetParam(&commonCtx, param);
}
typedef struct LowKeyObjectMethodInfo {
CRYPT_EAL_ImplPkeyMgmtExport export;
CRYPT_EAL_ImplPkeyMgmtDupCtx dupCtx;
CRYPT_EAL_ImplPkeyMgmtFreeCtx freeCtx;
} LowKeyObjectMethodInfo;
static int32_t GetLowKeyObjectInfo(const BSL_Param *inParam, void **object, int32_t *objectType,
LowKeyObjectMethodInfo *method)
{
const BSL_Param *lowObjectRef = BSL_PARAM_FindConstParam(inParam, CRYPT_PARAM_DECODE_OBJECT_DATA);
if (lowObjectRef == NULL || lowObjectRef->valueType != BSL_PARAM_TYPE_CTX_PTR) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
const BSL_Param *lowObjectRefType = BSL_PARAM_FindConstParam(inParam, CRYPT_PARAM_DECODE_OBJECT_TYPE);
if (lowObjectRefType == NULL || lowObjectRefType->valueType != BSL_PARAM_TYPE_INT32) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
const BSL_Param *exportFunc = BSL_PARAM_FindConstParam(inParam, CRYPT_PARAM_DECODE_PKEY_EXPORT_METHOD_FUNC);
if (exportFunc == NULL || exportFunc->valueType != BSL_PARAM_TYPE_FUNC_PTR) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
const BSL_Param *dupFunc = BSL_PARAM_FindConstParam(inParam, CRYPT_PARAM_DECODE_PKEY_DUP_METHOD_FUNC);
if (dupFunc == NULL || dupFunc->valueType != BSL_PARAM_TYPE_FUNC_PTR) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
const BSL_Param *freeFunc = BSL_PARAM_FindConstParam(inParam, CRYPT_PARAM_DECODE_PKEY_FREE_METHOD_FUNC);
if (freeFunc == NULL || freeFunc->valueType != BSL_PARAM_TYPE_FUNC_PTR) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
if (lowObjectRef->value == NULL || lowObjectRefType->value == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
*object = (void *)(uintptr_t)lowObjectRef->value;
*objectType = *((int32_t *)(uintptr_t)lowObjectRefType->value);
method->export = (CRYPT_EAL_ImplPkeyMgmtExport)(uintptr_t)exportFunc->value;
method->dupCtx = (CRYPT_EAL_ImplPkeyMgmtDupCtx)(uintptr_t)dupFunc->value;
method->freeCtx = (CRYPT_EAL_ImplPkeyMgmtFreeCtx)(uintptr_t)freeFunc->value;
return CRYPT_SUCCESS;
}
static int32_t GetProviderInfo(const BSL_Param *inParam, CRYPT_EAL_ProvMgrCtx **lastDecoderProviderCtx)
{
const BSL_Param *lastDecoderProvCtxParam = BSL_PARAM_FindConstParam(inParam, CRYPT_PARAM_DECODE_PROVIDER_CTX);
if (lastDecoderProvCtxParam != NULL) {
if (lastDecoderProvCtxParam->valueType != BSL_PARAM_TYPE_CTX_PTR) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
*lastDecoderProviderCtx = (CRYPT_EAL_ProvMgrCtx *)(uintptr_t)lastDecoderProvCtxParam->value;
}
return CRYPT_SUCCESS;
}
typedef struct {
CRYPT_EAL_PkeyMgmtInfo *pkeyAlgInfo;
void *targetKeyRef;
} ImportTargetPkeyArgs;
static int32_t ImportTargetPkey(const BSL_Param *param, void *args)
{
if (param == NULL || args == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
ImportTargetPkeyArgs *importTargetPkeyArgs = (ImportTargetPkeyArgs *)args;
void *provCtx = NULL;
CRYPT_EAL_PkeyMgmtInfo *pkeyAlgInfo = importTargetPkeyArgs->pkeyAlgInfo;
if (pkeyAlgInfo == NULL || pkeyAlgInfo->keyMgmtMethod->provNewCtx == NULL ||
pkeyAlgInfo->keyMgmtMethod->import == NULL || pkeyAlgInfo->keyMgmtMethod->freeCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret = CRYPT_EAL_ProviderCtrl(pkeyAlgInfo->mgrCtx, CRYPT_PROVIDER_GET_USER_CTX, &provCtx, sizeof(provCtx));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
void *keyRef = pkeyAlgInfo->keyMgmtMethod->provNewCtx(provCtx, pkeyAlgInfo->algId);
if (keyRef == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
ret = pkeyAlgInfo->keyMgmtMethod->import(keyRef, param);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
pkeyAlgInfo->keyMgmtMethod->freeCtx(keyRef);
return ret;
}
importTargetPkeyArgs->targetKeyRef = keyRef;
return CRYPT_SUCCESS;
}
static int32_t TransLowKeyToTargetLowKey(CRYPT_EAL_PkeyMgmtInfo *pkeyAlgInfo, const LowKeyObjectMethodInfo *method,
void *lowObjectRef, void **targetKeyRef)
{
ImportTargetPkeyArgs importTargetPkeyArgs = {0};
importTargetPkeyArgs.pkeyAlgInfo = pkeyAlgInfo;
if (method->export == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
BSL_Param param[3] = {
{CRYPT_PARAM_PKEY_PROCESS_FUNC, BSL_PARAM_TYPE_FUNC_PTR, ImportTargetPkey, 0, 0},
{CRYPT_PARAM_PKEY_PROCESS_ARGS, BSL_PARAM_TYPE_CTX_PTR, &importTargetPkeyArgs, 0, 0},
BSL_PARAM_END
};
int32_t ret = method->export(lowObjectRef, param);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
*targetKeyRef = importTargetPkeyArgs.targetKeyRef;
return CRYPT_SUCCESS;
}
static int32_t DupLowKey(const LowKeyObjectMethodInfo *method, void *lowObjectRef, void **targetKeyRef)
{
if (method->dupCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
*targetKeyRef = method->dupCtx(lowObjectRef);
if (*targetKeyRef == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
return CRYPT_SUCCESS;
}
static int32_t ConstructOutObjectParam(BSL_Param **outParam, void *object)
{
BSL_Param *result = BSL_SAL_Calloc(2, sizeof(BSL_Param));
if (result == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
int32_t ret = BSL_PARAM_InitValue(&result[0], CRYPT_PARAM_DECODE_OBJECT_DATA, BSL_PARAM_TYPE_CTX_PTR,
object, 0);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_Free(result);
BSL_ERR_PUSH_ERROR(ret);
}
*outParam = result;
return ret;
}
/* input is pem format buffer, output is der format buffer */
int32_t DECODER_LowKeyObject2PkeyObjectDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam)
{
if (ctx == NULL || inParam == NULL || outParam == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
DECODER_Lowkey2PkeyCtx *decoderCtx = (DECODER_Lowkey2PkeyCtx *)ctx;
void *lowObjectRef = NULL;
int32_t lowObjectRefType = 0;
CRYPT_EAL_ProvMgrCtx *lastDecoderProviderCtx = NULL;
LowKeyObjectMethodInfo method = {0};
void *targetKeyRef = NULL;
CRYPT_EAL_PkeyMgmtInfo pkeyAlgInfo = {0};
int32_t ret = 0;
RETURN_RET_IF_ERR(GetLowKeyObjectInfo(inParam, &lowObjectRef, &lowObjectRefType, &method), ret);
if (method.freeCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
RETURN_RET_IF_ERR(GetProviderInfo(inParam, &lastDecoderProviderCtx), ret);
RETURN_RET_IF_ERR(CRYPT_EAL_GetPkeyAlgInfo(decoderCtx->libCtx, lowObjectRefType, decoderCtx->targetAttrName,
&pkeyAlgInfo), ret);
if (pkeyAlgInfo.mgrCtx != lastDecoderProviderCtx) {
ret = TransLowKeyToTargetLowKey(&pkeyAlgInfo, &method, lowObjectRef, &targetKeyRef);
} else {
ret = DupLowKey(&method, lowObjectRef, &targetKeyRef);
}
if (ret != CRYPT_SUCCESS) {
goto EXIT;
}
CRYPT_EAL_PkeyCtx *ealPKey = CRYPT_EAL_MakeKeyByPkeyAlgInfo(&pkeyAlgInfo, targetKeyRef, sizeof(void *));
if (ealPKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
goto EXIT;
}
ret = ConstructOutObjectParam(outParam, ealPKey);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_PkeyFreeCtx(ealPKey);
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
EXIT:
BSL_SAL_Free(pkeyAlgInfo.keyMgmtMethod);
if (targetKeyRef != NULL) {
method.freeCtx(targetKeyRef);
}
return ret;
}
void DECODER_LowKeyObject2PkeyObjectFreeOutData(void *ctx, BSL_Param *outParam)
{
DECODER_Lowkey2PkeyCtx *decoderCtx = (DECODER_Lowkey2PkeyCtx *)ctx;
if (outParam == NULL || decoderCtx == NULL) {
return;
}
BSL_Param *objectDataParam = BSL_PARAM_FindParam(outParam, CRYPT_PARAM_DECODE_OBJECT_DATA);
if (objectDataParam == NULL || objectDataParam->valueType != BSL_PARAM_TYPE_CTX_PTR ||
objectDataParam->value == NULL) {
return;
}
CRYPT_EAL_PkeyCtx *ealPKey = (CRYPT_EAL_PkeyCtx *)objectDataParam->value;
CRYPT_EAL_PkeyFreeCtx(ealPKey);
BSL_SAL_Free(outParam);
}
void DECODER_LowKeyObject2PkeyObjectFreeCtx(void *ctx)
{
if (ctx == NULL) {
return;
}
BSL_SAL_Free(ctx);
}
#endif
|
2301_79861745/bench_create
|
crypto/codecskey/src/crypt_decode_lowkey2pkey.c
|
C
|
unknown
| 11,815
|
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_CODECSKEY) && defined(HITLS_BSL_PEM) && defined(HITLS_CRYPTO_PROVIDER)
#include <stdint.h>
#include <string.h>
#include "crypt_eal_implprovider.h"
#include "crypt_errno.h"
#include "crypt_params_key.h"
#include "bsl_sal.h"
#include "bsl_err_internal.h"
#include "bsl_pem_internal.h"
#include "crypt_encode_decode_local.h"
#include "crypt_decode_key_impl.h"
typedef struct {
void *provCtx;
const char *outFormat;
const char *outType;
} DECODER_Pem2DerCtx;
void *DECODER_Pem2DerNewCtx(void *provCtx)
{
(void)provCtx;
DECODER_Pem2DerCtx *ctx = (DECODER_Pem2DerCtx *)BSL_SAL_Calloc(1, sizeof(DECODER_Pem2DerCtx));
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
ctx->provCtx = provCtx;
ctx->outFormat = "ASN1";
ctx->outType = NULL;
return ctx;
}
int32_t DECODER_Pem2DerGetParam(void *ctx, BSL_Param *param)
{
DECODER_Pem2DerCtx *decoderCtx = (DECODER_Pem2DerCtx *)ctx;
if (decoderCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
DECODER_CommonCtx commonCtx = {
.outFormat = decoderCtx->outFormat,
.outType = decoderCtx->outType
};
return DECODER_CommonGetParam(&commonCtx, param);
}
int32_t DECODER_Pem2DerSetParam(void *ctx, const BSL_Param *param)
{
(void)ctx;
(void)param;
return CRYPT_SUCCESS;
}
/* input is pem format buffer, output is der format buffer */
int32_t DECODER_Pem2DerDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam)
{
if (ctx == NULL || inParam == NULL || outParam == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
BSL_PEM_Symbol symbol = {0};
char *dataType = NULL;
DECODER_Pem2DerCtx *decoderCtx = (DECODER_Pem2DerCtx *)ctx;
const BSL_Param *input = BSL_PARAM_FindConstParam(inParam, CRYPT_PARAM_DECODE_BUFFER_DATA);
if (input == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (input->value == NULL || input->valueLen == 0 || input->valueType != BSL_PARAM_TYPE_OCTETS) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
BSL_Buffer encode = {(uint8_t *)(uintptr_t)input->value, input->valueLen};
uint8_t *asn1Encode = NULL;
uint32_t asn1Len = 0;
int32_t ret = BSL_PEM_GetSymbolAndType((char *)encode.data, encode.dataLen, &symbol, &dataType);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = BSL_PEM_DecodePemToAsn1((char **)&encode.data, &encode.dataLen, &symbol, &asn1Encode, &asn1Len);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_Free(asn1Encode);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
decoderCtx->outType = dataType;
return CRYPT_DECODE_ConstructBufferOutParam(outParam, asn1Encode, asn1Len);
}
void DECODER_Pem2DerFreeOutData(void *ctx, BSL_Param *outParam)
{
(void)ctx;
if (outParam == NULL) {
return;
}
BSL_Param *asn1DataParam = BSL_PARAM_FindParam(outParam, CRYPT_PARAM_DECODE_BUFFER_DATA);
if (asn1DataParam == NULL) {
return;
}
BSL_SAL_Free(asn1DataParam->value);
asn1DataParam->value = NULL;
asn1DataParam->valueLen = 0;
BSL_SAL_Free(outParam);
}
void DECODER_Pem2DerFreeCtx(void *ctx)
{
if (ctx == NULL) {
return;
}
BSL_SAL_Free(ctx);
}
#endif /* HITLS_CRYPTO_CODECSKEY && HITLS_BSL_PEM && HITLS_CRYPTO_PROVIDER */
|
2301_79861745/bench_create
|
crypto/codecskey/src/crypt_decode_pem2der.c
|
C
|
unknown
| 4,088
|
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_CODECSKEY)
#include "securec.h"
#include "bsl_sal.h"
#include "bsl_list.h"
#include "sal_file.h"
#include "bsl_err_internal.h"
#include "crypt_errno.h"
#include "crypt_eal_provider.h"
#include "crypt_eal_implprovider.h"
#include "crypt_eal_codecs.h"
#include "crypt_provider.h"
#include "crypt_eal_pkey.h"
#include "bsl_types.h"
#include "crypt_types.h"
#include "crypt_utils.h"
#include "eal_pkey.h"
#include "crypt_encode_decode_local.h"
#include "crypt_encode_decode_key.h"
#if defined(HITLS_CRYPTO_PROVIDER)
static int32_t SetDecodePoolParamForKey(CRYPT_DECODER_PoolCtx *poolCtx, char *targetType, char *targetFormat)
{
int32_t ret = CRYPT_DECODE_PoolCtrl(poolCtx, CRYPT_DECODE_POOL_CMD_SET_TARGET_FORMAT, targetFormat,
(int32_t)strlen(targetFormat));
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = CRYPT_DECODE_PoolCtrl(poolCtx, CRYPT_DECODE_POOL_CMD_SET_TARGET_TYPE, targetType,
(int32_t)strlen(targetType));
if (ret != CRYPT_SUCCESS) {
return ret;
}
return ret;
}
static int32_t GetObjectFromOutData(BSL_Param *outData, void **object)
{
if (outData == NULL || object == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
BSL_Param *param = BSL_PARAM_FindParam(outData, CRYPT_PARAM_DECODE_OBJECT_DATA);
if (param == NULL || param->valueType != BSL_PARAM_TYPE_CTX_PTR || param->value == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
*object = param->value;
return CRYPT_SUCCESS;
}
int32_t CRYPT_EAL_ProviderDecodeBuffKeyInner(CRYPT_EAL_LibCtx *libCtx, const char *attrName, int32_t keyType,
const char *format, const char *type, BSL_Buffer *encode, const BSL_Buffer *pwd, CRYPT_EAL_PkeyCtx **ealPKey)
{
char *targetType = "HIGH_KEY";
char *targetFormat = "OBJECT";
uint32_t index = 0;
BSL_Param *outParam = NULL;
bool isFreeOutData = false;
BSL_Param input[3] = {{0}, {0}, BSL_PARAM_END};
CRYPT_EAL_PkeyCtx *tmpPKey = NULL;
if (encode == NULL || encode->data == NULL || encode->dataLen == 0 || ealPKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_DECODER_PoolCtx *poolCtx = CRYPT_DECODE_PoolNewCtx(libCtx, attrName, keyType, format, type);
if (poolCtx == NULL) {
return CRYPT_MEM_ALLOC_FAIL;
}
int32_t ret = SetDecodePoolParamForKey(poolCtx, targetType, targetFormat);
if (ret != CRYPT_SUCCESS) {
goto EXIT;
}
(void)BSL_PARAM_InitValue(&input[index++], CRYPT_PARAM_DECODE_BUFFER_DATA, BSL_PARAM_TYPE_OCTETS, encode->data,
encode->dataLen);
if (pwd != NULL) {
(void)BSL_PARAM_InitValue(&input[index++], CRYPT_PARAM_DECODE_PASSWORD, BSL_PARAM_TYPE_OCTETS, pwd->data,
pwd->dataLen);
}
ret = CRYPT_DECODE_PoolDecode(poolCtx, input, &outParam);
if (ret != CRYPT_SUCCESS) {
goto EXIT;
}
ret = GetObjectFromOutData(outParam, (void **)(&tmpPKey));
if (ret != CRYPT_SUCCESS) {
goto EXIT;
}
int32_t algId = CRYPT_EAL_PkeyGetId(tmpPKey);
if (keyType != BSL_CID_UNKNOWN && algId != keyType) {
ret = CRYPT_EAL_ERR_ALGID;
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_ALGID);
goto EXIT;
}
ret = CRYPT_DECODE_PoolCtrl(poolCtx, CRYPT_DECODE_POOL_CMD_SET_FLAG_FREE_OUT_DATA, &isFreeOutData, sizeof(bool));
if (ret != CRYPT_SUCCESS) {
goto EXIT;
}
*ealPKey = tmpPKey;
BSL_SAL_Free(outParam);
EXIT:
CRYPT_DECODE_PoolFreeCtx(poolCtx);
return ret;
}
#endif /* HITLS_CRYPTO_PROVIDER */
int32_t CRYPT_EAL_ProviderDecodeBuffKey(CRYPT_EAL_LibCtx *libCtx, const char *attrName, int32_t keyType,
const char *format, const char *type, BSL_Buffer *encode, const BSL_Buffer *pwd, CRYPT_EAL_PkeyCtx **ealPKey)
{
#ifdef HITLS_CRYPTO_PROVIDER
return CRYPT_EAL_ProviderDecodeBuffKeyInner(libCtx, attrName, keyType, format, type, encode, pwd, ealPKey);
#else
(void)libCtx;
(void)attrName;
(void)keyType;
int32_t encodeType = CRYPT_EAL_GetEncodeType(type);
int32_t encodeFormat = CRYPT_EAL_GetEncodeFormat(format);
if (pwd == NULL) {
return CRYPT_EAL_DecodeBuffKey(encodeFormat, encodeType, encode, NULL, 0, ealPKey);
} else {
return CRYPT_EAL_DecodeBuffKey(encodeFormat, encodeType, encode, pwd->data, pwd->dataLen, ealPKey);
}
#endif
}
#ifdef HITLS_BSL_SAL_FILE
int32_t CRYPT_EAL_ProviderDecodeFileKey(CRYPT_EAL_LibCtx *libCtx, const char *attrName, int32_t keyType,
const char *format, const char *type, const char *path, const BSL_Buffer *pwd, CRYPT_EAL_PkeyCtx **ealPKey)
{
if (path == NULL || strlen(path) > PATH_MAX_LEN) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
uint8_t *data = NULL;
uint32_t dataLen = 0;
int32_t ret = BSL_SAL_ReadFile(path, &data, &dataLen);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BSL_Buffer encode = {data, dataLen};
ret = CRYPT_EAL_ProviderDecodeBuffKey(libCtx, attrName, keyType, format, type, &encode, pwd, ealPKey);
BSL_SAL_Free(data);
return ret;
}
#endif /* HITLS_BSL_SAL_FILE */
#endif /* HITLS_CRYPTO_CODECSKEY */
|
2301_79861745/bench_create
|
crypto/codecskey/src/crypt_decode_pkey.c
|
C
|
unknown
| 5,857
|
/*
* 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_KEY_DECODE) && defined(HITLS_CRYPTO_RSA)
#include "crypt_rsa.h"
#include "bsl_asn1_internal.h"
#include "bsl_params.h"
#include "bsl_errno.h"
#include "bsl_err_internal.h"
#include "crypt_errno.h"
#include "crypt_params_key.h"
#include "crypt_encode_decode_local.h"
#include "crypt_encode_decode_key.h"
static int32_t ProcRsaPubKey(const BSL_ASN1_Buffer *asn1, CRYPT_RSA_Ctx *rsaKey)
{
const BSL_Param param[3] = {
{CRYPT_PARAM_RSA_E, BSL_PARAM_TYPE_OCTETS, asn1[CRYPT_RSA_PRV_E_IDX].buff,
asn1[CRYPT_RSA_PRV_E_IDX].len, 0},
{CRYPT_PARAM_RSA_N, BSL_PARAM_TYPE_OCTETS, asn1[CRYPT_RSA_PRV_N_IDX].buff,
asn1[CRYPT_RSA_PRV_N_IDX].len, 0},
BSL_PARAM_END
};
return CRYPT_RSA_SetPubKeyEx(rsaKey, param);
}
static int32_t ProcRsaPrivKey(const BSL_ASN1_Buffer *asn1, CRYPT_RSA_Ctx *rsaKey)
{
const BSL_Param param[10] = {
{CRYPT_PARAM_RSA_D, BSL_PARAM_TYPE_OCTETS, asn1[CRYPT_RSA_PRV_D_IDX].buff,
asn1[CRYPT_RSA_PRV_D_IDX].len, 0},
{CRYPT_PARAM_RSA_N, BSL_PARAM_TYPE_OCTETS, asn1[CRYPT_RSA_PRV_N_IDX].buff,
asn1[CRYPT_RSA_PRV_N_IDX].len, 0},
{CRYPT_PARAM_RSA_E, BSL_PARAM_TYPE_OCTETS, asn1[CRYPT_RSA_PRV_E_IDX].buff,
asn1[CRYPT_RSA_PRV_E_IDX].len, 0},
{CRYPT_PARAM_RSA_P, BSL_PARAM_TYPE_OCTETS, asn1[CRYPT_RSA_PRV_P_IDX].buff,
asn1[CRYPT_RSA_PRV_P_IDX].len, 0},
{CRYPT_PARAM_RSA_Q, BSL_PARAM_TYPE_OCTETS, asn1[CRYPT_RSA_PRV_Q_IDX].buff,
asn1[CRYPT_RSA_PRV_Q_IDX].len, 0},
{CRYPT_PARAM_RSA_DP, BSL_PARAM_TYPE_OCTETS, asn1[CRYPT_RSA_PRV_DP_IDX].buff,
asn1[CRYPT_RSA_PRV_DP_IDX].len, 0},
{CRYPT_PARAM_RSA_DQ, BSL_PARAM_TYPE_OCTETS, asn1[CRYPT_RSA_PRV_DQ_IDX].buff,
asn1[CRYPT_RSA_PRV_DQ_IDX].len, 0},
{CRYPT_PARAM_RSA_QINV, BSL_PARAM_TYPE_OCTETS, asn1[CRYPT_RSA_PRV_QINV_IDX].buff,
asn1[CRYPT_RSA_PRV_QINV_IDX].len, 0},
BSL_PARAM_END
};
return CRYPT_RSA_SetPrvKeyEx(rsaKey, param);
}
static int32_t ProcRsaKeyPair(uint8_t *buff, uint32_t buffLen, CRYPT_RSA_Ctx *rsaKey)
{
// decode n and e
BSL_ASN1_Buffer asn1[CRYPT_RSA_PRV_OTHER_PRIME_IDX + 1] = {0};
int32_t ret = CRYPT_DECODE_RsaPrikeyAsn1Buff(buff, buffLen, asn1, CRYPT_RSA_PRV_OTHER_PRIME_IDX + 1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = ProcRsaPrivKey(asn1, rsaKey);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
return ProcRsaPubKey(asn1, rsaKey);
}
static int32_t ProcRsaPssParam(BSL_ASN1_Buffer *rsaPssParam, CRYPT_RSA_Ctx *rsaPriKey)
{
CRYPT_RsaPadType padType = CRYPT_EMSA_PSS;
int32_t ret = CRYPT_RSA_Ctrl(rsaPriKey, CRYPT_CTRL_SET_RSA_PADDING, &padType, sizeof(CRYPT_RsaPadType));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (rsaPssParam == NULL || rsaPssParam->buff == NULL) {
return CRYPT_SUCCESS;
}
CRYPT_RSA_PssPara para = {0};
ret = CRYPT_EAL_ParseRsaPssAlgParam(rsaPssParam, ¶);
if (ret != CRYPT_SUCCESS) {
return ret;
}
BSL_Param param[4] = {
{CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, ¶.mdId, sizeof(para.mdId), 0},
{CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, ¶.mgfId, sizeof(para.mgfId), 0},
{CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, ¶.saltLen, sizeof(para.saltLen), 0},
BSL_PARAM_END};
return CRYPT_RSA_Ctrl(rsaPriKey, CRYPT_CTRL_SET_RSA_EMSA_PSS, param, 0);
}
static int32_t DecodeRsaPrikeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *rsaPssParam,
BslCid cid, CRYPT_RSA_Ctx **rsaPriKey)
{
CRYPT_RSA_Ctx *pctx = CRYPT_RSA_NewCtxEx(libCtx);
if (pctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
int32_t ret = ProcRsaKeyPair(buff, buffLen, pctx);
if (ret != CRYPT_SUCCESS) {
CRYPT_RSA_FreeCtx(pctx);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (cid != BSL_CID_RSASSAPSS) {
*rsaPriKey = pctx;
return CRYPT_SUCCESS;
}
ret = ProcRsaPssParam(rsaPssParam, pctx);
if (ret != CRYPT_SUCCESS) {
CRYPT_RSA_FreeCtx(pctx);
return ret;
}
*rsaPriKey = pctx;
return ret;
}
int32_t CRYPT_RSA_ParsePrikeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *rsaPssParam,
CRYPT_RSA_Ctx **rsaPriKey)
{
return DecodeRsaPrikeyAsn1Buff(libCtx, buff, buffLen, rsaPssParam, BSL_CID_UNKNOWN, rsaPriKey);
}
int32_t CRYPT_RSA_ParsePubkeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *param,
CRYPT_RSA_Ctx **rsaPubKey, BslCid cid)
{
// decode n and e
BSL_ASN1_Buffer pubAsn1[CRYPT_RSA_PUB_E_IDX + 1] = {0};
int32_t ret = CRYPT_DECODE_RsaPubkeyAsn1Buff(buff, buffLen, pubAsn1, CRYPT_RSA_PUB_E_IDX + 1);
if (ret != CRYPT_SUCCESS) {
return ret;
}
CRYPT_RSA_Ctx *pctx = CRYPT_RSA_NewCtxEx(libCtx);
if (pctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
BSL_Param pubParam[3] = {
{CRYPT_PARAM_RSA_E, BSL_PARAM_TYPE_OCTETS, pubAsn1[CRYPT_RSA_PUB_E_IDX].buff,
pubAsn1[CRYPT_RSA_PUB_E_IDX].len, 0},
{CRYPT_PARAM_RSA_N, BSL_PARAM_TYPE_OCTETS, pubAsn1[CRYPT_RSA_PUB_N_IDX].buff,
pubAsn1[CRYPT_RSA_PUB_N_IDX].len, 0},
BSL_PARAM_END
};
ret = CRYPT_RSA_SetPubKeyEx(pctx, pubParam);
if (cid != BSL_CID_RSASSAPSS) {
*rsaPubKey = pctx;
return CRYPT_SUCCESS;
}
ret = ProcRsaPssParam(param, pctx);
if (ret != CRYPT_SUCCESS) {
CRYPT_RSA_FreeCtx(pctx);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
*rsaPubKey = pctx;
return ret;
}
int32_t CRYPT_RSA_ParseSubPubkeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, CRYPT_RSA_Ctx **pubKey,
bool isComplete)
{
if (pubKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_DECODE_SubPubkeyInfo subPubkeyInfo = {0};
CRYPT_RSA_Ctx *pctx = NULL;
int32_t ret = CRYPT_DECODE_SubPubkey(buff, buffLen, NULL, &subPubkeyInfo, isComplete);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (subPubkeyInfo.keyType != BSL_CID_RSASSAPSS && subPubkeyInfo.keyType != BSL_CID_RSA) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH);
return CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH;
}
ret = CRYPT_RSA_ParsePubkeyAsn1Buff(libCtx, subPubkeyInfo.pubKey.buff, subPubkeyInfo.pubKey.len,
&subPubkeyInfo.keyParam, &pctx, subPubkeyInfo.keyType);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
*pubKey = pctx;
return ret;
}
int32_t CRYPT_RSA_ParsePkcs8Key(void *libCtx, uint8_t *buff, uint32_t buffLen, CRYPT_RSA_Ctx **rsaPriKey)
{
CRYPT_ENCODE_DECODE_Pk8PrikeyInfo pk8PrikeyInfo = {0};
int32_t ret = CRYPT_DECODE_Pkcs8Info(buff, buffLen, NULL, &pk8PrikeyInfo);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (pk8PrikeyInfo.keyType != BSL_CID_RSASSAPSS && pk8PrikeyInfo.keyType != BSL_CID_RSA) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH);
return CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH;
}
ret = DecodeRsaPrikeyAsn1Buff(libCtx, pk8PrikeyInfo.pkeyRawKey, pk8PrikeyInfo.pkeyRawKeyLen,
&pk8PrikeyInfo.keyParam, pk8PrikeyInfo.keyType, rsaPriKey);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
#endif // HITLS_CRYPTO_KEY_DECODE && HITLS_CRYPTO_RSA
|
2301_79861745/bench_create
|
crypto/codecskey/src/crypt_decode_rsa.c
|
C
|
unknown
| 8,338
|
/*
* 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_CODECSKEY
#include <stdint.h>
#include <string.h>
#ifdef HITLS_BSL_SAL_FILE
#include "sal_file.h"
#endif
#include "bsl_types.h"
#include "bsl_asn1_internal.h"
#ifdef HITLS_BSL_PEM
#include "bsl_pem_internal.h"
#endif // HITLS_BSL_PEM
#include "bsl_err_internal.h"
#include "crypt_errno.h"
#include "crypt_types.h"
#include "crypt_eal_pkey.h"
#include "crypt_eal_codecs.h"
#include "crypt_encode_decode_local.h"
#include "crypt_encode_decode_key.h"
int32_t CRYPT_EAL_GetEncodeFormat(const char *format)
{
if (format == NULL) {
return BSL_FORMAT_UNKNOWN;
}
static const struct {
const char *formatStr;
int32_t formatInt;
} FORMAT_MAP[] = {
{"ASN1", BSL_FORMAT_ASN1},
{"PEM", BSL_FORMAT_PEM},
{"PFX_COM", BSL_FORMAT_PFX_COM},
{"PKCS12", BSL_FORMAT_PKCS12},
{"OBJECT", BSL_FORMAT_OBJECT}
};
for (size_t i = 0; i < sizeof(FORMAT_MAP) / sizeof(FORMAT_MAP[0]); i++) {
if (strcmp(format, FORMAT_MAP[i].formatStr) == 0) {
return FORMAT_MAP[i].formatInt;
}
}
return BSL_FORMAT_UNKNOWN;
}
#ifdef HITLS_BSL_PEM
static int32_t EAL_GetPemPubKeySymbol(int32_t type, BSL_PEM_Symbol *symbol)
{
switch (type) {
case CRYPT_PUBKEY_SUBKEY:
symbol->head = BSL_PEM_PUB_KEY_BEGIN_STR;
symbol->tail = BSL_PEM_PUB_KEY_END_STR;
return CRYPT_SUCCESS;
#ifdef HITLS_CRYPTO_RSA
case CRYPT_PUBKEY_RSA:
symbol->head = BSL_PEM_RSA_PUB_KEY_BEGIN_STR;
symbol->tail = BSL_PEM_RSA_PUB_KEY_END_STR;
return CRYPT_SUCCESS;
#endif
default:
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_NO_SUPPORT_TYPE);
return CRYPT_DECODE_NO_SUPPORT_TYPE;
}
}
static int32_t EAL_GetPemPriKeySymbol(int32_t type, BSL_PEM_Symbol *symbol)
{
switch (type) {
#ifdef HITLS_CRYPTO_ECDSA
case CRYPT_PRIKEY_ECC:
symbol->head = BSL_PEM_EC_PRI_KEY_BEGIN_STR;
symbol->tail = BSL_PEM_EC_PRI_KEY_END_STR;
return CRYPT_SUCCESS;
#endif
#ifdef HITLS_CRYPTO_RSA
case CRYPT_PRIKEY_RSA:
symbol->head = BSL_PEM_RSA_PRI_KEY_BEGIN_STR;
symbol->tail = BSL_PEM_RSA_PRI_KEY_END_STR;
return CRYPT_SUCCESS;
#endif
case CRYPT_PRIKEY_PKCS8_UNENCRYPT:
symbol->head = BSL_PEM_PRI_KEY_BEGIN_STR;
symbol->tail = BSL_PEM_PRI_KEY_END_STR;
return CRYPT_SUCCESS;
case CRYPT_PRIKEY_PKCS8_ENCRYPT:
symbol->head = BSL_PEM_P8_PRI_KEY_BEGIN_STR;
symbol->tail = BSL_PEM_P8_PRI_KEY_END_STR;
return CRYPT_SUCCESS;
default:
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_NO_SUPPORT_TYPE);
return CRYPT_DECODE_NO_SUPPORT_TYPE;
}
}
#endif // HITLS_BSL_PEM
#ifdef HITLS_CRYPTO_KEY_DECODE
int32_t CRYPT_EAL_ParseAsn1PriKey(int32_t type, BSL_Buffer *encode, const BSL_Buffer *pwd,
CRYPT_EAL_PkeyCtx **ealPriKey)
{
(void)pwd;
switch (type) {
#ifdef HITLS_CRYPTO_ECDSA
case CRYPT_PRIKEY_ECC:
return ParseEccPrikeyAsn1Buff(encode->data, encode->dataLen, NULL, ealPriKey);
#endif
#ifdef HITLS_CRYPTO_RSA
case CRYPT_PRIKEY_RSA:
return ParseRsaPrikeyAsn1Buff(encode->data, encode->dataLen, NULL, BSL_CID_UNKNOWN,
ealPriKey);
#endif
case CRYPT_PRIKEY_PKCS8_UNENCRYPT:
return ParsePk8PriKeyBuff(encode, ealPriKey);
#ifdef HITLS_CRYPTO_KEY_EPKI
case CRYPT_PRIKEY_PKCS8_ENCRYPT:
return ParsePk8EncPriKeyBuff(encode, pwd, ealPriKey);
#endif
default:
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_NO_SUPPORT_TYPE);
return CRYPT_DECODE_NO_SUPPORT_TYPE;
}
}
#ifdef HITLS_BSL_PEM
int32_t CRYPT_EAL_ParsePemPriKey(int32_t type, BSL_Buffer *encode, const BSL_Buffer *pwd,
CRYPT_EAL_PkeyCtx **ealPriKey)
{
BSL_PEM_Symbol symbol = {0};
uint8_t *buff = encode->data;
uint32_t buffLen = encode->dataLen;
int32_t ret = EAL_GetPemPriKeySymbol(type, &symbol);
if (ret != CRYPT_SUCCESS) {
return ret;
}
BSL_Buffer asn1 = {0};
ret = BSL_PEM_DecodePemToAsn1((char **)&buff, &buffLen, &symbol, &(asn1.data),
&(asn1.dataLen));
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = CRYPT_EAL_ParseAsn1PriKey(type, &asn1, pwd, ealPriKey);
BSL_SAL_Free(asn1.data);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
#endif // HITLS_BSL_PEM
int32_t CRYPT_EAL_ParseUnknownPriKey(int32_t type, BSL_Buffer *encode, const BSL_Buffer *pwd,
CRYPT_EAL_PkeyCtx **ealPriKey)
{
#ifdef HITLS_BSL_PEM
bool isPem = BSL_PEM_IsPemFormat((char *)(encode->data), encode->dataLen);
if (isPem) {
return CRYPT_EAL_ParsePemPriKey(type, encode, pwd, ealPriKey);
}
#endif
return CRYPT_EAL_ParseAsn1PriKey(type, encode, pwd, ealPriKey);
}
int32_t CRYPT_EAL_PriKeyParseBuff(BSL_ParseFormat format, int32_t type, BSL_Buffer *encode, const BSL_Buffer *pwd,
CRYPT_EAL_PkeyCtx **ealPriKey)
{
if (encode == NULL || encode->data == NULL || encode->dataLen == 0 || ealPriKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
switch (format) {
case BSL_FORMAT_ASN1:
return CRYPT_EAL_ParseAsn1PriKey(type, encode, pwd, ealPriKey);
#ifdef HITLS_BSL_PEM
case BSL_FORMAT_PEM:
return CRYPT_EAL_ParsePemPriKey(type, encode, pwd, ealPriKey);
#endif // HITLS_BSL_PEM
case BSL_FORMAT_UNKNOWN:
return CRYPT_EAL_ParseUnknownPriKey(type, encode, pwd, ealPriKey);
default:
return CRYPT_DECODE_NO_SUPPORT_FORMAT;
}
}
int32_t CRYPT_EAL_ParseAsn1PubKey(int32_t type, BSL_Buffer *encode, CRYPT_EAL_PkeyCtx **ealPubKey)
{
switch (type) {
case CRYPT_PUBKEY_SUBKEY_WITHOUT_SEQ:
return CRYPT_EAL_ParseAsn1SubPubkey(encode->data, encode->dataLen, (void **)ealPubKey, false);
case CRYPT_PUBKEY_SUBKEY:
return CRYPT_EAL_ParseAsn1SubPubkey(encode->data, encode->dataLen, (void **)ealPubKey, true);
default:
#ifdef HITLS_CRYPTO_RSA
return ParseRsaPubkeyAsn1Buff(encode->data, encode->dataLen, NULL, ealPubKey, BSL_CID_UNKNOWN);
#else
return CRYPT_DECODE_NO_SUPPORT_TYPE;
#endif
}
}
#ifdef HITLS_BSL_PEM
int32_t CRYPT_EAL_ParsePemPubKey(int32_t type, BSL_Buffer *encode, CRYPT_EAL_PkeyCtx **ealPubKey)
{
BSL_PEM_Symbol symbol = {0};
int32_t ret = EAL_GetPemPubKeySymbol(type, &symbol);
if (ret != CRYPT_SUCCESS) {
return ret;
}
BSL_Buffer asn1 = {0};
ret = BSL_PEM_DecodePemToAsn1((char **)&(encode->data), &(encode->dataLen), &symbol, &(asn1.data), &(asn1.dataLen));
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = CRYPT_EAL_ParseAsn1PubKey(type, &asn1, ealPubKey);
BSL_SAL_Free(asn1.data);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
#endif // HITLS_BSL_PEM
int32_t CRYPT_EAL_ParseUnknownPubKey(int32_t type, BSL_Buffer *encode, CRYPT_EAL_PkeyCtx **ealPubKey)
{
#ifdef HITLS_BSL_PEM
bool isPem = BSL_PEM_IsPemFormat((char *)(encode->data), encode->dataLen);
if (isPem) {
return CRYPT_EAL_ParsePemPubKey(type, encode, ealPubKey);
}
#endif
return CRYPT_EAL_ParseAsn1PubKey(type, encode, ealPubKey);
}
int32_t CRYPT_EAL_PubKeyParseBuff(BSL_ParseFormat format, int32_t type, BSL_Buffer *encode,
CRYPT_EAL_PkeyCtx **ealPubKey)
{
if (encode == NULL || encode->data == NULL || encode->dataLen == 0 || ealPubKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
switch (format) {
case BSL_FORMAT_ASN1:
return CRYPT_EAL_ParseAsn1PubKey(type, encode, ealPubKey);
#ifdef HITLS_BSL_PEM
case BSL_FORMAT_PEM:
return CRYPT_EAL_ParsePemPubKey(type, encode, ealPubKey);
#endif // HITLS_BSL_PEM
case BSL_FORMAT_UNKNOWN:
return CRYPT_EAL_ParseUnknownPubKey(type, encode, ealPubKey);
default:
return CRYPT_DECODE_NO_SUPPORT_FORMAT;
}
}
int32_t CRYPT_EAL_UnKnownKeyParseBuff(BSL_ParseFormat format, const BSL_Buffer *pwd, BSL_Buffer *encode,
CRYPT_EAL_PkeyCtx **ealPKey)
{
int32_t ret;
for (int32_t type = CRYPT_PRIKEY_PKCS8_UNENCRYPT; type <= CRYPT_PRIKEY_ECC; type++) {
ret = CRYPT_EAL_PriKeyParseBuff(format, type, encode, pwd, ealPKey);
if (ret == CRYPT_SUCCESS) {
return ret;
}
}
for (int32_t type = CRYPT_PUBKEY_SUBKEY; type <= CRYPT_PUBKEY_SUBKEY_WITHOUT_SEQ; type++) {
ret = CRYPT_EAL_PubKeyParseBuff(format, type, encode, ealPKey);
if (ret == CRYPT_SUCCESS) {
return ret;
}
}
return CRYPT_DECODE_NO_SUPPORT_TYPE;
}
int32_t CRYPT_EAL_DecodeBuffKey(int32_t format, int32_t type, BSL_Buffer *encode,
const uint8_t *pwd, uint32_t pwdlen, CRYPT_EAL_PkeyCtx **ealPKey)
{
BSL_Buffer pwdBuffer = {(uint8_t *)(uintptr_t)pwd, pwdlen};
switch (type) {
case CRYPT_PRIKEY_PKCS8_UNENCRYPT:
case CRYPT_PRIKEY_PKCS8_ENCRYPT:
#ifdef HITLS_CRYPTO_ECDSA
case CRYPT_PRIKEY_ECC:
#endif
#ifdef HITLS_CRYPTO_RSA
case CRYPT_PRIKEY_RSA:
#endif
return CRYPT_EAL_PriKeyParseBuff(format, type, encode, &pwdBuffer, ealPKey);
case CRYPT_PUBKEY_SUBKEY_WITHOUT_SEQ:
case CRYPT_PUBKEY_SUBKEY:
#ifdef HITLS_CRYPTO_RSA
case CRYPT_PUBKEY_RSA:
#endif
return CRYPT_EAL_PubKeyParseBuff(format, type, encode, ealPKey);
case CRYPT_ENCDEC_UNKNOW:
return CRYPT_EAL_UnKnownKeyParseBuff(format, &pwdBuffer, encode, ealPKey);
default:
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_NO_SUPPORT_TYPE);
return CRYPT_DECODE_NO_SUPPORT_TYPE;
}
}
#ifdef HITLS_BSL_SAL_FILE
int32_t CRYPT_EAL_PriKeyParseFile(BSL_ParseFormat format, int32_t type, const char *path, const BSL_Buffer *pwd,
CRYPT_EAL_PkeyCtx **ealPriKey)
{
uint8_t *data = NULL;
uint32_t dataLen = 0;
int32_t ret = BSL_SAL_ReadFile(path, &data, &dataLen);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BSL_Buffer encode = {data, dataLen};
ret = CRYPT_EAL_PriKeyParseBuff(format, type, &encode, pwd, ealPriKey);
BSL_SAL_Free(data);
return ret;
}
int32_t CRYPT_EAL_PubKeyParseFile(BSL_ParseFormat format, int32_t type, const char *path, CRYPT_EAL_PkeyCtx **ealPubKey)
{
uint8_t *data = NULL;
uint32_t dataLen = 0;
int32_t ret = BSL_SAL_ReadFile(path, &data, &dataLen);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BSL_Buffer encode = {data, dataLen};
ret = CRYPT_EAL_PubKeyParseBuff(format, type, &encode, ealPubKey);
BSL_SAL_Free(data);
return ret;
}
int32_t CRYPT_EAL_UnKnownKeyParseFile(BSL_ParseFormat format, const char *path, const BSL_Buffer *pwd,
CRYPT_EAL_PkeyCtx **ealKey)
{
uint8_t *data = NULL;
uint32_t dataLen = 0;
int32_t ret = BSL_SAL_ReadFile(path, &data, &dataLen);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BSL_Buffer encode = {data, dataLen};
ret = CRYPT_EAL_UnKnownKeyParseBuff(format, pwd, &encode, ealKey);
BSL_SAL_Free(data);
return ret;
}
int32_t CRYPT_EAL_DecodeFileKey(int32_t format, int32_t type, const char *path,
uint8_t *pwd, uint32_t pwdlen, CRYPT_EAL_PkeyCtx **ealPKey)
{
BSL_Buffer pwdBuffer = {(uint8_t *)pwd, pwdlen};
if (path == NULL || strlen(path) > PATH_MAX_LEN) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
switch (type) {
case CRYPT_PRIKEY_PKCS8_UNENCRYPT:
case CRYPT_PRIKEY_PKCS8_ENCRYPT:
#ifdef HITLS_CRYPTO_RSA
case CRYPT_PRIKEY_RSA:
#endif
#ifdef HITLS_CRYPTO_ECDSA
case CRYPT_PRIKEY_ECC:
#endif
return CRYPT_EAL_PriKeyParseFile(format, type, path, &pwdBuffer, ealPKey);
case CRYPT_PUBKEY_SUBKEY_WITHOUT_SEQ:
case CRYPT_PUBKEY_SUBKEY:
#ifdef HITLS_CRYPTO_RSA
case CRYPT_PUBKEY_RSA:
return CRYPT_EAL_PubKeyParseFile(format, type, path, ealPKey);
#endif
case CRYPT_ENCDEC_UNKNOW:
return CRYPT_EAL_UnKnownKeyParseFile(format, path, &pwdBuffer, ealPKey);
default:
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_NO_SUPPORT_TYPE);
return CRYPT_DECODE_NO_SUPPORT_TYPE;
}
}
#endif // HITLS_BSL_SAL_FILE
#endif // HITLS_CRYPTO_KEY_DECODE
int32_t CRYPT_EAL_GetEncodeType(const char *type)
{
if (type == NULL) {
return CRYPT_ENCDEC_UNKNOW;
}
static const struct {
const char *typeStr;
int32_t typeInt;
} TYPE_MAP[] = {
{"PRIKEY_PKCS8_UNENCRYPT", CRYPT_PRIKEY_PKCS8_UNENCRYPT},
{"PRIKEY_PKCS8_ENCRYPT", CRYPT_PRIKEY_PKCS8_ENCRYPT},
{"PRIKEY_RSA", CRYPT_PRIKEY_RSA},
{"PRIKEY_ECC", CRYPT_PRIKEY_ECC},
{"PUBKEY_SUBKEY", CRYPT_PUBKEY_SUBKEY},
{"PUBKEY_RSA", CRYPT_PUBKEY_RSA},
{"PUBKEY_SUBKEY_WITHOUT_SEQ", CRYPT_PUBKEY_SUBKEY_WITHOUT_SEQ}
};
for (size_t i = 0; i < sizeof(TYPE_MAP) / sizeof(TYPE_MAP[0]); i++) {
if (strcmp(type, TYPE_MAP[i].typeStr) == 0) {
return TYPE_MAP[i].typeInt;
}
}
return CRYPT_ENCDEC_UNKNOW;
}
#ifdef HITLS_CRYPTO_KEY_ENCODE
int32_t CRYPT_EAL_EncodeAsn1PriKey(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_EAL_PkeyCtx *ealPriKey,
const CRYPT_EncodeParam *encodeParam, int32_t type, BSL_Buffer *encode)
{
#ifndef HITLS_CRYPTO_KEY_EPKI
(void)libCtx;
(void)attrName;
(void)encodeParam;
#endif
switch (type) {
#ifdef HITLS_CRYPTO_ECDSA
case CRYPT_PRIKEY_ECC:
return EncodeEccPrikeyAsn1Buff(ealPriKey, NULL, encode);
#endif
#ifdef HITLS_CRYPTO_RSA
case CRYPT_PRIKEY_RSA:
return EncodeRsaPrikeyAsn1Buff(ealPriKey, CRYPT_PKEY_RSA, encode);
#endif
case CRYPT_PRIKEY_PKCS8_UNENCRYPT:
return EncodePk8PriKeyBuff(ealPriKey, encode);
#ifdef HITLS_CRYPTO_KEY_EPKI
case CRYPT_PRIKEY_PKCS8_ENCRYPT:
return EncodePk8EncPriKeyBuff(libCtx, attrName, ealPriKey, encodeParam, encode);
#endif
default:
BSL_ERR_PUSH_ERROR(CRYPT_ENCODE_NO_SUPPORT_FORMAT);
return CRYPT_ENCODE_NO_SUPPORT_FORMAT;
}
}
#ifdef HITLS_BSL_PEM
int32_t CRYPT_EAL_EncodePemPriKey(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_EAL_PkeyCtx *ealPriKey,
const CRYPT_EncodeParam *encodeParam, int32_t type, BSL_Buffer *encode)
{
BSL_Buffer asn1 = {0};
int32_t ret = CRYPT_EAL_EncodeAsn1PriKey(libCtx, attrName, ealPriKey, encodeParam, type, &asn1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BSL_PEM_Symbol symbol = {0};
ret = EAL_GetPemPriKeySymbol(type, &symbol);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_Free(asn1.data);
return ret;
}
ret = BSL_PEM_EncodeAsn1ToPem(asn1.data, asn1.dataLen, &symbol, (char **)&encode->data, &encode->dataLen);
BSL_SAL_Free(asn1.data);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
#endif // HITLS_BSL_PEM
int32_t CRYPT_EAL_PriKeyEncodeBuff(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_EAL_PkeyCtx *ealPriKey,
const CRYPT_EncodeParam *encodeParam, BSL_ParseFormat format, int32_t type, BSL_Buffer *encode)
{
if (ealPriKey == NULL || encode == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
switch (format) {
case BSL_FORMAT_ASN1:
return CRYPT_EAL_EncodeAsn1PriKey(libCtx, attrName, ealPriKey, encodeParam, type, encode);
#ifdef HITLS_BSL_PEM
case BSL_FORMAT_PEM:
return CRYPT_EAL_EncodePemPriKey(libCtx, attrName, ealPriKey, encodeParam, type, encode);
#endif // HITLS_BSL_PEM
default:
BSL_ERR_PUSH_ERROR(CRYPT_ENCODE_NO_SUPPORT_FORMAT);
return CRYPT_ENCODE_NO_SUPPORT_FORMAT;
}
}
int32_t CRYPT_EAL_PubKeyEncodeBuff(CRYPT_EAL_PkeyCtx *ealPubKey,
BSL_ParseFormat format, int32_t type, BSL_Buffer *encode)
{
return CRYPT_EAL_EncodePubKeyBuffInternal(ealPubKey, format, type, true, encode);
}
static int32_t ProviderEncodeBuffKeyInternal(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_EAL_PkeyCtx *ealPKey,
const CRYPT_EncodeParam *encodeParam, int32_t format, int32_t type, BSL_Buffer *encode)
{
switch (type) {
case CRYPT_PRIKEY_PKCS8_UNENCRYPT:
case CRYPT_PRIKEY_PKCS8_ENCRYPT:
#ifdef HITLS_CRYPTO_RSA
case CRYPT_PRIKEY_RSA:
#endif
#ifdef HITLS_CRYPTO_ECDSA
case CRYPT_PRIKEY_ECC:
#endif
return CRYPT_EAL_PriKeyEncodeBuff(libCtx, attrName, ealPKey, encodeParam, format, type, encode);
case CRYPT_PUBKEY_SUBKEY:
#ifdef HITLS_CRYPTO_RSA
case CRYPT_PUBKEY_RSA:
#endif
return CRYPT_EAL_PubKeyEncodeBuff(ealPKey, format, type, encode);
default:
BSL_ERR_PUSH_ERROR(CRYPT_ENCODE_NO_SUPPORT_TYPE);
return CRYPT_ENCODE_NO_SUPPORT_TYPE;
}
}
int32_t CRYPT_EAL_ProviderEncodeBuffKey(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_EAL_PkeyCtx *ealPKey,
const CRYPT_EncodeParam *encodeParam, const char *format, const char *type, BSL_Buffer *encode)
{
int32_t encodeType = CRYPT_EAL_GetEncodeType(type);
int32_t encodeFormat = CRYPT_EAL_GetEncodeFormat(format);
return ProviderEncodeBuffKeyInternal(libCtx, attrName, ealPKey, encodeParam, encodeFormat, encodeType, encode);
}
int32_t CRYPT_EAL_EncodeBuffKey(CRYPT_EAL_PkeyCtx *ealPKey, const CRYPT_EncodeParam *encodeParam,
int32_t format, int32_t type, BSL_Buffer *encode)
{
return ProviderEncodeBuffKeyInternal(NULL, NULL, ealPKey, encodeParam, format, type, encode);
}
static int32_t CRYPT_EAL_EncodeAsn1PubKey(CRYPT_EAL_PkeyCtx *ealPubKey,
int32_t type, bool isComplete, BSL_Buffer *encode)
{
switch (type) {
case CRYPT_PUBKEY_SUBKEY:
return CRYPT_EAL_EncodeAsn1SubPubkey(ealPubKey, isComplete, encode);
#ifdef HITLS_CRYPTO_RSA
case CRYPT_PUBKEY_RSA:
return EncodeRsaPubkeyAsn1Buff(ealPubKey, NULL, encode);
#endif
default:
BSL_ERR_PUSH_ERROR(CRYPT_ENCODE_NO_SUPPORT_TYPE);
return CRYPT_ENCODE_NO_SUPPORT_TYPE;
}
}
#ifdef HITLS_BSL_PEM
static int32_t CRYPT_EAL_EncodePemPubKey(CRYPT_EAL_PkeyCtx *ealPubKey,
int32_t type, bool isComplete, BSL_Buffer *encode)
{
BSL_Buffer asn1 = {0};
int32_t ret = CRYPT_EAL_EncodeAsn1PubKey(ealPubKey, type, isComplete, &asn1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BSL_PEM_Symbol symbol = {0};
ret = EAL_GetPemPubKeySymbol(type, &symbol);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_Free(asn1.data);
return ret;
}
ret = BSL_PEM_EncodeAsn1ToPem(asn1.data, asn1.dataLen, &symbol, (char **)&encode->data, &encode->dataLen);
BSL_SAL_Free(asn1.data);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
#endif // HITLS_BSL_PEM
int32_t CRYPT_EAL_EncodePubKeyBuffInternal(CRYPT_EAL_PkeyCtx *ealPubKey,
BSL_ParseFormat format, int32_t type, bool isComplete, BSL_Buffer *encode)
{
if (ealPubKey == NULL || encode == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
switch (format) {
case BSL_FORMAT_ASN1:
return CRYPT_EAL_EncodeAsn1PubKey(ealPubKey, type, isComplete, encode);
#ifdef HITLS_BSL_PEM
case BSL_FORMAT_PEM:
return CRYPT_EAL_EncodePemPubKey(ealPubKey, type, isComplete, encode);
#endif // HITLS_BSL_PEM
default:
BSL_ERR_PUSH_ERROR(CRYPT_ENCODE_NO_SUPPORT_FORMAT);
return CRYPT_ENCODE_NO_SUPPORT_FORMAT;
}
}
#ifdef HITLS_BSL_SAL_FILE
int32_t CRYPT_EAL_PriKeyEncodeFile(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_EAL_PkeyCtx *ealPriKey,
const CRYPT_EncodeParam *encodeParam, BSL_ParseFormat format, int32_t type, const char *path)
{
BSL_Buffer encode = {0};
int32_t ret = CRYPT_EAL_PriKeyEncodeBuff(libCtx, attrName, ealPriKey, encodeParam, format, type, &encode);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = BSL_SAL_WriteFile(path, encode.data, encode.dataLen);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
BSL_SAL_Free(encode.data);
return ret;
}
int32_t CRYPT_EAL_PubKeyEncodeFile(CRYPT_EAL_PkeyCtx *ealPubKey, BSL_ParseFormat format, int32_t type, const char *path)
{
BSL_Buffer encode = {0};
int32_t ret = CRYPT_EAL_PubKeyEncodeBuff(ealPubKey, format, type, &encode);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = BSL_SAL_WriteFile(path, encode.data, encode.dataLen);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
BSL_SAL_FREE(encode.data);
return ret;
}
static int32_t ProviderEncodeFileKeyInternal(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_EAL_PkeyCtx *ealPKey,
const CRYPT_EncodeParam *encodeParam, int32_t format, int32_t type, const char *path)
{
if (path == NULL || strlen(path) > PATH_MAX_LEN) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
switch (type) {
case CRYPT_PRIKEY_PKCS8_UNENCRYPT:
case CRYPT_PRIKEY_PKCS8_ENCRYPT:
#ifdef HITLS_CRYPTO_RSA
case CRYPT_PRIKEY_RSA:
#endif
#ifdef HITLS_CRYPTO_ECDSA
case CRYPT_PRIKEY_ECC:
#endif
return CRYPT_EAL_PriKeyEncodeFile(libCtx, attrName, ealPKey, encodeParam, format, type, path);
case CRYPT_PUBKEY_SUBKEY:
#ifdef HITLS_CRYPTO_RSA
case CRYPT_PUBKEY_RSA:
#endif
return CRYPT_EAL_PubKeyEncodeFile(ealPKey, format, type, path);
default:
BSL_ERR_PUSH_ERROR(CRYPT_ENCODE_NO_SUPPORT_TYPE);
return CRYPT_ENCODE_NO_SUPPORT_TYPE;
}
}
int32_t CRYPT_EAL_ProviderEncodeFileKey(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_EAL_PkeyCtx *ealPKey,
const CRYPT_EncodeParam *encodeParam, const char *format, const char *type, const char *path)
{
int32_t encodeType = CRYPT_EAL_GetEncodeType(type);
int32_t encodeFormat = CRYPT_EAL_GetEncodeFormat(format);
return ProviderEncodeFileKeyInternal(libCtx, attrName, ealPKey, encodeParam, encodeFormat, encodeType, path);
}
int32_t CRYPT_EAL_EncodeFileKey(CRYPT_EAL_PkeyCtx *ealPKey, const CRYPT_EncodeParam *encodeParam,
int32_t format, int32_t type, const char *path)
{
return ProviderEncodeFileKeyInternal(NULL, NULL, ealPKey, encodeParam, format, type, path);
}
#endif // HITLS_BSL_SAL_FILE
#endif // HITLS_CRYPTO_KEY_ENCODE
#endif // HITLS_CRYPTO_CODECSKEY
|
2301_79861745/bench_create
|
crypto/codecskey/src/crypt_encode_decode.c
|
C
|
unknown
| 23,492
|
/*
* 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_CODECSKEY
#include "securec.h"
#include "bsl_asn1_internal.h"
#include "bsl_params.h"
#include "bsl_err_internal.h"
#include "bsl_obj_internal.h"
#include "crypt_errno.h"
#include "crypt_algid.h"
#include "crypt_eal_kdf.h"
#include "crypt_eal_rand.h"
#include "crypt_eal_cipher.h"
#include "crypt_params_key.h"
#include "crypt_encode_decode_key.h"
#include "crypt_encode_decode_local.h"
#if defined(HITLS_CRYPTO_KEY_EPKI) && defined(HITLS_CRYPTO_KEY_ENCODE)
/**
* EncryptedPrivateKeyInfo ::= SEQUENCE {
* encryptionAlgorithm EncryptionAlgorithmIdentifier,
* encryptedData EncryptedData }
*
* https://datatracker.ietf.org/doc/html/rfc5208#autoid-6
*/
static BSL_ASN1_TemplateItem g_pk8EncPriKeyTempl[] = {
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0},
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, // EncryptionAlgorithmIdentifier
{BSL_ASN1_TAG_OBJECT_ID, 0, 2},
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 2},
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 3}, // derivation param
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 3}, // enc scheme
{BSL_ASN1_TAG_OBJECT_ID, 0, 4}, // alg
{BSL_ASN1_TAG_OCTETSTRING, 0, 4}, // iv
{BSL_ASN1_TAG_OCTETSTRING, 0, 1}, // EncryptedData
};
#endif // HITLS_CRYPTO_KEY_EPKI && HITLS_CRYPTO_KEY_ENCODE
#if defined(HITLS_CRYPTO_RSA) && (defined(HITLS_CRYPTO_KEY_ENCODE) || defined(HITLS_CRYPTO_KEY_INFO))
int32_t CRYPT_EAL_GetRsaPssPara(CRYPT_EAL_PkeyCtx *ealPriKey, CRYPT_RSA_PssPara *rsaPssParam)
{
int32_t ret;
ret = CRYPT_EAL_PkeyCtrl(ealPriKey, CRYPT_CTRL_GET_RSA_SALTLEN, &rsaPssParam->saltLen,
sizeof(rsaPssParam->saltLen));
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = CRYPT_EAL_PkeyCtrl(ealPriKey, CRYPT_CTRL_GET_RSA_MD, &rsaPssParam->mdId, sizeof(rsaPssParam->mdId));
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = CRYPT_EAL_PkeyCtrl(ealPriKey, CRYPT_CTRL_GET_RSA_MGF, &rsaPssParam->mgfId, sizeof(rsaPssParam->mgfId));
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
#ifdef HITLS_CRYPTO_KEY_ENCODE
int32_t CRYPT_EAL_InitRsaPrv(const CRYPT_EAL_PkeyCtx *ealPriKey, CRYPT_PKEY_AlgId cid, CRYPT_EAL_PkeyPrv *rsaPrv)
{
uint32_t bnLen = CRYPT_EAL_PkeyGetKeyLen(ealPriKey);
if (bnLen == 0) {
return CRYPT_EAL_ALG_NOT_SUPPORT;
}
uint8_t *pri = (uint8_t *)BSL_SAL_Malloc(bnLen * 8); // 8 items
if (pri == NULL) {
return CRYPT_MEM_ALLOC_FAIL;
}
rsaPrv->id = cid;
rsaPrv->key.rsaPrv.d = pri;
rsaPrv->key.rsaPrv.n = pri + bnLen;
rsaPrv->key.rsaPrv.p = pri + bnLen * 2; // 2nd buffer
rsaPrv->key.rsaPrv.q = pri + bnLen * 3; // 3rd buffer
rsaPrv->key.rsaPrv.dP = pri + bnLen * 4; // 4th buffer
rsaPrv->key.rsaPrv.dQ = pri + bnLen * 5; // 5th buffer
rsaPrv->key.rsaPrv.qInv = pri + bnLen * 6; // 6th buffer
rsaPrv->key.rsaPrv.e = pri + bnLen * 7; // 7th buffer
rsaPrv->key.rsaPrv.dLen = bnLen;
rsaPrv->key.rsaPrv.nLen = bnLen;
rsaPrv->key.rsaPrv.pLen = bnLen;
rsaPrv->key.rsaPrv.qLen = bnLen;
rsaPrv->key.rsaPrv.dPLen = bnLen;
rsaPrv->key.rsaPrv.dQLen = bnLen;
rsaPrv->key.rsaPrv.qInvLen = bnLen;
rsaPrv->key.rsaPrv.eLen = bnLen;
return CRYPT_SUCCESS;
}
void CRYPT_EAL_DeinitRsaPrv(CRYPT_EAL_PkeyPrv *rsaPrv)
{
BSL_SAL_ClearFree(rsaPrv->key.rsaPrv.d, rsaPrv->key.rsaPrv.dLen * 8); // 8 items
}
#endif // HITLS_CRYPTO_KEY_ENCODE
#endif // HITLS_CRYPTO_RSA
#ifdef HITLS_CRYPTO_KEY_DECODE
#ifdef HITLS_CRYPTO_RSA
static int32_t ProcRsaPssParam(BSL_ASN1_Buffer *rsaPssParam, CRYPT_EAL_PkeyCtx *ealPriKey)
{
CRYPT_RsaPadType padType = CRYPT_EMSA_PSS;
int32_t ret = CRYPT_EAL_PkeyCtrl(ealPriKey, CRYPT_CTRL_SET_RSA_PADDING, &padType, sizeof(CRYPT_RsaPadType));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (rsaPssParam == NULL || rsaPssParam->buff == NULL) {
return CRYPT_SUCCESS;
}
CRYPT_RSA_PssPara para = {0};
ret = CRYPT_EAL_ParseRsaPssAlgParam(rsaPssParam, ¶);
if (ret != CRYPT_SUCCESS) {
return ret;
}
BSL_Param param[4] = {
{CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, ¶.mdId, sizeof(para.mdId), 0},
{CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, ¶.mgfId, sizeof(para.mgfId), 0},
{CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, ¶.saltLen, sizeof(para.saltLen), 0},
BSL_PARAM_END};
return CRYPT_EAL_PkeyCtrl(ealPriKey, CRYPT_CTRL_SET_RSA_EMSA_PSS, param, 0);
}
static int32_t SetRsaPubKey(const BSL_ASN1_Buffer *n, const BSL_ASN1_Buffer *e, CRYPT_EAL_PkeyCtx *ealPkey)
{
CRYPT_EAL_PkeyPub rsaPub = {
.id = CRYPT_PKEY_RSA, .key.rsaPub = {.n = n->buff, .nLen = n->len, .e = e->buff, .eLen = e->len}};
return CRYPT_EAL_PkeySetPub(ealPkey, &rsaPub);
}
int32_t ParseRsaPubkeyAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *param, CRYPT_EAL_PkeyCtx **ealPubKey,
BslCid cid)
{
// decode n and e
BSL_ASN1_Buffer pubAsn1[CRYPT_RSA_PUB_E_IDX + 1] = {0};
int32_t ret = CRYPT_DECODE_RsaPubkeyAsn1Buff(buff, buffLen, pubAsn1, CRYPT_RSA_PUB_E_IDX + 1);
if (ret != CRYPT_SUCCESS) {
return ret;
}
CRYPT_EAL_PkeyCtx *pctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_RSA);
if (pctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
ret = SetRsaPubKey(pubAsn1 + CRYPT_RSA_PUB_N_IDX, pubAsn1 + CRYPT_RSA_PUB_E_IDX, pctx);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_PkeyFreeCtx(pctx);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (cid != BSL_CID_RSASSAPSS) {
*ealPubKey = pctx;
return CRYPT_SUCCESS;
}
ret = ProcRsaPssParam(param, pctx);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_PkeyFreeCtx(pctx);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
*ealPubKey = pctx;
return ret;
}
static int32_t ProcEalRsaPrivKey(const BSL_ASN1_Buffer *asn1, CRYPT_EAL_PkeyCtx *ealPkey)
{
CRYPT_EAL_PkeyPrv rsaPrv = {0};
rsaPrv.id = CRYPT_PKEY_RSA;
rsaPrv.key.rsaPrv.d = asn1[CRYPT_RSA_PRV_D_IDX].buff;
rsaPrv.key.rsaPrv.dLen = asn1[CRYPT_RSA_PRV_D_IDX].len;
rsaPrv.key.rsaPrv.n = asn1[CRYPT_RSA_PRV_N_IDX].buff;
rsaPrv.key.rsaPrv.nLen = asn1[CRYPT_RSA_PRV_N_IDX].len;
rsaPrv.key.rsaPrv.e = asn1[CRYPT_RSA_PRV_E_IDX].buff;
rsaPrv.key.rsaPrv.eLen = asn1[CRYPT_RSA_PRV_E_IDX].len;
rsaPrv.key.rsaPrv.p = asn1[CRYPT_RSA_PRV_P_IDX].buff;
rsaPrv.key.rsaPrv.pLen = asn1[CRYPT_RSA_PRV_P_IDX].len;
rsaPrv.key.rsaPrv.q = asn1[CRYPT_RSA_PRV_Q_IDX].buff;
rsaPrv.key.rsaPrv.qLen = asn1[CRYPT_RSA_PRV_Q_IDX].len;
rsaPrv.key.rsaPrv.dP = asn1[CRYPT_RSA_PRV_DP_IDX].buff;
rsaPrv.key.rsaPrv.dPLen = asn1[CRYPT_RSA_PRV_DP_IDX].len;
rsaPrv.key.rsaPrv.dQ = asn1[CRYPT_RSA_PRV_DQ_IDX].buff;
rsaPrv.key.rsaPrv.dQLen = asn1[CRYPT_RSA_PRV_DQ_IDX].len;
rsaPrv.key.rsaPrv.qInv = asn1[CRYPT_RSA_PRV_QINV_IDX].buff;
rsaPrv.key.rsaPrv.qInvLen = asn1[CRYPT_RSA_PRV_QINV_IDX].len;
return CRYPT_EAL_PkeySetPrv(ealPkey, &rsaPrv);
}
static int32_t ProcEalRsaKeyPair(uint8_t *buff, uint32_t buffLen, CRYPT_EAL_PkeyCtx *ealPkey)
{
// decode n and e
BSL_ASN1_Buffer asn1[CRYPT_RSA_PRV_OTHER_PRIME_IDX + 1] = {0};
int32_t ret = CRYPT_DECODE_RsaPrikeyAsn1Buff(buff, buffLen, asn1, CRYPT_RSA_PRV_OTHER_PRIME_IDX + 1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = ProcEalRsaPrivKey(asn1, ealPkey);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
return SetRsaPubKey(asn1 + CRYPT_RSA_PRV_N_IDX, asn1 + CRYPT_RSA_PRV_E_IDX, ealPkey);
}
int32_t ParseRsaPrikeyAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *rsaPssParam, BslCid cid,
CRYPT_EAL_PkeyCtx **ealPriKey)
{
CRYPT_EAL_PkeyCtx *pctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_RSA);
if (pctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
int32_t ret = ProcEalRsaKeyPair(buff, buffLen, pctx);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_PkeyFreeCtx(pctx);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (cid != BSL_CID_RSASSAPSS) {
*ealPriKey = pctx;
return CRYPT_SUCCESS;
}
ret = ProcRsaPssParam(rsaPssParam, pctx);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_PkeyFreeCtx(pctx);
return ret;
}
*ealPriKey = pctx;
return ret;
}
#endif
#if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2)
static int32_t EccEalKeyNew(BSL_ASN1_Buffer *ecParamOid, int32_t *alg, CRYPT_EAL_PkeyCtx **ealKey)
{
int32_t algId;
BslOidString oidStr = {ecParamOid->len, (char *)ecParamOid->buff, 0};
CRYPT_PKEY_ParaId paraId = (CRYPT_PKEY_ParaId)BSL_OBJ_GetCID(&oidStr);
if (paraId == CRYPT_ECC_SM2) {
algId = CRYPT_PKEY_SM2;
} else if (IsEcdsaEcParaId(paraId)) {
algId = CRYPT_PKEY_ECDSA;
} else { // scenario ecdh is not considered, and it will be improved in the future
return CRYPT_DECODE_UNKNOWN_OID;
}
CRYPT_EAL_PkeyCtx *key = CRYPT_EAL_PkeyNewCtx(algId);
if (key == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
#ifdef HITLS_CRYPTO_ECDSA
if (paraId != CRYPT_ECC_SM2) {
int32_t ret = CRYPT_EAL_PkeySetParaById(key, paraId);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_PkeyFreeCtx(key);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
#endif
*ealKey = key;
*alg = algId;
return CRYPT_SUCCESS;
}
static int32_t ParseEccPubkeyAsn1Buff(BSL_ASN1_BitString *bitPubkey, BSL_ASN1_Buffer *ecParamOid,
CRYPT_EAL_PkeyCtx **ealPubKey)
{
int32_t algId;
CRYPT_EAL_PkeyCtx *pctx = NULL;
int32_t ret = EccEalKeyNew(ecParamOid, &algId, &pctx);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
CRYPT_EAL_PkeyPub pub = {.id = algId, .key.eccPub = {.data = bitPubkey->buff, .len = bitPubkey->len}};
ret = CRYPT_EAL_PkeySetPub(pctx, &pub);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_PkeyFreeCtx(pctx);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
*ealPubKey = pctx;
return ret;
}
static int32_t ParseEccPrikeyAsn1(BSL_ASN1_Buffer *encode, BSL_ASN1_Buffer *pk8AlgoParam, CRYPT_EAL_PkeyCtx **ealPriKey)
{
BSL_ASN1_Buffer *prikey = &encode[CRYPT_ECPRIKEY_PRIKEY_IDX]; // the ECC OID
BSL_ASN1_Buffer *ecParamOid = &encode[CRYPT_ECPRIKEY_PARAM_IDX]; // the parameters OID
BSL_ASN1_Buffer *pubkey = &encode[CRYPT_ECPRIKEY_PUBKEY_IDX]; // the ECC OID
BSL_ASN1_Buffer *param = pk8AlgoParam;
if (ecParamOid->len != 0) {
// has a valid Algorithm param
param = ecParamOid;
} else {
if (param == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (param->len == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PKCS8_INVALID_ALGO_PARAM);
return CRYPT_DECODE_PKCS8_INVALID_ALGO_PARAM;
}
}
if (pubkey->len == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ASN1_BUFF_FAILED);
return CRYPT_DECODE_ASN1_BUFF_FAILED;
}
int32_t algId;
CRYPT_EAL_PkeyCtx *pctx = NULL;
int32_t ret = EccEalKeyNew(param, &algId, &pctx); // Changed ecParamOid to param
if (ret != CRYPT_SUCCESS) {
return ret;
}
CRYPT_EAL_PkeyPrv prv = {.id = algId, .key.eccPrv = {.data = prikey->buff, .len = prikey->len}};
ret = CRYPT_EAL_PkeySetPrv(pctx, &prv);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_PkeyFreeCtx(pctx);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// the tag of public key is BSL_ASN1_TAG_BITSTRING, 1 denote unusedBits
CRYPT_EAL_PkeyPub pub = {.id = algId, .key.eccPub = {.data = pubkey->buff + 1, .len = pubkey->len - 1}};
ret = CRYPT_EAL_PkeySetPub(pctx, &pub);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_PkeyFreeCtx(pctx);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
*ealPriKey = pctx;
return ret;
}
int32_t ParseEccPrikeyAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *pk8AlgoParam,
CRYPT_EAL_PkeyCtx **ealPriKey)
{
BSL_ASN1_Buffer asn1[CRYPT_ECPRIKEY_PUBKEY_IDX + 1] = {0};
int32_t ret = CRYPT_DECODE_PrikeyAsn1Buff(buff, buffLen, asn1, CRYPT_ECPRIKEY_PUBKEY_IDX + 1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
return ParseEccPrikeyAsn1(asn1, pk8AlgoParam, ealPriKey);
}
#endif // HITLS_CRYPTO_ECDSA || HITLS_CRYPTO_SM2
#ifdef HITLS_CRYPTO_ED25519
static int32_t ParseEd25519PrikeyAsn1Buff(uint8_t *buff, uint32_t buffLen, CRYPT_EAL_PkeyCtx **ealPriKey)
{
uint8_t *tmpBuff = buff;
uint32_t tmpBuffLen = buffLen;
int32_t ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_OCTETSTRING, &tmpBuff, &tmpBuffLen, &tmpBuffLen);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
CRYPT_EAL_PkeyCtx *pctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ED25519);
if (pctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
CRYPT_EAL_PkeyPrv prv = {.id = CRYPT_PKEY_ED25519, .key.curve25519Prv = {.data = tmpBuff, .len = tmpBuffLen}};
ret = CRYPT_EAL_PkeySetPrv(pctx, &prv);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_PkeyFreeCtx(pctx);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
*ealPriKey = pctx;
return CRYPT_SUCCESS;
}
static int32_t ParseEd25519PubkeyAsn1Buff(uint8_t *buff, uint32_t buffLen, CRYPT_EAL_PkeyCtx **ealPubKey)
{
CRYPT_EAL_PkeyCtx *pctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ED25519);
if (pctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
CRYPT_EAL_PkeyPub pub = {.id = CRYPT_PKEY_ED25519, .key.curve25519Pub = {.data = buff, .len = buffLen}};
int32_t ret = CRYPT_EAL_PkeySetPub(pctx, &pub);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_PkeyFreeCtx(pctx);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
*ealPubKey = pctx;
return ret;
}
#endif // HITLS_CRYPTO_ED25519
static int32_t ParsePk8PrikeyAsn1(CRYPT_ENCODE_DECODE_Pk8PrikeyInfo *pk8PrikeyInfo, CRYPT_EAL_PkeyCtx **ealPriKey)
{
#ifdef HITLS_CRYPTO_RSA
if (pk8PrikeyInfo->keyType == BSL_CID_RSA || pk8PrikeyInfo->keyType == BSL_CID_RSASSAPSS) {
return ParseRsaPrikeyAsn1Buff(pk8PrikeyInfo->pkeyRawKey, pk8PrikeyInfo->pkeyRawKeyLen,
&pk8PrikeyInfo->keyParam, pk8PrikeyInfo->keyType, ealPriKey);
}
#endif
#if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2)
if (pk8PrikeyInfo->keyType == BSL_CID_EC_PUBLICKEY) {
return ParseEccPrikeyAsn1Buff(pk8PrikeyInfo->pkeyRawKey, pk8PrikeyInfo->pkeyRawKeyLen,
&pk8PrikeyInfo->keyParam, ealPriKey);
}
#endif
#ifdef HITLS_CRYPTO_ED25519
if (pk8PrikeyInfo->keyType == BSL_CID_ED25519) {
return ParseEd25519PrikeyAsn1Buff(pk8PrikeyInfo->pkeyRawKey, pk8PrikeyInfo->pkeyRawKeyLen,
ealPriKey);
}
#endif
return CRYPT_DECODE_UNSUPPORTED_PKCS8_TYPE;
}
int32_t ParseSubPubkeyAsn1(BSL_ASN1_Buffer *encode, CRYPT_EAL_PkeyCtx **ealPubKey)
{
uint8_t *algoBuff = encode->buff; // AlgorithmIdentifier Tag and Len, 2 bytes.
uint32_t algoBuffLen = encode->len;
BSL_ASN1_Buffer algoId[BSL_ASN1_TAG_ALGOID_ANY_IDX + 1] = {0};
int32_t ret = CRYPT_DECODE_AlgoIdAsn1Buff(algoBuff, algoBuffLen, NULL, algoId, BSL_ASN1_TAG_ALGOID_ANY_IDX + 1);
if (ret != CRYPT_SUCCESS) {
return ret;
}
BSL_ASN1_Buffer *oid = algoId; // OID
BSL_ASN1_Buffer *algParam = algoId + 1; // the parameters
BSL_ASN1_Buffer *pubkey = &encode[CRYPT_SUBKEYINFO_BITSTRING_IDX]; // the last BSL_ASN1_Buffer, the pubkey
BSL_ASN1_BitString bitPubkey = {0};
ret = BSL_ASN1_DecodePrimitiveItem(pubkey, &bitPubkey);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BslOidString oidStr = {oid->len, (char *)oid->buff, 0};
BslCid cid = BSL_OBJ_GetCID(&oidStr);
#if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2)
if (cid == BSL_CID_EC_PUBLICKEY || cid == BSL_CID_SM2PRIME256) {
return ParseEccPubkeyAsn1Buff(&bitPubkey, algParam, ealPubKey);
}
#endif
#ifdef HITLS_CRYPTO_RSA
if (cid == BSL_CID_RSA || cid == BSL_CID_RSASSAPSS) {
return ParseRsaPubkeyAsn1Buff(bitPubkey.buff, bitPubkey.len, algParam, ealPubKey, cid);
}
#endif
#ifdef HITLS_CRYPTO_ED25519
(void)algParam;
if (cid == BSL_CID_ED25519) {
return ParseEd25519PubkeyAsn1Buff(bitPubkey.buff, bitPubkey.len, ealPubKey);
}
#endif
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_UNKNOWN_OID);
return CRYPT_DECODE_UNKNOWN_OID;
}
int32_t ParsePk8PriKeyBuff(BSL_Buffer *buff, CRYPT_EAL_PkeyCtx **ealPriKey)
{
uint8_t *tmpBuff = buff->data;
uint32_t tmpBuffLen = buff->dataLen;
CRYPT_ENCODE_DECODE_Pk8PrikeyInfo pk8PrikeyInfo = {0};
int32_t ret = CRYPT_DECODE_Pkcs8Info(tmpBuff, tmpBuffLen, NULL, &pk8PrikeyInfo);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
return ParsePk8PrikeyAsn1(&pk8PrikeyInfo, ealPriKey);
}
#ifdef HITLS_CRYPTO_KEY_EPKI
int32_t ParsePk8EncPriKeyBuff(BSL_Buffer *buff, const BSL_Buffer *pwd, CRYPT_EAL_PkeyCtx **ealPriKey)
{
BSL_Buffer decode = {0};
int32_t ret = CRYPT_DECODE_Pkcs8PrvDecrypt(NULL, NULL, buff, pwd, NULL, &decode);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = ParsePk8PriKeyBuff(&decode, ealPriKey);
BSL_SAL_ClearFree(decode.data, decode.dataLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
#endif
int32_t CRYPT_EAL_ParseAsn1SubPubkey(uint8_t *buff, uint32_t buffLen, void **ealPubKey, bool isComplete)
{
// decode sub pubkey info
BSL_ASN1_Buffer pubAsn1[CRYPT_SUBKEYINFO_BITSTRING_IDX + 1] = {0};
int32_t ret = CRYPT_DECODE_ParseSubKeyInfo(buff, buffLen, pubAsn1, isComplete);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
return ParseSubPubkeyAsn1(pubAsn1, (CRYPT_EAL_PkeyCtx **)ealPubKey);
}
#endif // HITLS_CRYPTO_KEY_DECODE
#ifdef HITLS_CRYPTO_KEY_ENCODE
#ifdef HITLS_CRYPTO_RSA
static int32_t EncodePssParam(CRYPT_EAL_PkeyCtx *ealPubKey, BSL_ASN1_Buffer *pssParam)
{
if (pssParam == NULL) {
return CRYPT_SUCCESS;
}
int32_t padType = 0;
int32_t ret = CRYPT_EAL_PkeyCtrl(ealPubKey, CRYPT_CTRL_GET_RSA_PADDING, &padType, sizeof(padType));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (padType != CRYPT_EMSA_PSS) {
pssParam->tag = BSL_ASN1_TAG_NULL;
return CRYPT_SUCCESS;
}
CRYPT_RSA_PssPara rsaPssParam = {0};
ret = CRYPT_EAL_GetRsaPssPara(ealPubKey, &rsaPssParam);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
pssParam->tag = BSL_ASN1_TAG_SEQUENCE | BSL_ASN1_TAG_CONSTRUCTED;
return CRYPT_EAL_EncodeRsaPssAlgParam(&rsaPssParam, &pssParam->buff, &pssParam->len);
}
int32_t EncodeRsaPubkeyAsn1Buff(CRYPT_EAL_PkeyCtx *ealPubKey, BSL_ASN1_Buffer *pssParam, BSL_Buffer *encodePub)
{
uint32_t bnLen = CRYPT_EAL_PkeyGetKeyLen(ealPubKey);
if (bnLen == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_NOT_SUPPORT);
return CRYPT_EAL_ALG_NOT_SUPPORT;
}
CRYPT_EAL_PkeyPub pub = {0};
pub.id = CRYPT_PKEY_RSA;
pub.key.rsaPub.n = (uint8_t *)BSL_SAL_Malloc(bnLen);
if (pub.key.rsaPub.n == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
pub.key.rsaPub.e = (uint8_t *)BSL_SAL_Malloc(bnLen);
if (pub.key.rsaPub.e == NULL) {
BSL_SAL_FREE(pub.key.rsaPub.n);
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
pub.key.rsaPub.nLen = bnLen;
pub.key.rsaPub.eLen = bnLen;
int32_t ret = CRYPT_EAL_PkeyGetPub(ealPubKey, &pub);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_FREE(pub.key.rsaPub.n);
BSL_SAL_FREE(pub.key.rsaPub.e);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BSL_ASN1_Buffer pubAsn1[CRYPT_RSA_PUB_E_IDX + 1] = {
{BSL_ASN1_TAG_INTEGER, pub.key.rsaPub.nLen, pub.key.rsaPub.n},
{BSL_ASN1_TAG_INTEGER, pub.key.rsaPub.eLen, pub.key.rsaPub.e},
};
ret = CRYPT_ENCODE_RsaPubkeyAsn1Buff(pubAsn1, encodePub);
BSL_SAL_FREE(pub.key.rsaPub.n);
BSL_SAL_FREE(pub.key.rsaPub.e);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = EncodePssParam(ealPubKey, pssParam);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_FREE(encodePub->data);
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
static int32_t EncodeRsaPrvKey(CRYPT_EAL_PkeyCtx *ealPriKey, BSL_ASN1_Buffer *pk8AlgoParam, BSL_Buffer *bitStr,
CRYPT_PKEY_AlgId *cid)
{
CRYPT_RsaPadType pad = CRYPT_RSA_PADDINGMAX;
int32_t ret = CRYPT_EAL_PkeyCtrl(ealPriKey, CRYPT_CTRL_GET_RSA_PADDING, &pad, sizeof(pad));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
CRYPT_RSA_PssPara rsaPssParam = {0};
BSL_Buffer tmp = {0};
switch (pad) {
case CRYPT_EMSA_PSS:
ret = CRYPT_EAL_GetRsaPssPara(ealPriKey, &rsaPssParam);
if (ret != BSL_SUCCESS) {
return ret;
}
ret = EncodeRsaPrikeyAsn1Buff(ealPriKey, CRYPT_PKEY_RSA, &tmp);
if (ret != BSL_SUCCESS) {
return ret;
}
ret = CRYPT_EAL_EncodeRsaPssAlgParam(&rsaPssParam, &pk8AlgoParam->buff, &pk8AlgoParam->len);
if (ret != BSL_SUCCESS) {
BSL_SAL_ClearFree(tmp.data, tmp.dataLen);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
pk8AlgoParam->tag = BSL_ASN1_TAG_SEQUENCE | BSL_ASN1_TAG_CONSTRUCTED;
*cid = (CRYPT_PKEY_AlgId)BSL_CID_RSASSAPSS;
break;
default:
ret = EncodeRsaPrikeyAsn1Buff(ealPriKey, CRYPT_PKEY_RSA, &tmp);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
pk8AlgoParam->tag = BSL_ASN1_TAG_NULL;
break;
}
bitStr->data = tmp.data;
bitStr->dataLen = tmp.dataLen;
return CRYPT_SUCCESS;
}
static void SetRsaPrv2Arr(const CRYPT_EAL_PkeyPrv *rsaPrv, BSL_ASN1_Buffer *asn1)
{
asn1[CRYPT_RSA_PRV_D_IDX].buff = rsaPrv->key.rsaPrv.d;
asn1[CRYPT_RSA_PRV_D_IDX].len = rsaPrv->key.rsaPrv.dLen;
asn1[CRYPT_RSA_PRV_N_IDX].buff = rsaPrv->key.rsaPrv.n;
asn1[CRYPT_RSA_PRV_N_IDX].len = rsaPrv->key.rsaPrv.nLen;
asn1[CRYPT_RSA_PRV_E_IDX].buff = rsaPrv->key.rsaPrv.e;
asn1[CRYPT_RSA_PRV_E_IDX].len = rsaPrv->key.rsaPrv.eLen;
asn1[CRYPT_RSA_PRV_P_IDX].buff = rsaPrv->key.rsaPrv.p;
asn1[CRYPT_RSA_PRV_P_IDX].len = rsaPrv->key.rsaPrv.pLen;
asn1[CRYPT_RSA_PRV_Q_IDX].buff = rsaPrv->key.rsaPrv.q;
asn1[CRYPT_RSA_PRV_Q_IDX].len = rsaPrv->key.rsaPrv.qLen;
asn1[CRYPT_RSA_PRV_DP_IDX].buff = rsaPrv->key.rsaPrv.dP;
asn1[CRYPT_RSA_PRV_DP_IDX].len = rsaPrv->key.rsaPrv.dPLen;
asn1[CRYPT_RSA_PRV_DQ_IDX].buff = rsaPrv->key.rsaPrv.dQ;
asn1[CRYPT_RSA_PRV_DQ_IDX].len = rsaPrv->key.rsaPrv.dQLen;
asn1[CRYPT_RSA_PRV_QINV_IDX].buff = rsaPrv->key.rsaPrv.qInv;
asn1[CRYPT_RSA_PRV_QINV_IDX].len = rsaPrv->key.rsaPrv.qInvLen;
asn1[CRYPT_RSA_PRV_D_IDX].tag = BSL_ASN1_TAG_INTEGER;
asn1[CRYPT_RSA_PRV_N_IDX].tag = BSL_ASN1_TAG_INTEGER;
asn1[CRYPT_RSA_PRV_E_IDX].tag = BSL_ASN1_TAG_INTEGER;
asn1[CRYPT_RSA_PRV_P_IDX].tag = BSL_ASN1_TAG_INTEGER;
asn1[CRYPT_RSA_PRV_Q_IDX].tag = BSL_ASN1_TAG_INTEGER;
asn1[CRYPT_RSA_PRV_DP_IDX].tag = BSL_ASN1_TAG_INTEGER;
asn1[CRYPT_RSA_PRV_DQ_IDX].tag = BSL_ASN1_TAG_INTEGER;
asn1[CRYPT_RSA_PRV_QINV_IDX].tag = BSL_ASN1_TAG_INTEGER;
}
int32_t EncodeRsaPrikeyAsn1Buff(CRYPT_EAL_PkeyCtx *ealPriKey, CRYPT_PKEY_AlgId cid, BSL_Buffer *encode)
{
int32_t ret;
BSL_ASN1_Buffer asn1[CRYPT_RSA_PRV_OTHER_PRIME_IDX + 1] = {0};
CRYPT_EAL_PkeyPrv rsaPrv = {0};
ret = CRYPT_EAL_InitRsaPrv(ealPriKey, cid, &rsaPrv);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = CRYPT_EAL_PkeyGetPrv(ealPriKey, &rsaPrv);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_DeinitRsaPrv(&rsaPrv);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
SetRsaPrv2Arr(&rsaPrv, asn1);
uint8_t version = 0;
asn1[CRYPT_RSA_PRV_VERSION_IDX].buff = (uint8_t *)&version;
asn1[CRYPT_RSA_PRV_VERSION_IDX].len = sizeof(version);
asn1[CRYPT_RSA_PRV_VERSION_IDX].tag = BSL_ASN1_TAG_INTEGER;
ret = CRYPT_ENCODE_RsaPrikeyAsn1Buff(asn1, CRYPT_RSA_PRV_OTHER_PRIME_IDX + 1, encode);
CRYPT_EAL_DeinitRsaPrv(&rsaPrv);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
#endif
#if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2)
static inline void SetAsn1Buffer(BSL_ASN1_Buffer *asn, uint8_t tag, uint32_t len, uint8_t *buff)
{
asn->tag = tag;
asn->len = len;
asn->buff = buff;
}
static int32_t EncodeEccKeyPair(CRYPT_EAL_PkeyCtx *ealPriKey, CRYPT_PKEY_AlgId cid,
BSL_ASN1_Buffer *asn1, BSL_Buffer *encode)
{
int32_t ret;
uint32_t keyLen = CRYPT_EAL_PkeyGetKeyLen(ealPriKey);
if (keyLen == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_NOT_SUPPORT);
return CRYPT_EAL_ALG_NOT_SUPPORT;
}
uint8_t *pri = (uint8_t *)BSL_SAL_Malloc(keyLen);
if (pri == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
CRYPT_EAL_PkeyPrv prv = {.id = cid, .key.eccPrv = {.data = pri, .len = keyLen}};
uint8_t *pub = NULL;
do {
ret = CRYPT_EAL_PkeyGetPrv(ealPriKey, &prv);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
break;
}
SetAsn1Buffer(asn1 + CRYPT_ECPRIKEY_PRIKEY_IDX, BSL_ASN1_TAG_OCTETSTRING,
prv.key.eccPrv.len, prv.key.eccPrv.data);
pub = (uint8_t *)BSL_SAL_Malloc(keyLen);
if (pub == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
break;
}
CRYPT_EAL_PkeyPub pubKey = {.id = cid, .key.eccPub = {.data = pub, .len = keyLen}};
ret = CRYPT_EAL_PkeyCtrl(ealPriKey, CRYPT_CTRL_GEN_ECC_PUBLICKEY, NULL, 0);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
break;
}
ret = CRYPT_EAL_PkeyGetPub(ealPriKey, &pubKey);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
break;
}
BSL_ASN1_BitString bitStr = {pubKey.key.eccPub.data, pubKey.key.eccPub.len, 0};
SetAsn1Buffer(asn1 + CRYPT_ECPRIKEY_PUBKEY_IDX, BSL_ASN1_TAG_BITSTRING,
sizeof(BSL_ASN1_BitString), (uint8_t *)&bitStr);
ret = CRYPT_ENCODE_EccPrikeyAsn1Buff(asn1, CRYPT_ECPRIKEY_PUBKEY_IDX + 1, encode);
} while (0);
BSL_SAL_ClearFree(pri, keyLen);
BSL_SAL_FREE(pub);
return ret;
}
int32_t EncodeEccPrikeyAsn1Buff(CRYPT_EAL_PkeyCtx *ealPriKey, BSL_ASN1_Buffer *pk8AlgoParam, BSL_Buffer *encode)
{
uint8_t version = 1;
BSL_ASN1_Buffer asn1[CRYPT_ECPRIKEY_PUBKEY_IDX + 1] = {
{BSL_ASN1_TAG_INTEGER, sizeof(version), &version}, {0}, {0}, {0}};
CRYPT_PKEY_AlgId cid = CRYPT_EAL_PkeyGetId(ealPriKey);
BslOidString *oid = cid == CRYPT_PKEY_SM2 ? BSL_OBJ_GetOID((BslCid)CRYPT_ECC_SM2)
: BSL_OBJ_GetOID((BslCid)CRYPT_EAL_PkeyGetParaId(ealPriKey));
if (oid == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID);
return CRYPT_ERR_ALGID;
}
if (pk8AlgoParam != NULL) { // pkcs8
pk8AlgoParam->buff = (uint8_t *)oid->octs;
pk8AlgoParam->len = oid->octetLen;
pk8AlgoParam->tag = BSL_ASN1_TAG_OBJECT_ID;
} else { // pkcs1
asn1[CRYPT_ECPRIKEY_PARAM_IDX].buff = (uint8_t *)oid->octs;
asn1[CRYPT_ECPRIKEY_PARAM_IDX].len = oid->octetLen;
asn1[CRYPT_ECPRIKEY_PARAM_IDX].tag = BSL_ASN1_TAG_OBJECT_ID;
}
return EncodeEccKeyPair(ealPriKey, cid, asn1, encode);
}
static int32_t EncodeEccPubkeyAsn1Buff(CRYPT_EAL_PkeyCtx *ealPubKey, BSL_ASN1_Buffer *ecParamOid, BSL_Buffer *encodePub)
{
int32_t ret;
CRYPT_PKEY_ParaId paraId = CRYPT_EAL_PkeyGetParaId(ealPubKey);
BslOidString *oid = BSL_OBJ_GetOID((BslCid)paraId);
if (CRYPT_EAL_PkeyGetId(ealPubKey) == CRYPT_PKEY_SM2) {
oid = BSL_OBJ_GetOID((BslCid)CRYPT_ECC_SM2);
}
if (oid == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID);
return CRYPT_ERR_ALGID;
}
ecParamOid->buff = (uint8_t *)oid->octs;
ecParamOid->len = oid->octetLen;
ecParamOid->tag = BSL_ASN1_TAG_OBJECT_ID;
uint32_t pubLen = CRYPT_EAL_PkeyGetKeyLen(ealPubKey);
if (pubLen == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_NOT_SUPPORT);
return CRYPT_EAL_ALG_NOT_SUPPORT;
}
uint8_t *pub = (uint8_t *)BSL_SAL_Malloc(pubLen);
if (pub == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
CRYPT_EAL_PkeyPub pubKey = {.id = CRYPT_EAL_PkeyGetId(ealPubKey), .key.eccPub = {.data = pub, .len = pubLen}};
ret = CRYPT_EAL_PkeyGetPub(ealPubKey, &pubKey);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_FREE(pub);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
encodePub->data = pubKey.key.eccPub.data;
encodePub->dataLen = pubKey.key.eccPub.len;
return ret;
}
#endif // HITLS_CRYPTO_ECDSA || HITLS_CRYPTO_SM2
#ifdef HITLS_CRYPTO_ED25519
static int32_t EncodeEd25519PubkeyAsn1Buff(CRYPT_EAL_PkeyCtx *ealPubKey, BSL_Buffer *bitStr)
{
uint32_t pubLen = CRYPT_EAL_PkeyGetKeyLen(ealPubKey);
if (pubLen == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_NOT_SUPPORT);
return CRYPT_EAL_ALG_NOT_SUPPORT;
}
uint8_t *pub = (uint8_t *)BSL_SAL_Malloc(pubLen);
if (pub == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
CRYPT_EAL_PkeyPub pubKey = {.id = CRYPT_PKEY_ED25519, .key.curve25519Pub = {.data = pub, .len = pubLen}};
int32_t ret = CRYPT_EAL_PkeyGetPub(ealPubKey, &pubKey);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_Free(pub);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
bitStr->data = pubKey.key.curve25519Pub.data;
bitStr->dataLen = pubKey.key.curve25519Pub.len;
return CRYPT_SUCCESS;
}
static int32_t EncodeEd25519PrikeyAsn1Buff(CRYPT_EAL_PkeyCtx *ealPriKey, BSL_Buffer *bitStr)
{
uint8_t keyBuff[32] = {0}; // The length of the ed25519 private key is 32
CRYPT_EAL_PkeyPrv prv = {.id = CRYPT_PKEY_ED25519, .key.curve25519Prv = {.data = keyBuff, .len = sizeof(keyBuff)}};
int32_t ret = CRYPT_EAL_PkeyGetPrv(ealPriKey, &prv);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BSL_ASN1_TemplateItem octStr[] = {{BSL_ASN1_TAG_OCTETSTRING, 0, 0}};
BSL_ASN1_Template templ = {octStr, 1};
BSL_ASN1_Buffer prvAsn1 = {BSL_ASN1_TAG_OCTETSTRING, prv.key.curve25519Prv.len, prv.key.curve25519Prv.data};
return BSL_ASN1_EncodeTemplate(&templ, &prvAsn1, 1, &bitStr->data, &bitStr->dataLen);
}
#endif // HITLS_CRYPTO_ED25519
static int32_t EncodePk8AlgidAny(CRYPT_EAL_PkeyCtx *ealPriKey, BSL_Buffer *bitStr,
BSL_ASN1_Buffer *keyParam, BslCid *cidOut)
{
(void)keyParam;
int32_t ret = CRYPT_DECODE_NO_SUPPORT_TYPE;
BSL_Buffer tmp = {0};
CRYPT_PKEY_AlgId cid = CRYPT_EAL_PkeyGetId(ealPriKey);
switch (cid) {
#ifdef HITLS_CRYPTO_RSA
case CRYPT_PKEY_RSA:
ret = EncodeRsaPrvKey(ealPriKey, keyParam, &tmp, &cid);
break;
#endif
#if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2)
case CRYPT_PKEY_ECDSA:
case CRYPT_PKEY_SM2:
cid = (CRYPT_PKEY_AlgId)BSL_CID_EC_PUBLICKEY;
ret = EncodeEccPrikeyAsn1Buff(ealPriKey, keyParam, &tmp);
break;
#endif
#ifdef HITLS_CRYPTO_ED25519
case CRYPT_PKEY_ED25519:
ret = EncodeEd25519PrikeyAsn1Buff(ealPriKey, &tmp);
break;
#endif
default:
ret = CRYPT_DECODE_NO_SUPPORT_TYPE;
break;
}
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
bitStr->data = tmp.data;
bitStr->dataLen = tmp.dataLen;
*cidOut = (BslCid)cid;
return ret;
}
int32_t EncodePk8PriKeyBuff(CRYPT_EAL_PkeyCtx *ealPriKey, BSL_Buffer *asn1)
{
int32_t ret;
BSL_Buffer bitStr = {0};
CRYPT_ENCODE_DECODE_Pk8PrikeyInfo pk8PrikeyInfo = {0};
do {
ret = EncodePk8AlgidAny(ealPriKey, &bitStr, &pk8PrikeyInfo.keyParam, &pk8PrikeyInfo.keyType);
if (ret != CRYPT_SUCCESS) {
break;
}
pk8PrikeyInfo.pkeyRawKey = bitStr.data;
pk8PrikeyInfo.pkeyRawKeyLen = bitStr.dataLen;
ret = CRYPT_ENCODE_Pkcs8Info(&pk8PrikeyInfo, asn1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
break;
}
} while (0);
// rsa-pss mode release buffer
if (pk8PrikeyInfo.keyParam.tag == (BSL_ASN1_TAG_SEQUENCE | BSL_ASN1_TAG_CONSTRUCTED)) {
BSL_SAL_FREE(pk8PrikeyInfo.keyParam.buff);
}
BSL_SAL_ClearFree(bitStr.data, bitStr.dataLen);
return ret;
}
#ifdef HITLS_CRYPTO_KEY_EPKI
static int32_t CheckEncodeParam(const CRYPT_EncodeParam *encodeParam)
{
if (encodeParam == NULL || encodeParam->param == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (encodeParam->deriveMode != CRYPT_DERIVE_PBKDF2) {
BSL_ERR_PUSH_ERROR(CRYPT_ENCODE_NO_SUPPORT_TYPE);
return CRYPT_ENCODE_NO_SUPPORT_TYPE;
}
CRYPT_Pbkdf2Param *pkcsParam = (CRYPT_Pbkdf2Param *)encodeParam->param;
if (pkcsParam->pwdLen > PWD_MAX_LEN || (pkcsParam->pwd == NULL && pkcsParam->pwdLen != 0)) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
if (pkcsParam->pbesId != BSL_CID_PBES2 || pkcsParam->pbkdfId != BSL_CID_PBKDF2) {
BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID);
return CRYPT_ERR_ALGID;
}
return CRYPT_SUCCESS;
}
int32_t EncodePk8EncPriKeyBuff(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_EAL_PkeyCtx *ealPriKey,
const CRYPT_EncodeParam *encodeParam, BSL_Buffer *encode)
{
/* EncAlgid */
int32_t ret = CheckEncodeParam(encodeParam);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
CRYPT_Pbkdf2Param *pkcs8Param = (CRYPT_Pbkdf2Param *)encodeParam->param;
BSL_Buffer unEncrypted = {0};
ret = EncodePk8PriKeyBuff(ealPriKey, &unEncrypted);
if (ret != CRYPT_SUCCESS) {
return ret;
}
BSL_ASN1_Buffer asn1[CRYPT_PKCS_ENCPRIKEY_MAX] = {0};
ret = CRYPT_ENCODE_PkcsEncryptedBuff(libCtx, attrName, pkcs8Param, &unEncrypted, asn1);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_ClearFree(unEncrypted.data, unEncrypted.dataLen);
return ret;
}
BSL_ASN1_Template templ = {g_pk8EncPriKeyTempl, sizeof(g_pk8EncPriKeyTempl) / sizeof(g_pk8EncPriKeyTempl[0])};
ret = BSL_ASN1_EncodeTemplate(&templ, asn1, CRYPT_PKCS_ENCPRIKEY_MAX, &encode->data, &encode->dataLen);
BSL_SAL_ClearFree(unEncrypted.data, unEncrypted.dataLen);
BSL_SAL_ClearFree(asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].buff, asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].len);
BSL_SAL_ClearFree(asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].buff, asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].len);
BSL_SAL_FREE(asn1[CRYPT_PKCS_ENCPRIKEY_ENCDATA_IDX].buff);
return ret;
}
#endif // HITLS_CRYPTO_KEY_EPKI
static int32_t CRYPT_EAL_SubPubkeyGetInfo(CRYPT_EAL_PkeyCtx *ealPubKey, BSL_ASN1_Buffer *algo, BSL_Buffer *bitStr)
{
int32_t ret = CRYPT_ERR_ALGID;
CRYPT_PKEY_AlgId cid = CRYPT_EAL_PkeyGetId(ealPubKey);
BSL_Buffer bitTmp = {0};
BSL_ASN1_Buffer algoId[BSL_ASN1_TAG_ALGOID_ANY_IDX + 1] = {0};
#ifdef HITLS_CRYPTO_RSA
if (cid == CRYPT_PKEY_RSA) {
ret = EncodeRsaPubkeyAsn1Buff(ealPubKey, &algoId[BSL_ASN1_TAG_ALGOID_ANY_IDX], &bitTmp);
if (algoId[BSL_ASN1_TAG_ALGOID_ANY_IDX].tag == (BSL_ASN1_TAG_SEQUENCE | BSL_ASN1_TAG_CONSTRUCTED)) {
cid = (CRYPT_PKEY_AlgId)BSL_CID_RSASSAPSS;
}
}
#endif
#if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2)
if (cid == CRYPT_PKEY_ECDSA || cid == CRYPT_PKEY_SM2) {
cid = (CRYPT_PKEY_AlgId)BSL_CID_EC_PUBLICKEY;
ret = EncodeEccPubkeyAsn1Buff(ealPubKey, &algoId[BSL_ASN1_TAG_ALGOID_ANY_IDX], &bitTmp);
}
#endif
#ifdef HITLS_CRYPTO_ED25519
if (cid == CRYPT_PKEY_ED25519) {
ret = EncodeEd25519PubkeyAsn1Buff(ealPubKey, &bitTmp);
}
#endif
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BslOidString *oidStr = BSL_OBJ_GetOID((BslCid)cid);
if (oidStr == NULL) {
BSL_SAL_FREE(bitTmp.data);
ret = CRYPT_ERR_ALGID;
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
algoId[BSL_ASN1_TAG_ALGOID_IDX].buff = (uint8_t *)oidStr->octs;
algoId[BSL_ASN1_TAG_ALGOID_IDX].len = oidStr->octetLen;
algoId[BSL_ASN1_TAG_ALGOID_IDX].tag = BSL_ASN1_TAG_OBJECT_ID;
ret = CRYPT_ENCODE_AlgoIdAsn1Buff(algoId, BSL_ASN1_TAG_ALGOID_ANY_IDX + 1, &algo->buff, &algo->len);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_FREE(bitTmp.data);
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
bitStr->data = bitTmp.data;
bitStr->dataLen = bitTmp.dataLen;
EXIT:
#ifdef HITLS_CRYPTO_RSA
if (cid == (CRYPT_PKEY_AlgId)BSL_CID_RSASSAPSS) {
BSL_SAL_FREE(algoId[BSL_ASN1_TAG_ALGOID_ANY_IDX].buff);
}
#endif
return ret;
}
int32_t CRYPT_EAL_EncodeAsn1SubPubkey(CRYPT_EAL_PkeyCtx *ealPubKey, bool isComplete, BSL_Buffer *encodeH)
{
BSL_ASN1_Buffer algo = {0};
BSL_Buffer bitStr = {0};
int32_t ret = CRYPT_EAL_SubPubkeyGetInfo(ealPubKey, &algo, &bitStr);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = CRYPT_ENCODE_SubPubkeyByInfo(&algo, &bitStr, encodeH, isComplete);
BSL_SAL_FREE(bitStr.data);
BSL_SAL_FREE(algo.buff);
return ret;
}
#ifdef HITLS_CRYPTO_RSA
int32_t EncodeHashAlg(CRYPT_MD_AlgId mdId, BSL_ASN1_Buffer *asn)
{
if (mdId == CRYPT_MD_SHA1) {
asn->tag = BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_HASH;
asn->buff = NULL;
asn->len = 0;
return CRYPT_SUCCESS;
}
BslOidString *oidStr = BSL_OBJ_GetOID((BslCid)mdId);
if (oidStr == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID);
return CRYPT_ERR_ALGID;
}
BSL_ASN1_TemplateItem hashTempl[] = {
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0},
{BSL_ASN1_TAG_OBJECT_ID, 0, 1},
{BSL_ASN1_TAG_ANY, BSL_ASN1_FLAG_OPTIONAL, 1},
};
BSL_ASN1_Template templ = {hashTempl, sizeof(hashTempl) / sizeof(hashTempl[0])};
BSL_ASN1_Buffer asnArr[2] = {
{BSL_ASN1_TAG_OBJECT_ID, oidStr->octetLen, (uint8_t *)oidStr->octs},
{BSL_ASN1_TAG_NULL, 0, NULL},
};
int32_t ret = BSL_ASN1_EncodeTemplate(&templ, asnArr, 2, &(asn->buff), &(asn->len)); // 2: oid and null
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
asn->tag = BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_HASH;
return CRYPT_SUCCESS;
}
static int32_t EncodeMgfAlg(CRYPT_MD_AlgId mgfId, BSL_ASN1_Buffer *asn)
{
if (mgfId == CRYPT_MD_SHA1) {
asn->tag = BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_MASKGEN;
asn->buff = NULL;
asn->len = 0;
return CRYPT_SUCCESS;
}
BslOidString *mgfStr = BSL_OBJ_GetOID(BSL_CID_MGF1);
if (mgfStr == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID);
return CRYPT_ERR_ALGID;
}
BslOidString *oidStr = BSL_OBJ_GetOID((BslCid)mgfId);
if (oidStr == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID);
return CRYPT_ERR_ALGID;
}
BSL_ASN1_TemplateItem mgfTempl[] = {
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0},
{BSL_ASN1_TAG_OBJECT_ID, 0, 1},
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1},
{BSL_ASN1_TAG_OBJECT_ID, 0, 2},
{BSL_ASN1_TAG_ANY, BSL_ASN1_FLAG_OPTIONAL, 2},
};
BSL_ASN1_Template templ = {mgfTempl, sizeof(mgfTempl) / sizeof(mgfTempl[0])};
BSL_ASN1_Buffer asnArr[3] = {
{BSL_ASN1_TAG_OBJECT_ID, mgfStr->octetLen, (uint8_t *)mgfStr->octs},
{BSL_ASN1_TAG_OBJECT_ID, oidStr->octetLen, (uint8_t *)oidStr->octs},
{BSL_ASN1_TAG_NULL, 0, NULL}, // param
};
int32_t ret = BSL_ASN1_EncodeTemplate(&templ, asnArr, 3, &(asn->buff), &(asn->len));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
asn->tag = BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_MASKGEN;
return CRYPT_SUCCESS;
}
static int32_t EncodeSaltLen(int32_t saltLen, BSL_ASN1_Buffer *asn)
{
if (saltLen == 20) { // 20 : default saltLen
asn->tag = BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED |
CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_SALTLEN;
asn->buff = NULL;
asn->len = 0;
return CRYPT_SUCCESS;
}
BSL_ASN1_Buffer saltAsn = {0};
int32_t ret = BSL_ASN1_EncodeLimb(BSL_ASN1_TAG_INTEGER, (uint64_t)saltLen, &saltAsn);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BSL_ASN1_TemplateItem saltTempl = {BSL_ASN1_TAG_INTEGER, 0, 0};
BSL_ASN1_Template templ = {&saltTempl, 1};
ret = BSL_ASN1_EncodeTemplate(&templ, &saltAsn, 1, &(asn->buff), &(asn->len));
BSL_SAL_Free(saltAsn.buff);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
asn->tag = BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_SALTLEN;
return CRYPT_SUCCESS;
}
#define X509_RSAPSS_ELEM_NUMBER 4
int32_t CRYPT_EAL_EncodeRsaPssAlgParam(const CRYPT_RSA_PssPara *rsaPssParam, uint8_t **buf, uint32_t *bufLen)
{
BSL_ASN1_Buffer asnArr[X509_RSAPSS_ELEM_NUMBER] = {0};
int32_t ret = EncodeHashAlg(rsaPssParam->mdId, &asnArr[0]);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = EncodeMgfAlg(rsaPssParam->mgfId, &asnArr[1]);
if (ret != CRYPT_SUCCESS) {
goto EXIT;
}
ret = EncodeSaltLen(rsaPssParam->saltLen, &asnArr[2]); // 2: saltLength
if (ret != CRYPT_SUCCESS) {
goto EXIT;
}
if (asnArr[0].len + asnArr[1].len + asnArr[2].len == 0) { // [0]:hash + [1]:mgf + [2]:salt all default
return ret;
}
// 3 : trailed
asnArr[3].tag = BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_TRAILED;
BSL_ASN1_TemplateItem rsapssTempl[] = {
{BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_HASH,
BSL_ASN1_FLAG_DEFAULT, 0},
{BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_MASKGEN,
BSL_ASN1_FLAG_DEFAULT, 0},
{BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_SALTLEN,
BSL_ASN1_FLAG_DEFAULT, 0},
{BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_TRAILED,
BSL_ASN1_FLAG_DEFAULT, 0},
};
BSL_ASN1_Template templ = {rsapssTempl, sizeof(rsapssTempl) / sizeof(rsapssTempl[0])};
ret = BSL_ASN1_EncodeTemplate(&templ, asnArr, X509_RSAPSS_ELEM_NUMBER, buf, bufLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
EXIT:
for (uint32_t i = 0; i < X509_RSAPSS_ELEM_NUMBER; i++) {
BSL_SAL_Free(asnArr[i].buff);
}
return ret;
}
#endif // HITLS_CRYPTO_RSA
#endif // HITLS_CRYPTO_KEY_ENCODE
#ifdef HITLS_PKI_PKCS12
#define HITLS_P7_SPECIFIC_ENCONTENTINFO_EXTENSION 0
/**
* EncryptedContentInfo ::= SEQUENCE {
* contentType ContentType,
* contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
* encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL
* }
*
* https://datatracker.ietf.org/doc/html/rfc5652#section-6.1
*/
static BSL_ASN1_TemplateItem g_enContentInfoTempl[] = {
/* ContentType */
{BSL_ASN1_TAG_OBJECT_ID, 0, 0},
/* ContentEncryptionAlgorithmIdentifier */
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, // ContentEncryptionAlgorithmIdentifier
{BSL_ASN1_TAG_OBJECT_ID, 0, 1},
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1},
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 2}, // derivation param
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 2}, // enc scheme
{BSL_ASN1_TAG_OBJECT_ID, 0, 3}, // alg
{BSL_ASN1_TAG_OCTETSTRING, 0, 3}, // iv
/* encryptedContent */
{BSL_ASN1_CLASS_CTX_SPECIFIC | HITLS_P7_SPECIFIC_ENCONTENTINFO_EXTENSION, BSL_ASN1_FLAG_OPTIONAL, 0},
};
typedef enum {
HITLS_P7_ENC_CONTINFO_TYPE_IDX,
HITLS_P7_ENC_CONTINFO_ENCALG_IDX,
HITLS_P7_ENC_CONTINFO_DERIVE_PARAM_IDX,
HITLS_P7_ENC_CONTINFO_SYMALG_IDX,
HITLS_P7_ENC_CONTINFO_SYMIV_IDX,
HITLS_P7_ENC_CONTINFO_ENCONTENT_IDX,
HITLS_P7_ENC_CONTINFO_MAX_IDX,
} HITLS_P7_ENC_CONTINFO_IDX;
#define HITLS_P7_SPECIFIC_UNPROTECTEDATTRS_EXTENSION 1
/**
* EncryptedData ::= SEQUENCE {
* version CMSVersion,
* encryptedContentInfo EncryptedContentInfo,
* unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL
* }
*
* https://datatracker.ietf.org/doc/html/rfc5652#page-29
*/
static BSL_ASN1_TemplateItem g_encryptedDataTempl[] = {
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0},
/* version */
{BSL_ASN1_TAG_INTEGER, 0, 1},
/* EncryptedContentInfo */
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 1},
/* unprotectedAttrs */
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SET | HITLS_P7_SPECIFIC_UNPROTECTEDATTRS_EXTENSION,
BSL_ASN1_FLAG_OPTIONAL | BSL_ASN1_FLAG_HEADERONLY, 1},
};
typedef enum {
HITLS_P7_ENCRYPTDATA_VERSION_IDX,
HITLS_P7_ENCRYPTDATA_ENCRYPTINFO_IDX,
HITLS_P7_ENCRYPTDATA_UNPROTECTEDATTRS_IDX,
HITLS_P7_ENCRYPTDATA_MAX_IDX,
} HITLS_P7_ENCRYPTDATA_IDX;
#ifdef HITLS_PKI_PKCS12_PARSE
static int32_t ParsePKCS7EncryptedContentInfo(CRYPT_EAL_LibCtx *libCtx, const char *attrName, BSL_Buffer *encode,
const uint8_t *pwd, uint32_t pwdlen, BSL_Buffer *output)
{
uint8_t *temp = encode->data;
uint32_t tempLen = encode->dataLen;
BSL_ASN1_Buffer asn1[HITLS_P7_ENC_CONTINFO_MAX_IDX] = {0};
BSL_ASN1_Template templ = {g_enContentInfoTempl, sizeof(g_enContentInfoTempl) / sizeof(g_enContentInfoTempl[0])};
int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &temp, &tempLen, asn1, HITLS_P7_ENC_CONTINFO_MAX_IDX);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BslOidString typeOidStr = {asn1[HITLS_P7_ENC_CONTINFO_TYPE_IDX].len,
(char *)asn1[HITLS_P7_ENC_CONTINFO_TYPE_IDX].buff, 0};
BslCid cid = BSL_OBJ_GetCID(&typeOidStr);
if (cid != BSL_CID_PKCS7_SIMPLEDATA) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_UNSUPPORTED_PKCS7_TYPE);
return CRYPT_DECODE_UNSUPPORTED_PKCS7_TYPE;
}
BslOidString encOidStr = {asn1[HITLS_P7_ENC_CONTINFO_ENCALG_IDX].len,
(char *)asn1[HITLS_P7_ENC_CONTINFO_ENCALG_IDX].buff, 0};
cid = BSL_OBJ_GetCID(&encOidStr);
if (cid != BSL_CID_PBES2) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_UNSUPPORTED_ENCRYPT_TYPE);
return CRYPT_DECODE_UNSUPPORTED_ENCRYPT_TYPE;
}
// parse sym alg id
BslOidString symOidStr = {asn1[HITLS_P7_ENC_CONTINFO_SYMALG_IDX].len,
(char *)asn1[HITLS_P7_ENC_CONTINFO_SYMALG_IDX].buff, 0};
BslCid symId = BSL_OBJ_GetCID(&symOidStr);
if (symId == BSL_CID_UNKNOWN) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_UNKNOWN_OID);
return CRYPT_DECODE_UNKNOWN_OID;
}
BSL_Buffer derivekeyData = {asn1[HITLS_P7_ENC_CONTINFO_DERIVE_PARAM_IDX].buff,
asn1[HITLS_P7_ENC_CONTINFO_DERIVE_PARAM_IDX].len};
BSL_Buffer ivData = {asn1[HITLS_P7_ENC_CONTINFO_SYMIV_IDX].buff, asn1[HITLS_P7_ENC_CONTINFO_SYMIV_IDX].len};
BSL_Buffer enData = {asn1[HITLS_P7_ENC_CONTINFO_ENCONTENT_IDX].buff, asn1[HITLS_P7_ENC_CONTINFO_ENCONTENT_IDX].len};
EncryptPara encPara = {.derivekeyData = &derivekeyData, .ivData = &ivData, .enData = &enData};
BSL_Buffer pwdBuffer = {(uint8_t *)(uintptr_t)pwd, pwdlen};
ret = CRYPT_DECODE_ParseEncDataAsn1(libCtx, attrName, symId, &encPara, &pwdBuffer, NULL, output);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
int32_t CRYPT_EAL_ParseAsn1PKCS7EncryptedData(CRYPT_EAL_LibCtx *libCtx, const char *attrName, BSL_Buffer *encode,
const uint8_t *pwd, uint32_t pwdlen, BSL_Buffer *output)
{
if (encode == NULL || pwd == NULL || output == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (pwdlen > PWD_MAX_LEN) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
uint8_t *temp = encode->data;
uint32_t tempLen = encode->dataLen;
BSL_ASN1_Buffer asn1[HITLS_P7_ENCRYPTDATA_MAX_IDX] = {0};
BSL_ASN1_Template templ = {g_encryptedDataTempl, sizeof(g_encryptedDataTempl) / sizeof(g_encryptedDataTempl[0])};
int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &temp, &tempLen, asn1, HITLS_P7_ENCRYPTDATA_MAX_IDX);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
uint32_t version = 0;
ret = BSL_ASN1_DecodePrimitiveItem(&asn1[HITLS_P7_ENCRYPTDATA_VERSION_IDX], &version);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (version == 0 && asn1[HITLS_P7_ENCRYPTDATA_UNPROTECTEDATTRS_IDX].buff != NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PKCS7_INVALIDE_ENCRYPTDATA_TYPE);
return CRYPT_DECODE_PKCS7_INVALIDE_ENCRYPTDATA_TYPE;
}
// In RFC5652, if the encapsulated content type is other than id-data, then the value of version MUST be 2.
if (version == 2 && asn1[HITLS_P7_ENCRYPTDATA_UNPROTECTEDATTRS_IDX].buff == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PKCS7_INVALIDE_ENCRYPTDATA_TYPE);
return CRYPT_DECODE_PKCS7_INVALIDE_ENCRYPTDATA_TYPE;
}
BSL_Buffer encryptInfo = {asn1[HITLS_P7_ENCRYPTDATA_ENCRYPTINFO_IDX].buff,
asn1[HITLS_P7_ENCRYPTDATA_ENCRYPTINFO_IDX].len};
ret = ParsePKCS7EncryptedContentInfo(libCtx, attrName, &encryptInfo, pwd, pwdlen, output);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
#endif // HITLS_PKI_PKCS12_PARSE
#ifdef HITLS_PKI_PKCS12_GEN
/* Encode PKCS7-EncryptData:only support PBES2 + PBKDF2, the param check ref CheckEncodeParam. */
static int32_t EncodePKCS7EncryptedContentInfo(CRYPT_EAL_LibCtx *libCtx, const char *attrName, BSL_Buffer *data,
const CRYPT_EncodeParam *encodeParam, BSL_Buffer *encode)
{
/* EncAlgid */
int32_t ret = CheckEncodeParam(encodeParam);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
CRYPT_Pbkdf2Param *pkcs7Param = (CRYPT_Pbkdf2Param *)encodeParam->param;
BSL_ASN1_Buffer asn1[CRYPT_PKCS_ENCPRIKEY_MAX] = {0};
ret = CRYPT_ENCODE_PkcsEncryptedBuff(libCtx, attrName, pkcs7Param, data, asn1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
do {
BslOidString *oidStr = BSL_OBJ_GetOID(BSL_CID_PKCS7_SIMPLEDATA);
if (oidStr == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID);
ret = CRYPT_ERR_ALGID;
break;
}
BSL_ASN1_Buffer p7asn[HITLS_P7_ENC_CONTINFO_MAX_IDX] = {
{BSL_ASN1_TAG_OBJECT_ID, oidStr->octetLen, (uint8_t *)oidStr->octs},
{asn1[CRYPT_PKCS_ENCPRIKEY_ENCALG_IDX].tag,
asn1[CRYPT_PKCS_ENCPRIKEY_ENCALG_IDX].len, asn1[CRYPT_PKCS_ENCPRIKEY_ENCALG_IDX].buff},
{asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].tag,
asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].len, asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].buff},
{asn1[CRYPT_PKCS_ENCPRIKEY_SYMALG_IDX].tag,
asn1[CRYPT_PKCS_ENCPRIKEY_SYMALG_IDX].len, asn1[CRYPT_PKCS_ENCPRIKEY_SYMALG_IDX].buff},
{asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].tag,
asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].len, asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].buff},
{BSL_ASN1_CLASS_CTX_SPECIFIC | HITLS_P7_SPECIFIC_ENCONTENTINFO_EXTENSION,
asn1[CRYPT_PKCS_ENCPRIKEY_ENCDATA_IDX].len, asn1[CRYPT_PKCS_ENCPRIKEY_ENCDATA_IDX].buff},
};
BSL_ASN1_Template templ = {g_enContentInfoTempl,
sizeof(g_enContentInfoTempl) / sizeof(g_enContentInfoTempl[0])};
ret = BSL_ASN1_EncodeTemplate(&templ, p7asn, HITLS_P7_ENC_CONTINFO_MAX_IDX, &encode->data, &encode->dataLen);
} while (0);
BSL_SAL_ClearFree(asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].buff, asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].len);
BSL_SAL_ClearFree(asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].buff, asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].len);
BSL_SAL_FREE(asn1[CRYPT_PKCS_ENCPRIKEY_ENCDATA_IDX].buff);
return ret;
}
int32_t CRYPT_EAL_EncodePKCS7EncryptDataBuff(CRYPT_EAL_LibCtx *libCtx, const char *attrName, BSL_Buffer *data,
const void *encodeParam, BSL_Buffer *encode)
{
if (data == NULL || encodeParam == NULL || encode == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
BSL_Buffer contentInfo = {0};
int32_t ret = EncodePKCS7EncryptedContentInfo(libCtx, attrName, data, encodeParam, &contentInfo);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
uint8_t version = 0;
BSL_ASN1_Buffer asn1[HITLS_P7_ENCRYPTDATA_MAX_IDX] = {
{BSL_ASN1_TAG_INTEGER, sizeof(version), &version},
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, contentInfo.dataLen, contentInfo.data},
{0, 0, 0},
};
BSL_ASN1_Template templ = {g_encryptedDataTempl, sizeof(g_encryptedDataTempl) / sizeof(g_encryptedDataTempl[0])};
BSL_Buffer tmp = {0};
ret = BSL_ASN1_EncodeTemplate(&templ, asn1, HITLS_P7_ENCRYPTDATA_MAX_IDX, &tmp.data, &tmp.dataLen);
BSL_SAL_FREE(contentInfo.data);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
encode->data = tmp.data;
encode->dataLen = tmp.dataLen;
return ret;
}
#endif // HITLS_PKI_PKCS12_GEN
#endif // HITLS_PKI_PKCS12
#endif // HITLS_CRYPTO_CODECSKEY
|
2301_79861745/bench_create
|
crypto/codecskey/src/crypt_encode_decode_local.c
|
C
|
unknown
| 56,034
|
/*
* 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_DECODE_KEY_LOCAL_H
#define CRYPT_ENCODE_DECODE_KEY_LOCAL_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_CODECSKEY
#include "bsl_types.h"
#include "bsl_asn1_internal.h"
#include "crypt_types.h"
#include "crypt_eal_pkey.h"
#ifdef HITLS_CRYPTO_RSA
#include "crypt_rsa.h"
#endif
#ifdef HITLS_CRYPTO_SM2
#include "crypt_sm2.h"
#endif
#ifdef HITLS_CRYPTO_ED25519
#include "crypt_curve25519.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
typedef struct {
BSL_Buffer *derivekeyData;
BSL_Buffer *ivData;
BSL_Buffer *enData;
} EncryptPara;
typedef enum {
CRYPT_RSA_PUB_N_IDX = 0,
CRYPT_RSA_PUB_E_IDX = 1,
} CRYPT_RSA_PUB_TEMPL_IDX;
typedef enum {
BSL_ASN1_TAG_ALGOID_IDX = 0,
BSL_ASN1_TAG_ALGOID_ANY_IDX = 1,
} ALGOID_TEMPL_IDX;
typedef enum {
CRYPT_SUBKEYINFO_ALGOID_IDX = 0,
CRYPT_SUBKEYINFO_BITSTRING_IDX = 1,
} CRYPT_SUBKEYINFO_TEMPL_IDX;
typedef enum {
CRYPT_PKCS_ENCPRIKEY_ENCALG_IDX,
CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX,
CRYPT_PKCS_ENCPRIKEY_SYMALG_IDX,
CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX,
CRYPT_PKCS_ENCPRIKEY_ENCDATA_IDX,
CRYPT_PKCS_ENCPRIKEY_MAX
} CRYPT_PKCS_ENCPRIKEY_TEMPL_IDX;
typedef enum {
CRYPT_ECPRIKEY_VERSION_IDX = 0,
CRYPT_ECPRIKEY_PRIKEY_IDX = 1,
CRYPT_ECPRIKEY_PARAM_IDX = 2,
CRYPT_ECPRIKEY_PUBKEY_IDX = 3,
} CRYPT_ECPRIKEY_TEMPL_IDX;
typedef enum {
CRYPT_RSA_PRV_VERSION_IDX = 0,
CRYPT_RSA_PRV_N_IDX = 1,
CRYPT_RSA_PRV_E_IDX = 2,
CRYPT_RSA_PRV_D_IDX = 3,
CRYPT_RSA_PRV_P_IDX = 4,
CRYPT_RSA_PRV_Q_IDX = 5,
CRYPT_RSA_PRV_DP_IDX = 6,
CRYPT_RSA_PRV_DQ_IDX = 7,
CRYPT_RSA_PRV_QINV_IDX = 8,
CRYPT_RSA_PRV_OTHER_PRIME_IDX = 9
} CRYPT_RSA_PRV_TEMPL_IDX;
#define CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_HASH 0
#define CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_MASKGEN 1
#define CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_SALTLEN 2
#define CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_TRAILED 3
#define PATH_MAX_LEN 4096
#define PWD_MAX_LEN 4096
#ifdef HITLS_CRYPTO_KEY_DECODE
int32_t ParseSubPubkeyAsn1(BSL_ASN1_Buffer *encode, CRYPT_EAL_PkeyCtx **ealPubKey);
int32_t ParseRsaPubkeyAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *param, CRYPT_EAL_PkeyCtx **ealPubKey,
BslCid cid);
int32_t ParseRsaPrikeyAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *rsaPssParam, BslCid cid,
CRYPT_EAL_PkeyCtx **ealPriKey);
int32_t ParseEccPrikeyAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *pk8AlgoParam,
CRYPT_EAL_PkeyCtx **ealPriKey);
int32_t ParsePk8PriKeyBuff(BSL_Buffer *buff, CRYPT_EAL_PkeyCtx **ealPriKey);
#ifdef HITLS_CRYPTO_KEY_EPKI
int32_t ParsePk8EncPriKeyBuff(BSL_Buffer *buff, const BSL_Buffer *pwd, CRYPT_EAL_PkeyCtx **ealPriKey);
int32_t CRYPT_DECODE_Pkcs8PrvDecrypt(CRYPT_EAL_LibCtx *libctx, const char *attrName, BSL_Buffer *buff,
const BSL_Buffer *pwd, BSL_ASN1_DecTemplCallBack keyInfoCb, BSL_Buffer *decode);
int32_t CRYPT_DECODE_ParseEncDataAsn1(CRYPT_EAL_LibCtx *libctx, const char *attrName, BslCid symAlg,
EncryptPara *encPara, const BSL_Buffer *pwd, BSL_ASN1_DecTemplCallBack keyInfoCb, BSL_Buffer *decode);
#endif
int32_t CRYPT_EAL_ParseAsn1SubPubkey(uint8_t *buff, uint32_t buffLen, void **ealPubKey, bool isComplete);
int32_t CRYPT_DECODE_AlgoIdAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_DecTemplCallBack keyInfoCb,
BSL_ASN1_Buffer *algoId, uint32_t algoIdNum);
int32_t CRYPT_DECODE_ConstructBufferOutParam(BSL_Param **outParam, uint8_t *buffer, uint32_t bufferLen);
int32_t CRYPT_DECODE_ParseSubKeyInfo(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *pubAsn1, bool isComplete);
int32_t CRYPT_DECODE_PrikeyAsn1Buff(uint8_t *buffer, uint32_t bufferLen, BSL_ASN1_Buffer *asn1, uint32_t arrNum);
#ifdef HITLS_CRYPTO_RSA
int32_t CRYPT_DECODE_RsaPubkeyAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *pubAsn1, uint32_t arrNum);
int32_t CRYPT_DECODE_RsaPrikeyAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *asn1, uint32_t asn1Num);
int32_t CRYPT_RSA_ParsePubkeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *param,
CRYPT_RSA_Ctx **rsaPubKey, BslCid cid);
int32_t CRYPT_RSA_ParsePkcs8Key(void *libCtx, uint8_t *buff, uint32_t buffLen, CRYPT_RSA_Ctx **rsaPriKey);
int32_t CRYPT_RSA_ParseSubPubkeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, CRYPT_RSA_Ctx **pubKey,
bool isComplete);
int32_t CRYPT_RSA_ParsePrikeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *rsaPssParam,
CRYPT_RSA_Ctx **rsaPriKey);
#endif
#if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_ECDH)
int32_t CRYPT_ECC_ParseSubPubkeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, void **pubKey, bool isComplete);
int32_t CRYPT_ECC_ParsePkcs8Key(void *libCtx, uint8_t *buff, uint32_t buffLen, void **ecdsaPriKey);
int32_t CRYPT_ECC_ParsePrikeyAsn1Buff(void *libCtx, uint8_t *buffer, uint32_t bufferLen, BSL_ASN1_Buffer *pk8AlgoParam,
void **ecPriKey);
#endif
#ifdef HITLS_CRYPTO_SM2
int32_t CRYPT_SM2_ParseSubPubkeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, CRYPT_SM2_Ctx **pubKey,
bool isComplete);
int32_t CRYPT_SM2_ParsePrikeyAsn1Buff(void *libCtx, uint8_t *buffer, uint32_t bufferLen, BSL_ASN1_Buffer *pk8AlgoParam,
CRYPT_SM2_Ctx **sm2PriKey);
int32_t CRYPT_SM2_ParsePkcs8Key(void *libCtx, uint8_t *buff, uint32_t buffLen, CRYPT_SM2_Ctx **sm2PriKey);
#endif
#ifdef HITLS_CRYPTO_ED25519
int32_t CRYPT_ED25519_ParsePkcs8Key(void *libCtx, uint8_t *buffer, uint32_t bufferLen,
CRYPT_CURVE25519_Ctx **ed25519PriKey);
int32_t CRYPT_ED25519_ParseSubPubkeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen,
CRYPT_CURVE25519_Ctx **pubKey, bool isComplete);
#endif
#endif
#ifdef HITLS_CRYPTO_KEY_ENCODE
int32_t EncodeRsaPubkeyAsn1Buff(CRYPT_EAL_PkeyCtx *ealPubKey, BSL_ASN1_Buffer *pssParam, BSL_Buffer *encodePub);
int32_t EncodeRsaPrikeyAsn1Buff(CRYPT_EAL_PkeyCtx *ealPriKey, CRYPT_PKEY_AlgId cid, BSL_Buffer *encode);
int32_t EncodeEccPrikeyAsn1Buff(CRYPT_EAL_PkeyCtx *ealPriKey, BSL_ASN1_Buffer *pk8AlgoParam, BSL_Buffer *encode);
int32_t EncodePk8PriKeyBuff(CRYPT_EAL_PkeyCtx *ealPriKey, BSL_Buffer *asn1);
int32_t CRYPT_ENCODE_SubPubkeyByInfo(BSL_ASN1_Buffer *algo, BSL_Buffer *bitStr, BSL_Buffer *encodeH,
bool isComplete);
int32_t CRYPT_ENCODE_AlgoIdAsn1Buff(BSL_ASN1_Buffer *algoId, uint32_t algoIdNum, uint8_t **buff,
uint32_t *buffLen);
int32_t CRYPT_ENCODE_PkcsEncryptedBuff(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_Pbkdf2Param *pkcsParam,
BSL_Buffer *unEncrypted, BSL_ASN1_Buffer *asn1);
int32_t CRYPT_ENCODE_EccPrikeyAsn1Buff(BSL_ASN1_Buffer *asn1, uint32_t asn1Num, BSL_Buffer *encode);
#ifdef HITLS_CRYPTO_KEY_EPKI
int32_t EncodePk8EncPriKeyBuff(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_EAL_PkeyCtx *ealPriKey,
const CRYPT_EncodeParam *encodeParam, BSL_Buffer *encode);
#endif
int32_t CRYPT_EAL_EncodeAsn1SubPubkey(CRYPT_EAL_PkeyCtx *ealPubKey, bool isComplete, BSL_Buffer *encodeH);
#ifdef HITLS_CRYPTO_RSA
int32_t CRYPT_ENCODE_RsaPrikeyAsn1Buff(BSL_ASN1_Buffer *asn1, uint32_t asn1Num, BSL_Buffer *encode);
int32_t CRYPT_ENCODE_RsaPubkeyAsn1Buff(BSL_ASN1_Buffer *pubAsn1, BSL_Buffer *encodePub);
#endif
#endif
static inline bool IsEcdsaEcParaId(int32_t paraId)
{
return paraId == CRYPT_ECC_NISTP224 || paraId == CRYPT_ECC_NISTP256 ||
paraId == CRYPT_ECC_NISTP384 || paraId == CRYPT_ECC_NISTP521 ||
paraId == CRYPT_ECC_BRAINPOOLP256R1 || paraId == CRYPT_ECC_BRAINPOOLP384R1 ||
paraId == CRYPT_ECC_BRAINPOOLP512R1;
}
#ifdef __cplusplus
}
#endif
#endif // HITLS_CRYPTO_CODECSKEY
#endif // CRYPT_ENCODE_DECODE_KEY_LOCAL_H
|
2301_79861745/bench_create
|
crypto/codecskey/src/crypt_encode_decode_local.h
|
C
|
unknown
| 8,212
|
/*
* 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_CODECSKEY
#include <stdint.h>
#include "securec.h"
#include "bsl_types.h"
#include "bsl_asn1_internal.h"
#include "bsl_obj_internal.h"
#include "bsl_err_internal.h"
#include "crypt_params_key.h"
#include "crypt_errno.h"
#include "crypt_encode_decode_key.h"
#include "crypt_encode_decode_local.h"
#include "crypt_eal_kdf.h"
#include "crypt_eal_cipher.h"
#include "crypt_eal_rand.h"
#ifdef HITLS_CRYPTO_RSA
/**
* RSAPrivateKey ::= SEQUENCE {
* version Version,
* modulus INTEGER, -- n
* publicExponent INTEGER, -- e
* privateExponent INTEGER, -- d
* prime1 INTEGER, -- p
* prime2 INTEGER, -- q
* exponent1 INTEGER, -- d mod (p-1)
* exponent2 INTEGER, -- d mod (q-1)
* coefficient INTEGER, -- (inverse of q) mod p
* otherPrimeInfos OtherPrimeInfos OPTIONAL
* }
*
* https://datatracker.ietf.org/doc/html/rfc3447#autoid-39
*/
static BSL_ASN1_TemplateItem g_rsaPrvTempl[] = {
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, /* ignore seq header */
{BSL_ASN1_TAG_INTEGER, 0, 1}, /* version */
{BSL_ASN1_TAG_INTEGER, 0, 1}, /* n */
{BSL_ASN1_TAG_INTEGER, 0, 1}, /* e */
{BSL_ASN1_TAG_INTEGER, 0, 1}, /* d */
{BSL_ASN1_TAG_INTEGER, 0, 1}, /* p */
{BSL_ASN1_TAG_INTEGER, 0, 1}, /* q */
{BSL_ASN1_TAG_INTEGER, 0, 1}, /* d mod (p-1) */
{BSL_ASN1_TAG_INTEGER, 0, 1}, /* d mod (q-1) */
{BSL_ASN1_TAG_INTEGER, 0, 1}, /* q^-1 mod p */
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE,
BSL_ASN1_FLAG_OPTIONAL | BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 1}, /* OtherPrimeInfos OPTIONAL */
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 2}, /* OtherPrimeInfo */
{BSL_ASN1_TAG_INTEGER, 0, 3}, /* ri */
{BSL_ASN1_TAG_INTEGER, 0, 3}, /* di */
{BSL_ASN1_TAG_INTEGER, 0, 3} /* ti */
};
/**
* RSAPublicKey ::= SEQUENCE {
* modulus INTEGER, -- n
* publicExponent INTEGER } -- e
*
* https://datatracker.ietf.org/doc/html/rfc4055#autoid-3
*/
static BSL_ASN1_TemplateItem g_rsaPubTempl[] = {
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, /* ignore seq */
{BSL_ASN1_TAG_INTEGER, 0, 1}, /* n */
{BSL_ASN1_TAG_INTEGER, 0, 1}, /* e */
};
#ifdef HITLS_CRYPTO_KEY_DECODE
/**
* ref: rfc4055
* RSASSA-PSS-params ::= SEQUENCE {
* hashAlgorithm [0] HashAlgorithm DEFAULT sha1Identifier,
* maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT mgf1SHA1Identifier,
* saltLength [2] INTEGER DEFAULT 20,
* trailerField [3] INTEGER DEFAULT 1
* }
* HashAlgorithm ::= AlgorithmIdentifier
* MaskGenAlgorithm ::= AlgorithmIdentifier
*/
static BSL_ASN1_TemplateItem g_rsaPssTempl[] = {
{BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_HASH,
BSL_ASN1_FLAG_DEFAULT, 0},
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1},
{BSL_ASN1_TAG_OBJECT_ID, 0, 2},
{BSL_ASN1_TAG_ANY, BSL_ASN1_FLAG_OPTIONAL, 2},
{BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_MASKGEN,
BSL_ASN1_FLAG_DEFAULT, 0},
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1},
{BSL_ASN1_TAG_OBJECT_ID, 0, 2},
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 2},
{BSL_ASN1_TAG_OBJECT_ID, 0, 3},
{BSL_ASN1_TAG_ANY, BSL_ASN1_FLAG_OPTIONAL, 3},
{BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_SALTLEN,
BSL_ASN1_FLAG_DEFAULT, 0},
{BSL_ASN1_TAG_INTEGER, 0, 1},
{BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_TRAILED,
BSL_ASN1_FLAG_DEFAULT, 0},
{BSL_ASN1_TAG_INTEGER, 0, 1}
};
typedef enum {
CRYPT_RSAPSS_HASH_IDX,
CRYPT_RSAPSS_HASHANY_IDX,
CRYPT_RSAPSS_MGF1_IDX,
CRYPT_RSAPSS_MGF1PARAM_IDX,
CRYPT_RSAPSS_MGF1PARAMANY_IDX,
CRYPT_RSAPSS_SALTLEN_IDX,
CRYPT_RSAPSS_TRAILED_IDX,
CRYPT_RSAPSS_MAX
} CRYPT_RSAPSS_IDX;
#endif // HITLS_CRYPTO_KEY_DECODE
#endif
#if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2)
/**
* ECPrivateKey ::= SEQUENCE {
* version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
* privateKey OCTET STRING,
* parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
* publicKey [1] BIT STRING OPTIONAL
* }
*
* https://datatracker.ietf.org/doc/html/rfc5915#autoid-3
*/
#define BSL_ASN1_TAG_EC_PRIKEY_PARAM 0
#define BSL_ASN1_TAG_EC_PRIKEY_PUBKEY 1
static BSL_ASN1_TemplateItem g_ecPriKeyTempl[] = {
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, // ignore seq header
{BSL_ASN1_TAG_INTEGER, 0, 1}, /* version */
{BSL_ASN1_TAG_OCTETSTRING, 0, 1}, /* private key */
{BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_EC_PRIKEY_PARAM,
BSL_ASN1_FLAG_OPTIONAL, 1},
{BSL_ASN1_TAG_OBJECT_ID, 0, 2},
{BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_EC_PRIKEY_PUBKEY,
BSL_ASN1_FLAG_OPTIONAL, 1},
{BSL_ASN1_TAG_BITSTRING, 0, 2},
};
#endif
/**
* PrivateKeyInfo ::= SEQUENCE {
* version INTEGER,
* privateKeyAlgorithm AlgorithmIdentifier,
* privateKey OCTET STRING,
* attributes [0] IMPLICIT Attributes OPTIONAL }
*
* https://datatracker.ietf.org/doc/html/rfc5208#autoid-5
*/
static BSL_ASN1_TemplateItem g_pk8PriKeyTempl[] = {
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, // ignore seq header
{BSL_ASN1_TAG_INTEGER, 0, 1},
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 1},
{BSL_ASN1_TAG_OCTETSTRING, 0, 1},
};
typedef enum {
CRYPT_PK8_PRIKEY_VERSION_IDX = 0,
CRYPT_PK8_PRIKEY_ALGID_IDX = 1,
CRYPT_PK8_PRIKEY_PRIKEY_IDX = 2,
} CRYPT_PK8_PRIKEY_TEMPL_IDX;
#ifdef HITLS_CRYPTO_KEY_EPKI
#ifdef HITLS_CRYPTO_KEY_DECODE
/**
* EncryptedPrivateKeyInfo ::= SEQUENCE {
* encryptionAlgorithm EncryptionAlgorithmIdentifier,
* encryptedData EncryptedData }
*
* https://datatracker.ietf.org/doc/html/rfc5208#autoid-6
*/
static BSL_ASN1_TemplateItem g_pk8EncPriKeyTempl[] = {
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0},
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, // EncryptionAlgorithmIdentifier
{BSL_ASN1_TAG_OBJECT_ID, 0, 2},
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 2},
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 3}, // derivation param
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 3}, // enc scheme
{BSL_ASN1_TAG_OBJECT_ID, 0, 4}, // alg
{BSL_ASN1_TAG_OCTETSTRING, 0, 4}, // iv
{BSL_ASN1_TAG_OCTETSTRING, 0, 1}, // EncryptedData
};
#endif
static BSL_ASN1_TemplateItem g_pbkdf2DerParamTempl[] = {
{BSL_ASN1_TAG_OBJECT_ID, 0, 0}, // derive alg
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0},
{BSL_ASN1_TAG_OCTETSTRING, 0, 1}, // salt
{BSL_ASN1_TAG_INTEGER, 0, 1}, // iteration
{BSL_ASN1_TAG_INTEGER, BSL_ASN1_FLAG_OPTIONAL, 1}, // keyLen
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_DEFAULT | BSL_ASN1_FLAG_HEADERONLY, 1}, // prf
};
#endif // HITLS_CRYPTO_KEY_EPKI
/**
* SubjectPublicKeyInfo ::= SEQUENCE {
* algorithm AlgorithmIdentifier,
* subjectPublicKey BIT STRING
* }
*
* https://datatracker.ietf.org/doc/html/rfc5480#autoid-3
*/
static BSL_ASN1_TemplateItem g_subKeyInfoTempl[] = {
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0},
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 1},
{BSL_ASN1_TAG_BITSTRING, 0, 1},
};
static BSL_ASN1_TemplateItem g_subKeyInfoInnerTempl[] = {
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 0},
{BSL_ASN1_TAG_BITSTRING, 0, 0},
};
/**
* AlgorithmIdentifier ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER,
* parameters ANY DEFINED BY algorithm OPTIONAL }
*
* https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.1.2
*/
static BSL_ASN1_TemplateItem g_algoIdTempl[] = {
{BSL_ASN1_TAG_OBJECT_ID, 0, 0},
{BSL_ASN1_TAG_ANY, BSL_ASN1_FLAG_OPTIONAL, 0},
};
#ifdef HITLS_CRYPTO_KEY_EPKI
typedef enum {
CRYPT_PKCS_ENC_DERALG_IDX,
CRYPT_PKCS_ENC_DERSALT_IDX,
CRYPT_PKCS_ENC_DERITER_IDX,
CRYPT_PKCS_ENC_DERKEYLEN_IDX,
CRYPT_PKCS_ENC_DERPRF_IDX,
CRYPT_PKCS_ENC_DERPARAM_MAX
} CRYPT_PKCS_ENC_DERIVEPARAM_IDX;
static int32_t CRYPT_ENCODE_DECODE_DecryptEncData(CRYPT_EAL_LibCtx *libctx, const char *attrName, BSL_Buffer *ivData,
BSL_Buffer *enData, int32_t alg, bool isEnc, BSL_Buffer *key, uint8_t *output, uint32_t *dataLen)
{
uint32_t buffLen = *dataLen;
CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_ProviderCipherNewCtx(libctx, alg, attrName);
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
int32_t ret = CRYPT_EAL_CipherInit(ctx, key->data, key->dataLen, ivData->data, ivData->dataLen, isEnc);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
uint32_t blockSize;
ret = CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_BLOCKSIZE, &blockSize, sizeof(blockSize));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
if (blockSize != 1) {
ret = CRYPT_EAL_CipherSetPadding(ctx, CRYPT_PADDING_PKCS7);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
}
ret = CRYPT_EAL_CipherUpdate(ctx, enData->data, enData->dataLen, output, dataLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
buffLen -= *dataLen;
ret = CRYPT_EAL_CipherFinal(ctx, output + *dataLen, &buffLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
*dataLen += buffLen;
EXIT:
CRYPT_EAL_CipherFreeCtx(ctx);
return ret;
}
static int32_t PbkdfDeriveKey(CRYPT_EAL_LibCtx *libctx, const char *attrName, uint32_t iter, int32_t prfId,
BSL_Buffer *salt, const uint8_t *pwd, uint32_t pwdLen, BSL_Buffer *key)
{
CRYPT_EAL_KdfCTX *kdfCtx = CRYPT_EAL_ProviderKdfNewCtx(libctx, CRYPT_KDF_PBKDF2, attrName);
if (kdfCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_PBKDF2_NOT_SUPPORTED);
return CRYPT_PBKDF2_NOT_SUPPORTED;
}
BSL_Param params[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END};
(void)BSL_PARAM_InitValue(¶ms[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &prfId, sizeof(prfId));
(void)BSL_PARAM_InitValue(¶ms[1], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS,
(uint8_t *)(uintptr_t)pwd, pwdLen); // Fixed pwd parameter
(void)BSL_PARAM_InitValue(¶ms[2], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt->data, salt->dataLen);
(void)BSL_PARAM_InitValue(¶ms[3], CRYPT_PARAM_KDF_ITER, BSL_PARAM_TYPE_UINT32, &iter, sizeof(iter));
int32_t ret = CRYPT_EAL_KdfSetParam(kdfCtx, params);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = CRYPT_EAL_KdfDerive(kdfCtx, key->data, key->dataLen);
EXIT:
CRYPT_EAL_KdfFreeCtx(kdfCtx);
return ret;
}
#endif // HITLS_CRYPTO_EPKI
#ifdef HITLS_CRYPTO_KEY_DECODE
#if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2)
int32_t CRYPT_DECODE_PrikeyAsn1Buff(uint8_t *buffer, uint32_t bufferLen, BSL_ASN1_Buffer *asn1, uint32_t arrNum)
{
uint8_t *tmpBuff = buffer;
uint32_t tmpBuffLen = bufferLen;
BSL_ASN1_Template templ = {g_ecPriKeyTempl, sizeof(g_ecPriKeyTempl) / sizeof(g_ecPriKeyTempl[0])};
int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &tmpBuff, &tmpBuffLen, asn1, arrNum);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
#endif
#ifdef HITLS_CRYPTO_RSA
int32_t CRYPT_DECODE_RsaPubkeyAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *pubAsn1, uint32_t arrNum)
{
if (buff == NULL || pubAsn1 == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
uint8_t *tmpBuff = buff;
uint32_t tmpBuffLen = buffLen;
BSL_ASN1_Template pubTempl = {g_rsaPubTempl, sizeof(g_rsaPubTempl) / sizeof(g_rsaPubTempl[0])};
int32_t ret = BSL_ASN1_DecodeTemplate(&pubTempl, NULL, &tmpBuff, &tmpBuffLen, pubAsn1, arrNum);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
int32_t CRYPT_DECODE_RsaPrikeyAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *asn1, uint32_t asn1Num)
{
uint8_t *tmpBuff = buff;
uint32_t tmpBuffLen = buffLen;
BSL_ASN1_Template templ = {g_rsaPrvTempl, sizeof(g_rsaPrvTempl) / sizeof(g_rsaPrvTempl[0])};
int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &tmpBuff, &tmpBuffLen, asn1, asn1Num);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
static int32_t RsaPssTagGetOrCheck(int32_t type, uint32_t idx, void *data, void *expVal)
{
(void) idx;
(void) data;
if (type == BSL_ASN1_TYPE_GET_ANY_TAG) {
*(uint8_t *) expVal = BSL_ASN1_TAG_NULL; // is null
return CRYPT_SUCCESS;
}
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_RSSPSS_GET_ANY_TAG);
return CRYPT_DECODE_ERR_RSSPSS_GET_ANY_TAG;
}
int32_t CRYPT_EAL_ParseRsaPssAlgParam(BSL_ASN1_Buffer *param, CRYPT_RSA_PssPara *para)
{
para->mdId = (CRYPT_MD_AlgId)BSL_CID_SHA1; // hashAlgorithm [0] HashAlgorithm DEFAULT sha1Identifier,
para->mgfId = (CRYPT_MD_AlgId)BSL_CID_SHA1; // maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT mgf1SHA1Identifier,
para->saltLen = 20; // saltLength [2] INTEGER DEFAULT 20
uint8_t *temp = param->buff;
uint32_t tempLen = param->len;
BSL_ASN1_Buffer asns[CRYPT_RSAPSS_MAX] = {0};
BSL_ASN1_Template templ = {g_rsaPssTempl, sizeof(g_rsaPssTempl) / sizeof(g_rsaPssTempl[0])};
int32_t ret = BSL_ASN1_DecodeTemplate(&templ, RsaPssTagGetOrCheck, &temp, &tempLen, asns, CRYPT_RSAPSS_MAX);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_RSSPSS);
return CRYPT_DECODE_ERR_RSSPSS;
}
if (asns[CRYPT_RSAPSS_HASH_IDX].tag != 0) {
BslOidString hashOid = {asns[CRYPT_RSAPSS_HASH_IDX].len, (char *)asns[CRYPT_RSAPSS_HASH_IDX].buff, 0};
para->mdId = (CRYPT_MD_AlgId)BSL_OBJ_GetCID(&hashOid);
if (para->mdId == (CRYPT_MD_AlgId)BSL_CID_UNKNOWN) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_RSSPSS_MD);
return CRYPT_DECODE_ERR_RSSPSS_MD;
}
}
if (asns[CRYPT_RSAPSS_MGF1PARAM_IDX].tag != 0) {
BslOidString mgf1 = {asns[CRYPT_RSAPSS_MGF1PARAM_IDX].len, (char *)asns[CRYPT_RSAPSS_MGF1PARAM_IDX].buff, 0};
para->mgfId = (CRYPT_MD_AlgId)BSL_OBJ_GetCID(&mgf1);
if (para->mgfId == (CRYPT_MD_AlgId)BSL_CID_UNKNOWN) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_RSSPSS_MGF1MD);
return CRYPT_DECODE_ERR_RSSPSS_MGF1MD;
}
}
if (asns[CRYPT_RSAPSS_SALTLEN_IDX].tag != 0) {
ret = BSL_ASN1_DecodePrimitiveItem(&asns[CRYPT_RSAPSS_SALTLEN_IDX], ¶->saltLen);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
if (asns[CRYPT_RSAPSS_TRAILED_IDX].tag != 0) {
// trailerField
ret = BSL_ASN1_DecodePrimitiveItem(&asns[CRYPT_RSAPSS_TRAILED_IDX], &tempLen);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (tempLen != 1) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_RSSPSS_TRAILER);
return CRYPT_DECODE_ERR_RSSPSS_TRAILER;
}
}
return ret;
}
#endif
static int32_t DecSubKeyInfoCb(int32_t type, uint32_t idx, void *data, void *expVal)
{
(void)idx;
BSL_ASN1_Buffer *param = (BSL_ASN1_Buffer *)data;
switch (type) {
case BSL_ASN1_TYPE_GET_ANY_TAG: {
BslOidString oidStr = {param->len, (char *)param->buff, 0};
BslCid cid = BSL_OBJ_GetCID(&oidStr);
if (cid == BSL_CID_EC_PUBLICKEY || cid == BSL_CID_SM2PRIME256) {
// note: any It can be encoded empty or it can be null
*(uint8_t *)expVal = BSL_ASN1_TAG_OBJECT_ID;
} else if (cid == BSL_CID_RSASSAPSS) {
*(uint8_t *)expVal = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE;
} else if (cid == BSL_CID_ED25519) {
/* RFC8410: Ed25519 has no algorithm parameters */
*(uint8_t *)expVal = BSL_ASN1_TAG_EMPTY; // is empty
} else {
*(uint8_t *)expVal = BSL_ASN1_TAG_NULL; // is null
}
return CRYPT_SUCCESS;
}
default:
break;
}
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ASN1_BUFF_FAILED);
return CRYPT_DECODE_ASN1_BUFF_FAILED;
}
int32_t CRYPT_DECODE_ParseSubKeyInfo(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *pubAsn1, bool isComplete)
{
uint8_t *tmpBuff = buff;
uint32_t tmpBuffLen = buffLen;
// decode sub pubkey info
BSL_ASN1_Template pubTempl;
if (isComplete) {
pubTempl.templItems = g_subKeyInfoTempl;
pubTempl.templNum = sizeof(g_subKeyInfoTempl) / sizeof(g_subKeyInfoTempl[0]);
} else {
pubTempl.templItems = g_subKeyInfoInnerTempl;
pubTempl.templNum = sizeof(g_subKeyInfoInnerTempl) / sizeof(g_subKeyInfoInnerTempl[0]);
}
int32_t ret = BSL_ASN1_DecodeTemplate(&pubTempl, DecSubKeyInfoCb, &tmpBuff, &tmpBuffLen, pubAsn1,
CRYPT_SUBKEYINFO_BITSTRING_IDX + 1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
int32_t CRYPT_DECODE_AlgoIdAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_DecTemplCallBack keyInfoCb,
BSL_ASN1_Buffer *algoId, uint32_t algoIdNum)
{
uint8_t *tmpBuff = buff;
uint32_t tmpBuffLen = buffLen;
BSL_ASN1_DecTemplCallBack cb = keyInfoCb == NULL ? DecSubKeyInfoCb : keyInfoCb;
BSL_ASN1_Template templ = {g_algoIdTempl, sizeof(g_algoIdTempl) / sizeof(g_algoIdTempl[0])};
return BSL_ASN1_DecodeTemplate(&templ, cb, &tmpBuff, &tmpBuffLen, algoId, algoIdNum);
}
int32_t CRYPT_DECODE_SubPubkey(uint8_t *buff, uint32_t buffLen, BSL_ASN1_DecTemplCallBack keyInfoCb,
CRYPT_DECODE_SubPubkeyInfo *subPubkeyInfo, bool isComplete)
{
if (buff == NULL || subPubkeyInfo == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
BSL_ASN1_Buffer pubAsn1[CRYPT_SUBKEYINFO_BITSTRING_IDX + 1] = {0};
BSL_ASN1_BitString bitPubkey = {0};
BSL_ASN1_Buffer algoId[BSL_ASN1_TAG_ALGOID_ANY_IDX + 1] = {0};
int32_t ret = CRYPT_DECODE_ParseSubKeyInfo(buff, buffLen, pubAsn1, isComplete);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = CRYPT_DECODE_AlgoIdAsn1Buff(pubAsn1->buff, pubAsn1->len, keyInfoCb, algoId, BSL_ASN1_TAG_ALGOID_ANY_IDX + 1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BSL_ASN1_Buffer *oid = algoId;
BSL_ASN1_Buffer *pubkey = &pubAsn1[CRYPT_SUBKEYINFO_BITSTRING_IDX];
ret = BSL_ASN1_DecodePrimitiveItem(pubkey, &bitPubkey);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BslOidString oidStr = {oid->len, (char *)oid->buff, 0};
BslCid cid = BSL_OBJ_GetCID(&oidStr);
if (cid == BSL_CID_UNKNOWN) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_UNKNOWN_OID);
return CRYPT_DECODE_UNKNOWN_OID;
}
subPubkeyInfo->keyType = cid;
subPubkeyInfo->keyParam = *(algoId + 1);
subPubkeyInfo->pubKey = bitPubkey;
return CRYPT_SUCCESS;
}
static int32_t ParsePk8PriParamAsn1(BSL_ASN1_Buffer *encode, BSL_ASN1_DecTemplCallBack keyInfoCb, BslCid *keyType,
BSL_ASN1_Buffer *keyParam)
{
BSL_ASN1_Buffer *algo = &encode[CRYPT_PK8_PRIKEY_ALGID_IDX]; // AlgorithmIdentifier
BSL_ASN1_Buffer algoId[BSL_ASN1_TAG_ALGOID_ANY_IDX + 1] = {0};
int32_t ret = CRYPT_DECODE_AlgoIdAsn1Buff(algo->buff, algo->len, keyInfoCb,
algoId, BSL_ASN1_TAG_ALGOID_ANY_IDX + 1);
if (ret != CRYPT_SUCCESS) {
return ret;
}
BslOidString oidStr = {algoId[0].len, (char *)algoId[0].buff, 0};
BslCid cid = BSL_OBJ_GetCID(&oidStr);
if (cid == BSL_CID_UNKNOWN) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_UNKNOWN_OID);
return CRYPT_DECODE_UNKNOWN_OID;
}
*keyType = cid;
*keyParam = *(algoId + 1);
return CRYPT_SUCCESS;
}
int32_t CRYPT_DECODE_Pkcs8Info(uint8_t *buff, uint32_t buffLen, BSL_ASN1_DecTemplCallBack keyInfoCb,
CRYPT_ENCODE_DECODE_Pk8PrikeyInfo *pk8PrikeyInfo)
{
if (buff == NULL || buffLen == 0 || pk8PrikeyInfo == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
uint8_t *tmpBuff = buff;
uint32_t tmpBuffLen = buffLen;
int32_t version = 0;
BslCid keyType = BSL_CID_UNKNOWN;
BSL_ASN1_Buffer keyParam = {0};
BSL_ASN1_Buffer asn1[CRYPT_PK8_PRIKEY_PRIKEY_IDX + 1] = {0};
BSL_ASN1_Template templ = {g_pk8PriKeyTempl, sizeof(g_pk8PriKeyTempl) / sizeof(g_pk8PriKeyTempl[0])};
int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &tmpBuff, &tmpBuffLen, asn1, CRYPT_PK8_PRIKEY_PRIKEY_IDX + 1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = BSL_ASN1_DecodePrimitiveItem(&asn1[CRYPT_PK8_PRIKEY_VERSION_IDX], &version);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BSL_ASN1_Buffer octPriKey = asn1[CRYPT_PK8_PRIKEY_PRIKEY_IDX];
ret = ParsePk8PriParamAsn1(asn1, keyInfoCb, &keyType, &keyParam);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
pk8PrikeyInfo->version = version;
pk8PrikeyInfo->keyType = keyType;
pk8PrikeyInfo->pkeyRawKey = octPriKey.buff;
pk8PrikeyInfo->pkeyRawKeyLen = octPriKey.len;
pk8PrikeyInfo->keyParam = keyParam;
pk8PrikeyInfo->attrs = NULL;
return CRYPT_SUCCESS;
}
#ifdef HITLS_CRYPTO_KEY_EPKI
static int32_t ParseDeriveKeyPrfAlgId(BSL_ASN1_Buffer *asn, int32_t *prfId, BSL_ASN1_DecTemplCallBack keyInfoCb)
{
if (asn->len != 0) {
BSL_ASN1_Buffer algoId[2] = {0};
int32_t ret = CRYPT_DECODE_AlgoIdAsn1Buff(asn->buff, asn->len, keyInfoCb, algoId, 2);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BslOidString oidStr = {algoId[BSL_ASN1_TAG_ALGOID_IDX].len,
(char *)algoId[BSL_ASN1_TAG_ALGOID_IDX].buff, 0};
*prfId = BSL_OBJ_GetCID(&oidStr);
if (*prfId == BSL_CID_UNKNOWN) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PKCS8_INVALID_ALGO_PARAM);
return CRYPT_DECODE_PKCS8_INVALID_ALGO_PARAM;
}
} else {
*prfId = BSL_CID_HMAC_SHA1;
}
return CRYPT_SUCCESS;
}
static int32_t ParseDeriveKeyParam(BSL_Buffer *derivekeyData, uint32_t *iter, uint32_t *keyLen, BSL_Buffer *salt,
int32_t *prfId, BSL_ASN1_DecTemplCallBack keyInfoCb)
{
uint8_t *tmpBuff = derivekeyData->data;
uint32_t tmpBuffLen = derivekeyData->dataLen;
BSL_ASN1_Buffer derParam[CRYPT_PKCS_ENC_DERPARAM_MAX] = {0};
BSL_ASN1_Template templ = {g_pbkdf2DerParamTempl, sizeof(g_pbkdf2DerParamTempl) / sizeof(g_pbkdf2DerParamTempl[0])};
int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL,
&tmpBuff, &tmpBuffLen, derParam, CRYPT_PKCS_ENC_DERPARAM_MAX);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BslOidString oidStr = {derParam[CRYPT_PKCS_ENC_DERALG_IDX].len,
(char *)derParam[CRYPT_PKCS_ENC_DERALG_IDX].buff, 0};
BslCid cid = BSL_OBJ_GetCID(&oidStr);
if (cid != BSL_CID_PBKDF2) { // only pbkdf2 is supported
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PKCS8_INVALID_ALGO_PARAM);
return CRYPT_DECODE_PKCS8_INVALID_ALGO_PARAM;
}
ret = BSL_ASN1_DecodePrimitiveItem(&derParam[CRYPT_PKCS_ENC_DERITER_IDX], iter);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PKCS8_INVALID_ITER);
return CRYPT_DECODE_PKCS8_INVALID_ITER;
}
if (derParam[CRYPT_PKCS_ENC_DERKEYLEN_IDX].len != 0) {
ret = BSL_ASN1_DecodePrimitiveItem(&derParam[CRYPT_PKCS_ENC_DERKEYLEN_IDX], keyLen);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PKCS8_INVALID_KEYLEN);
return CRYPT_DECODE_PKCS8_INVALID_KEYLEN;
}
}
salt->data = derParam[CRYPT_PKCS_ENC_DERSALT_IDX].buff;
salt->dataLen = derParam[CRYPT_PKCS_ENC_DERSALT_IDX].len;
return ParseDeriveKeyPrfAlgId(&derParam[CRYPT_PKCS_ENC_DERPRF_IDX], prfId, keyInfoCb);
}
int32_t CRYPT_DECODE_ParseEncDataAsn1(CRYPT_EAL_LibCtx *libctx, const char *attrName, BslCid symAlg,
EncryptPara *encPara, const BSL_Buffer *pwd, BSL_ASN1_DecTemplCallBack keyInfoCb, BSL_Buffer *decode)
{
uint32_t iter;
int32_t prfId;
uint32_t keylen = 0;
uint8_t key[512] = {0}; // The maximum length of the symmetry algorithm
BSL_Buffer salt = {0};
int32_t ret = ParseDeriveKeyParam(encPara->derivekeyData, &iter, &keylen, &salt, &prfId, keyInfoCb);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
uint32_t symKeyLen;
ret = CRYPT_EAL_CipherGetInfo((CRYPT_CIPHER_AlgId)symAlg, CRYPT_INFO_KEY_LEN, &symKeyLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (keylen != 0 && symKeyLen != keylen) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PKCS8_INVALID_KEYLEN);
return CRYPT_DECODE_PKCS8_INVALID_KEYLEN;
}
BSL_Buffer keyBuff = {key, symKeyLen};
ret = PbkdfDeriveKey(libctx, attrName, iter, prfId, &salt, pwd->data, pwd->dataLen, &keyBuff);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (encPara->enData->dataLen != 0) {
uint8_t *output = BSL_SAL_Malloc(encPara->enData->dataLen);
if (output == NULL) {
(void)memset_s(key, sizeof(key), 0, sizeof(key));
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
uint32_t dataLen = encPara->enData->dataLen;
ret = CRYPT_ENCODE_DECODE_DecryptEncData(libctx, attrName, encPara->ivData, encPara->enData, symAlg, false,
&keyBuff, output, &dataLen);
if (ret != CRYPT_SUCCESS) {
(void)memset_s(key, sizeof(key), 0, sizeof(key));
BSL_SAL_Free(output);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
decode->data = output;
decode->dataLen = dataLen;
}
(void)memset_s(key, sizeof(key), 0, sizeof(key));
return CRYPT_SUCCESS;
}
int32_t CRYPT_DECODE_Pkcs8PrvDecrypt(CRYPT_EAL_LibCtx *libctx, const char *attrName, BSL_Buffer *buff,
const BSL_Buffer *pwd, BSL_ASN1_DecTemplCallBack keyInfoCb, BSL_Buffer *decode)
{
if (buff == NULL || buff->dataLen == 0 || pwd == NULL || decode == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (pwd->dataLen > PWD_MAX_LEN || (pwd->data == NULL && pwd->dataLen != 0)) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
uint8_t *tmpBuff = buff->data;
uint32_t tmpBuffLen = buff->dataLen;
BSL_ASN1_Buffer asn1[CRYPT_PKCS_ENCPRIKEY_MAX] = {0};
BSL_ASN1_Template templ = {g_pk8EncPriKeyTempl, sizeof(g_pk8EncPriKeyTempl) / sizeof(g_pk8EncPriKeyTempl[0])};
int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &tmpBuff, &tmpBuffLen, asn1, CRYPT_PKCS_ENCPRIKEY_MAX);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BslOidString encOidStr = {asn1[CRYPT_PKCS_ENCPRIKEY_ENCALG_IDX].len,
(char *)asn1[CRYPT_PKCS_ENCPRIKEY_ENCALG_IDX].buff, 0};
BslCid cid = BSL_OBJ_GetCID(&encOidStr);
if (cid != BSL_CID_PBES2) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_UNKNOWN_OID);
return CRYPT_DECODE_UNKNOWN_OID;
}
// parse sym alg id
BslOidString symOidStr = {asn1[CRYPT_PKCS_ENCPRIKEY_SYMALG_IDX].len,
(char *)asn1[CRYPT_PKCS_ENCPRIKEY_SYMALG_IDX].buff, 0};
BslCid symId = BSL_OBJ_GetCID(&symOidStr);
if (symId == BSL_CID_UNKNOWN) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_UNKNOWN_OID);
return CRYPT_DECODE_UNKNOWN_OID;
}
BSL_Buffer derivekeyData = {asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].buff,
asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].len};
BSL_Buffer ivData = {asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].buff, asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].len};
BSL_Buffer enData = {asn1[CRYPT_PKCS_ENCPRIKEY_ENCDATA_IDX].buff, asn1[CRYPT_PKCS_ENCPRIKEY_ENCDATA_IDX].len};
EncryptPara encPara = {
.derivekeyData = &derivekeyData,
.ivData = &ivData,
.enData = &enData,
};
ret = CRYPT_DECODE_ParseEncDataAsn1(libctx, attrName, symId, &encPara, pwd, keyInfoCb, decode);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
#endif /* HITLS_CRYPTO_KEY_EPKI */
int32_t CRYPT_DECODE_ConstructBufferOutParam(BSL_Param **outParam, uint8_t *buffer, uint32_t bufferLen)
{
BSL_Param *result = BSL_SAL_Calloc(2, sizeof(BSL_Param));
if (result == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
int32_t ret = BSL_PARAM_InitValue(&result[0], CRYPT_PARAM_DECODE_BUFFER_DATA, BSL_PARAM_TYPE_OCTETS,
buffer, bufferLen);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_Free(result);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
*outParam = result;
return ret;
}
#endif /* HITLS_CRYPTO_KEY_DECODE */
#ifdef HITLS_CRYPTO_KEY_ENCODE
#if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2)
int32_t CRYPT_ENCODE_EccPrikeyAsn1Buff(BSL_ASN1_Buffer *asn1, uint32_t asn1Num, BSL_Buffer *encode)
{
BSL_ASN1_Template templ = {g_ecPriKeyTempl, sizeof(g_ecPriKeyTempl) / sizeof(g_ecPriKeyTempl[0])};
return BSL_ASN1_EncodeTemplate(&templ, asn1, asn1Num, &encode->data, &encode->dataLen);
}
#endif /* HITLS_CRYPTO_ECDSA || HITLS_CRYPTO_SM2 */
#ifdef HITLS_CRYPTO_RSA
int32_t CRYPT_ENCODE_RsaPubkeyAsn1Buff(BSL_ASN1_Buffer *pubAsn1, BSL_Buffer *encodePub)
{
BSL_ASN1_Template pubTempl = {g_rsaPubTempl, sizeof(g_rsaPubTempl) / sizeof(g_rsaPubTempl[0])};
int32_t ret = BSL_ASN1_EncodeTemplate(&pubTempl, pubAsn1, CRYPT_RSA_PUB_E_IDX + 1,
&encodePub->data, &encodePub->dataLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_ENCODE_RsaPrikeyAsn1Buff(BSL_ASN1_Buffer *asn1, uint32_t asn1Num, BSL_Buffer *encode)
{
BSL_ASN1_Template templ = {g_rsaPrvTempl, sizeof(g_rsaPrvTempl) / sizeof(g_rsaPrvTempl[0])};
int32_t ret = BSL_ASN1_EncodeTemplate(&templ, asn1, asn1Num, &encode->data, &encode->dataLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
#endif
int32_t CRYPT_ENCODE_SubPubkeyByInfo(BSL_ASN1_Buffer *algo, BSL_Buffer *bitStr, BSL_Buffer *encodeH,
bool isComplete)
{
BSL_ASN1_Buffer encode[CRYPT_SUBKEYINFO_BITSTRING_IDX + 1] = {0};
encode[CRYPT_SUBKEYINFO_ALGOID_IDX].buff = algo->buff;
encode[CRYPT_SUBKEYINFO_ALGOID_IDX].len = algo->len;
encode[CRYPT_SUBKEYINFO_ALGOID_IDX].tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE;
BSL_ASN1_BitString bitPubkey = {bitStr->data, bitStr->dataLen, 0};
encode[CRYPT_SUBKEYINFO_BITSTRING_IDX].buff = (uint8_t *)&bitPubkey;
encode[CRYPT_SUBKEYINFO_BITSTRING_IDX].len = sizeof(BSL_ASN1_BitString);
encode[CRYPT_SUBKEYINFO_BITSTRING_IDX].tag = BSL_ASN1_TAG_BITSTRING;
BSL_ASN1_Template pubTempl;
if (isComplete) {
pubTempl.templItems = g_subKeyInfoTempl;
pubTempl.templNum = sizeof(g_subKeyInfoTempl) / sizeof(g_subKeyInfoTempl[0]);
} else {
pubTempl.templItems = g_subKeyInfoInnerTempl;
pubTempl.templNum = sizeof(g_subKeyInfoInnerTempl) / sizeof(g_subKeyInfoInnerTempl[0]);
}
int32_t ret = BSL_ASN1_EncodeTemplate(&pubTempl,
encode, CRYPT_SUBKEYINFO_BITSTRING_IDX + 1, &encodeH->data, &encodeH->dataLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
int32_t CRYPT_ENCODE_AlgoIdAsn1Buff(BSL_ASN1_Buffer *algoId, uint32_t algoIdNum, uint8_t **buff,
uint32_t *buffLen)
{
BSL_ASN1_Template templ = {g_algoIdTempl, sizeof(g_algoIdTempl) / sizeof(g_algoIdTempl[0])};
return BSL_ASN1_EncodeTemplate(&templ, algoId, algoIdNum, buff, buffLen);
}
#ifdef HITLS_CRYPTO_KEY_EPKI
static int32_t EncodeDeriveKeyParam(CRYPT_EAL_LibCtx *libCtx, CRYPT_Pbkdf2Param *param, BSL_Buffer *encode,
BSL_Buffer *salt)
{
BSL_ASN1_Buffer derParam[CRYPT_PKCS_ENC_DERPRF_IDX + 1] = {0};
/* deralg */
BslOidString *oidPbkdf = BSL_OBJ_GetOID((BslCid)param->pbkdfId);
if (oidPbkdf == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID);
return CRYPT_ERR_ALGID;
}
derParam[CRYPT_PKCS_ENC_DERALG_IDX].buff = (uint8_t *)oidPbkdf->octs;
derParam[CRYPT_PKCS_ENC_DERALG_IDX].len = oidPbkdf->octetLen;
derParam[CRYPT_PKCS_ENC_DERALG_IDX].tag = BSL_ASN1_TAG_OBJECT_ID;
/* salt */
int32_t ret = CRYPT_EAL_RandbytesEx(libCtx, salt->data, salt->dataLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
derParam[CRYPT_PKCS_ENC_DERSALT_IDX].buff = salt->data;
derParam[CRYPT_PKCS_ENC_DERSALT_IDX].len = salt->dataLen;
derParam[CRYPT_PKCS_ENC_DERSALT_IDX].tag = BSL_ASN1_TAG_OCTETSTRING;
/* iter */
ret = BSL_ASN1_EncodeLimb(BSL_ASN1_TAG_INTEGER, param->itCnt, &derParam[CRYPT_PKCS_ENC_DERITER_IDX]);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BSL_ASN1_Template templ = {g_pbkdf2DerParamTempl, sizeof(g_pbkdf2DerParamTempl) / sizeof(g_pbkdf2DerParamTempl[0])};
if (param->hmacId == CRYPT_MAC_HMAC_SHA1) {
ret = BSL_ASN1_EncodeTemplate(&templ, derParam, CRYPT_PKCS_ENC_DERPRF_IDX + 1, &encode->data, &encode->dataLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
BSL_SAL_FREE(derParam[CRYPT_PKCS_ENC_DERITER_IDX].buff);
return ret;
}
BslOidString *oidHmac = BSL_OBJ_GetOID((BslCid)param->hmacId);
if (oidHmac == NULL) {
BSL_SAL_FREE(derParam[CRYPT_PKCS_ENC_DERITER_IDX].buff);
BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID);
return CRYPT_ERR_ALGID;
}
BSL_Buffer algo = {0};
BSL_ASN1_Buffer algoId[BSL_ASN1_TAG_ALGOID_ANY_IDX + 1] = {
{BSL_ASN1_TAG_OBJECT_ID, oidHmac->octetLen, (uint8_t *)oidHmac->octs},
{BSL_ASN1_TAG_NULL, 0, NULL},
};
ret = CRYPT_ENCODE_AlgoIdAsn1Buff(algoId, BSL_ASN1_TAG_ALGOID_ANY_IDX + 1, &algo.data, &algo.dataLen);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_FREE(derParam[CRYPT_PKCS_ENC_DERITER_IDX].buff);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
derParam[CRYPT_PKCS_ENC_DERPRF_IDX].buff = algo.data;
derParam[CRYPT_PKCS_ENC_DERPRF_IDX].len = algo.dataLen;
derParam[CRYPT_PKCS_ENC_DERPRF_IDX].tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE;
ret = BSL_ASN1_EncodeTemplate(&templ,
derParam, CRYPT_PKCS_ENC_DERPRF_IDX + 1, &encode->data, &encode->dataLen);
BSL_SAL_FREE(algo.data);
BSL_SAL_FREE(derParam[CRYPT_PKCS_ENC_DERITER_IDX].buff);
return ret;
}
static int32_t EncodeEncryptedData(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_Pbkdf2Param *pkcsParam,
BSL_Buffer *unEncrypted, BSL_Buffer *salt, BSL_ASN1_Buffer *asn1)
{
int32_t ret;
uint8_t *output = NULL;
BSL_Buffer keyBuff = {0};
do {
ret = CRYPT_EAL_CipherGetInfo(pkcsParam->symId, CRYPT_INFO_KEY_LEN, &keyBuff.dataLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
break;
}
keyBuff.data = (uint8_t *)BSL_SAL_Malloc(keyBuff.dataLen);
if (keyBuff.data == NULL) {
ret = BSL_MALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
break;
}
ret = PbkdfDeriveKey(libCtx, attrName, pkcsParam->itCnt, (int32_t)pkcsParam->hmacId, salt,
pkcsParam->pwd, pkcsParam->pwdLen, &keyBuff);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
break;
}
uint32_t pkcsDataLen = unEncrypted->dataLen + 16; // extras 16 for padding.
output = (uint8_t *)BSL_SAL_Malloc(pkcsDataLen);
if (output == NULL) {
ret = BSL_MALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
break;
}
BSL_Buffer enData = {unEncrypted->data, unEncrypted->dataLen};
BSL_Buffer ivData = {asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].buff, asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].len};
ret = CRYPT_ENCODE_DECODE_DecryptEncData(libCtx, attrName, &ivData, &enData,
(int32_t)pkcsParam->symId, true, &keyBuff, output, &pkcsDataLen);
if (ret != CRYPT_SUCCESS) {
break;
}
asn1[CRYPT_PKCS_ENCPRIKEY_ENCDATA_IDX].buff = output;
asn1[CRYPT_PKCS_ENCPRIKEY_ENCDATA_IDX].len = pkcsDataLen;
asn1[CRYPT_PKCS_ENCPRIKEY_ENCDATA_IDX].tag = BSL_ASN1_TAG_OCTETSTRING;
BSL_SAL_ClearFree(keyBuff.data, keyBuff.dataLen);
return ret;
} while (0);
BSL_SAL_ClearFree(keyBuff.data, keyBuff.dataLen);
BSL_SAL_FREE(output);
return ret;
}
static int32_t GenRandIv(CRYPT_EAL_LibCtx *libCtx, CRYPT_Pbkdf2Param *pkcsParam, BSL_ASN1_Buffer *asn1)
{
int32_t ret;
BslOidString *oidSym = BSL_OBJ_GetOID((BslCid)pkcsParam->symId);
if (oidSym == NULL) {
return CRYPT_ERR_ALGID;
}
asn1[CRYPT_PKCS_ENCPRIKEY_SYMALG_IDX].buff = (uint8_t *)oidSym->octs;
asn1[CRYPT_PKCS_ENCPRIKEY_SYMALG_IDX].len = oidSym->octetLen;
asn1[CRYPT_PKCS_ENCPRIKEY_SYMALG_IDX].tag = BSL_ASN1_TAG_OBJECT_ID;
uint32_t ivLen;
ret = CRYPT_EAL_CipherGetInfo(pkcsParam->symId, CRYPT_INFO_IV_LEN, &ivLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (ivLen == 0) {
asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].tag = BSL_ASN1_TAG_OCTETSTRING;
return CRYPT_SUCCESS;
}
uint8_t *iv = (uint8_t *)BSL_SAL_Malloc(ivLen);
if (iv == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
ret = CRYPT_EAL_RandbytesEx(libCtx, iv, ivLen);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_FREE(iv);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].buff = iv;
asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].len = ivLen;
asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].tag = BSL_ASN1_TAG_OCTETSTRING;
return ret;
}
int32_t CRYPT_ENCODE_PkcsEncryptedBuff(CRYPT_EAL_LibCtx *libCtx, const char *attrName,
CRYPT_Pbkdf2Param *pkcsParam, BSL_Buffer *unEncrypted, BSL_ASN1_Buffer *asn1)
{
int32_t ret;
BslOidString *oidPbes = BSL_OBJ_GetOID((BslCid)pkcsParam->pbesId);
if (oidPbes == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID);
return CRYPT_ERR_ALGID;
}
/* derivation param */
BSL_Buffer derParam = {0};
uint8_t *saltData = (uint8_t *)BSL_SAL_Malloc(pkcsParam->saltLen);
if (saltData == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
do {
BSL_Buffer salt = {saltData, pkcsParam->saltLen};
ret = EncodeDeriveKeyParam(libCtx, pkcsParam, &derParam, &salt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
break;
}
asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].buff = derParam.data;
asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].len = derParam.dataLen;
asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE;
/* iv */
ret = GenRandIv(libCtx, pkcsParam, asn1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
break;
}
/* encryptedData */
ret = EncodeEncryptedData(libCtx, attrName, pkcsParam, unEncrypted, &salt, asn1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
break;
}
BSL_SAL_ClearFree(saltData, pkcsParam->saltLen);
asn1[CRYPT_PKCS_ENCPRIKEY_ENCALG_IDX].buff = (uint8_t *)oidPbes->octs;
asn1[CRYPT_PKCS_ENCPRIKEY_ENCALG_IDX].len = oidPbes->octetLen;
asn1[CRYPT_PKCS_ENCPRIKEY_ENCALG_IDX].tag = BSL_ASN1_TAG_OBJECT_ID;
return CRYPT_SUCCESS;
} while (0);
BSL_SAL_ClearFree(saltData, pkcsParam->saltLen);
BSL_SAL_ClearFree(asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].buff, asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].len);
BSL_SAL_ClearFree(asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].buff, asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].len);
return ret;
}
#endif // HITLS_CRYPTO_KEY_EPKI
int32_t CRYPT_ENCODE_Pkcs8Info(CRYPT_ENCODE_DECODE_Pk8PrikeyInfo *pk8PrikeyInfo, BSL_Buffer *asn1)
{
if (pk8PrikeyInfo == NULL || asn1 == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
int32_t ret;
BSL_ASN1_Buffer algo = {0};
BSL_ASN1_Buffer algoId[BSL_ASN1_TAG_ALGOID_ANY_IDX + 1] = {0};
do {
BslOidString *oidStr = BSL_OBJ_GetOID((BslCid)pk8PrikeyInfo->keyType);
if (oidStr == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID);
ret = CRYPT_ERR_ALGID;
break;
}
algoId[BSL_ASN1_TAG_ALGOID_IDX].buff = (uint8_t *)oidStr->octs;
algoId[BSL_ASN1_TAG_ALGOID_IDX].len = oidStr->octetLen;
algoId[BSL_ASN1_TAG_ALGOID_IDX].tag = BSL_ASN1_TAG_OBJECT_ID;
algoId[BSL_ASN1_TAG_ALGOID_ANY_IDX] = pk8PrikeyInfo->keyParam;
ret = CRYPT_ENCODE_AlgoIdAsn1Buff(algoId, BSL_ASN1_TAG_ALGOID_ANY_IDX + 1, &algo.buff, &algo.len);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
break;
}
BSL_ASN1_Buffer encode[CRYPT_PK8_PRIKEY_PRIKEY_IDX + 1] = {
{BSL_ASN1_TAG_INTEGER, sizeof(pk8PrikeyInfo->version), (uint8_t *)&pk8PrikeyInfo->version},
{BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, algo.len, algo.buff},
{BSL_ASN1_TAG_OCTETSTRING, pk8PrikeyInfo->pkeyRawKeyLen, pk8PrikeyInfo->pkeyRawKey}
};
BSL_ASN1_Template pubTempl = {g_pk8PriKeyTempl, sizeof(g_pk8PriKeyTempl) / sizeof(g_pk8PriKeyTempl[0])};
ret = BSL_ASN1_EncodeTemplate(&pubTempl, encode, CRYPT_PK8_PRIKEY_PRIKEY_IDX + 1, &asn1->data, &asn1->dataLen);
} while (0);
BSL_SAL_ClearFree(algo.buff, algo.len);
return ret;
}
#endif /* HITLS_CRYPTO_KEY_ENCODE */
#endif /* HITLS_CRYPTO_CODECSKEY */
|
2301_79861745/bench_create
|
crypto/codecskey/src/crypt_encode_decode_utils.c
|
C
|
unknown
| 43,490
|
/*
* 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_KEY_INFO
#include <stdint.h>
#include <string.h>
#include "bsl_err_internal.h"
#include "bsl_obj_internal.h"
#include "bsl_print.h"
#include "crypt_utils.h"
#include "crypt_eal_pkey.h"
#include "crypt_errno.h"
#include "crypt_encode_decode_key.h"
#define CRYPT_UNKOWN_STRING "Unknown\n"
#define CRYPT_UNSUPPORT_ALG "Unsupported alg\n"
static inline int32_t PrintPubkeyBits(bool isEcc, uint32_t layer, CRYPT_EAL_PkeyCtx *pkey, BSL_UIO *uio)
{
if (!isEcc) {
return BSL_PRINT_Fmt(layer, uio, "Public-Key: (%d bit)\n", CRYPT_EAL_PkeyGetKeyBits(pkey));
}
uint32_t bits = 0;
int32_t ret = CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_ECC_ORDER_BITS, &bits, sizeof(uint32_t));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
return BSL_PRINT_Fmt(layer, uio, "Public-Key: (%d bit)\n", bits);
}
#if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2)
static int32_t GetEccPub(const CRYPT_EAL_PkeyCtx *pkey, CRYPT_EAL_PkeyPub *pub)
{
uint32_t keyLen = CRYPT_EAL_PkeyGetKeyLen(pkey);
if (keyLen == 0) {
return CRYPT_DECODE_PRINT_NO_KEY;
}
uint8_t *buff = (uint8_t *)BSL_SAL_Malloc(keyLen);
if (buff == NULL) {
return CRYPT_MEM_ALLOC_FAIL;
}
pub->id = CRYPT_EAL_PkeyGetId(pkey);
pub->key.eccPub.data = buff;
pub->key.eccPub.len = keyLen;
int32_t ret = CRYPT_EAL_PkeyGetPub(pkey, pub);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
BSL_SAL_Free(buff);
pub->key.eccPub.data = NULL;
}
return ret;
}
static int32_t PrintEccPubkey(uint32_t layer, CRYPT_EAL_PkeyCtx *pkey, BSL_UIO *uio)
{
RETURN_RET_IF(PrintPubkeyBits(true, layer, pkey, uio) != 0, CRYPT_DECODE_PRINT_KEYBITS);
/* pub key */
CRYPT_EAL_PkeyPub pub = {0};
int32_t ret = GetEccPub(pkey, &pub);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if (BSL_PRINT_Fmt(layer, uio, "Pub:\n") != 0 ||
BSL_PRINT_Hex(layer + 1, false, pub.key.eccPub.data, pub.key.eccPub.len, uio) != 0) {
BSL_SAL_Free(pub.key.eccPub.data);
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_ECC_PUB);
return CRYPT_DECODE_PRINT_ECC_PUB;
}
BSL_SAL_Free(pub.key.eccPub.data);
/* ASN1 OID */
CRYPT_PKEY_ParaId paraId =
CRYPT_EAL_PkeyGetId(pkey) == CRYPT_PKEY_SM2 ? CRYPT_ECC_SM2 : CRYPT_EAL_PkeyGetParaId(pkey);
const char *name = BSL_OBJ_GetOidNameFromCID((BslCid)paraId);
if (BSL_PRINT_Fmt(layer, uio, "ANS1 OID: %s\n", name == NULL ? CRYPT_UNKOWN_STRING : name) != 0) {
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_ECC_OID);
return CRYPT_DECODE_PRINT_ECC_OID;
}
return CRYPT_SUCCESS;
}
#endif // HITLS_CRYPTO_ECDSA || HITLS_CRYPTO_SM2
#ifdef HITLS_CRYPTO_RSA
static int32_t GetRsaPub(const CRYPT_EAL_PkeyCtx *pkey, CRYPT_EAL_PkeyPub *pub)
{
uint32_t keyLen = CRYPT_EAL_PkeyGetKeyLen(pkey);
if (keyLen == 0) {
return CRYPT_DECODE_PRINT_NO_KEY;
}
uint8_t *buff = (uint8_t *)BSL_SAL_Malloc(keyLen * 2); // 2: n + e
if (buff == NULL) {
return CRYPT_MEM_ALLOC_FAIL;
}
pub->id = CRYPT_PKEY_RSA;
pub->key.rsaPub.n = buff;
pub->key.rsaPub.e = buff + keyLen;
pub->key.rsaPub.nLen = keyLen;
pub->key.rsaPub.eLen = keyLen;
int32_t ret = CRYPT_EAL_PkeyGetPub(pkey, pub);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
BSL_SAL_Free(buff);
pub->key.rsaPub.n = NULL;
pub->key.rsaPub.e = NULL;
}
return ret;
}
int32_t CRYPT_EAL_PrintRsaPssPara(uint32_t layer, CRYPT_RSA_PssPara *para, BSL_UIO *uio)
{
if (para == NULL || uio == NULL) {
return CRYPT_INVALID_ARG;
}
/* hash */
const char *mdIdName = BSL_OBJ_GetOidNameFromCID((BslCid)para->mdId);
RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, "Hash Algorithm: %s%s\n",
mdIdName == NULL ? CRYPT_UNKOWN_STRING : mdIdName, para->mdId ==
CRYPT_MD_SHA1 ? " (default)" : "") != BSL_SUCCESS, CRYPT_DECODE_PRINT_RSAPSS_PARA);
/* mgf */
const char *mgfIdName = BSL_OBJ_GetOidNameFromCID((BslCid)para->mgfId);
RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, "Mask Algorithm: %s%s\n",
mgfIdName == NULL ? CRYPT_UNKOWN_STRING : mgfIdName, para->mgfId ==
CRYPT_MD_SHA1 ? " (default)" : "") != BSL_SUCCESS, CRYPT_DECODE_PRINT_RSAPSS_PARA);
/* saltLen */
RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, "Salt Length: 0x%x%s\n",
para->saltLen, para->saltLen == 20 ? " (default)" : "") != 0,
CRYPT_DECODE_PRINT_RSAPSS_PARA);
/* trailer is not supported */
return CRYPT_SUCCESS;
}
static int32_t PrintRsaPssPara(uint32_t layer, CRYPT_EAL_PkeyCtx *pkey, BSL_UIO *uio)
{
CRYPT_RsaPadType padType = 0;
int32_t ret = CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_RSA_PADDING, &padType, sizeof(CRYPT_RsaPadType));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (padType != CRYPT_EMSA_PSS) {
return CRYPT_SUCCESS;
}
CRYPT_RSA_PssPara para = {0};
ret = CRYPT_EAL_GetRsaPssPara(pkey, ¶);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (para.saltLen <= 0 && para.mdId == 0 && para.mgfId == 0) {
return BSL_PRINT_Fmt(layer, uio, "No PSS parameter restrictions\n");
}
RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, "PSS parameter restrictions:\n") != 0,
CRYPT_DECODE_PRINT_RSAPSS_PARA);
return CRYPT_EAL_PrintRsaPssPara(layer + 1, ¶, uio);
}
static int32_t PrintRsaPubkey(uint32_t layer, CRYPT_EAL_PkeyCtx *pkey, BSL_UIO *uio)
{
RETURN_RET_IF(PrintPubkeyBits(false, layer, pkey, uio) != 0, CRYPT_DECODE_PRINT_KEYBITS);
/* pub key */
CRYPT_EAL_PkeyPub pub = {0};
int32_t ret = GetRsaPub(pkey, &pub);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if (BSL_PRINT_Fmt(layer, uio, "Modulus:\n") != 0 ||
BSL_PRINT_Hex(layer + 1, false, pub.key.rsaPub.n, pub.key.rsaPub.nLen, uio) != 0) {
BSL_SAL_Free(pub.key.rsaPub.n);
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_MODULUS);
return CRYPT_DECODE_PRINT_MODULUS;
}
if (BSL_PRINT_Number(layer, "Exponent", pub.key.rsaPub.e, pub.key.rsaPub.eLen, uio) != 0) {
BSL_SAL_Free(pub.key.rsaPub.n);
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_EXPONENT);
return CRYPT_DECODE_PRINT_EXPONENT;
}
BSL_SAL_Free(pub.key.rsaPub.n);
return PrintRsaPssPara(layer, pkey, uio);
}
#endif // HITLS_CRYPTO_RSA
int32_t CRYPT_EAL_PrintPubkey(uint32_t layer, CRYPT_EAL_PkeyCtx *pkey, BSL_UIO *uio)
{
if (uio == NULL) {
return CRYPT_INVALID_ARG;
}
CRYPT_PKEY_AlgId algId = CRYPT_EAL_PkeyGetId(pkey);
switch (algId) {
#ifdef HITLS_CRYPTO_RSA
case CRYPT_PKEY_RSA:
return PrintRsaPubkey(layer, pkey, uio);
#endif
#if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2)
case CRYPT_PKEY_ECDSA:
case CRYPT_PKEY_SM2:
return PrintEccPubkey(layer, pkey, uio);
#endif
default:
return CRYPT_DECODE_PRINT_UNSUPPORT_ALG;
}
}
#ifdef HITLS_CRYPTO_RSA
static inline int32_t PrintPrikeyBits(bool isEcc, uint32_t layer, CRYPT_EAL_PkeyCtx *pkey, BSL_UIO *uio)
{
if (!isEcc) {
return BSL_PRINT_Fmt(layer, uio, "Private-Key: (%d bit)\n", CRYPT_EAL_PkeyGetKeyBits(pkey));
}
uint32_t bits = 0;
int32_t ret = CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_ECC_ORDER_BITS, &bits, sizeof(uint32_t));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
return BSL_PRINT_Fmt(layer, uio, "Private-Key: (%d bit)\n", bits);
}
static int32_t PrintRsaPrikey(uint32_t layer, CRYPT_EAL_PkeyCtx *pkey, BSL_UIO *uio)
{
RETURN_RET_IF(PrintPrikeyBits(false, layer, pkey, uio) != 0, CRYPT_DECODE_PRINT_KEYBITS);
int32_t ret;
/* pri key */
CRYPT_EAL_PkeyPrv pri = {0};
ret = CRYPT_EAL_InitRsaPrv(pkey, CRYPT_PKEY_RSA, &pri);
if (ret != CRYPT_SUCCESS) {
return ret;
}
ret = CRYPT_EAL_PkeyGetPrv(pkey, &pri);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_DeinitRsaPrv(&pri);
return ret;
}
if (BSL_PRINT_Fmt(layer, uio, "Modulus:\n") != 0 ||
BSL_PRINT_Hex(layer + 1, false, pri.key.rsaPrv.n, pri.key.rsaPrv.nLen, uio) != 0) {
CRYPT_EAL_DeinitRsaPrv(&pri);
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_MODULUS);
return CRYPT_DECODE_PRINT_MODULUS;
}
if (BSL_PRINT_Number(layer, "PublicExponent", pri.key.rsaPrv.e, pri.key.rsaPrv.eLen, uio) != 0) {
CRYPT_EAL_DeinitRsaPrv(&pri);
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_EXPONENT);
return CRYPT_DECODE_PRINT_EXPONENT;
}
if (BSL_PRINT_Fmt(layer, uio, "PrivateExponent:\n") != 0 ||
BSL_PRINT_Hex(layer + 1, false, pri.key.rsaPrv.d, pri.key.rsaPrv.dLen, uio) != 0) {
CRYPT_EAL_DeinitRsaPrv(&pri);
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_MODULUS);
return CRYPT_DECODE_PRINT_MODULUS;
}
if (BSL_PRINT_Fmt(layer, uio, "Prime1:\n") != 0 ||
BSL_PRINT_Hex(layer + 1, false, pri.key.rsaPrv.p, pri.key.rsaPrv.pLen, uio) != 0) {
CRYPT_EAL_DeinitRsaPrv(&pri);
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_MODULUS);
return CRYPT_DECODE_PRINT_MODULUS;
}
if (BSL_PRINT_Fmt(layer, uio, "Prime2:\n") != 0 ||
BSL_PRINT_Hex(layer + 1, false, pri.key.rsaPrv.q, pri.key.rsaPrv.qLen, uio) != 0) {
CRYPT_EAL_DeinitRsaPrv(&pri);
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_MODULUS);
return CRYPT_DECODE_PRINT_MODULUS;
}
if (BSL_PRINT_Fmt(layer, uio, "Exponent1:\n") != 0 ||
BSL_PRINT_Hex(layer + 1, false, pri.key.rsaPrv.dP, pri.key.rsaPrv.dPLen, uio) != 0) {
CRYPT_EAL_DeinitRsaPrv(&pri);
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_MODULUS);
return CRYPT_DECODE_PRINT_MODULUS;
}
if (BSL_PRINT_Fmt(layer, uio, "Exponent2:\n") != 0 ||
BSL_PRINT_Hex(layer + 1, false, pri.key.rsaPrv.dQ, pri.key.rsaPrv.dQLen, uio) != 0) {
CRYPT_EAL_DeinitRsaPrv(&pri);
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_MODULUS);
return CRYPT_DECODE_PRINT_MODULUS;
}
if (BSL_PRINT_Fmt(layer, uio, "Coefficient:\n") != 0 ||
BSL_PRINT_Hex(layer + 1, false, pri.key.rsaPrv.qInv, pri.key.rsaPrv.qInvLen, uio) != 0) {
CRYPT_EAL_DeinitRsaPrv(&pri);
BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_MODULUS);
return CRYPT_DECODE_PRINT_MODULUS;
}
CRYPT_EAL_DeinitRsaPrv(&pri);
return CRYPT_SUCCESS;
}
#endif
int32_t CRYPT_EAL_PrintPrikey(uint32_t layer, CRYPT_EAL_PkeyCtx *pkey, BSL_UIO *uio)
{
if (uio == NULL) {
return CRYPT_INVALID_ARG;
}
CRYPT_PKEY_AlgId algId = CRYPT_EAL_PkeyGetId(pkey);
switch (algId) {
#ifdef HITLS_CRYPTO_RSA
case CRYPT_PKEY_RSA:
return PrintRsaPrikey(layer, pkey, uio);
#endif
default:
return CRYPT_DECODE_PRINT_UNSUPPORT_ALG;
}
}
#endif // HITLS_CRYPTO_KEY_INFO
|
2301_79861745/bench_create
|
crypto/codecskey/src/crypt_encode_print.c
|
C
|
unknown
| 11,557
|
/*
* 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_CURVE25519_H
#define CRYPT_CURVE25519_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_CURVE25519
#include <stdint.h>
#include "crypt_local_types.h"
#include "bsl_params.h"
#ifdef __cplusplus
extern "C" {
#endif
#define CRYPT_CURVE25519_KEYLEN 32
#define CRYPT_CURVE25519_SIGNLEN 64
typedef struct CryptCurve25519Ctx CRYPT_CURVE25519_Ctx;
#ifdef HITLS_CRYPTO_X25519
/**
* @ingroup curve25519
* @brief curve25519 Create a key pair structure and allocate memory space.
*
* @retval (CRYPT_CURVE25519_Ctx *) Pointer to the key pair structure
* @retval NULL Invalid null pointer
*/
CRYPT_CURVE25519_Ctx *CRYPT_X25519_NewCtx(void);
/**
* @ingroup curve25519
* @brief curve25519 Create a key pair structure and allocate memory space.
*
* @param libCtx [IN] Library context
*
* @retval (CRYPT_CURVE25519_Ctx *) Pointer to the key pair structure
* @retval NULL Invalid null pointer
*/
CRYPT_CURVE25519_Ctx *CRYPT_X25519_NewCtxEx(void *libCtx);
#endif
#ifdef HITLS_CRYPTO_ED25519
/**
* @ingroup ed25519
* @brief curve25519 Create a key pair structure for ED25519 algorithm and allocate memory space.
*
* @retval (CRYPT_CURVE25519_Ctx *) Pointer to the key pair structure
* @retval NULL Invalid null pointer
*/
CRYPT_CURVE25519_Ctx *CRYPT_ED25519_NewCtx(void);
/**
* @ingroup ed25519
* @brief curve25519 Create a key pair structure for ED25519 algorithm and allocate memory space.
*
* @param libCtx [IN] Library context
*
* @retval (CRYPT_CURVE25519_Ctx *) Pointer to the key pair structure
* @retval NULL Invalid null pointer
*/
CRYPT_CURVE25519_Ctx *CRYPT_ED25519_NewCtxEx(void *libCtx);
#endif
/**
* @ingroup curve25519
* @brief Copy the curve25519 context. The memory management of the return value is handed over to the caller.
*
* @param ctx [IN] Source curve25519 context. The CTX is set NULL by the invoker.
*
* @return CRYPT_CURVE25519_Ctx curve25519 Context pointer
* If the operation fails, null is returned.
*/
CRYPT_CURVE25519_Ctx *CRYPT_CURVE25519_DupCtx(CRYPT_CURVE25519_Ctx *ctx);
/**
* @ingroup curve25519
* @brief Clear the curve25519 key pair data and releases memory.
*
* @param pkey [IN] curve25519 Key pair structure. The pkey is set NULL by the invoker.
*/
void CRYPT_CURVE25519_FreeCtx(CRYPT_CURVE25519_Ctx *pkey);
/**
* @ingroup curve25519
* @brief curve25519 Control interface
*
* @param pkey [IN/OUT] curve25519 Key pair structure
* @param val [IN] Hash method, which must be SHA512.
* @param opt [IN] Operation mode
* @param len [IN] val length
*
* @retval CRYPT_SUCCESS set successfully.
* @retval CRYPT_NULL_INPUT If any input parameter is empty
* @retval CRYPT_CURVE25519_UNSUPPORTED_CTRL_OPTION The opt mode is not supported.
* @retval CRYPT_CURVE25519_HASH_METH_ERROR The hash method is not SHA512
*/
int32_t CRYPT_CURVE25519_Ctrl(CRYPT_CURVE25519_Ctx *pkey, int32_t opt, void *val, uint32_t len);
/**
* @ingroup curve25519
* @brief curve25519 Set the public key.
*
* @param pkey [IN] curve25519 Key pair structure
* @param pub [IN] Public key
*
* @retval CRYPT_SUCCESS set successfully.
* @retval CRYPT_NULL_INPUT If any input parameter is empty
* @retval CRYPT_CURVE25519_KEYLEN_ERROR pubKeyLen is not equal to curve25519 public key length
*/
int32_t CRYPT_CURVE25519_SetPubKey(CRYPT_CURVE25519_Ctx *pkey, const CRYPT_Curve25519Pub *pub);
/**
* @ingroup curve25519
* @brief curve25519 Obtain the public key.
*
* @param pkey [IN] curve25519 Key pair structure
* @param pub [OUT] Public key
*
* @retval CRYPT_SUCCESS set successfully.
* @retval CRYPT_NULL_INPUT If any input parameter is empty
* @retval CRYPT_CURVE25519_NO_PUBKEY The key pair has no public key.
* @retval CRYPT_CURVE25519_KEYLEN_ERROR pubKeyLen is less than curve25519 public key length.
*/
int32_t CRYPT_CURVE25519_GetPubKey(const CRYPT_CURVE25519_Ctx *pkey, CRYPT_Curve25519Pub *pub);
/**
* @ingroup curve25519
* @brief curve25519 Set the private key.
*
* @param pkey [IN] curve25519 Key pair structure
* @param prv [IN] Private key
*
* @retval CRYPT_SUCCESS set successfully.
* @retval CRYPT_NULL_INPUT If any input parameter is empty
* @retval CRYPT_CURVE25519_KEYLEN_ERROR prvKeyLen is not equal to curve25519 private key length
*/
int32_t CRYPT_CURVE25519_SetPrvKey(CRYPT_CURVE25519_Ctx *pkey, const CRYPT_Curve25519Prv *prv);
/**
* @ingroup curve25519
* @brief curve25519 Obtain the private key.
*
* @param pkey [IN] curve25519 Key pair structure
* @param prv [OUT] private key
*
* @retval CRYPT_SUCCESS successfully set.
* @retval CRYPT_NULL_INPUT Any input parameter is empty.
* @retval CRYPT_CURVE25519_NO_PRVKEY The key pair has no private key.
* @retval CRYPT_CURVE25519_KEYLEN_ERROR prvKeyLen is less than the private key length of curve25519.
*/
int32_t CRYPT_CURVE25519_GetPrvKey(const CRYPT_CURVE25519_Ctx *pkey, CRYPT_Curve25519Prv *prv);
#ifdef HITLS_BSL_PARAMS
/**
* @ingroup curve25519
* @brief curve25519 Set the public key.
*
* @param pkey [IN] curve25519 Key pair structure
* @param para [IN] Public key
*
* @retval CRYPT_SUCCESS set successfully.
* @retval CRYPT_NULL_INPUT If any input parameter is empty
* @retval CRYPT_CURVE25519_KEYLEN_ERROR pubKeyLen is not equal to curve25519 public key length
*/
int32_t CRYPT_CURVE25519_SetPubKeyEx(CRYPT_CURVE25519_Ctx *pkey, const BSL_Param *para);
/**
* @ingroup curve25519
* @brief curve25519 Set the private key.
*
* @param pkey [IN] curve25519 Key pair structure
* @param para [IN] Private key
*
* @retval CRYPT_SUCCESS set successfully.
* @retval CRYPT_NULL_INPUT If any input parameter is empty
* @retval CRYPT_CURVE25519_KEYLEN_ERROR prvKeyLen is not equal to curve25519 private key length
*/
int32_t CRYPT_CURVE25519_SetPrvKeyEx(CRYPT_CURVE25519_Ctx *pkey, const BSL_Param *para);
/**
* @ingroup curve25519
* @brief curve25519 Obtain the public key.
*
* @param pkey [IN] curve25519 Key pair structure
* @param para [OUT] Public key
*
* @retval CRYPT_SUCCESS set successfully.
* @retval CRYPT_NULL_INPUT If any input parameter is empty
* @retval CRYPT_CURVE25519_NO_PUBKEY The key pair has no public key.
* @retval CRYPT_CURVE25519_KEYLEN_ERROR pubKeyLen is less than curve25519 public key length.
*/
int32_t CRYPT_CURVE25519_GetPubKeyEx(const CRYPT_CURVE25519_Ctx *pkey, BSL_Param *para);
/**
* @ingroup curve25519
* @brief curve25519 Obtain the private key.
*
* @param pkey [IN] curve25519 Key pair structure
* @param para [OUT] private key
*
* @retval CRYPT_SUCCESS successfully set.
* @retval CRYPT_NULL_INPUT Any input parameter is empty.
* @retval CRYPT_CURVE25519_NO_PRVKEY The key pair has no private key.
* @retval CRYPT_CURVE25519_KEYLEN_ERROR prvKeyLen is less than the private key length of curve25519.
*/
int32_t CRYPT_CURVE25519_GetPrvKeyEx(const CRYPT_CURVE25519_Ctx *pkey, BSL_Param *para);
#endif
/**
* @ingroup curve25519
* @brief curve25519 Obtain the key length, in bits.
*
* @param pkey [IN] curve25519 Key pair structure
*
* @retval Key length
*/
int32_t CRYPT_CURVE25519_GetBits(const CRYPT_CURVE25519_Ctx *pkey);
#ifdef HITLS_CRYPTO_ED25519
/**
* @ingroup curve25519
* @brief curve25519 Sign
*
* @param pkey [IN/OUT] curve25519 Key pair structure. A private key is required for signature.
* After signature, a public key is generated.
* @param algid [IN] md algid
* @param msg [IN] Data to be signed
* @param msgLen [IN] Data length: 0 <= msgLen <= (2^125 - 64) bytes
* @param hashMethod [IN] SHA512 method
* @param sign [OUT] Signature
* @param signLen [IN/OUT] Length of the signature buffer (must be greater than 64 bytes)/Length of the signature
*
* @retval CRYPT_SUCCESS generated successfully.
* @retval CRYPT_CURVE25519_NO_PRVKEY The key pair has no private key.
* @retval CRYPT_NULL_INPUT If any input parameter is empty
* @retval Error code of the hash module. An error occurs in the sha512 operation.
* @retval CRYPT_CURVE25519_NO_HASH_METHOD No hash method is set.
* @retval CRYPT_CURVE25519_SIGNLEN_ERROR signLen is less than the signature length of curve25519.
*/
int32_t CRYPT_CURVE25519_Sign(CRYPT_CURVE25519_Ctx *pkey, int32_t algId, const uint8_t *msg,
uint32_t msgLen, uint8_t *sign, uint32_t *signLen);
/**
* @ingroup curve25519
* @brief curve25519 Obtain the signature length, in bytes.
*
* @param pkey [IN] curve25519 Key pair structure
*
* @retval Signature length
*/
int32_t CRYPT_CURVE25519_GetSignLen(const CRYPT_CURVE25519_Ctx *pkey);
/**
* @ingroup curve25519
* @brief curve25519 Verification
*
* @param pkey [IN] curve25519 Key pair structure. A public key is required for signature verification.
* @param algid [IN] md algid
* @param msg [IN] Data
* @param msgLen [IN] Data length: 0 <= msgLen <= (2^125 - 64) bytes
* @param sign [IN] Signature
* @param signLen [IN] Signature length, which must be 64 bytes
*
* @retval CRYPT_SUCCESS The signature verification is successful.
* @retval CRYPT_CURVE25519_NO_PUBKEY The key pair has no public key.
* @retval CRYPT_NULL_INPUT If any input parameter is empty
* @retval Error code of the hash module. An error occurs in the sha512 operation.
* @retval CRYPT_CURVE25519_VERIFY_FAIL Failed to verify the signature.
* @retval CRYPT_CURVE25519_INVALID_PUBKEY Invalid public key.
* @retval CRYPT_CURVE25519_SIGNLEN_ERROR signLen is not equal to curve25519 signature length
* @retval CRYPT_CURVE25519_NO_HASH_METHOD No hash method is set.
*/
int32_t CRYPT_CURVE25519_Verify(const CRYPT_CURVE25519_Ctx *pkey, int32_t algId, const uint8_t *msg,
uint32_t msgLen, const uint8_t *sign, uint32_t signLen);
/**
* @ingroup curve25519
* @brief ed25519 Generate a key pair (public and private keys).
*
* @param pkey [IN/OUT] curve25519 Key pair structure/Key pair structure containing public and private keys
*
* @retval CRYPT_SUCCESS generated successfully.
* @retval CRYPT_NO_REGIST_RAND Unregistered random number
* @retval Error code of the hash module. An error occurs during the SHA512 operation.
* @retval Error code of the registered random number module. Failed to obtain the random number.
* @retval CRYPT_CURVE25519_NO_HASH_METHOD No hash method is set.
* @retval CRYPT_NULL_INPUT The input parameter is empty.
*/
int32_t CRYPT_ED25519_GenKey(CRYPT_CURVE25519_Ctx *pkey);
#endif /* HITLS_CRYPTO_ED25519 */
#ifdef HITLS_CRYPTO_X25519
/**
* @ingroup curve25519
* @brief x25519 Calculate the shared key based on the private key of the local end and the public key of the peer end.
*
* @param prvKey [IN] curve25519 Key pair structure, local private key
* @param pubKey [IN] curve25519 Key pair structure, peer public key
* @param sharedKey [OUT] Shared key
* @param shareKeyLen [IN/OUT] Shared key length
*
* @retval CRYPT_SUCCESS generated successfully.
* @retval CRYPT_CURVE25519_KEY_COMPUTE_FAILED Failed to generate the shared key.
*/
int32_t CRYPT_CURVE25519_ComputeSharedKey(CRYPT_CURVE25519_Ctx *prvKey, CRYPT_CURVE25519_Ctx *pubKey,
uint8_t *sharedKey, uint32_t *shareKeyLen);
/**
* @ingroup curve25519
* @brief x25519 Generate a key pair (public and private keys).
*
* @param pkey [IN/OUT] curve25519 Key pair structure/Key pair structure containing public and private keys
*
* @retval CRYPT_SUCCESS generated successfully.
* @retval CRYPT_NO_REGIST_RAND Unregistered random number callback
* @retval Error code of the registered random number module. Failed to obtain the random number.
* @retval CRYPT_NULL_INPUT The input parameter is empty.
*/
int32_t CRYPT_X25519_GenKey(CRYPT_CURVE25519_Ctx *pkey);
#endif /* HITLS_CRYPTO_X25519 */
/**
* @ingroup curve25519
* @brief curve25519 Public key comparison
*
* @param a [IN] curve25519 Context structure
* @param b [IN] curve25519 Context structure
*
* @retval CRYPT_SUCCESS is the same
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_CURVE25519_PUBKEY_NOT_EQUAL Public Keys are not equal
*/
int32_t CRYPT_CURVE25519_Cmp(const CRYPT_CURVE25519_Ctx *a, const CRYPT_CURVE25519_Ctx *b);
/**
* @ingroup curve25519
* @brief curve25519 get security bits
*
* @param ctx [IN] curve25519 Context structure
*
* @retval security bits
*/
int32_t CRYPT_CURVE25519_GetSecBits(const CRYPT_CURVE25519_Ctx *ctx);
#ifdef HITLS_CRYPTO_PROVIDER
/**
* @ingroup curve25519
* @brief curve25519 import key
*
* @param ctx [IN/OUT] curve25519 context structure
* @param params [IN] parameters
*/
int32_t CRYPT_CURVE25519_Import(CRYPT_CURVE25519_Ctx *ctx, const BSL_Param *params);
/**
* @ingroup curve25519
* @brief curve25519 export key
*
* @param ctx [IN] curve25519 context structure
* @param params [IN/OUT] key parameters
*/
int32_t CRYPT_CURVE25519_Export(const CRYPT_CURVE25519_Ctx *ctx, BSL_Param *params);
#endif // HITLS_CRYPTO_PROVIDER
#ifdef HITLS_CRYPTO_ED25519_CHECK
/**
* @ingroup ed25519
* @brief ed25519 check key pair
*
* @param checkType [IN] check type
* @param pkey1 [IN] ed25519 context structure
* @param pkey2 [IN] ed25519 context structure
*
* @retval CRYPT_SUCCESS successfully.
* @retval other error.
*/
int32_t CRYPT_ED25519_Check(uint32_t checkType, const CRYPT_CURVE25519_Ctx *pkey1, const CRYPT_CURVE25519_Ctx *pkey2);
#endif // HITLS_CRYPTO_ED25519_CHECK
#ifdef HITLS_CRYPTO_X25519_CHECK
/**
* @ingroup x25519
* @brief x25519 check key pair
*
* @param checkType [IN] check type
* @param pkey1 [IN] x25519 context structure
* @param pkey2 [IN] x25519 context structure
*
* @retval CRYPT_SUCCESS successfully.
* @retval other error.
*/
int32_t CRYPT_X25519_Check(uint32_t checkType, const CRYPT_CURVE25519_Ctx *pkey1, const CRYPT_CURVE25519_Ctx *pkey2);
#endif // HITLS_CRYPTO_X25519_CHECK
#ifdef __cplusplus
}
#endif
#endif // HITLS_CRYPTO_CURVE25519
#endif // CRYPT_CURVE25519_H
|
2301_79861745/bench_create
|
crypto/curve25519/include/crypt_curve25519.h
|
C
|
unknown
| 15,400
|
/*
* 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_X25519
#include "crypt_arm.h"
.file "x25519_armv8.S"
.text
.macro push_stack
/* save register. */
stp x19, x20, [sp, #-16]!
stp x21, x22, [sp, #-16]!
sub sp, sp, #32
.endm
.macro pop_stack
add sp, sp, #32
/* pop register */
ldp x21, x22, [sp], #16
ldp x19, x20, [sp], #16
.endm
.macro u64mul oper1, oper2
mul x19, \oper1, \oper2
umulh x2, \oper1, \oper2
.endm
.macro u51mul cur, low, high
u64mul x3, \cur
adds \low, \low, x19
adc \high, \high, x2
.endm
.macro reduce
/* retain the last 51 bits */
mov x8, #0x7ffffffffffff
/* 计算 h2' */
mov x3, x9
lsr x9, x9, #51 // carry(h2-low)
lsl x10, x10, #13 // (h2-high) << 13
/* 计算 h0' */
mov x1, x4
lsr x4, x4, #51 // carry(h1-low)
lsl x5, x5, #13 // (h1-high) << 13
/* 计算 h2' */
and x3, x3, x8 // h2' = rax = h2 & (2^51 - 1) = r12 & (2^51 - 1)
orr x10, x10, x9 // r13 = (h2 >> 51)
adds x11, x11, x10 // h3 += (h2 >> 51)
adc x12, x12, XZR // h3-high carry
/* 计算 h0' */
and x1, x1, x8 // h0' = rsi = h0 & (2^51 - 1) = r8 & (2^51 - 1)
orr x5, x5, x4 // r9 = (h0 >> 51)
adds x6, x6, x5 // h1 += (h0 >> 51)
adc x7, x7, XZR // h1-high carry
/* 计算 h3' */
mov x4, x11 // h3-low -> x4
lsr x11, x11, #51 // h3->low >> 51
lsl x12, x12, #13 // h3-high << 13
and x4, x4, x8 // h3' = r8 = h3 & (2^51 - 1) = r14 & (2^51 - 1)
orr x12, x12, x11 // r15 = (h3 >> 51)
adds x13, x13, x12 // h4 += (h3 >> 51)
adc x14, x14, XZR // h4-high carry
/* 计算 h1' */
mov x2, x6 // h1-low -> x2
lsr x6, x6, #51 // h1->low >> 51
lsl x7, x7, #13 // h1-high << 13
and x2, x2, x8 // h1' = rdx = h1 & (2^51 - 1) = r10 & (2^51 - 1)
orr x7, x7, x6 // r11 = (h1 >> 51)
adds x3, x3, x7 // h2 += (h1 >> 51)
/* 计算 h4' */
mov x5, x13 // h4-low -> x5
lsr x13, x13, #51 // h4->low >> 51
lsl x14, x14, #13 // h4-high << 13
and x5, x5, x8 // h4' = r9 = h4 & (2^51 - 1) = rbx & (2^51 - 1)
orr x14, x14, x13 // rcx = (h4 >> 51)
/* out[0] = out[0] + 19 * carry */
lsl x6, x14, #3
adds x6, x6, x14 // h4-high * 8 + h4-high -> x6 (9 * h4-high)
adds x14, x14, x6, lsl #1 // x6 *2 + x14 => x6 --- h4-high * 9 * 2 + h4-high
adds x1, x1, x14 // h4-high * 19 +->h0-low
/* h2 剩余 */
mov x6, x3 // h2-low -> x6
and x3, x8, x3 // h2 &= (2^51 - 1)
lsr x6, x6, #51 // h2-low << 51
adds x4, x4, x6 // h2-low << 51 -> h3-low
/* out[1] += out[0] >> 51 */
mov x6, x1 // h0-low -> x6
/* out[0] &= (2^51 - 1) */
and x1, x1, x8 // clear the upper 13 bits of h0-low
lsr x6, x6, #51 // h0-low << 51
adds x2, x2, x6 // h0-low << 51 -> h1-low
/* 存储结果 */
str x1, [x0] // h0'
str x2, [x0, #8] // h1'
str x3, [x0, #16] // h2'
str x4, [x0, #24] // h3'
str x5, [x0, #32] // h4'
.endm
#############################################################
# void Fp51Mul (Fp51 *out, const Fp51 *f, const Fp51 *g);
#############################################################
.globl Fp51Mul
.type Fp51Mul, @function
.align 6
Fp51Mul:
AARCH64_PACIASP
/* save register */
push_stack
/*
* x0: out; x1: f; x2: g; fp51: array[u64; 5]
*/
ldr x3, [x1] // f0
ldr x13, [x2] // g0
ldp x11, x12, [x2, #8] // g1, g2
ldp x15, x14, [x2, #24] // g3, g4
str x0, [sp, #24]
/*
* x13, x11, and x12 will be overwritten in subsequent calculation, and g0 to g2 will be stored.
*/
mov x8, #19
/* h0 = f0g0 + 19f1g4 + 19f2g3 + 19f3g2 + 19f4g1; save in x4(low), x5(high) */
mul x4, x3, x13 // (x4, x5) = f0 * g0
umulh x5, x3, x13
str x13, [sp, #16] // g0
/* h1 = f0g1 + f1g0 + 19f2g4 + 19f3g3 + 19f4g2; save in x6, x7 */
mul x6, x3, x11 // (x6, x7) = f0 * g1
umulh x7, x3, x11
lsl x13, x14, #3
add x13, x13, x14 // g4 * 8 + g4 = g4 * 9
str x11, [sp, #8] // g1
/* h2 = f0g2 + f1g1 + f2g0 + 19f3g4 + 19f4g3; save in x9, x10 */
mul x9, x3, x12 // (x9, x10) = f0 * g2
umulh x10, x3, x12
lsl x0, x13, #1
add x0, x0, x14 // rdi = 2 * (9 * g4) + g4
str x12, [sp] // g2
/* h3 = f0g3 + f1g2 + f2g1 + f3g0 + 19f4g4; save in x11, x12 */
mul x11, x3, x15 // (x11, x12) = f0 * g3
umulh x12, x3, x15
/* h4 = f0g4 + f1g3 + f2g2 + f3g1 + f4g0; save in x13, x14 */
mul x13, x3, x14 // (x13, x14) = f0 * g4
umulh x14, x3, x14
ldr x3, [x1, #8] // f1
/* compute 19 * g4 */
u51mul x0, x4, x5 // (x4, x5) = 19 * f1 * g4; load f2
ldr x3, [x1, #16]
u51mul x0, x6, x7 // (x6, x7) = 19 * f2 * g4; load f3
ldr x3, [x1, #24]
u51mul x0, x9, x10 // (x9, x10) = 19 * f3 * g4; load f4
ldr x3, [x1, #32]
u51mul x0, x11, x12 // (x11, x12) = 19 * f3 * g4; load f4
ldr x3, [x1, #8]
mul x0, x15, x8 // 19 * g3
/* compute g3 */
u64mul x3, x15 // (x13, x14) = f1 * g3
ldr x15, [sp] // g2
adds x13, x13, x19
ldr x3, [x1, #16] // f2
adc x14, x14, x2
u51mul x0, x4, x5 // (x4, x5) = 19 * f2 * g3; load f3
ldr x3, [x1, #24]
u51mul x0, x6, x7 // (x6, x7) = 19 * f3 * g3; load f4
ldr x3, [x1, #32]
u64mul x3, x0 // (rax, rdx) = 19 * f4 * g3
mul x0, x15, x8 // 19 * g2
adds x9, x9, x19
ldr x3, [x1, #8] // f1
adc x10, x10, x2
/* compute g2 */
u51mul x15, x11, x12 // (x11, x12) = f1 * g2; load f2
ldr x3, [x1, #16]
u64mul x3, x15 // (rax, rdx) = f2 * g2
ldr x15, [sp, #8] // g1
adds x13, x13, x19
ldr x3, [x1, #24] // f3
adc x14, x14, x2
u51mul x0, x4, x5 // (x4, x5) = 19 * f3 * g2; load f4
ldr x3, [x1, #32]
u51mul x0, x6, x7 // (x6, x7) = 19 * f4 * g2; load f2
ldr x3, [x1, #8]
/* compute g1 */
u64mul x3, x15 // (x19, x2) = f1 * g1
mul x0, x15, x8 // 19 * g1
adds x9, x9, x19
ldr x3, [x1, #16] // f2
adc x10, x10, x2
u51mul x15, x11, x12 // (x11, x12) += f2 * g1; load f3
ldr x3, [x1, #24]
u64mul x3, x15 // (x19, x2) = f3 * g1
ldr x15, [sp, #16] // g0
adds x13, x13, x19
ldr x3, [x1, #32] // f4
adc x14, x14, x2
u51mul x0, x4, x5 // (x4, x5) += 19 * f4 * g1; load f1
ldr x3, [x1, #8]
/* compute g0 */
u51mul x15, x6, x7 // (x6, x7) += f1 * g0; load f2
ldr x3, [x1, #16]
u51mul x15, x9, x10 // (x9, x10) += f2 * g0; load f3
ldr x3, [x1, #24]
u51mul x15, x11, x12 // (x11, x12) = f3 * g0; load f4
ldr x3, [x1, #32]
u64mul x3, x15 // (x13, x14) += f4 * g0
adds x13, x13, x19
adc x14, x14, x2
/* pop stack register */
ldr x0, [sp, #24]
reduce
pop_stack
AARCH64_AUTIASP
ret
.size Fp51Mul,.-Fp51Mul
#############################################################
# void Fp51Square(Fp51 *out, const Fp51 *f);
#############################################################
.globl Fp51Square
.type Fp51Square, @function
.align 6
Fp51Square:
AARCH64_PACIASP
push_stack
/*
* x0: out; x1: f; fp51 : array [u64; 5]
*/
ldr x3, [x1] // f0
ldr x12, [x1, #16] // f2
ldr x14, [x1, #32] // f4
mov x8, #19
lsl x2, x3, #1 // 2 * f0
str x0, [sp, #24]
/* h0 = f0^2 + 38f1f4 + 38f2f3; save in x4, x5 */
mul x4, x3, x3 // (x4, x5) = f0^2
umulh x5, x3, x3
ldr x3, [x1, #8] // f1
/* h1 = 19f3^2 + 2f0f1 + 38f2g4; save in x6, x7 */
mul x6, x3, x2 // (x6, x7) = 2f0 * f1
umulh x7, x3, x2
str x12, [sp, #16] // save f2
/* h2 = f1^2 + 2f0f2 + 38f3g4; save in x9, x10 */
mul x9, x12, x2 // (x9, x10) = 2f0 * f2
umulh x10, x12, x2
ldr x3, [x1, #24] // f3
mul x0, x14, x8 // 19 * f4
/* h3 = 19f4^2 + 2f0f3 + 2f1f2; save in r14, r15 */
mul x11, x3, x2 // (x11, x12) = 2f0 * f3
umulh x12, x3, x2
mov x3, x14 // f4
/* h4 = f2^2 + 2f0f4 + 2f1f3; save in x13, x14 */
mul x13, x3, x2 // (x13, x14) = 2f0 * f4
umulh x14, x3, x2
/*
* h3: compute 19 * f4
*/
u51mul x0, x11, x12 // (x11, x12) += 19 * f4^2; load f1
ldr x3, [x1, #8]
/*
* h2 : compute f1
*/
lsl x15, x3, #1 // 2 * f1
u51mul x3, x9, x10 // (x9, x10) += f1^2; load f2
ldr x3, [sp, #16]
/* h3 */
u51mul x15, x11, x12 // (x11, x12) += 2 * f1 * f2; load f3
ldr x3, [x1, #24]
/* h4 */
u51mul x15, x13, x14 // (x13, x14) = 2 * f1 * f3; load 2 * f1
mov x3, x15
ldr x1, [x1, #24] // f3
mul x15, x1, x8 // 19 * f3
/* h0 */
u64mul x3, x0
lsl x3, x1, #1 // 2 * f3
adds x4, x4, x19 // (x4, x5) += 2 * f1 * 19 * f4
adc x5, x5, x2
/*
* h2: compute f3
*/
u51mul x0, x9, x10 // (x9, x10) += f3 * 2 * 19 * f4; load f3
mov x3, x1
/* h1 */
u51mul x15, x6, x7 // (x6, x7) += 19 * f3 * f3; load f2
ldr x3, [sp, #16]
/*
* h4: compute f2
*/
lsl x1, x3, #1 // 2 * f2
u51mul x3, x13, x14 // (x13, x14) += f2 * f2; load 19 * f3
mov x3, x15
/* h0 */
u51mul x1, x4, x5 // (x4, x5) = 2 * f2 * 19 * f3; load 2 * f2
mov x3, x1
/* h1 */
u64mul x3, x0 // (x6, x7) += 2 * f2 * 19 * f4
adds x6, x19, x6
adc x7, x2, x7
ldr x0, [sp, #24]
reduce
pop_stack
AARCH64_AUTIASP
ret
.size Fp51Square,.-Fp51Square
#############################################################
# void Fp51MulScalar(Fp51 *out, const Fp51 *in);
#############################################################
.globl Fp51MulScalar
.type Fp51MulScalar, @function
.align 6
Fp51MulScalar:
AARCH64_PACIASP
/*
* x0: out; x1: in; fp51 array [u64; 5]
*/
/* mov 121666 */
mov x3, #0xDB42
movk x3, #0x1, lsl #16
/* ldr f0, f1 */
ldp x2, x8, [x1]
/* h0 */
mul x4, x2, x3 // f0 * 121666
umulh x5, x2, x3
/* h1 */
mul x6, x8, x3 // f1 * 121666
umulh x7, x8, x3
/* ldr f2, f3 */
ldp x2, x8, [x1, #16]
/* h2 */
mul x9, x2, x3 // f2 * 121666
umulh x10, x2, x3
/* h3 */
mul x11, x8, x3 // f3 * 121666
umulh x12, x8, x3
/* ldr f4 */
ldr x8, [x1, #32]
/* h4 */
mul x13, x3, x8 // f4 * 121666
umulh x14, x3, x8
reduce
AARCH64_AUTIASP
ret
.size Fp51MulScalar,.-Fp51MulScalar
#endif
|
2301_79861745/bench_create
|
crypto/curve25519/src/asm/x25519_armv8.S
|
Unix Assembly
|
unknown
| 13,608
|
/*
* 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_X25519
.file "x25519_x86_64.S"
.text
.macro push_stack
/* Save register. The following registers need to be saved by the caller and restored when the function exits. */
pushq %rbx
pushq %rbp
pushq %r12
pushq %r13
pushq %r14
pushq %r15
/* Allocate stack space and store the following necessary content: */
leaq -32(%rsp), %rsp
.endm
.macro pop_stack
/* Recovery register */
movq 32(%rsp),%r15
movq 40(%rsp),%r14
movq 48(%rsp),%r13
movq 56(%rsp),%r12
movq 64(%rsp),%rbp
movq 72(%rsp),%rbx
/* Restore stack pointer. The stack is opened with 32 bytes and 6 registers are restored.
The total number is 80 bytes. */
leaq 80(%rsp), %rsp
.endm
.macro u51mul cur, low, high, next
mulq \cur
addq %rax, \low
movq \next, %rax
adcq %rdx, \high
.endm
.macro reduce
/* Retain the last 51 digits. */
movq $0x7ffffffffffff, %rbp
/* Calculate h2' */
movq %r12, %rax
shrq $51, %r12
shlq $13, %r13
/* Calculate h0' */
movq %r8, %rsi
shrq $51, %r8
shlq $13, %r9
/* Calculate h2' */
andq %rbp, %rax // h2' = rax = h2 & (2^51 - 1) = r12 & (2^51 - 1)
orq %r12, %r13 // r13 = (h2 >> 51)
addq %r13, %r14 // h3 += (h2 >> 51)
adcq $0, %r15
/* Calculate h0' */
andq %rbp, %rsi // h0' = rsi = h0 & (2^51 - 1) = r8 & (2^51 - 1)
orq %r8, %r9 // r9 = (h0 >> 51)
addq %r9, %r10 // h1 += (h0 >> 51)
adcq $0, %r11
/* Calculate h3' */
movq %r14, %r8
shrq $51, %r14
shlq $13, %r15
andq %rbp, %r8 // h3' = r8 = h3 & (2^51 - 1) = r14 & (2^51 - 1)
orq %r14, %r15 // r15 = (h3 >> 51)
addq %r15, %rbx // h4 += (h3 >> 51)
adcq $0, %rcx
/* Calculate h1' */
movq %r10, %rdx
shrq $51, %r10
shlq $13, %r11
andq %rbp, %rdx // h1' = rdx = h1 & (2^51 - 1) = r10 & (2^51 - 1)
orq %r10, %r11 // r11 = (h1 >> 51)
addq %r11, %rax // h2 += (h1 >> 51)
/* Calculate h4' */
movq %rbx, %r9
shrq $51, %rbx
shlq $13, %rcx
andq %rbp, %r9 // h4' = r9 = h4 & (2^51 - 1) = rbx & (2^51 - 1)
orq %rbx, %rcx // rcx = (h4 >> 51)
/* out[0] = out[0] + 19 * carry */
leaq (%rcx, %rcx, 8), %r10 // r10 = 8 * rcx
leaq (%rcx, %r10, 2), %rcx // rcx = 2 * (8 * rcx) + rcx = 19 * rcx
addq %rcx, %rsi
/* h2 remaining */
movq %rax, %r10
andq %rbp, %rax // h2 &= (2^51 - 1)
shrq $51, %r10
addq %r10, %r8
/* out[1] += out[0] >> 51 */
movq %rsi, %r10
/* out[0] &= (2^51 - 1) */
andq %rbp, %rsi
shrq $51, %r10
addq %r10, %rdx
/* Storing Results */
movq %rsi, (%rdi) // h0'
movq %rdx, 8(%rdi) // h1'
movq %rax, 16(%rdi) // h2'
movq %r8, 24(%rdi) // h3'
movq %r9, 32(%rdi) // h4'
.endm
#############################################################
# void Fp51Mul (Fp51 *out, const Fp51 *f, const Fp51 *g);
#############################################################
.globl Fp51Mul
.type Fp51Mul, @function
.align 32
Fp51Mul:
.cfi_startproc
/* Save Register */
push_stack
/* The input and output parameters are transferred by registers rdi, rsi, and rdx.
* rdi: out; rsi: f; rdx: g; fp51 is an array of [u64; 5]
* rdx will be overwritten in subsequent calculation.
* Therefore, you need to load the data in the rdx variable in advance.
*/
movq (%rsi), %rax // f0
movq (%rdx), %rbx // g0
movq 8(%rdx), %r14 // g1
movq 16(%rdx), %r15 // g2
movq 24(%rdx), %rbp // g3, Store g0-g3, store g3 in unaffected registers
movq 32(%rdx), %rcx // g4
/* Stores the out pointer and frees the rdi so that the rdi can be used in subsequent calculations. Stores 19 * g4. */
movq %rdi, 24(%rsp)
movq %rax, %rdi // f0
/* r14, r15, rbx, and rcx will be overwritten in subsequent calculations. g0 to g2 will be stored.
* Storage actions will be scattered in the calculation code for performance purposes.
*/
/* h0 = f0g0 + 19f1g4 + 19f2g3 + 19f3g2 + 19f4g1; Stored in r8, r9 */
mulq %rbx // (rax, rdx) = f0 * g0, in le
movq %rax, %r8
movq %rdi, %rax // f0
movq %rbx, 16(%rsp) // g0
movq %rdx, %r9
/* h1 = f0g1 + f1g0 + 19f2g4 + 19f3g3 + 19f4g2; Stored in r10, r11 */
mulq %r14 // (rax, rdx) = f0 * g1
movq %rax, %r10
movq %rdi, %rax // f0
leaq (%rcx, %rcx, 8), %rbx // g4 * 8 + g4 = g4 * 9
movq %r14, 8(%rsp) // g1
movq %rdx, %r11
/* h2 = f0g2 + f1g1 + f2g0 + 19f3g4 + 19f4g3; Stored in r12, r13 */
mulq %r15 // (rax, rdx) = f0 * g2
movq %rax, %r12
movq %rdi, %rax // f0
leaq (%rcx, %rbx, 2), %rdi // rdi = 2 * (9 * g4) + g4, Store 19 * g4 to rdi before rcx is overwritten
movq %r15, (%rsp) // g2
movq %rdx, %r13
/* h3 = f0g3 + f1g2 + f2g1 + f3g0 + 19f4g4; Stored in r14, r15 */
mulq %rbp // (rax, rdx) = f0 * g3
movq %rax, %r14
movq (%rsi), %rax // f0
movq %rdx, %r15
/* h4 = f0g4 + f1g3 + f2g2 + f3g1 + f4g0; Stored in rbx, rcx */
mulq %rcx // (rax, rdx) = f0 * g4
movq %rax, %rbx
movq 8(%rsi), %rax // f1
movq %rdx, %rcx
/* Calculate 19 * g4 related */
u51mul %rdi, %r8, %r9, 16(%rsi) // (rax, rdx) = 19 * f1 * g4; load f2
u51mul %rdi, %r10, %r11, 24(%rsi) // (rax, rdx) = 19 * f2 * g4; load f3
u51mul %rdi, %r12, %r13, 32(%rsi) // (rax, rdx) = 19 * f3 * g4; load f4
mulq %rdi // (rax, rdx) = 19 * f4 * g4
imulq $19, %rbp, %rdi // 19 * g3
addq %rax, %r14
movq 8(%rsi), %rax // f1
adcq %rdx, %r15
/* Calculate g3 related */
mulq %rbp // (rax, rdx) = f1 * g3
movq (%rsp), %rbp // g2
addq %rax, %rbx
movq 16(%rsi), %rax // f2
adcq %rdx, %rcx
u51mul %rdi, %r8, %r9, 24(%rsi) // (rax, rdx) = 19 * f2 * g3; load f3
u51mul %rdi, %r10, %r11, 32(%rsi) // (rax, rdx) = 19 * f3 * g3; load f4
mulq %rdi // (rax, rdx) = 19 * f4 * g3
imulq $19, %rbp, %rdi // 19 * g2
addq %rax, %r12
movq 8(%rsi), %rax // f1
adcq %rdx, %r13
/* Calculate g2 related */
u51mul %rbp, %r14, %r15, 16(%rsi) // (rax, rdx) = f1 * g2; load f2
mulq %rbp // (rax, rdx) = f2 * g2
movq 8(%rsp), %rbp // g1
addq %rax, %rbx
movq 24(%rsi), %rax // f3
adcq %rdx, %rcx
u51mul %rdi, %r8, %r9, 32(%rsi) // (rax, rdx) = 19 * f3 * g2; load f4
u51mul %rdi, %r10, %r11, 8(%rsi) // (rax, rdx) = 19 * f4 * g2; load f2
/* Calculate g1 related */
mulq %rbp // (rax, rdx) = f1 * g1
imulq $19, %rbp, %rdi // 19 * g1
addq %rax, %r12
movq 16(%rsi), %rax // f2
adcq %rdx, %r13
u51mul %rbp, %r14, %r15, 24(%rsi) // (rax, rdx) = f2 * g1; load f3
mulq %rbp // (rax, rdx) = f3 * g1
movq 16(%rsp), %rbp // g0
addq %rax, %rbx
movq 32(%rsi), %rax // f4
adcq %rdx, %rcx
u51mul %rdi, %r8, %r9, 8(%rsi) // (rax, rdx) = 19 * f4 * g1; load f1
/* Calculate g0 related */
u51mul %rbp, %r10, %r11, 16(%rsi) // (rax, rdx) = f1 * g0; load f2
u51mul %rbp, %r12, %r13, 24(%rsi) // (rax, rdx) = f2 * g0; load f3
u51mul %rbp, %r14, %r15, 32(%rsi) // (rax, rdx) = f3 * g0; load f4
mulq %rbp // (rax, rdx) = f4 * g0
addq %rax, %rbx
adcq %rdx, %rcx
/* Restore the stack pointer. */
movq 24(%rsp), %rdi
reduce
/* Recovery register */
pop_stack
ret
.cfi_endproc
.size Fp51Mul,.-Fp51Mul
#############################################################
# void Fp51Square(Fp51 *out, const Fp51 *f);
#############################################################
.globl Fp51Square
.type Fp51Square, @function
.align 32
Fp51Square:
.cfi_startproc
/* Save Register */
push_stack
/* The input and output parameters are transferred by registers rdi and rsi.
* rdi: out; rsi: f; fp51 is an array of [u64; 5]
* Loads only non-adjacent data, vacating registers for storage calculations
*/
movq (%rsi), %rax // f0
movq 16(%rsi), %r15 // f2
movq 32(%rsi), %rcx // f4
/* Open the stack and store the following necessary content, which is consistent with the Fp51Mul.
* Stores the out pointer, frees the rdi,
* so that the rdi can be used in subsequent calculations, and stores 19 * f4.
*/
leaq (%rax, %rax, 1), %rbp // 2 * f0
movq %rdi, 24(%rsp)
/* h0 = f0^2 + 38f1f4 + 38f2f3; Stored in r8, r9 */
mulq %rax // (rax, rdx) = f0^2
movq %rax, %r8
movq 8(%rsi), %rax // f1
movq %rdx, %r9
/* h1 = 19f3^2 + 2f0f1 + 38f2g4; Stored in r10, r11 */
mulq %rbp // (rax, rdx) = 2f0 * f1
movq %rax, %r10
movq %r15, %rax // f2
movq %r15, 16(%rsp) // Store f2 for later use of rsi
movq %rdx, %r11
/* h2 = f1^2 + 2f0f2 + 38f3g4; Stored in r12, r13 */
mulq %rbp // (rax, rdx) = 2f0 * f2
movq %rax, %r12
movq 24(%rsi), %rax // f3
movq %rdx, %r13
imulq $19, %rcx, %rdi // Store 19 * f4 to rdi before rcx is overwritten
/* h3 = 19f4^2 + 2f0f3 + 2f1f2; Stored in r14, r15 */
mulq %rbp // (rax, rdx) = 2f0 * f3
movq %rax, %r14
movq %rcx, %rax // f4
movq %rdx, %r15
/* h4 = f2^2 + 2f0f4 + 2f1f3; Stored in rbx, rcx */
mulq %rbp // (rax, rdx) = 2f0 * f4
movq %rax, %rbx
movq %rcx, %rax // f4
movq %rdx, %rcx
/* Calculate 19 * f4 related
* h3
*/
u51mul %rdi, %r14, %r15, 8(%rsi) // (rax, rdx) = 19 * f4^2; load f1
movq 24(%rsi), %rsi // f3
/* Calculate f1 related
* h2
*/
leaq (%rax, %rax, 1), %rbp // 2 * f1
u51mul %rax, %r12, %r13, 16(%rsp) // (rax, rdx) = f1^2; load f2
/* h3 */
u51mul %rbp, %r14, %r15, %rsi // (rax, rdx) = 2 * f1 * f2; load f3
/* h4 */
u51mul %rbp, %rbx, %rcx, %rbp // (rax, rdx) = 2 * f1 * f3; load 2 * f1
imulq $19, %rsi, %rbp // 19 * f3
/* h0 */
mulq %rdi // (rax, rdx) = 2 * f1 * 19 * f4
addq %rax, %r8
leaq (%rsi, %rsi, 1), %rax // 2 * f3
adcq %rdx, %r9
/* Calculate f3 related
* h2
*/
u51mul %rdi, %r12, %r13, %rsi // (rax, rdx) = f3 * 2 * 19 * f4; load f3
/* h1 */
u51mul %rbp, %r10, %r11, 16(%rsp) // (rax, rdx) = 19 * f3^2; load f2
/* Calculate f2 related
* h4
*/
leaq (%rax, %rax, 1), %rsi // 2 * f2
u51mul %rax, %rbx, %rcx, %rbp // (rax, rdx) = f2^2; load 19 * f3
/* h0 */
u51mul %rsi, %r8, %r9, %rsi // (rax, rdx) = 2 * f2 * 19 * f3; load 2 * f2
/* h1 */
mulq %rdi // (rax, rdx) = 2 * f2 * 19 * f4
addq %rax, %r10
adcq %rdx, %r11
/* Recovery register */
movq 24(%rsp), %rdi
reduce
/* Recovery register */
pop_stack
ret
.cfi_endproc
.size Fp51Square,.-Fp51Square
#############################################################
# void Fp51MulScalar(Fp51 *out, const Fp51 *in);
#############################################################
.globl Fp51MulScalar
.type Fp51MulScalar, @function
.align 32
Fp51MulScalar:
.cfi_startproc
/* Save Register */
push_stack
/*The input and output parameters are transferred by registers rdi, rsi, and rdx.
* rdi: out; rsi: in; rdx: scalar; fp51 Is an array of [u64; 5]
* Open stack, consistent with Fp51Mul
*/
/* h0 */
movl $121666, %eax
mulq (%rsi) // f0 * 121666
movq %rax, %r8
movl $121666, %eax // Modify the rax immediately after the rax is vacated.
movq %rdx, %r9
/* h1 */
mulq 8(%rsi) // f1 * 121666
movq %rax, %r10
movl $121666, %eax
movq %rdx, %r11
/* h2 */
mulq 16(%rsi) // f2 * 121666
movq %rax, %r12
movl $121666, %eax
movq %rdx, %r13
/* h3 */
mulq 24(%rsi) // f3 * 121666
movq %rax, %r14
movl $121666, %eax
movq %rdx, %r15
/* h4 */
mulq 32(%rsi) // f4 * 121666
movq %rax, %rbx
movq %rdx, %rcx
reduce
/* Recovery register */
pop_stack
ret
.cfi_endproc
.size Fp51MulScalar,.-Fp51MulScalar
/**
* Fp64 reduce:
* +------+-----+-----+-----+------+
* | | r15 | r14 | r13 | r12 |
* | | | | | 38 |
* +-------------------------------+
* | | | | r12'| r12' |
* | | | r13'| r13'| |
* | | r14'| r14'| | |
* | r15' | r15'| | | |
* +-------------------------------+
* | | r11'| r10'| r9' | r8' |
* | | | | |19r15'|
* +-------------------------------+
* | | r11 | r10 | r9 | r8 |
* +------+-----+-----+-----+------+
*/
.macro Fp64Reduce
xorq %rsi, %rsi
movq $38, %rdx
mulx %r12, %rax, %rbx
adcx %rax, %r8
adox %rbx, %r9
mulx %r13, %rax, %rbx
adcx %rax, %r9
adox %rbx, %r10
mulx %r14, %rax, %rbx
adcx %rax, %r10
adox %rbx, %r11
mulx %r15, %rax, %r12
adcx %rax, %r11
adcx %rsi, %r12
adox %rsi, %r12
shld $1, %r11, %r12
movq $0x7FFFFFFFFFFFFFFF, %rbp
andq %rbp, %r11
imulq $19, %r12, %r12
addq %r12, %r8
adcx %rsi, %r9
adcx %rsi, %r10
adcx %rsi, %r11
movq 0(%rsp), %rdi
movq %r9, 8(%rdi)
movq %r10, 16(%rdi)
movq %r11, 24(%rdi)
movq %r8, 0(%rdi)
.endm
.globl Fp64Mul
.type Fp64Mul,@function
.align 32
Fp64Mul:
.cfi_startproc
pushq %rbp
pushq %rbx
pushq %r12
pushq %r13
pushq %r14
pushq %r15
pushq %rdi
/**
* (f3, f2, f1, f0) * (g3, g2, g1, g0) :
* + + + + + + + + +
* | | | | | A3 | A2 | A1 | A0 |
* | | | | | B3 | B2 | B1 | B0 |
* +------------------------------------------+
* | | | | | | |A0B0|A0B0|
* | | | | | |A1B0|A1B0| |
* | | | | |A2B0|A2B0| | |
* | | | |A3B0|A3B0| | | |
* | | | | | |A0B1|A0B1| |
* | | | | |A1B1|A1B1| | |
* | | | |A2B1|A2B1| | | |
* | | |A3B1|A3B1| | | | |
* | | | | |A2B0|A2B0| | |
* | | | |A2B1|A2B1| | | |
* | | |A2B2|A2B2| | | | |
* | |A2B3|A2B3| | | | | |
* | | | |A3B0|A3B0| | | |
* | | |A3B1|A3B1| | | | |
* | |A3B2|A3B2| | | | | |
* |A3B3|A3B3| | | | | | |
* +------------------------------------------+
* |r15 |r14 |r13 |r12 |r11 |r10 |r9 |r8 |
* + + + + + + + + +
*/
movq 0(%rdx), %rcx
movq 8(%rdx), %rbp
movq 16(%rdx), %rdi
movq 24(%rdx), %r15
movq 0(%rsi), %rdx
xorq %r14, %r14
// (f3, f2, f1, f0) * g0
mulx %rcx, %r8, %rax
mulx %rbp, %r9, %rbx
adcx %rax, %r9
mulx %rdi, %r10, %rax
adcx %rbx, %r10
mulx %r15, %r11, %r12
movq 8(%rsi), %rdx
adcx %rax, %r11
adcx %r14, %r12
// (f3, f2, f1, f0) * g1
mulx %rcx, %rax, %rbx
adcx %rax, %r9
adox %rbx, %r10
mulx %rbp, %rax, %rbx
adcx %rax, %r10
adox %rbx, %r11
mulx %rdi, %rax, %rbx
adcx %rax, %r11
adox %rbx, %r12
mulx %r15, %rax, %r13
movq 16(%rsi), %rdx
adcx %rax, %r12
adox %r14, %r13
adcx %r14, %r13
// (f3, f2, f1, f0) * g2
mulx %rcx, %rax, %rbx
adcx %rax, %r10
adox %rbx, %r11
mulx %rbp, %rax, %rbx
adcx %rax, %r11
adox %rbx, %r12
mulx %rdi, %rax, %rbx
adcx %rax, %r12
adox %rbx, %r13
mulx %r15, %rax, %r14
movq 24(%rsi), %rdx
adcx %rax, %r13
movq $0, %rsi
adox %rsi, %r14
adcx %rsi, %r14
// (f3, f2, f1, f0) * g3
mulx %rcx, %rax, %rbx
adcx %rax, %r11
adox %rbx, %r12
mulx %rbp, %rax, %rbx
adcx %rax, %r12
adox %rbx, %r13
mulx %rdi, %rax, %rbx
adcx %rax, %r13
adox %rbx, %r14
mulx %r15, %rax, %r15
adcx %rax, %r14
adox %rsi, %r15
adcx %rsi, %r15
// reduce
Fp64Reduce
movq 8(%rsp), %r15
movq 16(%rsp), %r14
movq 24(%rsp), %r13
movq 32(%rsp), %r12
movq 40(%rsp), %rbx
movq 48(%rsp), %rbp
leaq 56(%rsp), %rsp
ret
.cfi_endproc
.size Fp64Mul,.-Fp64Mul
.globl Fp64Sqr
.type Fp64Sqr,@function
.align 32
Fp64Sqr:
.cfi_startproc
pushq %rbp
pushq %rbx
pushq %r12
pushq %r13
pushq %r14
pushq %r15
pushq %rdi
/**
* (f3, f2, f1, f0) ^ 2 :
* +----+----+----+----+----+----+----+----+----+
* | | | | | | A3 | A2 | A1 | A0 |
* | * | | | | | A3 | A2 | A1 | A0 |
* +--------------------------------------------+
* | | | | | | |A0A1|A0A1| |
* | | | | | |A0A2|A0A2| | |
* | + | | | |A0A3|A0A3| | | |
* | | | | |A1A2|A1A2| | | |
* | | | |A1A3|A1A3| | | | |
* | | |A2A3|A2A3| | | | | |
* +--------------------------------------------+
* | *2 | |r14`|r13`|r12`|r11`|r10`|r9` | |
* +--------------------------------------------+
* | |r15'|r14'|r13'|r12'|r11'|r10'|r9' | |
* +--------------------------------------------+
* | | | | | | | |A0A0|A0A0|
* | | | | | |A1A1|A1A1| | |
* | + | | |A2A2|A2A2| | | | |
* | |A3A3|A3A3| | | | | | |
* +--------------------------------------------+
* | |r15 |r14 |r13 |r12 |r11 |r10 |r9 |r8 |
* +--------------------------------------------+
*/
movq 0(%rsi), %rbx // a0
movq 8(%rsi), %rcx // a1
movq 16(%rsi), %rbp // a2
movq 24(%rsi), %rdi // a3
xorq %r15, %r15
// (a1, a2, a3) * a0
movq %rbx, %rdx
mulx %rcx, %r9, %rsi
mulx %rbp, %r10, %rax
adcx %rsi, %r10
mulx %rdi, %r11, %r12
movq %rcx, %rdx
adcx %rax, %r11
adcx %r15, %r12
// (a2, a3) * a1
mulx %rbp, %rsi, %rax
adcx %rsi, %r11
adox %rax, %r12
mulx %rdi, %rsi, %r13
movq %rbp, %rdx
adcx %rsi, %r12
adcx %r15, %r13
adox %r15, %r13
// a3 * a2
mulx %rdi, %rsi, %r14
movq %rbx, %rdx
adcx %rsi, %r13
adcx %r15, %r14
// (r9 --- r14) *2
shld $1, %r14, %r15
shld $1, %r13, %r14
shld $1, %r12, %r13
shld $1, %r11, %r12
shld $1, %r10, %r11
shld $1, %r9, %r10
shlq $1, %r9
xorq %r8, %r8 // clear cf flag
// a0 * a0
mulx %rdx, %r8, %rax
movq %rcx, %rdx
adcx %rax, %r9
// a1 * a1
mulx %rdx, %rsi, %rax
movq %rbp, %rdx
adcx %rsi, %r10
adcx %rax, %r11
// a2 * a2
mulx %rdx, %rsi, %rax
movq %rdi, %rdx
adcx %rsi, %r12
adcx %rax, %r13
// a3 * a3
mulx %rdx, %rsi, %rax
adcx %rsi, %r14
adcx %rax, %r15
// reduce
Fp64Reduce
movq 8(%rsp), %r15
movq 16(%rsp), %r14
movq 24(%rsp), %r13
movq 32(%rsp), %r12
movq 40(%rsp), %rbx
movq 48(%rsp), %rbp
leaq 56(%rsp), %rsp
ret
.cfi_endproc
.size Fp64Sqr, .-Fp64Sqr
.globl Fp64MulScalar
.type Fp64MulScalar, @function
.align 32
Fp64MulScalar:
.cfi_startproc
movl $121666, %edx
mulx 0(%rsi), %r8, %rax
mulx 8(%rsi), %r9, %rcx
addq %rax, %r9
mulx 16(%rsi), %r10, %rax
adcx %rcx, %r10
mulx 24(%rsi), %r11, %rcx
adcx %rax, %r11
movl $0, %edx
adcx %rdx, %rcx
movq $0x7FFFFFFFFFFFFFFF, %rax
shld $1, %r11, %rcx
andq %rax, %r11
imulq $19, %rcx, %rcx
addq %rcx, %r8
adcx %rdx, %r9
movq %r8, 0(%rdi)
adcx %rdx, %r10
movq %r9, 8(%rdi)
adcx %rdx, %r11
movq %r10, 16(%rdi)
movq %r11, 24(%rdi)
ret
.cfi_endproc
.size Fp64MulScalar, .-Fp64MulScalar
.globl Fp64Add
.type Fp64Add, @function
.align 32
Fp64Add:
.cfi_startproc
movq 0(%rsi),%r8
movq 8(%rsi),%r9
addq 0(%rdx),%r8
adcx 8(%rdx),%r9
movq 16(%rsi),%r10
movq 24(%rsi),%r11
adcx 16(%rdx),%r10
adcx 24(%rdx),%r11
movq $0, %rax
movq $38, %rcx
cmovae %rax, %rcx
addq %rcx, %r8
adcx %rax, %r9
adcx %rax, %r10
movq %r9, 8(%rdi)
adcx %rax, %r11
movq %r10, 16(%rdi)
movq %r11, 24(%rdi)
cmovc %rcx, %rax
addq %rax, %r8
movq %r8, 0(%rdi)
ret
.cfi_endproc
.size Fp64Add, .-Fp64Add
.globl Fp64Sub
.type Fp64Sub,@function
.align 32
Fp64Sub:
.cfi_startproc
movq 0(%rsi),%r8
movq 8(%rsi),%r9
subq 0(%rdx),%r8
sbbq 8(%rdx),%r9
movq 16(%rsi),%r10
movq 24(%rsi),%r11
sbbq 16(%rdx),%r10
sbbq 24(%rdx),%r11
movq $0, %rax
movq $38, %rcx
cmovae %rax, %rcx
subq %rcx, %r8
sbbq %rax, %r9
sbbq %rax, %r10
movq %r9,8(%rdi)
sbbq %rax, %r11
movq %r10,16(%rdi)
cmovc %rcx, %rax
movq %r11,24(%rdi)
subq %rax, %r8
movq %r8,0(%rdi)
ret
.cfi_endproc
.size Fp64Sub,.-Fp64Sub
.globl Fp64PolyToData
.type Fp64PolyToData,@function
.align 32
Fp64PolyToData:
.cfi_startproc
movq 24(%rsi), %r11
movq 16(%rsi), %r10
xorq %rax, %rax
leaq (%r11, %r11, 1), %rcx
sarq $63, %r11
shrq $1, %rcx
andq $19, %r11
addq $19, %r11
movq 0(%rsi), %r8
movq 8(%rsi), %r9
addq %r11, %r8
adcx %rax, %r9
adcx %rax, %r10
adcx %rax, %rcx
leaq (%rcx, %rcx, 1), %r11
sarq $63, %rcx
shrq $1, %r11
notq %rcx
andq $19, %rcx
subq %rcx, %r8
sbbq $0, %r9
movq %r8, 0(%rdi)
movq %r9, 8(%rdi)
sbbq $0, %r10
sbbq $0, %r11
movq %r10, 16(%rdi)
movq %r11, 24(%rdi)
ret
.cfi_endproc
.size Fp64PolyToData,.-Fp64PolyToData
#endif
|
2301_79861745/bench_create
|
crypto/curve25519/src/asm/x25519_x86_64.S
|
Unix Assembly
|
unknown
| 25,769
|
/*
* 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_X25519
#include "x25519_asm.h"
#include "securec.h"
#include "curve25519_local.h"
#ifdef HITLS_CRYPTO_X25519_X8664
#include "crypt_utils.h"
#endif
// X25519 alternative implementation, faster but require asm
#define CURVE25519_51BITS_MASK 0x7ffffffffffff
#define CURVE25519_51BITS 51
static void Fp51DataToPoly(Fp51 *out, const uint8_t in[32])
{
uint64_t h[5];
CURVE25519_BYTES7_LOAD(h, in); // load 7 bytes
CURVE25519_BYTES6_LOAD(h + 1, in + 7); // load 6 bytes from in7 to h1
h[1] <<= 5; // shift 5 to fit 51 bits
CURVE25519_BYTES7_LOAD(h + 2, in + 13); // load 7 bytes from in13 to h2
h[2] <<= 2; // shift 2 to fit 51 bits
CURVE25519_BYTES6_LOAD(h + 3, in + 20); // load 6 bytes from in20 to h3
h[3] <<= 7; // shift 7 to fit 51 bits
CURVE25519_BYTES6_LOAD(h + 4, in + 26); // load 6 bytes from in26 to h4
h[4] &= 0x7fffffffffff; // 41 bits mask = 0x7fffffffffff
h[4] <<= 4; // shift 4 to fit 51 bits
h[1] |= h[0] >> CURVE25519_51BITS; // carry h[0] -> h[1]
h[0] &= CURVE25519_51BITS_MASK; // clear h[0]
h[2] |= h[1] >> CURVE25519_51BITS; // carry h[1] -> h[2]
h[1] &= CURVE25519_51BITS_MASK; // clear h[1]
h[3] |= h[2] >> CURVE25519_51BITS; // carry h[2] -> h[3]
h[2] &= CURVE25519_51BITS_MASK; // clear h[2]
h[4] |= h[3] >> CURVE25519_51BITS; // carry h[3] -> h[4]
h[3] &= CURVE25519_51BITS_MASK; // clear h[3]
out->data[0] = h[0]; // 0
out->data[1] = h[1]; // 1
out->data[2] = h[2]; // 2
out->data[3] = h[3]; // 3
out->data[4] = h[4]; // 4
}
static void Fp51UnloadTo8Bits(uint8_t out[32], uint64_t h[5])
{
// load from uint64 to uint8, load 8 bits at a time
out[0] = (uint8_t)h[0];
out[1] = (uint8_t)(h[0] >> 8); // load from position 8 to out[1]
out[2] = (uint8_t)(h[0] >> 16); // load from position 16 to out[2]
out[3] = (uint8_t)(h[0] >> 24); // load from position 24 to out[3]
out[4] = (uint8_t)(h[0] >> 32); // load from position 32 to out[4]
out[5] = (uint8_t)(h[0] >> 40); // load from position 40 to out[5]
// load from position 48 from h[1] and (8-5)=3 bits from h[1] to out[6]
out[6] = (uint8_t)((h[0] >> 48) | (uint8_t)(h[1] << 3));
out[7] = (uint8_t)(h[1] >> 5); // load h[1] from position 5 to out[7]
out[8] = (uint8_t)(h[1] >> 13); // load h[1] from position 13 to out[8]
out[9] = (uint8_t)(h[1] >> 21); // load h[1] from position 21 to out[9]
out[10] = (uint8_t)(h[1] >> 29); // load h[1] from position 29 to out[10]
out[11] = (uint8_t)(h[1] >> 37); // load h[1] from position 37 to out[11]
// load from position 45 from h[1] and (8-2)=6 bits from h[2] to out[12]
out[12] = (uint8_t)((h[1] >> 45) | (uint8_t)(h[2] << 6));
out[13] = (uint8_t)(h[2] >> 2); // load h[2] from position 2 to out[13]
out[14] = (uint8_t)(h[2] >> 10); // load h[2] from position 10 to out[14]
out[15] = (uint8_t)(h[2] >> 18); // load h[2] from position 18 to out[15]
out[16] = (uint8_t)(h[2] >> 26); // load h[2] from position 26 to out[16]
out[17] = (uint8_t)(h[2] >> 34); // load h[2] from position 34 to out[17]
out[18] = (uint8_t)(h[2] >> 42); // load h[2] from position 42 to out[18]
// load from position 50 from h[2] and (8-1)=7 bits from h[3] to out[19]
out[19] = (uint8_t)((h[2] >> 50) | (uint8_t)(h[3] << 1));
out[20] = (uint8_t)(h[3] >> 7); // load h[3] from position 7 to out[20]
out[21] = (uint8_t)(h[3] >> 15); // load h[3] from position 15 to out[21]
out[22] = (uint8_t)(h[3] >> 23); // load h[3] from position 23 to out[22]
out[23] = (uint8_t)(h[3] >> 31); // load h[3] from position 31 to out[23]
out[24] = (uint8_t)(h[3] >> 39); // load h[3] from position 39 to out[24]
// load from position 47 from h[3] and (4-4)=4 bits from h[4] to out[25]
out[25] = (uint8_t)((h[3] >> 47) | (uint8_t)(h[4] << 4));
out[26] = (uint8_t)(h[4] >> 4); // load h[4] from position 4 to out[26]
out[27] = (uint8_t)(h[4] >> 12); // load h[4] from position 12 to out[27]
out[28] = (uint8_t)(h[4] >> 20); // load h[4] from position 20 to out[28]
out[29] = (uint8_t)(h[4] >> 28); // load h[4] from position 28 to out[29]
out[30] = (uint8_t)(h[4] >> 36); // load h[4] from position 36 to out[30]
out[31] = (uint8_t)(h[4] >> 44); // load h[4] from position 44 to out[31]
}
static void Fp51PolyToData(const Fp51 *in, uint8_t out[32])
{
uint64_t h[5];
h[0] = in->data[0]; // 0
h[1] = in->data[1]; // 1
h[2] = in->data[2]; // 2
h[3] = in->data[3]; // 3
h[4] = in->data[4]; // 4
uint64_t carry;
carry = (h[0] + 19) >> CURVE25519_51BITS; // plus 19 then calculate carry
carry = (h[1] + carry) >> CURVE25519_51BITS; // carry of h[1]
carry = (h[2] + carry) >> CURVE25519_51BITS; // carry of h[2]
carry = (h[3] + carry) >> CURVE25519_51BITS; // carry of h[3]
carry = (h[4] + carry) >> CURVE25519_51BITS; // carry of h[4]
h[0] += 19 * carry; // process carry h[4] -> h[0], h[0] += 19 * carry
h[1] += h[0] >> CURVE25519_51BITS; // process carry h[0] -> h[1]
h[0] &= CURVE25519_51BITS_MASK; // clear h[0]
h[2] += h[1] >> CURVE25519_51BITS; // process carry h[1] -> h[2]
h[1] &= CURVE25519_51BITS_MASK; // clear h[1]
h[3] += h[2] >> CURVE25519_51BITS; // process carry h[2] -> h[3]
h[2] &= CURVE25519_51BITS_MASK; // clear h[2]
h[4] += h[3] >> CURVE25519_51BITS; // process carry h[3] -> h[4]
h[3] &= CURVE25519_51BITS_MASK; // clear h[3]
h[4] &= CURVE25519_51BITS_MASK; // clear h[4]
Fp51UnloadTo8Bits(out, h);
}
/* out = in1 ^ (4 * 2 ^ (2 * times)) * in2 */
static inline void Fp51MultiSquare(Fp51 *in1, Fp51 *in2, Fp51 *out, int32_t times)
{
int32_t i;
Fp51 temp1, temp2;
Fp51Square(&temp1, in1);
Fp51Square(&temp2, &temp1);
for (i = 0; i < times; i++) {
Fp51Square(&temp1, &temp2);
Fp51Square(&temp2, &temp1);
}
Fp51Mul(out, in2, &temp2);
}
/* out = a ^ -1 */
static void Fp51Invert(Fp51 *out, const Fp51 *a)
{
Fp51 a0; /* save a^1 */
Fp51 a1; /* save a^2 */
Fp51 a2; /* save a^11 */
Fp51 a3; /* save a^(2^5-1) */
Fp51 a4; /* save a^(2^10-1) */
Fp51 a5; /* save a^(2^20-1) */
Fp51 a6; /* save a^(2^40-1) */
Fp51 a7; /* save a^(2^50-1) */
Fp51 a8; /* save a^(2^100-1) */
Fp51 a9; /* save a^(2^200-1) */
Fp51 a10; /* save a^(2^250-1) */
Fp51 temp1, temp2;
/* We know a×b=1(mod p), then a and b are inverses of mod p, i.e. a=b^(-1), b=a^(-1);
* According to Fermat's little theorem a^(p-1)=1(mod p), so a*a^(p-2)=1(mod p);
* So the inverse element of a is a^(-1) = a^(p-2)(mod p)
* Here it is, p=2^255-19, thus we need to compute a^(2^255-21)(mod(2^255-19))
*/
/* a^1 */
CURVE25519_FP51_COPY(a0.data, a->data);
/* a^2 */
Fp51Square(&a1, &a0);
/* a^4 */
Fp51Square(&temp1, &a1);
/* a^8 */
Fp51Square(&temp2, &temp1);
/* a^9 */
Fp51Mul(&temp1, &a0, &temp2);
/* a^11 */
Fp51Mul(&a2, &a1, &temp1);
/* a^22 */
Fp51Square(&temp2, &a2);
/* a^(2^5-1) = a^(9+22) */
Fp51Mul(&a3, &temp1, &temp2);
/* a^(2^10-1) = a^(2^10-2^5) * a^(2^5-1) */
Fp51Square(&temp1, &a3);
Fp51Square(&temp2, &temp1);
Fp51Square(&temp1, &temp2);
Fp51Square(&temp2, &temp1);
Fp51Square(&temp1, &temp2);
Fp51Mul(&a4, &a3, &temp1);
/* a^(2^20-1) = a^(2^20-2^10) * a^(2^10-1) */
Fp51MultiSquare(&a4, &a4, &a5, 4); // (2 * 2) ^ 4
/* a^(2^40-1) = a^(2^40-2^20) * a^(2^20-1) */
Fp51MultiSquare(&a5, &a5, &a6, 9); // (2 * 2) ^ 9
/* a^(2^50-1) = a^(2^50-2^10) * a^(2^10-1) */
Fp51MultiSquare(&a6, &a4, &a7, 4); // (2 * 2) ^ 4
/* a^(2^100-1) = a^(2^100-2^50) * a^(2^50-1) */
Fp51MultiSquare(&a7, &a7, &a8, 24); // (2 * 2) ^ 24
/* a^(2^200-1) = a^(2^200-2^100) * a^(2^100-1) */
Fp51MultiSquare(&a8, &a8, &a9, 49); // (2 * 2) ^ 49
/* a^(2^250-1) = a^(2^250-2^50) * a^(2^50-1) */
Fp51MultiSquare(&a9, &a7, &a10, 24); // (2 * 2) ^ 24
/* a^(2^5*(2^250-1)) = (a^(2^250-1))^5 */
Fp51Square(&temp1, &a10);
Fp51Square(&temp2, &temp1);
Fp51Square(&temp1, &temp2);
Fp51Square(&temp2, &temp1);
Fp51Square(&temp1, &temp2);
/* The output:a^(2^255-21) = a(2^5*(2^250-1)+11) = a^(2^5*(2^250-1)) * a^11 */
Fp51Mul(out, &a2, &temp1);
}
void Fp51ScalarMultiPoint(uint8_t out[32], const uint8_t scalar[32], const uint8_t point[32])
{
uint8_t k[32];
const uint8_t *u = point;
int32_t t;
uint32_t swap;
uint32_t kTemp;
Fp51 x1, x2, x3;
Fp51 z2, z3;
Fp51 t1, t2;
/* Decord the scalar into k */
CURVE25519_DECODE_LITTLE_ENDIAN(k, scalar);
/* Reference RFC 7748 section 5:The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 */
Fp51DataToPoly(&x1, u);
CURVE25519_FP51_SET(x2.data, 1);
CURVE25519_FP51_SET(z2.data, 0);
CURVE25519_FP51_COPY(x3.data, x1.data);
CURVE25519_FP51_SET(z3.data, 1);
swap = 0;
/* "bits" parameter set to 255 for x25519 */ /* For t = bits-1(254) down to 0: */
for (t = 254; t >= 0; t--) {
/* t >> 3: calculation the index of bit; t & 7: Obtains the corresponding bit in the byte */
kTemp = (k[(uint32_t)t >> 3] >> ((uint32_t)t & 7)) & 1; /* kTemp = (k >> t) & 1 */
swap ^= kTemp; /* swap ^= kTemp */
CURVE25519_FP51_CSWAP(swap, x2.data, x3.data); /* (x_2, x_3) = cswap(swap, x_2, x_3) */
CURVE25519_FP51_CSWAP(swap, z2.data, z3.data); /* (z_2, z_3) = cswap(swap, z_2, z_3) */
swap = kTemp; /* swap = kTemp */
CURVE25519_FP51_SUB(t1.data, x3.data, z3.data); /* x3 = D */
CURVE25519_FP51_SUB(t2.data, x2.data, z2.data); /* t2 = B */
CURVE25519_FP51_ADD(x2.data, x2.data, z2.data); /* t1 = A */
CURVE25519_FP51_ADD(z2.data, x3.data, z3.data); /* x2 = C */
Fp51Mul(&z3, &t1, &x2);
Fp51Mul(&z2, &z2, &t2);
Fp51Square(&t1, &t2);
Fp51Square(&t2, &x2);
CURVE25519_FP51_ADD(x3.data, z3.data, z2.data);
CURVE25519_FP51_SUB(z2.data, z3.data, z2.data);
Fp51Mul(&x2, &t2, &t1);
CURVE25519_FP51_SUB(t2.data, t2.data, t1.data);
Fp51Square(&z2, &z2);
Fp51MulScalar(&z3, &t2); // z2 *= 121665 + 1 = 121666
Fp51Square(&x3, &x3);
CURVE25519_FP51_ADD(t1.data, t1.data, z3.data);
Fp51Mul(&z3, &x1, &z2);
Fp51Mul(&z2, &t2, &t1);
}
CURVE25519_FP51_CSWAP(swap, x2.data, x3.data);
CURVE25519_FP51_CSWAP(swap, z2.data, z3.data);
/* Return x2 * (z2 ^ (p - 2)) */
Fp51Invert(&t1, &z2);
Fp51Mul(&t2, &x2, &t1);
Fp51PolyToData(&t2, out);
(void)memset_s(k, sizeof(k), 0, sizeof(k));
}
#ifdef HITLS_CRYPTO_X25519_X8664
#define CURVE25519_63BITS_MASK 0x7fffffffffffffff
#define CURVE25519_FP64_SET(dst, value) \
do { \
(dst)[0] = (value); \
(dst)[1] = 0; \
(dst)[2] = 0; \
(dst)[3] = 0; \
} while (0)
#define CURVE25519_FP64_COPY(dst, src) \
do { \
(dst)[0] = (src)[0]; \
(dst)[1] = (src)[1]; \
(dst)[2] = (src)[2]; \
(dst)[3] = (src)[3]; \
} while (0)
#define CURVE25519_BYTES8_LOAD(dst, src) \
do { \
dst = (uint64_t)(src)[0]; \
dst |= ((uint64_t)(src)[1]) << 8; \
dst |= ((uint64_t)(src)[2]) << 16; \
dst |= ((uint64_t)(src)[3]) << 24; \
dst |= ((uint64_t)(src)[4]) << 32; \
dst |= ((uint64_t)(src)[5]) << 40; \
dst |= ((uint64_t)(src)[6]) << 48; \
dst |= ((uint64_t)(src)[7]) << 56; \
} while (0)
#define CURVE25519_FP64_CSWAP(s, a, b) \
do { \
uint64_t tt; \
const uint64_t tsMacro = 0 - (uint64_t)(s); \
for (uint32_t ii = 0; ii < 4; ii++) { \
tt = tsMacro & ((a)[ii] ^ (b)[ii]); \
(a)[ii] = (a)[ii] ^ tt; \
(b)[ii] = (b)[ii] ^ tt; \
} \
} while (0)
static void Fp64DataToPoly(Fp64 h, const uint8_t *point)
{
uint8_t *tmp = (uint8_t *)(uintptr_t)point;
CURVE25519_BYTES8_LOAD(h[0], tmp);
tmp += 8; // the second 8 bytes
CURVE25519_BYTES8_LOAD(h[1], tmp);
tmp += 8; // the third 8 bytes
CURVE25519_BYTES8_LOAD(h[2], tmp);
tmp += 8; // the forth 8 bytes
CURVE25519_BYTES8_LOAD(h[3], tmp);
h[3] &= CURVE25519_63BITS_MASK;
return;
}
/* out = in1 ^ (4 * 2 ^ (2 * times)) * in2 */
static inline void Fp64MultiSqr(Fp64 in1, Fp64 in2, Fp64 out, int32_t times)
{
int32_t i;
Fp64 temp1, temp2;
Fp64Sqr(temp1, in1);
Fp64Sqr(temp2, temp1);
for (i = 0; i < times; i++) {
Fp64Sqr(temp1, temp2);
Fp64Sqr(temp2, temp1);
}
Fp64Mul(out, in2, temp2);
}
static void Fe64Invert(Fp64 out, const Fp64 z)
{
Fp64 t0;
Fp64 t1;
Fp64 t2;
Fp64 t3;
Fp64 t4;
Fp64Sqr(t0, z); /* t^2 */
Fp64Sqr(t1, t0); /* t^4 */
Fp64Sqr(t1, t1); /* t^8 */
Fp64Mul(t1, z, t1); /* t^9 */
Fp64Mul(t0, t0, t1); /* t^11 */
Fp64Sqr(t2, t0); /* t^22 */
Fp64Mul(t1, t1, t2); /* t^(2^5-1) = t^(9+22) */
/* t^(2^10-1) = t^(2^10-2^5) * t^(2^5-1) */
Fp64Sqr(t2, t1);
Fp64Sqr(t4, t2);
Fp64Sqr(t2, t4);
Fp64Sqr(t4, t2);
Fp64Sqr(t2, t4);
Fp64Mul(t1, t2, t1);
/* t^(2^20-1) = t^(2^20-2^10) * t^(2^10-1) */
Fp64MultiSqr(t1, t1, t2, 4);
/* t^(2^40-1) = t^(2^40-2^20) * t^(2^20-1) */
Fp64MultiSqr(t2, t2, t4, 9); // (2 * 2) ^ 9
/* t^(2^50-1) = t^(2^50-2^10) * t^(2^10-1) */
Fp64MultiSqr(t4, t1, t2, 4); // (2 * 2) ^ 4
/* t^(2^100-1) = t^(2^100-2^50) * t^(2^50-1) */
Fp64MultiSqr(t2, t2, t1, 24); // (2 * 2) ^ 24
/* t^(2^200-1) = t^(2^200-2^100) * t^(2^100-1) */
Fp64MultiSqr(t1, t1, t4, 49); // (2 * 2) ^ 49
/* t^(2^250-1) = t^(2^250-2^50) * t^(2^50-1) */
Fp64MultiSqr(t4, t2, t3, 24); // (2 * 2) ^ 24
/* t^(2^5*(2^250-1)) = (t^(2^250-1))^5 */
Fp64Sqr(t1, t3);
Fp64Sqr(t2, t1);
Fp64Sqr(t1, t2);
Fp64Sqr(t2, t1);
Fp64Sqr(t1, t2);
/* The output:t^(2^255-21) = t(2^5*(2^250-1)+11) = t^(2^5*(2^250-1)) * t^11 */
Fp64Mul(out, t0, t1);
}
void Fp64ScalarMultiPoint(uint8_t out[32], const uint8_t scalar[32], const uint8_t point[32])
{
uint8_t e[32];
uint32_t swap = 0;
int32_t t;
Fp64 x1, x2, x3;
Fp64 z2, z3;
Fp64 t1, t2;
CURVE25519_DECODE_LITTLE_ENDIAN(e, scalar);
Fp64DataToPoly(x1, point);
CURVE25519_FP64_SET(x2, 1);
CURVE25519_FP64_SET(z2, 0);
CURVE25519_FP64_COPY(x3, x1);
CURVE25519_FP64_SET(z3, 1);
for (t = 254; t >= 0; --t) { /* For t = bits-1(254) down to 0: */
/* t >> 3: calculation the index of bit; t & 7: Obtains the corresponding bit in the byte */
uint32_t kTemp = (e[(uint32_t)t >> 3] >> ((uint32_t)t & 7)) & 1;
swap ^= kTemp;
CURVE25519_FP64_CSWAP(swap, x2, x3);
CURVE25519_FP64_CSWAP(swap, z2, z3);
swap = kTemp;
Fp64Sub(t1, x3, z3);
Fp64Sub(t2, x2, z2);
Fp64Add(x2, x2, z2);
Fp64Add(z2, x3, z3);
Fp64Mul(z3, x2, t1);
Fp64Mul(z2, z2, t2);
Fp64Sqr(t1, t2);
Fp64Sqr(t2, x2);
Fp64Add(x3, z3, z2);
Fp64Sub(z2, z3, z2);
Fp64Mul(x2, t2, t1);
Fp64Sub(t2, t2, t1);
Fp64Sqr(z2, z2);
Fp64MulScalar(z3, t2);
Fp64Sqr(x3, x3);
Fp64Add(t1, t1, z3);
Fp64Mul(z3, x1, z2);
Fp64Mul(z2, t2, t1);
}
Fe64Invert(z2, z2);
Fp64Mul(x2, x2, z2);
Fp64PolyToData(out, x2);
(void)memset_s(e, sizeof(e), 0, sizeof(e));
}
#endif
void ScalarMultiPoint(uint8_t out[32], const uint8_t scalar[32], const uint8_t point[32])
{
#if defined (__x86_64__) && defined (HITLS_CRYPTO_X25519_X8664)
if (IsSupportBMI2() && IsSupportADX()) {
Fp64ScalarMultiPoint(out, scalar, point);
return;
}
#endif
Fp51ScalarMultiPoint(out, scalar, point);
return;
}
#endif /* HITLS_CRYPTO_X25519 */
|
2301_79861745/bench_create
|
crypto/curve25519/src/asm_curve25519_ops.c
|
C
|
unknown
| 17,901
|
/*
* 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_CURVE25519
#include "securec.h"
#include "bsl_sal.h"
#include "bsl_err_internal.h"
#include "crypt_errno.h"
#include "crypt_utils.h"
#include "curve25519_local.h"
#include "crypt_util_rand.h"
#include "crypt_types.h"
#include "eal_md_local.h"
#ifdef HITLS_BSL_PARAMS
#include "bsl_params.h"
#include "crypt_params_key.h"
#endif
#ifdef HITLS_CRYPTO_X25519
CRYPT_CURVE25519_Ctx *CRYPT_X25519_NewCtx(void)
{
CRYPT_CURVE25519_Ctx *ctx = NULL;
ctx = (CRYPT_CURVE25519_Ctx *)BSL_SAL_Malloc(sizeof(CRYPT_CURVE25519_Ctx));
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
(void)memset_s(ctx, sizeof(CRYPT_CURVE25519_Ctx), 0, sizeof(CRYPT_CURVE25519_Ctx));
ctx->keyType = CURVE25519_NOKEY;
ctx->hashMethod = NULL;
BSL_SAL_ReferencesInit(&(ctx->references));
return ctx;
}
CRYPT_CURVE25519_Ctx *CRYPT_X25519_NewCtxEx(void *libCtx)
{
CRYPT_CURVE25519_Ctx *ctx = CRYPT_X25519_NewCtx();
if (ctx == NULL) {
return NULL;
}
ctx->libCtx = libCtx;
return ctx;
}
#endif
#ifdef HITLS_CRYPTO_ED25519
CRYPT_CURVE25519_Ctx *CRYPT_ED25519_NewCtx(void)
{
CRYPT_CURVE25519_Ctx *ctx = NULL;
ctx = (CRYPT_CURVE25519_Ctx *)BSL_SAL_Malloc(sizeof(CRYPT_CURVE25519_Ctx));
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
(void)memset_s(ctx, sizeof(CRYPT_CURVE25519_Ctx), 0, sizeof(CRYPT_CURVE25519_Ctx));
ctx->hashMethod = EAL_MdFindDefaultMethod(CRYPT_MD_SHA512);
if (ctx->hashMethod == NULL) {
BSL_SAL_Free(ctx);
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_ALGID);
return NULL;
}
ctx->keyType = CURVE25519_NOKEY;
BSL_SAL_ReferencesInit(&(ctx->references));
return ctx;
}
CRYPT_CURVE25519_Ctx *CRYPT_ED25519_NewCtxEx(void *libCtx)
{
CRYPT_CURVE25519_Ctx *ctx = CRYPT_ED25519_NewCtx();
if (ctx == NULL) {
return NULL;
}
ctx->libCtx = libCtx;
return ctx;
}
#endif
CRYPT_CURVE25519_Ctx *CRYPT_CURVE25519_DupCtx(CRYPT_CURVE25519_Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return NULL;
}
CRYPT_CURVE25519_Ctx *newCtx = (CRYPT_CURVE25519_Ctx *)BSL_SAL_Malloc(sizeof(CRYPT_CURVE25519_Ctx));
if (newCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
(void)memcpy_s(newCtx, sizeof(CRYPT_CURVE25519_Ctx), ctx, sizeof(CRYPT_CURVE25519_Ctx));
BSL_SAL_ReferencesInit(&(newCtx->references));
return newCtx;
}
static int32_t CRYPT_CURVE25519_GetLen(CRYPT_CURVE25519_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 CRYPT_CURVE25519_GetKeyLen(const CRYPT_CURVE25519_Ctx *pkey)
{
(void)pkey;
return CRYPT_CURVE25519_KEYLEN;
}
int32_t CRYPT_CURVE25519_Ctrl(CRYPT_CURVE25519_Ctx *pkey, int32_t opt, void *val, uint32_t len)
{
if (pkey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
switch (opt) {
case CRYPT_CTRL_GET_BITS:
return CRYPT_CURVE25519_GetLen(pkey, (GetLenFunc)CRYPT_CURVE25519_GetBits, val, len);
#ifdef HITLS_CRYPTO_ED25519
case CRYPT_CTRL_GET_SIGNLEN:
return CRYPT_CURVE25519_GetLen(pkey, (GetLenFunc)CRYPT_CURVE25519_GetSignLen, val, len);
#endif
case CRYPT_CTRL_GET_SECBITS:
return CRYPT_CURVE25519_GetLen(pkey, (GetLenFunc)CRYPT_CURVE25519_GetSecBits, val, len);
case CRYPT_CTRL_GET_PUBKEY_LEN:
case CRYPT_CTRL_GET_PRVKEY_LEN:
case CRYPT_CTRL_GET_SHARED_KEY_LEN:
return GetUintCtrl(pkey, val, len, (GetUintCallBack)CRYPT_CURVE25519_GetKeyLen);
case CRYPT_CTRL_UP_REFERENCES:
if (val == NULL || len != (uint32_t)sizeof(int)) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
return BSL_SAL_AtomicUpReferences(&(pkey->references), (int *)val);
#ifdef HITLS_CRYPTO_X25519
case CRYPT_CTRL_GEN_X25519_PUBLICKEY:
if ((pkey->keyType & CURVE25519_PUBKEY) != 0) {
return CRYPT_SUCCESS;
}
if ((pkey->keyType & CURVE25519_PRVKEY) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PRVKEY);
return CRYPT_CURVE25519_NO_PRVKEY;
}
CRYPT_X25519_PublicFromPrivate(pkey->prvKey, pkey->pubKey);
pkey->keyType |= CURVE25519_PUBKEY;
return CRYPT_SUCCESS;
#endif
default:
break;
}
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_UNSUPPORTED_CTRL_OPTION);
return CRYPT_CURVE25519_UNSUPPORTED_CTRL_OPTION;
}
void CRYPT_CURVE25519_FreeCtx(CRYPT_CURVE25519_Ctx *pkey)
{
if (pkey == NULL) {
return;
}
int ret = 0;
BSL_SAL_AtomicDownReferences(&(pkey->references), &ret);
if (ret > 0) {
return;
}
BSL_SAL_ReferencesFree(&(pkey->references));
BSL_SAL_CleanseData((void *)(pkey), sizeof(CRYPT_CURVE25519_Ctx));
BSL_SAL_FREE(pkey);
}
#ifdef HITLS_BSL_PARAMS
int32_t CRYPT_CURVE25519_SetPubKeyEx(CRYPT_CURVE25519_Ctx *pkey, const BSL_Param *para)
{
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_Curve25519Pub pub = {0};
if (GetConstParamValue(para, CRYPT_PARAM_CURVE25519_PUBKEY, &pub.data, &pub.len) == NULL) {
(void)GetConstParamValue(para, CRYPT_PARAM_PKEY_ENCODE_PUBKEY, (uint8_t **)&pub.data, &pub.len);
}
return CRYPT_CURVE25519_SetPubKey(pkey, &pub);
}
int32_t CRYPT_CURVE25519_SetPrvKeyEx(CRYPT_CURVE25519_Ctx *pkey, const BSL_Param *para)
{
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_Curve25519Prv prv = {0};
(void)GetConstParamValue(para, CRYPT_PARAM_CURVE25519_PRVKEY, &prv.data, &prv.len);
return CRYPT_CURVE25519_SetPrvKey(pkey, &prv);
}
int32_t CRYPT_CURVE25519_GetPubKeyEx(const CRYPT_CURVE25519_Ctx *pkey, BSL_Param *para)
{
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_Curve25519Pub pub = {0};
BSL_Param *paramPub = GetParamValue(para, CRYPT_PARAM_CURVE25519_PUBKEY, &pub.data, &(pub.len));
if (paramPub == NULL) {
paramPub = GetParamValue(para, CRYPT_PARAM_PKEY_ENCODE_PUBKEY, &pub.data, &(pub.len));
}
int32_t ret = CRYPT_CURVE25519_GetPubKey(pkey, &pub);
if (ret != CRYPT_SUCCESS) {
return ret;
}
paramPub->useLen = pub.len;
return CRYPT_SUCCESS;
}
int32_t CRYPT_CURVE25519_GetPrvKeyEx(const CRYPT_CURVE25519_Ctx *pkey, BSL_Param *para)
{
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_Curve25519Prv prv = {0};
BSL_Param *paramPrv = GetParamValue(para, CRYPT_PARAM_CURVE25519_PRVKEY, &prv.data, &(prv.len));
int32_t ret = CRYPT_CURVE25519_GetPrvKey(pkey, &prv);
if (ret != CRYPT_SUCCESS) {
return ret;
}
paramPrv->useLen = prv.len;
return CRYPT_SUCCESS;
}
#endif
int32_t CRYPT_CURVE25519_SetPubKey(CRYPT_CURVE25519_Ctx *pkey, const CRYPT_Curve25519Pub *pub)
{
if (pkey == NULL || pub == NULL || pub->data == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (pub->len != CRYPT_CURVE25519_KEYLEN) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_KEYLEN_ERROR);
return CRYPT_CURVE25519_KEYLEN_ERROR;
}
/* The keyLen has been checked and does not have the overlong problem.
The pkey memory is dynamically allocated and does not overlap with the pubkey memory. */
/* There is no failure case for memcpy_s. */
(void)memcpy_s(pkey->pubKey, CRYPT_CURVE25519_KEYLEN, pub->data, pub->len);
pkey->keyType |= CURVE25519_PUBKEY;
return CRYPT_SUCCESS;
}
int32_t CRYPT_CURVE25519_SetPrvKey(CRYPT_CURVE25519_Ctx *pkey, const CRYPT_Curve25519Prv *prv)
{
if (pkey == NULL || prv == NULL || prv->data == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (prv->len != CRYPT_CURVE25519_KEYLEN) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_KEYLEN_ERROR);
return CRYPT_CURVE25519_KEYLEN_ERROR;
}
/* The keyLen has been checked and does not have the overlong problem.
The pkey memory is dynamically allocated and does not overlap with the pubkey memory. */
/* There is no failure case for memcpy_s. */
(void)memcpy_s(pkey->prvKey, CRYPT_CURVE25519_KEYLEN, prv->data, prv->len);
pkey->keyType |= CURVE25519_PRVKEY;
return CRYPT_SUCCESS;
}
int32_t CRYPT_CURVE25519_GetPubKey(const CRYPT_CURVE25519_Ctx *pkey, CRYPT_Curve25519Pub *pub)
{
if (pkey == NULL || pub == NULL || pub->data == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (pub->len < CRYPT_CURVE25519_KEYLEN) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_KEYLEN_ERROR);
return CRYPT_CURVE25519_KEYLEN_ERROR;
}
if ((pkey->keyType & CURVE25519_PUBKEY) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PUBKEY);
return CRYPT_CURVE25519_NO_PUBKEY;
}
/* The keyLen has been checked and does not have the overlong problem.
The pkey memory is dynamically allocated and does not overlap with the pubkey memory. */
/* There is no failure case for memcpy_s. */
(void)memcpy_s(pub->data, pub->len, pkey->pubKey, CRYPT_CURVE25519_KEYLEN);
pub->len = CRYPT_CURVE25519_KEYLEN;
return CRYPT_SUCCESS;
}
int32_t CRYPT_CURVE25519_GetPrvKey(const CRYPT_CURVE25519_Ctx *pkey, CRYPT_Curve25519Prv *prv)
{
if (pkey == NULL || prv == NULL || prv->data == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (prv->len < CRYPT_CURVE25519_KEYLEN) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_KEYLEN_ERROR);
return CRYPT_CURVE25519_KEYLEN_ERROR;
}
if ((pkey->keyType & CURVE25519_PRVKEY) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PRVKEY);
return CRYPT_CURVE25519_NO_PRVKEY;
}
/* The keyLen has been checked and does not have the overlong problem.
The pkey memory is dynamically allocated and does not overlap with the pubkey memory. */
/* There is no failure case for memcpy_s. */
(void)memcpy_s(prv->data, prv->len, pkey->prvKey, CRYPT_CURVE25519_KEYLEN);
prv->len = CRYPT_CURVE25519_KEYLEN;
return CRYPT_SUCCESS;
}
int32_t CRYPT_CURVE25519_GetBits(const CRYPT_CURVE25519_Ctx *pkey)
{
(void)pkey;
return CRYPT_CURVE25519_KEYLEN * 8; // bits = 8 * bytes
}
#ifdef HITLS_CRYPTO_ED25519
static int32_t PrvKeyHash(const uint8_t *prvKey, uint32_t prvKeyLen, uint8_t *prvKeyHash, uint32_t prvHashLen,
const EAL_MdMethod *hashMethod)
{
void *mdCtx = NULL;
int32_t ret;
uint32_t hashLen = prvHashLen;
mdCtx = hashMethod->newCtx(NULL, hashMethod->id);
if (mdCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
ret = hashMethod->init(mdCtx, NULL);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = hashMethod->update(mdCtx, prvKey, prvKeyLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = hashMethod->final(mdCtx, prvKeyHash, &hashLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
EXIT:
hashMethod->freeCtx(mdCtx);
return ret;
}
static int32_t GetRHash(uint8_t r[CRYPT_CURVE25519_SIGNLEN], const uint8_t prefix[CRYPT_CURVE25519_KEYLEN],
const uint8_t *msg, uint32_t msgLen, const EAL_MdMethod *hashMethod)
{
void *mdCtx = NULL;
int32_t ret;
uint32_t hashLen = CRYPT_CURVE25519_SIGNLEN;
mdCtx = hashMethod->newCtx(NULL, hashMethod->id);
if (mdCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
ret = hashMethod->init(mdCtx, NULL);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = hashMethod->update(mdCtx, prefix, CRYPT_CURVE25519_KEYLEN);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = hashMethod->update(mdCtx, msg, msgLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = hashMethod->final(mdCtx, r, &hashLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
EXIT:
hashMethod->freeCtx(mdCtx);
return ret;
}
static int32_t GetKHash(uint8_t k[CRYPT_CURVE25519_SIGNLEN], const uint8_t r[CRYPT_CURVE25519_KEYLEN],
const uint8_t pubKey[CRYPT_CURVE25519_KEYLEN], const uint8_t *msg, uint32_t msgLen,
const EAL_MdMethod *hashMethod)
{
void *mdCtx = NULL;
uint32_t hashLen = CRYPT_CURVE25519_SIGNLEN;
mdCtx = hashMethod->newCtx(NULL, hashMethod->id);
if (mdCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
int32_t ret = hashMethod->init(mdCtx, NULL);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = hashMethod->update(mdCtx, r, CRYPT_CURVE25519_KEYLEN);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = hashMethod->update(mdCtx, pubKey, CRYPT_CURVE25519_KEYLEN);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = hashMethod->update(mdCtx, msg, msgLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = hashMethod->final(mdCtx, k, &hashLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
EXIT:
hashMethod->freeCtx(mdCtx);
return ret;
}
static int32_t SignInputCheck(const CRYPT_CURVE25519_Ctx *pkey, const uint8_t *msg,
uint32_t msgLen, const uint8_t *sign, const uint32_t *signLen)
{
if (pkey == NULL || (msg == NULL && msgLen != 0) || sign == NULL || signLen == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if ((pkey->keyType & CURVE25519_PRVKEY) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PRVKEY);
return CRYPT_CURVE25519_NO_PRVKEY;
}
if (*signLen < CRYPT_CURVE25519_SIGNLEN) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_SIGNLEN_ERROR);
return CRYPT_CURVE25519_SIGNLEN_ERROR;
}
if (pkey->hashMethod == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_HASH_METHOD);
return CRYPT_CURVE25519_NO_HASH_METHOD;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_CURVE25519_Sign(CRYPT_CURVE25519_Ctx *pkey, int32_t algId, const uint8_t *msg,
uint32_t msgLen, uint8_t *sign, uint32_t *signLen)
{
(void)algId;
uint8_t prvKeyHash[CRYPT_CURVE25519_SIGNLEN];
uint8_t r[CRYPT_CURVE25519_SIGNLEN];
uint8_t k[CRYPT_CURVE25519_SIGNLEN];
uint8_t outSign[CRYPT_CURVE25519_SIGNLEN];
GeE geTmp;
int32_t ret = SignInputCheck(pkey, msg, msgLen, sign, signLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = PrvKeyHash(pkey->prvKey, CRYPT_CURVE25519_KEYLEN, prvKeyHash, CRYPT_CURVE25519_SIGNLEN, pkey->hashMethod);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
prvKeyHash[0] &= 0xf8;
// on block 31, clear the highest bit
prvKeyHash[31] &= 0x7f;
// on block 31, set second highest bit to 1
prvKeyHash[31] |= 0x40;
// if ctx has no public key, generate public key and store it in ctx
if ((pkey->keyType & CURVE25519_PUBKEY) == 0) {
ScalarMultiBase(&geTmp, prvKeyHash);
PointEncoding(&geTmp, pkey->pubKey, CRYPT_CURVE25519_KEYLEN);
pkey->keyType |= CURVE25519_PUBKEY;
}
ret = GetRHash(r, prvKeyHash + CRYPT_CURVE25519_KEYLEN, msg, msgLen, pkey->hashMethod);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ModuloL(r);
ScalarMultiBase(&geTmp, r);
PointEncoding(&geTmp, outSign, CRYPT_CURVE25519_SIGNLEN);
ret = GetKHash(k, outSign, pkey->pubKey, msg, msgLen, pkey->hashMethod);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ModuloL(k);
ScalarMulAdd(outSign + CRYPT_CURVE25519_KEYLEN, k, prvKeyHash, r);
// The value of *signLen has been checked in SignInputCheck to ensure that
// the value is greater than or equal to CRYPT_CURVE25519_SIGNLEN.
// The sign memory is input from outside the function. The outSign memory is allocated within the function.
// Memory overlap does not exist. There is no failure case for memcpy_s.
(void)memcpy_s(sign, *signLen, outSign, CRYPT_CURVE25519_SIGNLEN);
*signLen = CRYPT_CURVE25519_SIGNLEN;
EXIT:
BSL_SAL_CleanseData(prvKeyHash, sizeof(prvKeyHash));
BSL_SAL_CleanseData(r, sizeof(r));
BSL_SAL_CleanseData(k, sizeof(k));
return ret;
}
int32_t CRYPT_CURVE25519_GetSignLen(const CRYPT_CURVE25519_Ctx *pkey)
{
(void)pkey;
return CRYPT_CURVE25519_SIGNLEN;
}
static int32_t VerifyInputCheck(const CRYPT_CURVE25519_Ctx *pkey, const uint8_t *msg,
uint32_t msgLen, const uint8_t *sign, uint32_t signLen)
{
if (pkey == NULL || (msg == NULL && msgLen != 0) || sign == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if ((pkey->keyType & CURVE25519_PUBKEY) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PUBKEY);
return CRYPT_CURVE25519_NO_PUBKEY;
}
if (signLen != CRYPT_CURVE25519_SIGNLEN) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_SIGNLEN_ERROR);
return CRYPT_CURVE25519_SIGNLEN_ERROR;
}
if (pkey->hashMethod == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_HASH_METHOD);
return CRYPT_CURVE25519_NO_HASH_METHOD;
}
return CRYPT_SUCCESS;
}
/* check 0 <= s < l, l = 2^252 + 27742317777372353535851937790883648493 */
static bool VerifyCheckSValid(const uint8_t s[CRYPT_CURVE25519_KEYLEN])
{
const uint8_t l[CRYPT_CURVE25519_KEYLEN] = {
0xED, 0xD3, 0xF5, 0x5C, 0x1A, 0x63, 0x12, 0x58, 0xD6, 0x9C, 0xF7, 0xA2, 0xDE, 0xF9, 0xDE, 0x14,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10
};
int32_t i;
// start from highest block 31
for (i = 31; i >= 0; i--) {
if (s[i] > l[i]) {
return false;
} else if (s[i] < l[i]) {
return true;
}
}
// s = l is invalid
return false;
}
int32_t CRYPT_CURVE25519_Verify(const CRYPT_CURVE25519_Ctx *pkey, int32_t algId, const uint8_t *msg,
uint32_t msgLen, const uint8_t *sign, uint32_t signLen)
{
if (algId != CRYPT_MD_SHA512) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_ALGID);
return CRYPT_EAL_ERR_ALGID;
}
GeE geA, sG;
uint8_t kHash[CRYPT_CURVE25519_SIGNLEN];
uint8_t localR[CRYPT_CURVE25519_KEYLEN];
const uint8_t *r = NULL;
const uint8_t *s = NULL;
int32_t ret = VerifyInputCheck(pkey, msg, msgLen, sign, signLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// r is first half of sign, length 32
r = sign;
// s is second half of the sign, length 32
s = sign + 32;
if (!VerifyCheckSValid(s)) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_VERIFY_FAIL);
ret = CRYPT_CURVE25519_VERIFY_FAIL;
return ret;
}
if (PointDecoding(&geA, pkey->pubKey) != 0) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_VERIFY_FAIL);
ret = CRYPT_CURVE25519_INVALID_PUBKEY;
return ret;
}
ret = GetKHash(kHash, r, pkey->pubKey, msg, msgLen, pkey->hashMethod);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
CURVE25519_FP_NEGATE(geA.x, geA.x);
CURVE25519_FP_NEGATE(geA.t, geA.t);
ModuloL(kHash);
KAMulPlusMulBase(&sG, kHash, &geA, s);
PointEncoding(&sG, localR, CRYPT_CURVE25519_KEYLEN);
if (memcmp(localR, r, CRYPT_CURVE25519_KEYLEN) != 0) {
ret = CRYPT_CURVE25519_VERIFY_FAIL;
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
static int32_t CRYPT_ED25519_PublicFromPrivate(const uint8_t prvKey[CRYPT_CURVE25519_KEYLEN],
uint8_t pubKey[CRYPT_CURVE25519_KEYLEN], const EAL_MdMethod *hashMethod)
{
GeE tmp;
uint8_t prvKeyHash[CRYPT_CURVE25519_SIGNLEN];
int32_t ret = PrvKeyHash(prvKey, CRYPT_CURVE25519_KEYLEN, prvKeyHash, CRYPT_CURVE25519_SIGNLEN, hashMethod);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
prvKeyHash[0] &= 0xf8;
// on block 31, clear the highest bit
prvKeyHash[31] &= 0x7f;
// on block 31, set second highest bit to 1
prvKeyHash[31] |= 0x40;
ScalarMultiBase(&tmp, prvKeyHash);
PointEncoding(&tmp, pubKey, CRYPT_CURVE25519_KEYLEN);
BSL_SAL_CleanseData(prvKeyHash, sizeof(prvKeyHash));
return CRYPT_SUCCESS;
}
int32_t CRYPT_ED25519_GenKey(CRYPT_CURVE25519_Ctx *pkey)
{
if (pkey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
// SHA512 digest size is 64, no other hash has 64 md size
if (pkey->hashMethod == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_HASH_METHOD);
return CRYPT_CURVE25519_NO_HASH_METHOD;
}
int32_t ret;
uint8_t prvKey[CRYPT_CURVE25519_KEYLEN];
ret = CRYPT_RandEx(pkey->libCtx, prvKey, sizeof(prvKey));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = CRYPT_ED25519_PublicFromPrivate(prvKey, pkey->pubKey, pkey->hashMethod);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
// The pkey is not empty. The length of the prvKey is CRYPT_CURVE25519_KEYLEN,
// which is the same as the length of local prvKey.
// The pkey->prvKey memory is input outside the function. The local prvKey memory is allocated within the function.
// Memory overlap does not exist. No failure case exists for memcpy_s.
(void)memcpy_s(pkey->prvKey, CRYPT_CURVE25519_KEYLEN, prvKey, CRYPT_CURVE25519_KEYLEN);
pkey->keyType = CURVE25519_PRVKEY | CURVE25519_PUBKEY;
EXIT:
BSL_SAL_CleanseData(prvKey, sizeof(prvKey));
return ret;
}
#endif /* HITLS_CRYPTO_ED25519 */
#ifdef HITLS_CRYPTO_X25519
/* Calculate the shared key based on the local private key and peer public key
* Shared12 = prv1 * Pub2 = prv1 * (prv2 * G) = prv1 * prv2 * G
*/
int32_t CRYPT_CURVE25519_ComputeSharedKey(CRYPT_CURVE25519_Ctx *prvKey, CRYPT_CURVE25519_Ctx *pubKey,
uint8_t *sharedKey, uint32_t *shareKeyLen)
{
if (prvKey == NULL || pubKey == NULL || sharedKey == NULL || shareKeyLen == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (*shareKeyLen < CRYPT_CURVE25519_KEYLEN) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_KEYLEN_ERROR);
return CRYPT_CURVE25519_KEYLEN_ERROR;
}
if ((prvKey->keyType & CURVE25519_PRVKEY) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PRVKEY);
return CRYPT_CURVE25519_NO_PRVKEY;
}
if ((pubKey->keyType & CURVE25519_PUBKEY) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PUBKEY);
return CRYPT_CURVE25519_NO_PUBKEY;
}
uint32_t tmpLen = *shareKeyLen;
ScalarMultiPoint(sharedKey, prvKey->prvKey, pubKey->pubKey);
int32_t i;
uint8_t checkValid = 0;
for (i = 0; i < CRYPT_CURVE25519_KEYLEN; i++) {
checkValid |= sharedKey[i];
}
if (checkValid == 0) {
*shareKeyLen = tmpLen;
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_KEY_COMPUTE_FAILED);
return CRYPT_CURVE25519_KEY_COMPUTE_FAILED;
} else {
*shareKeyLen = CRYPT_CURVE25519_KEYLEN;
return CRYPT_SUCCESS;
}
}
/**
* @brief x25519 Calculate the public key based on the private key.
*
* @param privateKey [IN] Private key
* @param publicKey [OUT] Public key
*
*/
void CRYPT_X25519_PublicFromPrivate(const uint8_t privateKey[CRYPT_CURVE25519_KEYLEN],
uint8_t publicKey[CRYPT_CURVE25519_KEYLEN])
{
uint8_t privateCopy[CRYPT_CURVE25519_KEYLEN];
GeE out;
Fp25 zPlusY, zMinusY, zMinusYInvert;
(void)memcpy_s(privateCopy, sizeof(privateCopy), privateKey, sizeof(privateCopy));
privateCopy[0] &= 0xf8; /* decodeScalar25519(k): k_list[0] &= 0xf8 */
privateCopy[31] &= 0x7f; /* decodeScalar25519(k): k_list[31] &= 0x7f */
privateCopy[31] |= 0x40; /* decodeScalar25519(k): k_list[31] |= 0x40 */
ScalarMultiBase(&out, privateCopy);
CURVE25519_FP_ADD(zPlusY, out.z, out.y);
CURVE25519_FP_SUB(zMinusY, out.z, out.y);
FpInvert(zMinusYInvert, zMinusY);
FpMul(zPlusY, zPlusY, zMinusYInvert);
PolynomialToData(publicKey, zPlusY);
/* cleanup tmp private key */
BSL_SAL_CleanseData(privateCopy, sizeof(privateCopy));
}
int32_t CRYPT_X25519_GenKey(CRYPT_CURVE25519_Ctx *pkey)
{
if (pkey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret = CRYPT_RandEx(pkey->libCtx, pkey->prvKey, sizeof(pkey->prvKey));
if (ret != CRYPT_SUCCESS) {
pkey->keyType = 0;
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
CRYPT_X25519_PublicFromPrivate(pkey->prvKey, pkey->pubKey);
pkey->keyType = CURVE25519_PRVKEY | CURVE25519_PUBKEY;
return CRYPT_SUCCESS;
}
#endif /* HITLS_CRYPTO_X25519 */
int32_t CRYPT_CURVE25519_Cmp(const CRYPT_CURVE25519_Ctx *a, const CRYPT_CURVE25519_Ctx *b)
{
RETURN_RET_IF(a == NULL || b == NULL, CRYPT_NULL_INPUT);
RETURN_RET_IF((a->keyType & CURVE25519_PUBKEY) == 0 || (b->keyType & CURVE25519_PUBKEY) == 0,
CRYPT_CURVE25519_NO_PUBKEY);
RETURN_RET_IF(memcmp(a->pubKey, b->pubKey, CRYPT_CURVE25519_KEYLEN) != 0, CRYPT_CURVE25519_PUBKEY_NOT_EQUAL);
return CRYPT_SUCCESS;
}
int32_t CRYPT_CURVE25519_GetSecBits(const CRYPT_CURVE25519_Ctx *ctx)
{
(void) ctx;
return 128;
}
#ifdef HITLS_CRYPTO_PROVIDER
int32_t CRYPT_CURVE25519_Import(CRYPT_CURVE25519_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_CURVE25519_PRVKEY);
const BSL_Param *pub = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_CURVE25519_PUBKEY);
if (prv != NULL) {
ret = CRYPT_CURVE25519_SetPrvKeyEx(ctx, params);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
if (pub != NULL) {
ret = CRYPT_CURVE25519_SetPubKeyEx(ctx, params);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
return ret;
}
int32_t CRYPT_CURVE25519_Export(const CRYPT_CURVE25519_Ctx *ctx, BSL_Param *params)
{
if (ctx == NULL || params == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
uint32_t index = 0;
uint32_t keyBytes = CRYPT_CURVE25519_KEYLEN;
CRYPT_EAL_ProcessFuncCb processCb = NULL;
void *args = NULL;
BSL_Param ed25519Params[3] = {0}; // 3: pub key + priv key + end marker
int32_t ret = CRYPT_GetPkeyProcessParams(params, &processCb, &args);
if (ret != CRYPT_SUCCESS) {
return ret;
}
uint8_t *buffer = BSL_SAL_Calloc(1, keyBytes * 2); // For public + private key
if (buffer == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
if ((ctx->keyType & CURVE25519_PUBKEY) != 0) {
(void)BSL_PARAM_InitValue(&ed25519Params[index], CRYPT_PARAM_CURVE25519_PUBKEY, BSL_PARAM_TYPE_OCTETS,
buffer, keyBytes);
ret = CRYPT_CURVE25519_GetPubKeyEx(ctx, ed25519Params);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_Free(buffer);
return ret;
}
ed25519Params[index].valueLen = ed25519Params[index].useLen;
index++;
}
if ((ctx->keyType & CURVE25519_PRVKEY) != 0) {
(void)BSL_PARAM_InitValue(&ed25519Params[index], CRYPT_PARAM_CURVE25519_PRVKEY, BSL_PARAM_TYPE_OCTETS,
buffer + keyBytes, keyBytes);
ret = CRYPT_CURVE25519_GetPrvKeyEx(ctx, ed25519Params);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_Free(buffer);
return ret;
}
ed25519Params[index].valueLen = ed25519Params[index].useLen;
index++;
}
ret = processCb(ed25519Params, args);
BSL_SAL_Free(buffer);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
#endif // HITLS_CRYPTO_PROVIDER
#if defined(HITLS_CRYPTO_X25519_CHECK) || defined(HITLS_CRYPTO_ED25519_CHECK)
static int32_t Curve25519PrvKeyCheck(const CRYPT_CURVE25519_Ctx *prvKey)
{
if (prvKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if ((prvKey->keyType & CURVE25519_PRVKEY) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PRVKEY);
return CRYPT_CURVE25519_NO_PRVKEY;
}
uint8_t tmp[CRYPT_CURVE25519_KEYLEN] = {0};
// prv key is not all 0.
if (memcmp(tmp, prvKey->prvKey, CRYPT_CURVE25519_KEYLEN) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_INVALID_PRVKEY);
return CRYPT_CURVE25519_INVALID_PRVKEY;
}
return CRYPT_SUCCESS;
}
#endif // HITLS_CRYPTO_X25519_CHECK || HITLS_CRYPTO_ED25519_CHECK
#ifdef HITLS_CRYPTO_ED25519_CHECK
static int32_t ED25519KeyPairCheck(const CRYPT_CURVE25519_Ctx *pubKey, const CRYPT_CURVE25519_Ctx *prvKey)
{
if (pubKey == NULL || prvKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if ((prvKey->keyType & CURVE25519_PRVKEY) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PRVKEY);
return CRYPT_CURVE25519_NO_PRVKEY;
}
if ((pubKey->keyType & CURVE25519_PUBKEY) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PUBKEY);
return CRYPT_CURVE25519_NO_PUBKEY;
}
uint8_t res[CRYPT_CURVE25519_KEYLEN];
int32_t ret = CRYPT_ED25519_PublicFromPrivate(prvKey->prvKey, res, prvKey->hashMethod);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if (memcmp(res, pubKey->pubKey, CRYPT_CURVE25519_KEYLEN) != 0) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_PAIRWISE_CHECK_FAIL);
return CRYPT_CURVE25519_PAIRWISE_CHECK_FAIL;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_ED25519_Check(uint32_t checkType, const CRYPT_CURVE25519_Ctx *pkey1, const CRYPT_CURVE25519_Ctx *pkey2)
{
switch (checkType) {
case CRYPT_PKEY_CHECK_KEYPAIR:
return ED25519KeyPairCheck(pkey1, pkey2);
case CRYPT_PKEY_CHECK_PRVKEY:
return Curve25519PrvKeyCheck(pkey1);
default:
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
}
#endif // HITLS_CRYPTO_ED25519_CHECK
#ifdef HITLS_CRYPTO_X25519_CHECK
static int32_t X25519KeyPairCheck(const CRYPT_CURVE25519_Ctx *pubKey, const CRYPT_CURVE25519_Ctx *prvKey)
{
if (pubKey == NULL || prvKey == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if ((prvKey->keyType & CURVE25519_PRVKEY) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PRVKEY);
return CRYPT_CURVE25519_NO_PRVKEY;
}
if ((pubKey->keyType & CURVE25519_PUBKEY) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PUBKEY);
return CRYPT_CURVE25519_NO_PUBKEY;
}
uint8_t res[CRYPT_CURVE25519_KEYLEN];
CRYPT_X25519_PublicFromPrivate(prvKey->prvKey, res);
if (memcmp(res, pubKey->pubKey, CRYPT_CURVE25519_KEYLEN) != 0) {
BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_PAIRWISE_CHECK_FAIL);
return CRYPT_CURVE25519_PAIRWISE_CHECK_FAIL;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_X25519_Check(uint32_t checkType, const CRYPT_CURVE25519_Ctx *pkey1, const CRYPT_CURVE25519_Ctx *pkey2)
{
switch (checkType) {
case CRYPT_PKEY_CHECK_KEYPAIR:
return X25519KeyPairCheck(pkey1, pkey2);
case CRYPT_PKEY_CHECK_PRVKEY:
return Curve25519PrvKeyCheck(pkey1);
default:
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
}
#endif // HITLS_CRYPTO_X25519_CHECK
#endif /* HITLS_CRYPTO_CURVE25519 */
|
2301_79861745/bench_create
|
crypto/curve25519/src/curve25519.c
|
C
|
unknown
| 33,267
|
/*
* 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 CURVE25519_LOCAL_H
#define CURVE25519_LOCAL_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_CURVE25519
#include "crypt_curve25519.h"
#include "sal_atomic.h"
#ifdef __cplusplus
extern "C" {
#endif
#define CURVE25519_NOKEY 0
#define CURVE25519_PRVKEY 0x1
#define CURVE25519_PUBKEY 0x10
#define UINT8_32_21BITS_BLOCKNUM 12
#define UINT8_64_21BITS_BLOCKNUM 24
struct CryptCurve25519Ctx {
uint8_t keyType; /* specify the key type */
const EAL_MdMethod *hashMethod;
uint8_t pubKey[CRYPT_CURVE25519_KEYLEN];
uint8_t prvKey[CRYPT_CURVE25519_KEYLEN];
BSL_SAL_RefCount references;
void *libCtx;
};
typedef int32_t Fp25[10];
typedef struct Fp51 {
uint64_t data[5];
} Fp51;
typedef struct H19 {
int64_t data[19];
} H19;
// group element in Projective Coordinate, x = X / Z, y = Y / Z
typedef struct GeP {
Fp25 x;
Fp25 y;
Fp25 z;
} GeP;
// group element in Extended Coordinate, x = X / Z, y = Y / Z, T = XY / Z which leads to XY = ZT
typedef struct GeE {
Fp25 x;
Fp25 y;
Fp25 t;
Fp25 z;
} GeE;
// group element in Completed Coordinate, x = X / Z, y = Y / T
typedef struct GeC {
Fp25 x;
Fp25 y;
Fp25 t;
Fp25 z;
} GeC;
typedef struct GePre {
Fp25 yplusx;
Fp25 yminusx;
Fp25 xy2d;
} GePre;
typedef struct GeEPre {
Fp25 yplusx;
Fp25 yminusx;
Fp25 t2z;
Fp25 z;
} GeEPre;
/* Get High x bits for 64bits block */
#define MASK_HIGH64(x) (0xFFFFFFFFFFFFFFFFLL << (64 - (x)))
/* Get low x bits for 32bits block */
#define MASK_LOW32(x) (0xFFFFFFFF >> (32 - (x)))
/* Get high x bits for 32bits block */
#define MASK_HIGH32(x) (0xFFFFFFFF << (32 - (x)))
/* low 21 bits for 64bits block */
#define MASK_64_LOW21 0x1fffffLL
#define CURVE25519_MASK_HIGH_38 0xfffffffffc000000LL
#define CURVE25519_MASK_HIGH_39 0xfffffffffe000000LL
/* process carry from h0_ to h1_, h0_ boundary restrictions is bits */
#define PROCESS_CARRY(h0_, h1_, signMask_, over_, bits) \
do { \
(over_) = (h0_) + (1 << (bits)); \
(signMask_) = MASK_HIGH64((bits) + 1) & (-((over_) >> 63)); \
(h1_) += ((over_) >> ((bits) + 1)) | (signMask_); \
(h0_) -= MASK_HIGH64(64 - ((bits) + 1)) & (over_); \
} while (0)
/* process carry from h0_ to h1_ ignoring sign, h0_ boundary restrictions is bits */
#define PROCESS_CARRY_UNSIGN(h0_, h1_, signMask_, over_, bits) \
do { \
(signMask_) = MASK_HIGH64((bits)) & (-((h0_) >> 63)); \
(over_) = ((h0_) >> (bits)) | (signMask_); \
(h1_) += (over_); \
(h0_) -= (over_) * (1 << (bits)); \
} while (0)
/* l = 2^252 + 27742317777372353535851937790883648493, let l0 = 27742317777372353535851937790883648493 */
/* -l0 = 666643 * 2^0 + 470296 * 2^21 + 654183 * 2^(2*21) - 997805 * 2^(3*21) + 136657 * 2^(4*21) - 683901 * 2^(5*21) */
#define CURVE25519_MULTI_BY_L0(src, pos) \
do { \
(src)[0 + (pos)] += (src)[12 + (pos)] * 666643; \
(src)[1 + (pos)] += (src)[12 + (pos)] * 470296; \
(src)[2 + (pos)] += (src)[12 + (pos)] * 654183; \
(src)[3 + (pos)] -= (src)[12 + (pos)] * 997805; \
(src)[4 + (pos)] += (src)[12 + (pos)] * 136657; \
(src)[5 + (pos)] -= (src)[12 + (pos)] * 683901; \
(src)[12 + (pos)] = 0; \
} while (0)
/* Compute multiplications by 19 */
#define CURVE25519_MULTI_BY_19(dst, src, t1_, t2_, t16_) \
do { \
(t1_) = (uint64_t)(src); \
(t2_) = (t1_) << 1; \
(t16_) = (t1_) << 4; \
(dst) += (int64_t)((t1_) + (t2_) + (t16_)); \
} while (0)
/* Set this parameter to value, */
#define CURVE25519_FP_SET(dst, value) \
do { \
(dst)[0] = (value); \
(dst)[1] = 0; \
(dst)[2] = 0; \
(dst)[3] = 0; \
(dst)[4] = 0; \
(dst)[5] = 0; \
(dst)[6] = 0; \
(dst)[7] = 0; \
(dst)[8] = 0; \
(dst)[9] = 0; \
} while (0)
#define CURVE25519_FP51_SET(dst, value) \
do { \
(dst)[0] = (value); \
(dst)[1] = 0; \
(dst)[2] = 0; \
(dst)[3] = 0; \
(dst)[4] = 0; \
} while (0)
/* Copy */
#define CURVE25519_FP_COPY(dst, src) \
do { \
(dst)[0] = (src)[0]; \
(dst)[1] = (src)[1]; \
(dst)[2] = (src)[2]; \
(dst)[3] = (src)[3]; \
(dst)[4] = (src)[4]; \
(dst)[5] = (src)[5]; \
(dst)[6] = (src)[6]; \
(dst)[7] = (src)[7]; \
(dst)[8] = (src)[8]; \
(dst)[9] = (src)[9]; \
} while (0)
#define CURVE25519_FP51_COPY(dst, src) \
do { \
(dst)[0] = (src)[0]; \
(dst)[1] = (src)[1]; \
(dst)[2] = (src)[2]; \
(dst)[3] = (src)[3]; \
(dst)[4] = (src)[4]; \
} while (0)
/* Negate */
#define CURVE25519_FP_NEGATE(dst, src) \
do { \
(dst)[0] = -(src)[0]; \
(dst)[1] = -(src)[1]; \
(dst)[2] = -(src)[2]; \
(dst)[3] = -(src)[3]; \
(dst)[4] = -(src)[4]; \
(dst)[5] = -(src)[5]; \
(dst)[6] = -(src)[6]; \
(dst)[7] = -(src)[7]; \
(dst)[8] = -(src)[8]; \
(dst)[9] = -(src)[9]; \
} while (0)
/* Basic operation */
#define CURVE25519_FP_OP(dst, src1, src2, op) \
do { \
(dst)[0] = (src1)[0] op (src2)[0]; \
(dst)[1] = (src1)[1] op (src2)[1]; \
(dst)[2] = (src1)[2] op (src2)[2]; \
(dst)[3] = (src1)[3] op (src2)[3]; \
(dst)[4] = (src1)[4] op (src2)[4]; \
(dst)[5] = (src1)[5] op (src2)[5]; \
(dst)[6] = (src1)[6] op (src2)[6]; \
(dst)[7] = (src1)[7] op (src2)[7]; \
(dst)[8] = (src1)[8] op (src2)[8]; \
(dst)[9] = (src1)[9] op (src2)[9]; \
} while (0)
/* Basic operation */
#define CURVE25519_FP51_ADD(dst, src1, src2) \
do { \
(dst)[0] = (src1)[0] + (src2)[0]; \
(dst)[1] = (src1)[1] + (src2)[1]; \
(dst)[2] = (src1)[2] + (src2)[2]; \
(dst)[3] = (src1)[3] + (src2)[3]; \
(dst)[4] = (src1)[4] + (src2)[4]; \
} while (0)
#define CURVE25519_FP51_SUB(dst, src1, src2) \
do { \
(dst)[0] = ((src1)[0] + 0xfffffffffffda) - (src2)[0]; \
(dst)[1] = ((src1)[1] + 0xffffffffffffe) - (src2)[1]; \
(dst)[2] = ((src1)[2] + 0xffffffffffffe) - (src2)[2]; \
(dst)[3] = ((src1)[3] + 0xffffffffffffe) - (src2)[3]; \
(dst)[4] = ((src1)[4] + 0xffffffffffffe) - (src2)[4]; \
} while (0)
#define CURVE25519_GE_COPY(dst, src) \
do { \
CURVE25519_FP_COPY((dst).x, (src).x); \
CURVE25519_FP_COPY((dst).y, (src).y); \
CURVE25519_FP_COPY((dst).z, (src).z); \
CURVE25519_FP_COPY((dst).t, (src).t); \
} while (0)
/* Add */
#define CURVE25519_FP_ADD(dst, src1, src2) CURVE25519_FP_OP(dst, src1, src2, +)
/* Subtract */
#define CURVE25519_FP_SUB(dst, src1, src2) CURVE25519_FP_OP(dst, src1, src2, -)
/* dst = dst * bit, bit = 0 or 1 */
#define CURVE25519_FP_MUL_BIT(dst, bit) \
do { \
int ii; \
for (ii = 0; ii < 10; ii++) { \
(dst)[ii] = (dst)[ii] * (bit); \
} \
} while (0)
/* dst[i] = src[i] * scalar */
#define CURVE25519_FP_MUL_SCALAR(dst, src, scalar) \
do { \
uint32_t ii; \
for (ii = 0; ii < 10; ii++) { \
(dst)[ii] = (uint64_t)((src)[ii] * (scalar)); \
} \
} while (0)
#define CURVE25519_BYTES3_LOAD_PADDING(dst, bits, src) \
do { \
uint64_t valMacro = ((uint64_t)*((src) + 0)) << 0; \
valMacro |= ((uint64_t)*((src) + 1)) << 8; \
valMacro |= ((uint64_t)*((src) + 2)) << 16; \
*(dst) = (uint64_t)(valMacro<< (bits)); \
} while (0)
#define CURVE25519_BYTES3_LOAD(dst, src) \
do { \
*(dst) = ((uint64_t)*((src) + 0)) << 0; \
*(dst) |= ((uint64_t)*((src) + 1)) << 8; \
*(dst) |= ((uint64_t)*((src) + 2)) << 16; \
} while (0)
#define CURVE25519_BYTES4_LOAD(dst, src) \
do { \
*(dst) = ((uint64_t)*((src) + 0)) << 0; \
*(dst) |= ((uint64_t)*((src) + 1)) << 8; \
*(dst) |= ((uint64_t)*((src) + 2)) << 16; \
*(dst) |= ((uint64_t)*((src) + 3)) << 24; \
} while (0)
#define CURVE25519_BYTES6_LOAD(dst, src) \
do { \
*(dst) = (uint64_t)*(src); \
*(dst) |= ((uint64_t)*((src) + 1)) << 8; \
*(dst) |= ((uint64_t)*((src) + 2)) << 16; \
*(dst) |= ((uint64_t)*((src) + 3)) << 24; \
*(dst) |= ((uint64_t)*((src) + 4)) << 32; \
*(dst) |= ((uint64_t)*((src) + 5)) << 40; \
} while (0)
#define CURVE25519_BYTES7_LOAD(dst, src) \
do { \
*(dst) = (uint64_t)*(src); \
*(dst) |= ((uint64_t)*((src) + 1)) << 8; \
*(dst) |= ((uint64_t)*((src) + 2)) << 16; \
*(dst) |= ((uint64_t)*((src) + 3)) << 24; \
*(dst) |= ((uint64_t)*((src) + 4)) << 32; \
*(dst) |= ((uint64_t)*((src) + 5)) << 40; \
*(dst) |= ((uint64_t)*((src) + 6)) << 48; \
} while (0)
#define CURVE25519_BYTES3_PADDING_UNLOAD(dst, bits1, bits2, src) \
do { \
const uint32_t posMacro = 8 - (bits1); \
uint32_t valMacro = (uint32_t)(*(src)); \
uint32_t signMaskMacro= -(valMacro >> 31); \
uint32_t expand =( (uint32_t)(*((src) + 1))) << (bits2); \
*((dst) + 0) = (uint8_t)(valMacro >> (0 + posMacro) | (signMaskMacro>> (0 + posMacro))); \
*((dst) + 1) = (uint8_t)(valMacro >> (8 + posMacro) | (signMaskMacro>> (8 + posMacro))); \
*((dst) + 2) = (uint8_t)(expand | ((valMacro >> (16 + posMacro)) | (signMaskMacro>> (16 + posMacro)))); \
} while (0)
#define CURVE25519_BYTES3_UNLOAD(dst, bits, src) \
do { \
const uint32_t posMacro = 8 - (bits); \
uint32_t valMacro = (uint32_t)(*(src)); \
uint32_t signMaskMacro= -(valMacro >> 31); \
*((dst) + 0) = (uint8_t)((valMacro >> (0 + posMacro)) | (signMaskMacro>> (0 + posMacro))); \
*((dst) + 1) = (uint8_t)((valMacro >> (8 + posMacro)) | (signMaskMacro>> (8 + posMacro))); \
*((dst) + 2) = (uint8_t)((valMacro >> (16 + posMacro)) | (signMaskMacro>> (16 + posMacro))); \
} while (0)
#define CURVE25519_BYTES4_PADDING_UNLOAD(dst, bits, src) \
do { \
uint32_t valMacro = (uint32_t)(*(src)); \
uint32_t signMaskMacro= -(valMacro >> 31); \
uint32_t expand = ((uint32_t)(*((src) + 1))) << (bits); \
*((dst) + 0) = (uint8_t)((valMacro >> 0) | (signMaskMacro>> 0)); \
*((dst) + 1) = (uint8_t)((valMacro >> 8) | (signMaskMacro>> 8)); \
*((dst) + 2) = (uint8_t)((valMacro >> 16) | (signMaskMacro>> 16)); \
*((dst) + 3) = (uint8_t)(expand | ((valMacro >> 24) | (signMaskMacro>> 24))); \
} while (0)
/**
* Reference RFC 7748 section 5: For X25519, in order to decode 32 random bytes as an integer scalar,
* set the three least significant bits of the first byte and the most significant bit of the last to zero,
* set the second most significant bit of the last byte to 1 and, finally, decode as little-endian.
*/
#define CURVE25519_DECODE_LITTLE_ENDIAN(dst, src) \
do { \
uint32_t ii; \
for (ii = 0; ii < 32; ii++) { \
(dst)[ii] = (src)[ii]; \
} \
(dst)[0] &= 248; \
(dst)[31] &= 127; \
(dst)[31] |= 64; \
} while (0)
#define CURVE25519_FP_CSWAP(s, a, b) \
do { \
uint32_t tt; \
const uint32_t tsMacro = 0 - (s); \
for (uint32_t ii = 0; ii < 10; ii++) { \
tt = tsMacro & (((uint32_t)(a)[ii]) ^ ((uint32_t)(b)[ii])); \
(a)[ii] = (int32_t)((uint32_t)(a)[ii] ^ tt); \
(b)[ii] = (int32_t)((uint32_t)(b)[ii] ^ tt); \
} \
} while (0)
#define CURVE25519_FP51_CSWAP(s, a, b) \
do { \
uint64_t tt; \
const uint64_t tsMacro = 0 - (uint64_t)(s); \
for (uint32_t ii = 0; ii < 5; ii++) { \
tt = tsMacro & ((a)[ii] ^ (b)[ii]); \
(a)[ii] = (a)[ii] ^ tt; \
(b)[ii] = (b)[ii] ^ tt; \
} \
} while (0)
void TableLookup(GePre *preCompute, int32_t pos, int8_t e);
void ConditionalMove(GePre *preCompute, const GePre *tableElement, uint32_t indicator);
void ScalarMultiBase(GeE *out, const uint8_t in[CRYPT_CURVE25519_KEYLEN]);
#ifdef HITLS_CRYPTO_ED25519
void PointEncoding(const GeE *point, uint8_t *output, uint32_t outputLen);
int32_t PointDecoding(GeE *point, const uint8_t in[CRYPT_CURVE25519_KEYLEN]);
void ScalarMulAdd(uint8_t s[CRYPT_CURVE25519_KEYLEN], const uint8_t a[CRYPT_CURVE25519_KEYLEN],
const uint8_t b[CRYPT_CURVE25519_KEYLEN], const uint8_t c[CRYPT_CURVE25519_KEYLEN]);
void ModuloL(uint8_t s[CRYPT_CURVE25519_SIGNLEN]);
void KAMulPlusMulBase(GeE *out, const uint8_t hash[CRYPT_CURVE25519_KEYLEN],
const GeE *p, const uint8_t s[CRYPT_CURVE25519_KEYLEN]);
#endif
#ifdef HITLS_CRYPTO_X25519
void ScalarMultiPoint(uint8_t out[32], const uint8_t scalar[32], const uint8_t point[32]);
#endif
void FpInvert(Fp25 out, const Fp25 a);
void FpMul(Fp25 out, const Fp25 f, const Fp25 g);
void FpSquareDoubleCore(Fp25 out, const Fp25 in, bool doDouble);
void PolynomialToData(uint8_t out[32], const Fp25 polynomial);
void DataToPolynomial(Fp25 out, const uint8_t data[32]);
#ifdef HITLS_CRYPTO_X25519
void CRYPT_X25519_PublicFromPrivate(const uint8_t privateKey[CRYPT_CURVE25519_KEYLEN],
uint8_t publicKey[CRYPT_CURVE25519_KEYLEN]);
#endif
#ifdef __cplusplus
}
#endif
#endif // HITLS_CRYPTO_CURVE25519
#endif // CURVE25519_LOCAL_H
|
2301_79861745/bench_create
|
crypto/curve25519/src/curve25519_local.h
|
C
|
unknown
| 18,563
|
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
/* Some of these codes are adapted from https://ed25519.cr.yp.to/software.html */
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_CURVE25519
#include <stdbool.h>
#include "securec.h"
#include "curve25519_local.h"
#include "bsl_sal.h"
#ifdef HITLS_CRYPTO_ED25519
#define CRYPT_CURVE25519_OPTLEN 32
#endif
#define CONDITION_COPY(dst, src, indicate) \
(int32_t)((uint32_t)(dst) ^ (((uint32_t)(dst) ^ (uint32_t)(src)) & (indicate)))
// process Fp multiplication carry
#define FP_PROCESS_CARRY(h) \
do { \
int64_t carry0, carry1, carry2, carry3, carry4, carry5, carry6, carry7, carry8, carry9; \
carry0 = h##0 + (1 << 25); h##1 += carry0 >> 26; h##0 -= carry0 & CURVE25519_MASK_HIGH_38; \
carry4 = h##4 + (1 << 25); h##5 += carry4 >> 26; h##4 -= carry4 & CURVE25519_MASK_HIGH_38; \
carry1 = h##1 + (1 << 24); h##2 += carry1 >> 25; h##1 -= carry1 & CURVE25519_MASK_HIGH_39; \
carry5 = h##5 + (1 << 24); h##6 += carry5 >> 25; h##5 -= carry5 & CURVE25519_MASK_HIGH_39; \
carry2 = h##2 + (1 << 25); h##3 += carry2 >> 26; h##2 -= carry2 & CURVE25519_MASK_HIGH_38; \
carry6 = h##6 + (1 << 25); h##7 += carry6 >> 26; h##6 -= carry6 & CURVE25519_MASK_HIGH_38; \
carry3 = h##3 + (1 << 24); h##4 += carry3 >> 25; h##3 -= carry3 & CURVE25519_MASK_HIGH_39; \
carry7 = h##7 + (1 << 24); h##8 += carry7 >> 25; h##7 -= carry7 & CURVE25519_MASK_HIGH_39; \
carry4 = h##4 + (1 << 25); h##5 += carry4 >> 26; h##4 -= carry4 & CURVE25519_MASK_HIGH_38; \
carry8 = h##8 + (1 << 25); h##9 += carry8 >> 26; h##8 -= carry8 & CURVE25519_MASK_HIGH_38; \
carry9 = h##9 + (1 << 24); h##0 += (carry9 >> 25) * 19; h##9 -= carry9 & CURVE25519_MASK_HIGH_39; \
carry0 = h##0 + (1 << 25); h##1 += carry0 >> 26; h##0 -= carry0 & CURVE25519_MASK_HIGH_38; \
} while (0)
// h0...h9 to Fp25
#define INT64_2_FP25(h, out) \
do { \
(out)[0] = (int32_t)h##0; \
(out)[1] = (int32_t)h##1; \
(out)[2] = (int32_t)h##2; \
(out)[3] = (int32_t)h##3; \
(out)[4] = (int32_t)h##4; \
(out)[5] = (int32_t)h##5; \
(out)[6] = (int32_t)h##6; \
(out)[7] = (int32_t)h##7; \
(out)[8] = (int32_t)h##8; \
(out)[9] = (int32_t)h##9; \
} while (0)
#define FP25_2_INT32(in, out) \
do { \
out##0 = (in)[0]; \
out##1 = (in)[1]; \
out##2 = (in)[2]; \
out##3 = (in)[3]; \
out##4 = (in)[4]; \
out##5 = (in)[5]; \
out##6 = (in)[6]; \
out##7 = (in)[7]; \
out##8 = (in)[8]; \
out##9 = (in)[9]; \
} while (0)
/* out = f * g */
void FpMul(Fp25 out, const Fp25 f, const Fp25 g)
{
int32_t f0, f1, f2, f3, f4, f5, f6, f7, f8, f9;
int32_t g0, g1, g2, g3, g4, g5, g6, g7, g8, g9;
int64_t h0, h1, h2, h3, h4, h5, h6, h7, h8, h9;
FP25_2_INT32(f, f);
FP25_2_INT32(g, g);
int32_t f1_2 = f1 * 2;
int32_t f3_2 = f3 * 2;
int32_t f5_2 = f5 * 2;
int32_t f7_2 = f7 * 2;
int32_t f9_2 = f9 * 2;
int32_t g1_19 = g1 * 19;
int32_t g2_19 = g2 * 19;
int32_t g3_19 = g3 * 19;
int32_t g4_19 = g4 * 19;
int32_t g5_19 = g5 * 19;
int32_t g6_19 = g6 * 19;
int32_t g7_19 = g7 * 19;
int32_t g8_19 = g8 * 19;
int32_t g9_19 = g9 * 19;
/* h0 = f0g0 + 38f1g9 + 19f2g8 + 38f3g7 + 19f4g6 + 38f5g5 + 19f6g4 + 38f7g3 + 19f8g2 + 38f9g1
h1 = f0g1 + f1g0 + 19f2g9 + 19f3g8 + 19f4g7 + 19f5g6 + 19f6g5 + 19f7g4 + 19f8g3 + 19f9g2
h2 = f0g2 + 2f1g1 + f2g0 + 38f3g9 + 19f4g8 + 38f5g7 + 19f6g6 + 38f7g5 + 19f8g4 + 38f9g2
h3 = f0g3 + f1g2 + f2g1 + f3g0 + 19f4g9 + 19f5g8 + 19f6g7 + 19f7g6 + 19f8g5 + 19f9g4
h4 = f0g4 + 2f1g3 + f2g2 + 2f3g1 + f4g0 + 38f5g9 + 19f6g8 + 38f7g7 + 19f8g6 + 38f9g5
h5 = f0g5 + f1g4 + f2g3 + f3g2 + f4g1 + f5g0 + 19f6g9 + 19f7g8 + 19f8g7 + 19f9g6
h6 = f0g6 + 2f1g5 + f2g4 + 2f3g3 + f4g2 + 2f5g1 + f6g0 + 38f7g9 + 19f8g8 + 38f9g7
h7 = f0g7 + f1g6 + f2g5 + f3g4 + f4g3 + f5g2 + f6g1 + f7g0 + 19f8g9 + 19f9g8
h8 = f0g8 + 2f1g7 + f2g6 + 2f3g5 + f4g4 + 2f5g3 + f6g2 + 2f7g1 + f8g0 + 38f9g9
h9 = f0g9 + f1g8 + f2g7 + f3g6 + f4g5 + f5g4 + f6g3 + f7g2 + f8g1 + f9g0
The calculation is performed by column. */
h0 = (int64_t)f0 * g0;
h1 = (int64_t)f0 * g1;
h2 = (int64_t)f0 * g2;
h3 = (int64_t)f0 * g3;
h4 = (int64_t)f0 * g4;
h5 = (int64_t)f0 * g5;
h6 = (int64_t)f0 * g6;
h7 = (int64_t)f0 * g7;
h8 = (int64_t)f0 * g8;
h9 = (int64_t)f0 * g9;
h0 += (int64_t)f1_2 * g9_19;
h1 += (int64_t)f1 * g0;
h2 += (int64_t)f1_2 * g1;
h3 += (int64_t)f1 * g2;
h4 += (int64_t)f1_2 * g3;
h5 += (int64_t)f1 * g4;
h6 += (int64_t)f1_2 * g5;
h7 += (int64_t)f1 * g6;
h8 += (int64_t)f1_2 * g7;
h9 += (int64_t)f1 * g8;
h0 += (int64_t)f2 * g8_19;
h1 += (int64_t)f2 * g9_19;
h2 += (int64_t)f2 * g0;
h3 += (int64_t)f2 * g1;
h4 += (int64_t)f2 * g2;
h5 += (int64_t)f2 * g3;
h6 += (int64_t)f2 * g4;
h7 += (int64_t)f2 * g5;
h8 += (int64_t)f2 * g6;
h9 += (int64_t)f2 * g7;
h0 += (int64_t)f3_2 * g7_19;
h1 += (int64_t)f3 * g8_19;
h2 += (int64_t)f3_2 * g9_19;
h3 += (int64_t)f3 * g0;
h4 += (int64_t)f3_2 * g1;
h5 += (int64_t)f3 * g2;
h6 += (int64_t)f3_2 * g3;
h7 += (int64_t)f3 * g4;
h8 += (int64_t)f3_2 * g5;
h9 += (int64_t)f3 * g6;
h0 += (int64_t)f4 * g6_19;
h1 += (int64_t)f4 * g7_19;
h2 += (int64_t)f4 * g8_19;
h3 += (int64_t)f4 * g9_19;
h4 += (int64_t)f4 * g0;
h5 += (int64_t)f4 * g1;
h6 += (int64_t)f4 * g2;
h7 += (int64_t)f4 * g3;
h8 += (int64_t)f4 * g4;
h9 += (int64_t)f4 * g5;
h0 += (int64_t)f5_2 * g5_19;
h1 += (int64_t)f5 * g6_19;
h2 += (int64_t)f5_2 * g7_19;
h3 += (int64_t)f5 * g8_19;
h4 += (int64_t)f5_2 * g9_19;
h5 += (int64_t)f5 * g0;
h6 += (int64_t)f5_2 * g1;
h7 += (int64_t)f5 * g2;
h8 += (int64_t)f5_2 * g3;
h9 += (int64_t)f5 * g4;
h0 += (int64_t)f6 * g4_19;
h1 += (int64_t)f6 * g5_19;
h2 += (int64_t)f6 * g6_19;
h3 += (int64_t)f6 * g7_19;
h4 += (int64_t)f6 * g8_19;
h5 += (int64_t)f6 * g9_19;
h6 += (int64_t)f6 * g0;
h7 += (int64_t)f6 * g1;
h8 += (int64_t)f6 * g2;
h9 += (int64_t)f6 * g3;
h0 += (int64_t)f7_2 * g3_19;
h1 += (int64_t)f7 * g4_19;
h2 += (int64_t)f7_2 * g5_19;
h3 += (int64_t)f7 * g6_19;
h4 += (int64_t)f7_2 * g7_19;
h5 += (int64_t)f7 * g8_19;
h6 += (int64_t)f7_2 * g9_19;
h7 += (int64_t)f7 * g0;
h8 += (int64_t)f7_2 * g1;
h9 += (int64_t)f7 * g2;
h0 += (int64_t)f8 * g2_19;
h1 += (int64_t)f8 * g3_19;
h2 += (int64_t)f8 * g4_19;
h3 += (int64_t)f8 * g5_19;
h4 += (int64_t)f8 * g6_19;
h5 += (int64_t)f8 * g7_19;
h6 += (int64_t)f8 * g8_19;
h7 += (int64_t)f8 * g9_19;
h8 += (int64_t)f8 * g0;
h9 += (int64_t)f8 * g1;
h0 += (int64_t)f9_2 * g1_19;
h1 += (int64_t)f9 * g2_19;
h2 += (int64_t)f9_2 * g3_19;
h3 += (int64_t)f9 * g4_19;
h4 += (int64_t)f9_2 * g5_19;
h5 += (int64_t)f9 * g6_19;
h6 += (int64_t)f9_2 * g7_19;
h7 += (int64_t)f9 * g8_19;
h8 += (int64_t)f9_2 * g9_19;
h9 += (int64_t)f9 * g0;
FP_PROCESS_CARRY(h);
INT64_2_FP25(h, out);
}
void FpSquareDoubleCore(Fp25 out, const Fp25 in, bool doDouble)
{
int64_t h0, h1, h2, h3, h4, h5, h6, h7, h8, h9;
int32_t f0, f1, f2, f3, f4, f5, f6, f7, f8, f9;
FP25_2_INT32(in, f);
int32_t f0_2 = f0 * 2;
int32_t f1_2 = f1 * 2;
int32_t f2_2 = f2 * 2;
int32_t f3_2 = f3 * 2;
int32_t f4_2 = f4 * 2;
int32_t f5_2 = f5 * 2;
int32_t f6_2 = f6 * 2;
int32_t f7_2 = f7 * 2;
int32_t f9_38 = f9 * 38;
int32_t f8_19 = f8 * 19;
int32_t f7_38 = f7 * 38;
int32_t f6_19 = f6 * 19;
int32_t f5_19 = f5 * 19;
h0 = (int64_t)f0 * f0;
h1 = (int64_t)f0_2 * f1;
h2 = (int64_t)f0_2 * f2;
h3 = (int64_t)f0_2 * f3;
h4 = (int64_t)f0_2 * f4;
h5 = (int64_t)f0_2 * f5;
h6 = (int64_t)f0_2 * f6;
h7 = (int64_t)f0_2 * f7;
h8 = (int64_t)f0_2 * f8;
h9 = (int64_t)f0_2 * f9;
h0 += (int64_t)f1_2 * f9_38;
h1 += (int64_t)f2 * f9_38;
h2 += (int64_t)f1_2 * f1;
h3 += (int64_t)f1_2 * f2;
h4 += (int64_t)f1_2 * f3_2;
h5 += (int64_t)f1_2 * f4;
h6 += (int64_t)f1_2 * f5_2;
h7 += (int64_t)f1_2 * f6;
h8 += (int64_t)f1_2 * f7_2;
h9 += (int64_t)f1_2 * f8;
h0 += (int64_t)f2_2 * f8_19;
h1 += (int64_t)f3_2 * f8_19;
h2 += (int64_t)f3_2 * f9_38;
h3 += (int64_t)f4 * f9_38;
h4 += (int64_t)f2 * f2;
h5 += (int64_t)f2_2 * f3;
h6 += (int64_t)f2_2 * f4;
h7 += (int64_t)f2_2 * f5;
h8 += (int64_t)f2_2 * f6;
h9 += (int64_t)f2_2 * f7;
h0 += (int64_t)f3_2 * f7_38;
h1 += (int64_t)f4 * f7_38;
h2 += (int64_t)f4_2 * f8_19;
h3 += (int64_t)f5_2 * f8_19;
h4 += (int64_t)f5_2 * f9_38;
h5 += (int64_t)f6 * f9_38;
h6 += (int64_t)f3_2 * f3;
h7 += (int64_t)f3_2 * f4;
h8 += (int64_t)f3_2 * f5_2;
h9 += (int64_t)f3_2 * f6;
h0 += (int64_t)f4_2 * f6_19;
h1 += (int64_t)f5_2 * f6_19;
h2 += (int64_t)f5_2 * f7_38;
h3 += (int64_t)f6 * f7_38;
h4 += (int64_t)f6_2 * f8_19;
h5 += (int64_t)f7_2 * f8_19;
h6 += (int64_t)f7_2 * f9_38;
h7 += (int64_t)f8 * f9_38;
h8 += (int64_t)f4 * f4;
h9 += (int64_t)f4_2 * f5;
h0 += (int64_t)f5_2 * f5_19;
h2 += (int64_t)f6 * f6_19;
h4 += (int64_t)f7 * f7_38;
h6 += (int64_t)f8 * f8_19;
h8 += (int64_t)f9 * f9_38;
if (doDouble) {
h0 *= 2;
h1 *= 2;
h2 *= 2;
h3 *= 2;
h4 *= 2;
h5 *= 2;
h6 *= 2;
h7 *= 2;
h8 *= 2;
h9 *= 2;
}
FP_PROCESS_CARRY(h);
INT64_2_FP25(h, out);
}
/* out = in1 ^ (4 * 2 ^ (2 * times)) * in2 */
static void FpMultiSquare(Fp25 in1, Fp25 in2, Fp25 out, int32_t times)
{
int32_t i;
Fp25 temp1, temp2;
FpSquareDoubleCore(temp1, in1, false);
FpSquareDoubleCore(temp2, temp1, false);
for (i = 0; i < times; i++) {
FpSquareDoubleCore(temp1, temp2, false);
FpSquareDoubleCore(temp2, temp1, false);
}
FpMul(out, in2, temp2);
}
/* out = a ^ -1 */
void FpInvert(Fp25 out, const Fp25 a)
{
int32_t i;
Fp25 a0; /* save a^1 */
Fp25 a1; /* save a^2 */
Fp25 a2; /* save a^11 */
Fp25 a3; /* save a^(2^5-1) */
Fp25 a4; /* save a^(2^10-1) */
Fp25 a5; /* save a^(2^20-1) */
Fp25 a6; /* save a^(2^40-1) */
Fp25 a7; /* save a^(2^50-1) */
Fp25 a8; /* save a^(2^100-1) */
Fp25 a9; /* save a^(2^200-1) */
Fp25 a10; /* save a^(2^250-1) */
Fp25 temp1, temp2;
/* We know a×b=1(mod p), then a and b are inverses of mod p, i.e. a=b^(-1), b=a^(-1);
* According to Fermat's little theorem a^(p-1)=1(mod p), so a*a^(p-2)=1(mod p);
* So the inverse element of a is a^(-1) = a^(p-2)(mod p)
* Here it is, p=2^255-19, thus we need to compute a^(2^255-21)(mod(2^255-19))
*/
/* a^1 */
CURVE25519_FP_COPY(a0, a);
/* a^2 */
FpSquareDoubleCore(a1, a0, false);
/* a^4 */
FpSquareDoubleCore(temp1, a1, false);
/* a^8 */
FpSquareDoubleCore(temp2, temp1, false);
/* a^9 */
FpMul(temp1, a0, temp2);
/* a^11 */
FpMul(a2, a1, temp1);
/* a^22 */
FpSquareDoubleCore(temp2, a2, false);
/* a^(2^5-1) = a^(9+22) */
FpMul(a3, temp1, temp2);
/* a^(2^10-1) = a^(2^10-2^5) * a^(2^5-1) */
FpSquareDoubleCore(temp1, a3, false);
for (i = 0; i < 2; i++) { // (2 * 2)^2
FpSquareDoubleCore(temp2, temp1, false);
FpSquareDoubleCore(temp1, temp2, false);
}
FpMul(a4, a3, temp1);
/* a^(2^20-1) = a^(2^20-2^10) * a^(2^10-1) */
FpMultiSquare(a4, a4, a5, 4); // (2 * 2) ^ 4
/* a^(2^40-1) = a^(2^40-2^20) * a^(2^20-1) */
FpMultiSquare(a5, a5, a6, 9); // (2 * 2) ^ 9
/* a^(2^50-1) = a^(2^50-2^10) * a^(2^10-1) */
FpMultiSquare(a6, a4, a7, 4); // (2 * 2) ^ 4
/* a^(2^100-1) = a^(2^100-2^50) * a^(2^50-1) */
FpMultiSquare(a7, a7, a8, 24); // (2 * 2) ^ 24
/* a^(2^200-1) = a^(2^200-2^100) * a^(2^100-1) */
FpMultiSquare(a8, a8, a9, 49); // (2 * 2) ^ 49
/* a^(2^250-1) = a^(2^250-2^50) * a^(2^50-1) */
FpMultiSquare(a9, a7, a10, 24); // (2 * 2) ^ 24
/* a^(2^5*(2^250-1)) = (a^(2^250-1))^5 */
FpSquareDoubleCore(temp1, a10, false);
FpSquareDoubleCore(temp2, temp1, false);
FpSquareDoubleCore(temp1, temp2, false);
FpSquareDoubleCore(temp2, temp1, false);
FpSquareDoubleCore(temp1, temp2, false);
/* The output:a^(2^255-21) = a(2^5*(2^250-1)+11) = a^(2^5*(2^250-1)) * a^11 */
FpMul(out, a2, temp1);
}
#ifdef HITLS_CRYPTO_ED25519
/* out = in ^ ((q - 5) / 8) */
static void FpPowq58(Fp25 out, Fp25 in)
{
Fp25 a, b, c;
int32_t i;
FpSquareDoubleCore(a, in, false);
FpSquareDoubleCore(b, a, false);
FpSquareDoubleCore(b, b, false);
FpMul(b, in, b);
FpMul(a, a, b);
FpSquareDoubleCore(a, a, false);
FpMul(a, b, a);
FpSquareDoubleCore(b, a, false);
// b = a ^ (2^5)
for (i = 1; i < 5; i++) {
FpSquareDoubleCore(b, b, false);
}
FpMul(a, b, a);
FpSquareDoubleCore(b, a, false);
// b = a ^ (2^10)
for (i = 1; i < 10; i++) {
FpSquareDoubleCore(b, b, false);
}
FpMul(b, b, a);
FpSquareDoubleCore(c, b, false);
// c = b ^ (2^20)
for (i = 1; i < 20; i++) {
FpSquareDoubleCore(c, c, false);
}
FpMul(b, c, b);
// b = b ^ (2^10)
for (i = 0; i < 10; i++) {
FpSquareDoubleCore(b, b, false);
}
FpMul(a, b, a);
FpSquareDoubleCore(b, a, false);
// b = a ^ (2^50)
for (i = 1; i < 50; i++) {
FpSquareDoubleCore(b, b, false);
}
FpMul(b, b, a);
FpSquareDoubleCore(c, b, false);
// c = b ^ (2 ^ 100)
for (i = 1; i < 100; i++) {
FpSquareDoubleCore(c, c, false);
}
FpMul(b, c, b);
// b = b ^ (2^50)
for (i = 0; i < 50; i++) {
FpSquareDoubleCore(b, b, false);
}
FpMul(a, b, a);
FpSquareDoubleCore(a, a, false);
FpSquareDoubleCore(a, a, false);
FpMul(out, a, in);
}
#endif
static void PaddingUnload(uint8_t out[32], Fp25 pFp25)
{
int32_t *p = (int32_t *)pFp25;
/* Take a polynomial form number into a 32-byte array */
CURVE25519_BYTES4_PADDING_UNLOAD(out, 2, p); /* p0 unload 4 bytes on out[0] expand 2 */
CURVE25519_BYTES3_PADDING_UNLOAD(out + 4, 2, 3, p + 1); /* p1 unload 3 bytes on out[4] shift 2 expand 3 */
CURVE25519_BYTES3_PADDING_UNLOAD(out + 7, 3, 5, p + 2); /* p2 unload 3 bytes on out[7] shift 3 expand 5 */
CURVE25519_BYTES3_PADDING_UNLOAD(out + 10, 5, 6, p + 3); /* p3 unload 3 bytes on out[10] shift 5 expand 6 */
CURVE25519_BYTES3_UNLOAD(out + 13, 6, p + 4); /* p4 unload 3 bytes on out[13] shift 6 */
CURVE25519_BYTES4_PADDING_UNLOAD(out + 16, 1, p + 5); /* p5 unload 4 bytes on out[16] expand 1 */
CURVE25519_BYTES3_PADDING_UNLOAD(out + 20, 1, 3, p + 6); /* p6 unload 3 bytes on out[20] shift 1 expand 3 */
CURVE25519_BYTES3_PADDING_UNLOAD(out + 23, 3, 4, p + 7); /* p7 unload 3 bytes on out[23] shift 3 expand 4 */
CURVE25519_BYTES3_PADDING_UNLOAD(out + 26, 4, 6, p + 8); /* p8 unload 3 bytes on out[26] shift 4 expand 6 */
CURVE25519_BYTES3_UNLOAD(out + 29, 6, p + 9); /* p9 unload 3 bytes on out[29] shift 6 */
}
void PolynomialToData(uint8_t out[32], const Fp25 polynomial)
{
Fp25 pFp25;
uint32_t pos;
uint32_t over;
uint32_t mul19;
uint32_t signMask;
CURVE25519_FP_COPY(pFp25, polynomial);
/* First process, all the carry transport to pFp25[0] */
mul19 = (uint32_t)pFp25[9] * 19; // mul 19 for mod
over = mul19 + (1 << 24); // plus 1 << 24 for carry
// restricted to 25 bits, shift 31 for sign
signMask = (-(over >> 31)) & MASK_HIGH32(25);
over = (over >> 25) | signMask; // 25 bits
pos = 0;
do {
over = (uint32_t)pFp25[pos] + over;
// first carry is restricted to 25 bits, shift 31 for sign
signMask = (-(over >> 31)) & MASK_HIGH32(25);
over = (over >> 25) | signMask; // 25 bits
pos++;
over = (uint32_t)pFp25[pos] + over;
// second carry is restricted to 26 bits, shift 31 for sign
signMask = (-(over >> 31)) & MASK_HIGH32(26);
over = (over >> 26) | signMask; // 26 bits
pos++;
} while (pos < 10); // process from 0 to 9, pos < 10
mul19 = over * 19; // mul 19 for mod
pFp25[0] += (int32_t)mul19;
/* We subtracted 2^255-19 and get the result
* all polynomial[i] is restricted to 25 bits or 26 bits
*/
pos = 0;
do {
// first polynomial is restricted to 26 bits, shift 31 for sign
signMask = (-((uint32_t)pFp25[pos] >> 31)) & MASK_HIGH32(26);
over = ((uint32_t)pFp25[pos] >> 26) | signMask; // 26 bits
pFp25[pos] = (int32_t)((uint32_t)pFp25[pos] & MASK_LOW32(26)); // 26 bits
pos++;
pFp25[pos] += (int32_t)over;
// second polynomial is restricted to 25 bits, shift 31 for sign
signMask = (-((uint32_t)pFp25[pos] >> 31)) & MASK_HIGH32(25);
over = ((uint32_t)pFp25[pos] >> 25) | signMask; // 25 bits
pFp25[pos] = (int32_t)((uint32_t)pFp25[pos] & MASK_LOW32(25));
pos++;
pFp25[pos] += (int32_t)over;
} while (pos < 8); // process form 0 to 7, pos < 8
// process pFp25[8], restricted to 26 bits, shift 31 for sign
signMask = (-((uint32_t)pFp25[pos] >> 31)) & MASK_HIGH32(26);
over = ((uint32_t)pFp25[pos] >> 26) | signMask; // 26 bits
pFp25[pos] = (int32_t)((uint32_t)pFp25[pos] & MASK_LOW32(26)); // 26 bits
pos++;
// process pFp25[9]
pFp25[pos] += (int32_t)over;
pFp25[pos] = (int32_t)((uint32_t)pFp25[pos] & MASK_LOW32(25)); // pFp25[9] is restricted to 25 bits
PaddingUnload(out, pFp25);
}
/* unified addition in Extended twist Edwards Coordinate */
/* out = out + tableElement */
static void GeAdd(GeE *out, const GePre *tableElement)
{
Fp25 a;
Fp25 b;
Fp25 c;
Fp25 d;
Fp25 e;
Fp25 f;
Fp25 g;
Fp25 h;
/* a = (Y1 − X1) * (Y2 − X2), b = (Y1 + X1) * (Y2 + X2)
* c = 2 * d * T1 * X2 * Y2, d = 2 * Z1
* e = b − a, f = d − c, g = d + c, h = b + a
* X3 = e * f, Y3 = g * h, T3 = e * h, Z3 = f * g
*/
CURVE25519_FP_ADD(e, out->y, out->x);
CURVE25519_FP_SUB(f, out->y, out->x);
FpMul(b, e, tableElement->yplusx);
FpMul(a, f, tableElement->yminusx);
FpMul(c, out->t, tableElement->xy2d);
CURVE25519_FP_ADD(d, out->z, out->z);
CURVE25519_FP_SUB(e, b, a);
CURVE25519_FP_SUB(f, d, c);
CURVE25519_FP_ADD(g, d, c);
CURVE25519_FP_ADD(h, b, a);
FpMul(out->x, e, f);
FpMul(out->y, h, g);
FpMul(out->z, g, f);
FpMul(out->t, e, h);
}
#ifdef HITLS_CRYPTO_ED25519
/* out = out - tableElement */
static void GeSub(GeE *out, const GePre *tableElement)
{
Fp25 a;
Fp25 b;
Fp25 c;
Fp25 d;
Fp25 e;
Fp25 f;
Fp25 g;
Fp25 h;
CURVE25519_FP_ADD(e, out->y, out->x);
CURVE25519_FP_SUB(f, out->y, out->x);
FpMul(b, e, tableElement->yminusx);
FpMul(a, f, tableElement->yplusx);
FpMul(c, out->t, tableElement->xy2d);
CURVE25519_FP_ADD(d, out->z, out->z);
CURVE25519_FP_SUB(e, b, a);
CURVE25519_FP_ADD(f, d, c);
CURVE25519_FP_SUB(g, d, c);
CURVE25519_FP_ADD(h, b, a);
FpMul(out->x, e, f);
FpMul(out->y, h, g);
FpMul(out->z, g, f);
FpMul(out->t, e, h);
}
#endif
/* double in Projective twist Edwards Coordinate */
static void ProjectiveDouble(GeC *complete, const GeP *projective)
{
Fp25 tmp;
FpSquareDoubleCore((complete->x), (projective->x), false);
FpSquareDoubleCore((complete->z), (projective->y), false);
// T = 2 * Z^2
FpSquareDoubleCore(complete->t, projective->z, true);
CURVE25519_FP_ADD(complete->y, projective->x, projective->y);
FpSquareDoubleCore(tmp, complete->y, false);
// tmp = (X1 + Y1) ^ 2, T = 2 * Z^2, X = X1 ^ 2, Y = Z1 ^ 2, Z = Y1 ^ 2
CURVE25519_FP_ADD(complete->y, complete->z, complete->x);
CURVE25519_FP_SUB(complete->z, complete->z, complete->x);
CURVE25519_FP_SUB(complete->x, tmp, complete->y);
CURVE25519_FP_SUB(complete->t, complete->t, complete->z);
}
/* Convert complete coordinate to projective coordinate */
static void GeCompleteToProjective(GeP *out, const GeC *complete)
{
FpMul(out->x, complete->t, complete->x);
FpMul(out->y, complete->z, complete->y);
FpMul(out->z, complete->t, complete->z);
}
/* p1 = 16 * p1 */
static void P1DoubleFourTimes(GeE *p1)
{
GeP p;
GeC c;
// From extended coordinate to projective coordinate, just ignore T
CURVE25519_FP_COPY(p.x, p1->x);
CURVE25519_FP_COPY(p.y, p1->y);
CURVE25519_FP_COPY(p.z, p1->z);
// double 4 times to get 16p1
ProjectiveDouble(&c, &p);
GeCompleteToProjective(&p, &c);
ProjectiveDouble(&c, &p);
GeCompleteToProjective(&p, &c);
ProjectiveDouble(&c, &p);
GeCompleteToProjective(&p, &c);
ProjectiveDouble(&c, &p);
FpMul(p1->x, c.x, c.t);
FpMul(p1->y, c.y, c.z);
FpMul(p1->z, c.z, c.t);
FpMul(p1->t, c.x, c.y);
}
static void SetExtendedBasePoint(GeE *out)
{
CURVE25519_FP_SET(out->x, 0);
CURVE25519_FP_SET(out->y, 1);
CURVE25519_FP_SET(out->t, 0);
CURVE25519_FP_SET(out->z, 1);
}
/* Multiple with Base point, see paper: High-speed high-security signatures */
void ScalarMultiBase(GeE *out, const uint8_t in[CRYPT_CURVE25519_KEYLEN])
{
uint8_t carry;
// inLen is always 32, buffer needs 32 * 2 = 64
uint8_t privateKey[64];
int32_t i;
GePre preCompute;
// split 32 8bits input into 64 4bits-based number
for (i = 0; i < 32; i++) {
privateKey[i * 2] = in[i] & 15; // and 15 to get low 4 bits, stored in 2i
privateKey[i * 2 + 1] = (in[i] >> 4) & 15; // shift 4 then and 15 to get upper 4 bits, stored in 2i+1
}
carry = 0;
/**
* change from 0 - 15 to -8 - 7, if privateKey[i] >= 8, carry = 1, privateKey[i] -= 16
* if privateKey[i] < 8, privateKey[i] = privateKey[i]
*/
for (i = 0; i < 63; i++) { // 0 to 63
privateKey[i] += carry;
carry = (privateKey[i] + 8) >> 4; // plus 8 then shit 4 to get carry
privateKey[i] -= carry << 4; // left shift 4
}
// never overflow since we set first bit to 0 of private key
privateKey[63] += carry; // last one is 63
// set base point X:Y:T:Z -> 0:1:0:1
SetExtendedBasePoint(out);
for (i = 1; i < 64; i += 2) { // form 1 to 63, process all odd element, increment by 2, i < 64
TableLookup(&preCompute, i / 2, (int8_t)privateKey[i]); // position goes from 0 to 31, i / 2 = pos
// Fit with paper: Twisted Edwards Curves Revisited
GeAdd(out, &preCompute);
}
// now we have P1, double it four times we have 16P1, P1 is in Extended now, we do double in projective coordinate
P1DoubleFourTimes(out);
// Add P0 with precomute
for (i = 0; i < 64; i += 2) { // form 0 to 62, process all even element, increment by 2, i < 64
TableLookup(&preCompute, i / 2, (int8_t)privateKey[i]); // position goes from 0 to 31, i / 2 = pos
GeAdd(out, &preCompute);
}
// clean up private key information
BSL_SAL_CleanseData(privateKey, sizeof(privateKey));
}
#ifdef HITLS_CRYPTO_ED25519
void PointEncoding(const GeE *point, uint8_t *output, uint32_t outputLen)
{
Fp25 zInvert;
Fp25 x;
Fp25 y;
uint8_t xData[CRYPT_CURVE25519_KEYLEN];
/* x = X / Z, y = Y / Z */
(void)outputLen;
FpInvert(zInvert, point->z);
FpMul(x, point->x, zInvert);
FpMul(y, point->y, zInvert);
PolynomialToData(output, y);
PolynomialToData(xData, x);
// PointEcoding writes only 32 bytes data, therefore output[31] is the last one
output[31] ^= (xData[0] & 0x1) << 7; // last one is output[31], get only last bit then shift 7
}
#endif
static void FeCmove(Fp25 dst, const Fp25 src, const uint32_t indicator)
{
// if indicator = 1, now it will be 111111111111b....
const uint32_t indicate = 0 - indicator;
/* des become source if dst->data[i] ^ src->data[i] is in 1111....b, or it does not change if
(dst->data[i] ^ src->data[i]) & indicate is all 0 */
dst[0] = CONDITION_COPY(dst[0], src[0], indicate); // 0
dst[1] = CONDITION_COPY(dst[1], src[1], indicate); // 1
dst[2] = CONDITION_COPY(dst[2], src[2], indicate); // 2
dst[3] = CONDITION_COPY(dst[3], src[3], indicate); // 3
dst[4] = CONDITION_COPY(dst[4], src[4], indicate); // 4
dst[5] = CONDITION_COPY(dst[5], src[5], indicate); // 5
dst[6] = CONDITION_COPY(dst[6], src[6], indicate); // 6
dst[7] = CONDITION_COPY(dst[7], src[7], indicate); // 7
dst[8] = CONDITION_COPY(dst[8], src[8], indicate); // 8
dst[9] = CONDITION_COPY(dst[9], src[9], indicate); // 9
}
void ConditionalMove(GePre *preCompute, const GePre *tableElement, uint32_t indicator)
{
FeCmove(preCompute->yplusx, tableElement->yplusx, indicator);
FeCmove(preCompute->yminusx, tableElement->yminusx, indicator);
FeCmove(preCompute->xy2d, tableElement->xy2d, indicator);
}
void DataToPolynomial(Fp25 out, const uint8_t data[32])
{
const uint8_t *t = data;
uint64_t p[10];
uint64_t over;
int32_t i;
uint64_t signMask;
/* f0, load 32 bits */
CURVE25519_BYTES4_LOAD(p, t);
/* f1, load 24 bits from t4, shift bits: 26 - 24 - (8 - x) = 0 -> x = 6 */
CURVE25519_BYTES3_LOAD_PADDING(p + 1, 6, t + 4);
/* f2, load 24 bits from t7, shift bits: 51 - 48 - (8 - x) = 0 -> x = 5 */
CURVE25519_BYTES3_LOAD_PADDING(p + 2, 5, t + 7);
/* f3, load 24 bits from t10, shift bits: 77 - 72 - (8 - x) = 0 -> x = 3 */
CURVE25519_BYTES3_LOAD_PADDING(p + 3, 3, t + 10);
/* f4, load 24 bits from t13, shift bits: 102 - 96 - (8 - x) = 0 -> x = 2 */
CURVE25519_BYTES3_LOAD_PADDING(p + 4, 2, t + 13);
/* f5, load 32 bits from t16 */
CURVE25519_BYTES4_LOAD(p + 5, t + 16);
/* f6, load 24 bits from t20, shift bits: 153 - 152 - (8 - x) = 0 -> x = 7 */
CURVE25519_BYTES3_LOAD_PADDING(p + 6, 7, t + 20);
/* f7, load 24 bits from t23, shift bits: 179 - 176 - (8 - x) = 0 -> x = 5 */
CURVE25519_BYTES3_LOAD_PADDING(p + 7, 5, t + 23);
/* f8, load 24 bits from t26, shift bits: 204 - 200 - (8 - x) = 0 -> x = 4 */
CURVE25519_BYTES3_LOAD_PADDING(p + 8, 4, t + 26);
/* f9, load 24 bits from t29, shift bits: 230 - 224 - (8 - x) = 0 -> x = 2 */
CURVE25519_BYTES3_LOAD(p + 9, t + 29);
p[9] = (p[9] & 0x7fffff) << 2; /* p9 is 25 bits, left shift 2 */
/* Limiting the number of bits, exchange 2^1 to 2^25.5, turn into polynomial representation */
/* f9->f0, shift 24 for carry */
over = p[9] + (1 << 24);
signMask = MASK_HIGH64(25) & (-((over) >> 63)); // shift 63 bits for sign, mask 25 bits
p[0] += ((over >> 25) | signMask) * 19; // 24 bits plus sign is 25, mul 19 for mod
p[9] -= MASK_HIGH64(39) & over; // 64 - 25 = 39 bits mask
/* f1->f2, restricted to 24 bits */
PROCESS_CARRY(p[1], p[2], signMask, over, 24);
/* f3->f4, restricted to 24 bits */
PROCESS_CARRY(p[3], p[4], signMask, over, 24);
/* f5->f6, restricted to 24 bits */
PROCESS_CARRY(p[5], p[6], signMask, over, 24);
/* f7->f8, restricted to 24 bits */
PROCESS_CARRY(p[7], p[8], signMask, over, 24);
/* f0->f1, restricted to 25 bits */
PROCESS_CARRY(p[0], p[1], signMask, over, 25);
/* f2->f3, restricted to 25 bits */
PROCESS_CARRY(p[2], p[3], signMask, over, 25);
/* f4->f5, restricted to 25 bits */
PROCESS_CARRY(p[4], p[5], signMask, over, 25);
/* f6->f7, restricted to 25 bits */
PROCESS_CARRY(p[6], p[7], signMask, over, 25);
/* f8->f9, restricted to 25 bits */
PROCESS_CARRY(p[8], p[9], signMask, over, 25);
/* After process carry, polynomial every term would not exceed 32 bits, convert form 0 to 9, i < 10 */
for (i = 0; i < 10; i++) {
out[i] = (int32_t)p[i];
}
}
#ifdef HITLS_CRYPTO_ED25519
static bool CheckZero(Fp25 x)
{
uint8_t tmp[32];
const uint8_t zero[32] = {0};
PolynomialToData(tmp, x);
if (memcmp(tmp, zero, sizeof(zero)) == 0) {
return true;
} else {
return false;
}
}
static uint8_t GetXBit(Fp25 in)
{
uint8_t tmp[32];
PolynomialToData(tmp, in);
return tmp[0] & 0x1;
}
static const Fp25 SQRTM1 = {-32595792, -7943725, 9377950, 3500415, 12389472, -272473,
-25146209, -2005654, 326686, 11406482};
static const Fp25 D = {-10913610, 13857413, -15372611, 6949391, 114729, -8787816,
-6275908, -3247719, -18696448, -12055116};
int32_t PointDecoding(GeE *point, const uint8_t in[CRYPT_CURVE25519_KEYLEN])
{
Fp25 u, v, v3, x2, result;
// get the last block (31), shift 7 for first bit
uint8_t x0 = in[31] >> 7;
DataToPolynomial(point->y, in);
CURVE25519_FP_SET(point->z, 1);
FpSquareDoubleCore(u, point->y, false);
FpMul(v, u, D);
CURVE25519_FP_SUB(u, u, point->z);
CURVE25519_FP_ADD(v, v, point->z);
FpSquareDoubleCore(v3, v, false);
FpMul(v3, v3, v);
FpSquareDoubleCore(point->x, v3, false);
FpMul(point->x, point->x, v);
FpMul(point->x, point->x, u);
/* x = x ^ ((q - 5) / 8) */
FpPowq58(point->x, point->x);
FpMul(point->x, point->x, v3);
FpMul(point->x, point->x, u);
FpSquareDoubleCore(x2, point->x, false);
FpMul(x2, x2, v);
CURVE25519_FP_SUB(result, x2, u);
if (CheckZero(result) == false) {
CURVE25519_FP_ADD(result, x2, u);
if (CheckZero(result) == false) {
return 1;
}
FpMul(point->x, point->x, SQRTM1);
}
uint8_t bit = GetXBit(point->x);
if (bit != x0) {
CURVE25519_FP_NEGATE(point->x, point->x);
}
FpMul(point->t, point->x, point->y);
return 0;
}
static void ScalarMulAddPreLoad(const uint8_t in[CRYPT_CURVE25519_KEYLEN],
uint64_t out[UINT8_32_21BITS_BLOCKNUM])
{
CURVE25519_BYTES3_LOAD(&out[0], in);
out[0] = out[0] & MASK_64_LOW21;
CURVE25519_BYTES4_LOAD(&out[1], in + 2); // 1: load 4 bytes form position 2
out[1] = MASK_64_LOW21 & (out[1] >> 5); // 1: 8 - ((3 * 8) mod 21) mod 8 = 5
CURVE25519_BYTES3_LOAD(&out[2], in + 5); // 2: load 3 bytes form position 5
out[2] = MASK_64_LOW21 & (out[2] >> 2); // 2: 8 - ((6 * 8) mod 21) mod 8 = 2
CURVE25519_BYTES4_LOAD(&out[3], in + 7); // 3: load 4 bytes form position 7
out[3] = MASK_64_LOW21 & (out[3] >> 7); // 3: 8 - ((8 * 8) mod 21) mod 8 = 7
CURVE25519_BYTES4_LOAD(&out[4], in + 10); // 4: load 4 bytes form position 10
out[4] = MASK_64_LOW21 & (out[4] >> 4); // 4: 8 - ((11 * 8) mod 21) mod 8 = 4
CURVE25519_BYTES3_LOAD(&out[5], in + 13); // 5: load 3 bytes form position 13
out[5] = MASK_64_LOW21 & (out[5] >> 1); // 5: 8 - ((14 * 8) mod 21) mod 8 = 1
CURVE25519_BYTES4_LOAD(&out[6], in + 15); // 6: load 4 bytes form position 15
out[6] = MASK_64_LOW21 & (out[6] >> 6); // 6: 8 - ((16 * 8) mod 21) mod 8 = 6
CURVE25519_BYTES3_LOAD(&out[7], in + 18); // 7: load 3 bytes form position 18
out[7] = MASK_64_LOW21 & (out[7] >> 3); // 7: 8 - ((19 * 8) mod 21) mod 8 = 3
CURVE25519_BYTES3_LOAD(&out[8], in + 21); // 8: load 3 bytes form position 21
out[8] = MASK_64_LOW21 & out[8]; // 8: ((22 * 8) mod 21) mod 8 = 0
CURVE25519_BYTES4_LOAD(&out[9], in + 23); // 9: load 4 bytes form position 23
out[9] = MASK_64_LOW21 & (out[9] >> 5); // 9: 8 - ((24 * 8) mod 21) mod 8 = 5
CURVE25519_BYTES3_LOAD(&out[10], in + 26); // 10: load 3 bytes form position 26
out[10] = MASK_64_LOW21 & (out[10] >> 2); // 10: 8 - ((27 * 8) mod 21) mod 8 = 2
CURVE25519_BYTES4_LOAD(&out[11], in + 28); // 11: load 4 bytes form position 28
out[11] = (out[11] >> 7); // 11: 8 - ((29 * 8) mod 21) mod 8 = 7
}
static void ModuloLPreLoad(const uint8_t s[CRYPT_CURVE25519_SIGNLEN], uint64_t s21Bits[UINT8_64_21BITS_BLOCKNUM])
{
CURVE25519_BYTES3_LOAD(&s21Bits[0], s);
s21Bits[0] = s21Bits[0] & MASK_64_LOW21;
CURVE25519_BYTES4_LOAD(&s21Bits[1], s + 2); // 1: load 4 bytes form position 2
s21Bits[1] = MASK_64_LOW21 & (s21Bits[1] >> 5); // 1: 8 - ((3 * 8) mod 21) mod 8 = 5
CURVE25519_BYTES3_LOAD(&s21Bits[2], s + 5); // 2: load 3 bytes form position 5
s21Bits[2] = MASK_64_LOW21 & (s21Bits[2] >> 2); // 2: 8 - ((6 * 8) mod 21) mod 8 = 2
CURVE25519_BYTES4_LOAD(&s21Bits[3], s + 7); // 3: load 4 bytes form position 7
s21Bits[3] = MASK_64_LOW21 & (s21Bits[3] >> 7); // 3: 8 - ((8 * 8) mod 21) mod 8 = 7
CURVE25519_BYTES4_LOAD(&s21Bits[4], s + 10); // 4: load 4 bytes form position 10
s21Bits[4] = MASK_64_LOW21 & (s21Bits[4] >> 4); // 4: 8 - ((11 * 8) mod 21) mod 8 = 4
CURVE25519_BYTES3_LOAD(&s21Bits[5], s + 13); // 5: load 3 bytes form position 13
s21Bits[5] = MASK_64_LOW21 & (s21Bits[5] >> 1); // 5: 8 - ((14 * 8) mod 21) mod 8 = 1
CURVE25519_BYTES4_LOAD(&s21Bits[6], s + 15); // 6: load 4 bytes form position 15
s21Bits[6] = MASK_64_LOW21 & (s21Bits[6] >> 6); // 6: 8 - ((16 * 8) mod 21) mod 8 = 6
CURVE25519_BYTES3_LOAD(&s21Bits[7], s + 18); // 7: load 3 bytes form position 18
s21Bits[7] = MASK_64_LOW21 & (s21Bits[7] >> 3); // 7: 8 - ((19 * 8) mod 21) mod 8 = 3
CURVE25519_BYTES3_LOAD(&s21Bits[8], s + 21); // 8: load 3 bytes form position 21
s21Bits[8] = MASK_64_LOW21 & s21Bits[8]; // 8: ((22 * 8) mod 21) mod 8 = 0
CURVE25519_BYTES4_LOAD(&s21Bits[9], s + 23); // 9: load 4 bytes form position 23
s21Bits[9] = MASK_64_LOW21 & (s21Bits[9] >> 5); // 9: 8 - ((24 * 8) mod 21) mod 8 = 5
CURVE25519_BYTES3_LOAD(&s21Bits[10], s + 26); // 10: load 3 bytes form position 26
s21Bits[10] = MASK_64_LOW21 & (s21Bits[10] >> 2); // 10: 8 - ((27 * 8) mod 21) mod 8 = 2
CURVE25519_BYTES4_LOAD(&s21Bits[11], s + 28); // 11: load 4 bytes form position 28
s21Bits[11] = MASK_64_LOW21 & (s21Bits[11] >> 7); // 11: 8 - ((29 * 8) mod 21) mod 8 = 7
CURVE25519_BYTES4_LOAD(&s21Bits[12], s + 31); // 12: load 4 bytes form position 31
s21Bits[12] = MASK_64_LOW21 & (s21Bits[12] >> 4); // 12: 8 - ((32 * 8) mod 21) mod 8 = 4
CURVE25519_BYTES3_LOAD(&s21Bits[13], s + 34); // 13: load 3 bytes form position 34
s21Bits[13] = MASK_64_LOW21 & (s21Bits[13] >> 1); // 13: 8 - ((35 * 8) mod 21) mod 8 = 1
CURVE25519_BYTES4_LOAD(&s21Bits[14], s + 36); // 14: load 4 bytes form position 36
s21Bits[14] = MASK_64_LOW21 & (s21Bits[14] >> 6); // 14: 8 - ((37 * 8) mod 21) mod 8 = 6
CURVE25519_BYTES3_LOAD(&s21Bits[15], s + 39); // 15: load 3 bytes form position 39
s21Bits[15] = MASK_64_LOW21 & (s21Bits[15] >> 3); // 15: 8 - ((40 * 8) mod 21) mod 8 = 3
CURVE25519_BYTES3_LOAD(&s21Bits[16], s + 42); // 16: load 3 bytes form position 42
s21Bits[16] = MASK_64_LOW21 & s21Bits[16]; // 16: ((43 * 8) mod 21) mod 8 = 0
CURVE25519_BYTES4_LOAD(&s21Bits[17], s + 44); // 17: load 4 bytes form position 44
s21Bits[17] = MASK_64_LOW21 & (s21Bits[17] >> 5); // 17: 8 - ((45 * 8) mod 21) mod 8 = 5
CURVE25519_BYTES3_LOAD(&s21Bits[18], s + 47); // 18: load 3 bytes form position 47
s21Bits[18] = MASK_64_LOW21 & (s21Bits[18] >> 2); // 18: 8 - ((48 * 8) mod 21) mod 8 = 2
CURVE25519_BYTES4_LOAD(&s21Bits[19], s + 49); // 19: load 4 bytes form position 49
s21Bits[19] = MASK_64_LOW21 & (s21Bits[19] >> 7); // 19: 8 - ((50 * 8) mod 21) mod 8 = 7
CURVE25519_BYTES4_LOAD(&s21Bits[20], s + 52); // 20: load 4 bytes form position 52
s21Bits[20] = MASK_64_LOW21 & (s21Bits[20] >> 4); // 20: 8 - ((53 * 8) mod 21) mod 8 = 4
CURVE25519_BYTES3_LOAD(&s21Bits[21], s + 55); // 21: load 3 bytes form position 55
s21Bits[21] = MASK_64_LOW21 & (s21Bits[21] >> 1); // 21: 8 - ((56 * 8) mod 21) mod 8 = 1
CURVE25519_BYTES4_LOAD(&s21Bits[22], s + 57); // 22: load 4 bytes form position 57
s21Bits[22] = MASK_64_LOW21 & (s21Bits[22] >> 6); // 22: 8 - ((58 * 8) mod 21) mod 8 = 6
CURVE25519_BYTES4_LOAD(&s21Bits[23], s + 60); // 23: load 4 bytes form position 60
s21Bits[23] = s21Bits[23] >> 3; // 23: 8 - ((61 * 8) mod 21) mod 8 = 3
}
static void UnloadTo8Bits(uint8_t s8Bits[CRYPT_CURVE25519_OPTLEN], uint64_t s21Bits[UINT8_64_21BITS_BLOCKNUM])
{
s8Bits[0] = (uint8_t)s21Bits[0];
// 1: load from 8 on block 0
s8Bits[1] = (uint8_t)(s21Bits[0] >> 8);
// 2: load from (16 + 1) to 21 on block 0 and 1 to 3 on block 1, 8 - 3 = 5
s8Bits[2] = (uint8_t)((s21Bits[0] >> 16) | (s21Bits[1] << 5));
// 3: load from (3 + 1) on block 1
s8Bits[3] = (uint8_t)(s21Bits[1] >> 3);
// 4: load from (11 + 1) on block 1
s8Bits[4] = (uint8_t)(s21Bits[1] >> 11);
// 5: load from (19 + 1) to 21 on block 1 and 1 to 6 on block 2, 8 - 6 = 2
s8Bits[5] = (uint8_t)((s21Bits[1] >> 19) | (s21Bits[2] << 2));
// 6: load from (6 + 1) on block 2
s8Bits[6] = (uint8_t)(s21Bits[2] >> 6);
// 7: load from (14 + 1) to 21 on block 2 and 1 on block 3, 8 - 7 = 1
s8Bits[7] = (uint8_t)((s21Bits[2] >> 14) | (s21Bits[3] << 7));
// 8: load from (1 + 1) on block 3
s8Bits[8] = (uint8_t)(s21Bits[3] >> 1);
// 9: load from (9 + 1) on block 3
s8Bits[9] = (uint8_t)(s21Bits[3] >> 9);
// 10: load from (17 + 1) to 21 on block 3 and 1 to 4 on block 4, 8 - 4 = 4
s8Bits[10] = (uint8_t)((s21Bits[3] >> 17) | (s21Bits[4] << 4));
// 11: load from (4 + 1) on block 4
s8Bits[11] = (uint8_t)(s21Bits[4] >> 4);
// 12: load from (12 + 1) on block 4
s8Bits[12] = (uint8_t)(s21Bits[4] >> 12);
// 13: load from (20 + 1) on block 4 and 1 to 7 on block 5, 8 - 7 = 1
s8Bits[13] = (uint8_t)((s21Bits[4] >> 20) | (s21Bits[5] << 1));
// 14: load from (7 + 1) on block 5
s8Bits[14] = (uint8_t)(s21Bits[5] >> 7);
// 15: load from (15 + 1) to 21 on block 5 and 1 to 2 on block 6, 8 - 2 = 6
s8Bits[15] = (uint8_t)((s21Bits[5] >> 15) | (s21Bits[6] << 6));
// 16: load from (2 + 1) on block 6
s8Bits[16] = (uint8_t)(s21Bits[6] >> 2);
// 17: load from (10 + 1) on block 6
s8Bits[17] = (uint8_t)(s21Bits[6] >> 10);
// 18: load from (18 + 1) to 21 on block 6 and 1 to 5 on block 7, 8 - 5 = 3
s8Bits[18] = (uint8_t)((s21Bits[6] >> 18) | (s21Bits[7] << 3));
// 19: load from (5 + 1) on block 7
s8Bits[19] = (uint8_t)(s21Bits[7] >> 5);
// 20: load from (13 + 1) on block 7
s8Bits[20] = (uint8_t)(s21Bits[7] >> 13);
// 21: load 8bits on block 8
s8Bits[21] = (uint8_t)s21Bits[8];
// 22: load from (8 + 1) on block 8
s8Bits[22] = (uint8_t)(s21Bits[8] >> 8);
// 23: load from (16 + 1) to 21 on block 8 and 1 to 3 on block 9, 8 - 3 = 5
s8Bits[23] = (uint8_t)((s21Bits[8] >> 16) | (s21Bits[9] << 5));
// 24: load from (3 + 1) on block 9
s8Bits[24] = (uint8_t)(s21Bits[9] >> 3);
// 25: load from (11 + 1) on block 9
s8Bits[25] = (uint8_t)(s21Bits[9] >> 11);
// 26: load from (19 + 1) to 21 on block 9 and 1 to 6 on block 10, 8 - 6 = 2
s8Bits[26] = (uint8_t)((s21Bits[9] >> 19) | (s21Bits[10] << 2));
// 27: load from (6 + 1) on block 10
s8Bits[27] = (uint8_t)(s21Bits[10] >> 6);
// 28: load from (14 + 1) to 21 on block 10 and 1 on block 11, 8 - 7 = 1
s8Bits[28] = (uint8_t)((s21Bits[10] >> 14) | (s21Bits[11] << 7));
// 29: load from (1 + 1) on block 11
s8Bits[29] = (uint8_t)(s21Bits[11] >> 1);
// 30: load from (9 + 1) on block 11
s8Bits[30] = (uint8_t)(s21Bits[11] >> 9);
// 31: load from (17 + 1) on block 11
s8Bits[31] = (uint8_t)(s21Bits[11] >> 17);
}
static void ModuloLCore(uint64_t s21Bits[UINT8_64_21BITS_BLOCKNUM])
{
int32_t i;
uint64_t signMask1, signMask2;
uint64_t carry1, carry2;
// multiply by l0, start with {11, 12, 13, 14, 15, 16} to {6, 7, 8, 9, 10, 11, 12}
CURVE25519_MULTI_BY_L0(s21Bits, 11);
CURVE25519_MULTI_BY_L0(s21Bits, 10);
CURVE25519_MULTI_BY_L0(s21Bits, 9);
CURVE25519_MULTI_BY_L0(s21Bits, 8);
CURVE25519_MULTI_BY_L0(s21Bits, 7);
CURVE25519_MULTI_BY_L0(s21Bits, 6);
// need to process carry to prevent overflow, process carry from 6->7, 8->9 ... 16->17, increment by 2
for (i = 6; i <= 16; i += 2) {
// 21 bits minus sign is 20 bits
PROCESS_CARRY(s21Bits[i], s21Bits[i + 1], signMask1, carry1, 20);
}
// process carry from 7->8, 9->10 ... 15->16, increment by 2
for (i = 7; i <= 15; i += 2) {
// 21 bits minus sign bit is 20 bits
PROCESS_CARRY(s21Bits[i], s21Bits[i + 1], signMask2, carry2, 20);
}
// {5, 6, 7, 8, 9, 10} to {0, 1, 2, 3, 4, 5, 6}
CURVE25519_MULTI_BY_L0(s21Bits, 5);
CURVE25519_MULTI_BY_L0(s21Bits, 4);
CURVE25519_MULTI_BY_L0(s21Bits, 3);
CURVE25519_MULTI_BY_L0(s21Bits, 2);
CURVE25519_MULTI_BY_L0(s21Bits, 1);
CURVE25519_MULTI_BY_L0(s21Bits, 0);
// process carry again, from 0->1, 2->3 ... 10->11, increment by 2
for (i = 0; i <= 10; i += 2) {
// 21 bits minus sign bit is 20 bits
PROCESS_CARRY(s21Bits[i], s21Bits[i + 1], signMask1, carry1, 20);
}
// from 1->2, 3->4 ... 11->12, increment by 2
for (i = 1; i <= 11; i += 2) {
// 21 bits minus sign is 20 bits
PROCESS_CARRY(s21Bits[i], s21Bits[i + 1], signMask2, carry2, 20);
}
CURVE25519_MULTI_BY_L0(s21Bits, 0);
// process carry from 0 to 11
for (i = 0; i <= 11; i++) {
PROCESS_CARRY_UNSIGN(s21Bits[i], s21Bits[i + 1], signMask1, carry1, 21); // s21Bits is 21 bits
}
CURVE25519_MULTI_BY_L0(s21Bits, 0);
// from 0 to 10
for (i = 0; i <= 10; i++) {
PROCESS_CARRY_UNSIGN(s21Bits[i], s21Bits[i + 1], signMask1, carry1, 21); // s21Bits is 21 bits
}
}
void ModuloL(uint8_t s[CRYPT_CURVE25519_SIGNLEN])
{
// 24 of 21 bits block
uint64_t s21Bits[UINT8_64_21BITS_BLOCKNUM] = {0};
ModuloLPreLoad(s, s21Bits);
ModuloLCore(s21Bits);
UnloadTo8Bits(s, s21Bits);
}
static void MulAdd(uint64_t s21Bits[UINT8_64_21BITS_BLOCKNUM], const uint64_t a21Bits[UINT8_32_21BITS_BLOCKNUM],
const uint64_t b21Bits[UINT8_32_21BITS_BLOCKNUM], const uint64_t c21Bits[UINT8_32_21BITS_BLOCKNUM])
{
// s0 = c0 + a0b0
s21Bits[0] = c21Bits[0] + a21Bits[0] * b21Bits[0];
// s1 = c1 + a0b1 + a1b0
s21Bits[1] = c21Bits[1] + a21Bits[0] * b21Bits[1] + a21Bits[1] * b21Bits[0];
// s2 = c2 + a0b2 + b1a1 + a2b0
s21Bits[2] = c21Bits[2] + a21Bits[0] * b21Bits[2] + a21Bits[1] * b21Bits[1] + a21Bits[2] * b21Bits[0];
// s3 = c3 + a0b3 + a1b2 + a2b1 + a3b0
s21Bits[3] = c21Bits[3] + a21Bits[0] * b21Bits[3] + a21Bits[1] * b21Bits[2] +
a21Bits[2] * b21Bits[1] + a21Bits[3] * b21Bits[0]; // a2b1 + a3b0
// s4 = c4 + a0b4 +a1b3 + a2b2 + a3b1 + a4b0
s21Bits[4] = c21Bits[4] + a21Bits[0] * b21Bits[4] + a21Bits[1] * b21Bits[3] +
a21Bits[2] * b21Bits[2] + a21Bits[3] * b21Bits[1] + a21Bits[4] * b21Bits[0]; // a2b2 + a3b1 + a4b0
// s5 = c5 + a0b5 + a1b4 + a2b3 + a3b2 + a4b1 + a5b0
s21Bits[5] = c21Bits[5] + a21Bits[0] * b21Bits[5] + a21Bits[1] * b21Bits[4] + a21Bits[2] * b21Bits[3] +
a21Bits[3] * b21Bits[2] + a21Bits[4] * b21Bits[1] + a21Bits[5] * b21Bits[0]; // a3b2 + a4b1 + a5b0
// s6 = c6 + a0b6 + a1b5 + a2b4 + a3b3 + a2b4 + a5b1 + a6b0
s21Bits[6] = c21Bits[6] + a21Bits[0] * b21Bits[6] + a21Bits[1] * b21Bits[5] + a21Bits[2] * b21Bits[4] +
a21Bits[3] * b21Bits[3] + a21Bits[4] * b21Bits[2] + a21Bits[5] * b21Bits[1] + // a3b3 + a2b4 + a5b1
a21Bits[6] * b21Bits[0]; // a6b0
// s7 = c7 + a0b7 + a1b6 + a2b5 + a3b4 + a4b3 + a5b2 + a6b1 + a7b0
s21Bits[7] = c21Bits[7] + a21Bits[0] * b21Bits[7] + a21Bits[1] * b21Bits[6] + a21Bits[2] * b21Bits[5] +
a21Bits[3] * b21Bits[4] + a21Bits[4] * b21Bits[3] + a21Bits[5] * b21Bits[2] + // a3b4 + a4b3 + a5b2
a21Bits[6] * b21Bits[1] + a21Bits[7] * b21Bits[0]; // a6b1 + a7b0
// s8 = c8 + a0b8 + a1b7 + a2b6 + a3b5 + a4b4 + a5b3 + a6b2 + a7b1 + a8b0
s21Bits[8] = c21Bits[8] + a21Bits[0] * b21Bits[8] + a21Bits[1] * b21Bits[7] + a21Bits[2] * b21Bits[6] +
a21Bits[3] * b21Bits[5] + a21Bits[4] * b21Bits[4] + a21Bits[5] * b21Bits[3] + // a3b5 + a4b4 + a5b3
a21Bits[6] * b21Bits[2] + a21Bits[7] * b21Bits[1] + a21Bits[8] * b21Bits[0]; // a6b2 + a7b1 + a8b0
// s9 = c9 + a0b9 + a1b8 + a2b7 + a3b6 + a4b5 + a5b4 + a6b3 + a7b2 + a8b1 + a9b0
s21Bits[9] = c21Bits[9] + a21Bits[0] * b21Bits[9] + a21Bits[1] * b21Bits[8] + a21Bits[2] * b21Bits[7] +
a21Bits[3] * b21Bits[6] + a21Bits[4] * b21Bits[5] + a21Bits[5] * b21Bits[4] + // a3b6 + a4b5 + a5b4
a21Bits[6] * b21Bits[3] + a21Bits[7] * b21Bits[2] + a21Bits[8] * b21Bits[1] + // a6b3 + a7b2 + a8b1
a21Bits[9] * b21Bits[0]; // a9b0
// s10 = c10 + a0b10 + a1b9 + a2b8 + a3b7 + a4b6 + a5b5 + a6b4 + a7b3 + a8b2 + a9b1 + a10b0
s21Bits[10] = c21Bits[10] + a21Bits[0] * b21Bits[10] + a21Bits[1] * b21Bits[9] + a21Bits[2] * b21Bits[8] +
a21Bits[3] * b21Bits[7] + a21Bits[4] * b21Bits[6] + a21Bits[5] * b21Bits[5] + // a3b7 + a4b6 + a5b5
a21Bits[6] * b21Bits[4] + a21Bits[7] * b21Bits[3] + a21Bits[8] * b21Bits[2] + // a6b4 + a7b3 + a8b2
a21Bits[9] * b21Bits[1] + a21Bits[10] * b21Bits[0]; // a9b1 + a10b0
// s11 = c11 + a0b11 + a1b10 + a2b9 + a3b8 + a4b7 + a5b6 + a6b5 + a7b4 + a8b3 + a9b2 + a10b1 + a11b0
s21Bits[11] = c21Bits[11] + a21Bits[0] * b21Bits[11] + a21Bits[1] * b21Bits[10] + a21Bits[2] * b21Bits[9] +
a21Bits[3] * b21Bits[8] + a21Bits[4] * b21Bits[7] + a21Bits[5] * b21Bits[6] + // a3b8 + a4b7 + a5b6
a21Bits[6] * b21Bits[5] + a21Bits[7] * b21Bits[4] + a21Bits[8] * b21Bits[3] + // a6b5 + a7b4 + a8b3
a21Bits[9] * b21Bits[2] + a21Bits[10] * b21Bits[1] + a21Bits[11] * b21Bits[0]; // a9b2 + a10b1 + a11b0
// s12 = a1b11 + a2b10 + a3b9 + a4b8 + a5b7 + a6b6 + a7b5 + a8b4 + a9b3 + a10b2 + a11b1
s21Bits[12] = a21Bits[1] * b21Bits[11] + a21Bits[2] * b21Bits[10] + a21Bits[3] * b21Bits[9] +
a21Bits[4] * b21Bits[8] + a21Bits[5] * b21Bits[7] + a21Bits[6] * b21Bits[6] + // a4b8 + a5b7 + a6b6
a21Bits[7] * b21Bits[5] + a21Bits[8] * b21Bits[4] + a21Bits[9] * b21Bits[3] + // a7b5 + a8b4 + a9b3
a21Bits[10] * b21Bits[2] + a21Bits[11] * b21Bits[1]; // a10b2 + a11b1
// s13 = a2b11 + a3b10 + a4b9 + a5b8 + a6b7 + a7b6 + a8b5 + a9b4 + a10b3 + a11b2
s21Bits[13] = a21Bits[2] * b21Bits[11] + a21Bits[3] * b21Bits[10] + a21Bits[4] * b21Bits[9] +
a21Bits[5] * b21Bits[8] + a21Bits[6] * b21Bits[7] + a21Bits[7] * b21Bits[6] + // a5b8 + a6b7 + a7b6
a21Bits[8] * b21Bits[5] + a21Bits[9] * b21Bits[4] + a21Bits[10] * b21Bits[3] + // a8b5 + a9b4 + a10b3
a21Bits[11] * b21Bits[2]; // a11b2
// s14 = a3b11 + a4b10 + a5b9 + a6b8 + a7b7 + a8b6 + a9b5 + a10b4 + a11b3
s21Bits[14] = a21Bits[3] * b21Bits[11] + a21Bits[4] * b21Bits[10] + a21Bits[5] * b21Bits[9] +
a21Bits[6] * b21Bits[8] + a21Bits[7] * b21Bits[7] + a21Bits[8] * b21Bits[6] + // a6b8 + a7b7 + a8b6
a21Bits[9] * b21Bits[5] + a21Bits[10] * b21Bits[4] + a21Bits[11] * b21Bits[3]; // a9b5 + a10b4 + a11b3
// s15 = a4b11 + a5b10 + a6b9 + a7b8 + a8b7 + a9b6 + a10b5 + a11b4
s21Bits[15] = a21Bits[4] * b21Bits[11] + a21Bits[5] * b21Bits[10] + a21Bits[6] * b21Bits[9] +
a21Bits[7] * b21Bits[8] + a21Bits[8] * b21Bits[7] + a21Bits[9] * b21Bits[6] + // a7b8 + a8b7 + a9b6
a21Bits[10] * b21Bits[5] + a21Bits[11] * b21Bits[4]; // a10b5 + a11b4
// s16 = a5b11 + a6b10 + a7b9 + a8b8 + a9b7 + a10b6 + a11b5
s21Bits[16] = a21Bits[5] * b21Bits[11] + a21Bits[6] * b21Bits[10] + a21Bits[7] * b21Bits[9] +
a21Bits[8] * b21Bits[8] + a21Bits[9] * b21Bits[7] + a21Bits[10] * b21Bits[6] + // a8b8 + a9b7 + a10b6
a21Bits[11] * b21Bits[5]; // a11b5
// s17 = a6b11 + a7b10 + a8b9 + a9b8 + a10b7 + a11b6
s21Bits[17] = a21Bits[6] * b21Bits[11] + a21Bits[7] * b21Bits[10] + a21Bits[8] * b21Bits[9] +
a21Bits[9] * b21Bits[8] + a21Bits[10] * b21Bits[7] + a21Bits[11] * b21Bits[6]; // a9b8 + a10b7 + a11b6
// s18 = a7b11 + a8b10 + a9b9 + a10b8 + a11b7
s21Bits[18] = a21Bits[7] * b21Bits[11] + a21Bits[8] * b21Bits[10] + a21Bits[9] * b21Bits[9] +
a21Bits[10] * b21Bits[8] + a21Bits[11] * b21Bits[7]; // a10b8 + a11b7
// s19 = a8b11 + a9b10 + a10b9 + a11b8
s21Bits[19] = a21Bits[8] * b21Bits[11] + a21Bits[9] * b21Bits[10] + a21Bits[10] * b21Bits[9] +
a21Bits[11] * b21Bits[8]; // a11b8
// s20 = a9b11 + a10b10 + a11b9
s21Bits[20] = a21Bits[9] * b21Bits[11] + a21Bits[10] * b21Bits[10] + a21Bits[11] * b21Bits[9];
// s21 = a10b11 + a11b10
s21Bits[21] = a21Bits[10] * b21Bits[11] + a21Bits[11] * b21Bits[10];
// s22 = a11b11
s21Bits[22] = a21Bits[11] * b21Bits[11];
// s23 = 0
s21Bits[23] = 0;
}
void ScalarMulAdd(uint8_t s[CRYPT_CURVE25519_KEYLEN], const uint8_t a[CRYPT_CURVE25519_KEYLEN],
const uint8_t b[CRYPT_CURVE25519_KEYLEN], const uint8_t c[CRYPT_CURVE25519_KEYLEN])
{
uint64_t a21Bits[UINT8_32_21BITS_BLOCKNUM];
uint64_t b21Bits[UINT8_32_21BITS_BLOCKNUM];
uint64_t c21Bits[UINT8_32_21BITS_BLOCKNUM];
ScalarMulAddPreLoad(a, a21Bits);
ScalarMulAddPreLoad(b, b21Bits);
ScalarMulAddPreLoad(c, c21Bits);
uint64_t s21Bits[UINT8_64_21BITS_BLOCKNUM];
MulAdd(s21Bits, a21Bits, b21Bits, c21Bits);
int32_t i;
uint64_t signMask1, signMask2;
uint64_t carryA, carryB;
// process carry 0->1, 2->3 ... 22->23
for (i = 0; i <= 22; i += 2) {
// 21 bits minus sign bit is 20 bits
PROCESS_CARRY(s21Bits[i], s21Bits[i + 1], signMask1, carryA, 20);
}
// process carry 1->2, 3->4 ... 21->22
for (i = 1; i <= 21; i += 2) {
// 21 bits minus sign bit is 20 bits
PROCESS_CARRY(s21Bits[i], s21Bits[i + 1], signMask2, carryB, 20);
}
ModuloLCore(s21Bits);
UnloadTo8Bits(s, s21Bits);
}
/* RFC8032, out = a + b */
static void PointAdd(GeE *out, GeE *greA, GeE *greB)
{
const Fp25 d2 = {-21827239, -5839606, -30745221, 13898782, 229458,
15978800, -12551817, -6495438, 29715968, 9444199};
Fp25 a, b, c, d, e, f, g, h;
CURVE25519_FP_SUB(e, greA->y, greA->x);
CURVE25519_FP_SUB(f, greB->y, greB->x);
CURVE25519_FP_ADD(g, greA->y, greA->x);
CURVE25519_FP_ADD(h, greB->y, greB->x);
FpMul(a, e, f);
FpMul(b, g, h);
FpMul(c, greA->t, greB->t);
FpMul(c, c, d2);
FpMul(d, greA->z, greB->z);
CURVE25519_FP_ADD(d, d, d);
CURVE25519_FP_SUB(e, b, a);
CURVE25519_FP_SUB(f, d, c);
CURVE25519_FP_ADD(g, d, c);
CURVE25519_FP_ADD(h, b, a);
FpMul(out->x, e, f);
FpMul(out->y, g, h);
FpMul(out->z, f, g);
FpMul(out->t, e, h);
}
static void PointAddPrecompute(GeE *out, GeE *greA, GeEPre *greB)
{
Fp25 a, b, c, d, e, f, g, h;
CURVE25519_FP_SUB(e, greA->y, greA->x);
CURVE25519_FP_ADD(g, greA->y, greA->x);
FpMul(a, e, greB->yminusx);
FpMul(b, g, greB->yplusx);
FpMul(c, greA->t, greB->t2z);
FpMul(d, greA->z, greB->z);
CURVE25519_FP_ADD(d, d, d);
CURVE25519_FP_SUB(e, b, a);
CURVE25519_FP_SUB(f, d, c);
CURVE25519_FP_ADD(g, d, c);
CURVE25519_FP_ADD(h, b, a);
FpMul(out->x, e, f);
FpMul(out->y, g, h);
FpMul(out->z, f, g);
FpMul(out->t, e, h);
}
static void PointSubPrecompute(GeE *out, GeE *greA, GeEPre *greB)
{
Fp25 a, b, c, d, e, f, g, h;
CURVE25519_FP_SUB(e, greA->y, greA->x);
CURVE25519_FP_ADD(g, greA->y, greA->x);
FpMul(a, e, greB->yplusx);
FpMul(b, g, greB->yminusx);
FpMul(c, greA->t, greB->t2z);
FpMul(d, greA->z, greB->z);
CURVE25519_FP_ADD(d, d, d);
CURVE25519_FP_SUB(e, b, a);
CURVE25519_FP_ADD(f, d, c);
CURVE25519_FP_SUB(g, d, c);
CURVE25519_FP_ADD(h, b, a);
FpMul(out->x, e, f);
FpMul(out->y, g, h);
FpMul(out->z, f, g);
FpMul(out->t, e, h);
}
static void P1DoubleN(GeE *p1, int32_t n)
{
GeP p;
GeC c;
int32_t i;
// From extended coordinate to projective coordinate, just ignore T
CURVE25519_FP_COPY(p.x, p1->x);
CURVE25519_FP_COPY(p.y, p1->y);
CURVE25519_FP_COPY(p.z, p1->z);
ProjectiveDouble(&c, &p);
for (i = 1; i < n; i++) {
GeCompleteToProjective(&p, &c);
ProjectiveDouble(&c, &p);
}
FpMul(p1->x, c.t, c.x);
FpMul(p1->y, c.z, c.y);
FpMul(p1->z, c.t, c.z);
FpMul(p1->t, c.y, c.x);
}
static void PointToPrecompute(GeEPre *out, GeE *in)
{
const Fp25 d2 = {-21827239, -5839606, -30745221, 13898782, 229458,
15978800, -12551817, -6495438, 29715968, 9444199};
CURVE25519_FP_ADD(out->yplusx, in->y, in->x);
CURVE25519_FP_SUB(out->yminusx, in->y, in->x);
CURVE25519_FP_COPY(out->z, in->z);
FpMul(out->t2z, in->t, d2);
}
static void FlipK(int8_t slide[256], uint32_t start)
{
uint32_t k;
for (k = start; k < 256; k++) {
if (slide[k] == 0) {
slide[k] = 1;
break;
} else {
slide[k] = 0;
}
}
}
static void SlideReduce(int8_t *out, uint32_t outLen, const uint8_t *in, uint32_t inLen)
{
uint32_t i, j;
int8_t tmp;
(void)outLen;
(void)inLen;
// 32 * 8 = 256
for (i = 0; i < 256; i++) {
// turn 32 8bits to 256 1bit, block: in[i >> 3], bit: (i & 7)
out[i] = (int8_t)((in[i >> 3] >> (i & 7)) & 1);
}
// 32 * 8 = 256
for (i = 0; i < 256; i++) {
if (out[i] == 0) {
continue;
}
for (j = 1; j <= 6 && (i + j) < 256; j++) { // check next 6 since 2^6 - 2^5 = 16 > 15, 256 is array length
if (out[i + j] == 0) {
continue;
}
// range 15 to -15
tmp = (int8_t)((uint8_t)(out[i + j]) << j);
if (out[i] + tmp <= 15) { // max 15, 0x1, 0x1, 0x1, 0x1 , 0 -> 0x1111, 0, 0, 0, 0
out[i] += tmp;
out[i + j] = 0;
} else if (out[i] - tmp >= -15) { // min -15, 0x1111, 0, 0, 0, 1, 1 -> -1, 0, 0, 0, 0, 1
out[i] -= tmp;
FlipK(out, i + j);
} else {
break;
}
}
}
}
// Base on article "High-speed high-security signatures"
// stores B, 3B, 5B, 7B, 9B, 11B, 13B, 15B, with B as ed25519 base point
static const GePre g_precomputedB[8] = {
{
{25967493, -14356035, 29566456, 3660896, -12694345, 4014787, 27544626,
-11754271, -6079156, 2047605},
{-12545711, 934262, -2722910, 3049990, -727428, 9406986, 12720692,
5043384, 19500929, -15469378},
{-8738181, 4489570, 9688441, -14785194, 10184609, -12363380, 29287919,
11864899, -24514362, -4438546},
},
{
{15636291, -9688557, 24204773, -7912398, 616977, -16685262, 27787600,
-14772189, 28944400, -1550024},
{16568933, 4717097, -11556148, -1102322, 15682896, -11807043, 16354577,
-11775962, 7689662, 11199574},
{30464156, -5976125, -11779434, -15670865, 23220365, 15915852, 7512774,
10017326, -17749093, -9920357},
},
{
{10861363, 11473154, 27284546, 1981175, -30064349, 12577861, 32867885,
14515107, -15438304, 10819380},
{4708026, 6336745, 20377586, 9066809, -11272109, 6594696, -25653668,
12483688, -12668491, 5581306},
{19563160, 16186464, -29386857, 4097519, 10237984, -4348115, 28542350,
13850243, -23678021, -15815942},
},
{
{5153746, 9909285, 1723747, -2777874, 30523605, 5516873, 19480852,
5230134, -23952439, -15175766},
{-30269007, -3463509, 7665486, 10083793, 28475525, 1649722, 20654025,
16520125, 30598449, 7715701},
{28881845, 14381568, 9657904, 3680757, -20181635, 7843316, -31400660,
1370708, 29794553, -1409300},
},
{
{-22518993, -6692182, 14201702, -8745502, -23510406, 8844726, 18474211,
-1361450, -13062696, 13821877},
{-6455177, -7839871, 3374702, -4740862, -27098617, -10571707, 31655028,
-7212327, 18853322, -14220951},
{4566830, -12963868, -28974889, -12240689, -7602672, -2830569, -8514358,
-10431137, 2207753, -3209784},
},
{
{-25154831, -4185821, 29681144, 7868801, -6854661, -9423865, -12437364,
-663000, -31111463, -16132436},
{25576264, -2703214, 7349804, -11814844, 16472782, 9300885, 3844789,
15725684, 171356, 6466918},
{23103977, 13316479, 9739013, -16149481, 817875, -15038942, 8965339,
-14088058, -30714912, 16193877},
},
{
{-33521811, 3180713, -2394130, 14003687, -16903474, -16270840, 17238398,
4729455, -18074513, 9256800},
{-25182317, -4174131, 32336398, 5036987, -21236817, 11360617, 22616405,
9761698, -19827198, 630305},
{-13720693, 2639453, -24237460, -7406481, 9494427, -5774029, -6554551,
-15960994, -2449256, -14291300},
},
{
{-3151181, -5046075, 9282714, 6866145, -31907062, -863023, -18940575,
15033784, 25105118, -7894876},
{-24326370, 15950226, -31801215, -14592823, -11662737, -5090925,
1573892, -2625887, 2198790, -15804619},
{-3099351, 10324967, -2241613, 7453183, -5446979, -2735503, -13812022,
-16236442, -32461234, -12290683},
},
};
/* out = hash * p + s * B */
void KAMulPlusMulBase(GeE *out, const uint8_t hash[CRYPT_CURVE25519_KEYLEN],
const GeE *p, const uint8_t s[CRYPT_CURVE25519_KEYLEN])
{
SetExtendedBasePoint(out);
GeE tmpP[8]; // stores p, 3p, 5p, 7p, 9p, 11p, 13p, 15p
GeE doubleP;
GeEPre preComputedP[8]; // stores p, 3p, 5p, 7p, 9p, 11p, 13p, 15p
int8_t slideP[256];
int8_t slideS[256];
int32_t i;
SlideReduce(slideP, 256, hash, CRYPT_CURVE25519_KEYLEN);
SlideReduce(slideS, 256, s, CRYPT_CURVE25519_KEYLEN);
CURVE25519_GE_COPY(tmpP[0], *p);
CURVE25519_GE_COPY(doubleP, *p);
PointToPrecompute(&preComputedP[0], &tmpP[0]);
P1DoubleN(&doubleP, 1);
for (i = 1; i < 8; i += 1) { // p, 3p, ....., 13p, 15p, total 8
PointAdd(&tmpP[i], &tmpP[i - 1], &doubleP);
PointToPrecompute(&preComputedP[i], &tmpP[i]);
}
int32_t zeroCount = 0;
i = 255; // 255 to 0
while (i >= 0 && slideP[i] == 0 && slideS[i] == 0) {
i--;
}
for (; i >= 0; i--) {
while (i >= 0 && slideP[i] == 0 && slideS[i] == 0) {
zeroCount++;
i--;
}
if (i < 0) {
P1DoubleN(out, zeroCount);
break;
} else {
P1DoubleN(out, zeroCount + 1);
}
zeroCount = 0;
if (slideP[i] > 0) {
PointAddPrecompute(out, out, &preComputedP[slideP[i] / 2]); // preComputedP[i] = (i * 2 + 1)P
} else if (slideP[i] < 0) {
PointSubPrecompute(out, out, &preComputedP[(-slideP[i]) / 2]); // preComputedP[i] = (i * 2 + 1)P
}
if (slideS[i] > 0) {
GeAdd(out, &g_precomputedB[slideS[i] / 2]); // g_precomputedB[i] = (i * 2 + 1)P
} else if (slideS[i] < 0) {
GeSub(out, &g_precomputedB[(-slideS[i]) / 2]); // g_precomputedB[i] = (i * 2 + 1)P
}
}
}
#endif /* HITLS_CRYPTO_ED25519 */
#endif /* HITLS_CRYPTO_CURVE25519 */
|
2301_79861745/bench_create
|
crypto/curve25519/src/curve25519_op.c
|
C
|
unknown
| 60,542
|
/*
* 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.
*/
/* Some of these codes are adapted from https://ed25519.cr.yp.to/software.html */
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_CURVE25519
#include "curve25519_local.h"
/* lookup table that computing y-x, y+x and 2dxy, with 512 ^ n B, n starts from 0 */
/* table is generated base on article "High-speed high-security signatures" */
static const GePre CURVE25519PRE_COMPUTE[32][8] = {
{
{
{25967493, -14356035, 29566456, 3660896, -12694345, 4014787, 27544626, -11754271, -6079156, 2047605},
{-12545711, 934262, -2722910, 3049990, -727428, 9406986, 12720692, 5043384, 19500929, -15469378},
{-8738181, 4489570, 9688441, -14785194, 10184609, -12363380, 29287919, 11864899, -24514362, -4438546},
},
{
{-12815894, -12976347, -21581243, 11784320, -25355658, -2750717, -11717903, -3814571, -358445, -10211303},
{-21703237, 6903825, 27185491, 6451973, -29577724, -9554005, -15616551, 11189268, -26829678, -5319081},
{26966642, 11152617, 32442495, 15396054, 14353839, -12752335, -3128826, -9541118, -15472047, -4166697},
},
{
{15636291, -9688557, 24204773, -7912398, 616977, -16685262, 27787600, -14772189, 28944400, -1550024},
{16568933, 4717097, -11556148, -1102322, 15682896, -11807043, 16354577, -11775962, 7689662, 11199574},
{30464156, -5976125, -11779434, -15670865, 23220365, 15915852, 7512774, 10017326, -17749093, -9920357},
},
{
{-17036878, 13921892, 10945806, -6033431, 27105052, -16084379, -28926210, 15006023, 3284568, -6276540},
{23599295, -8306047, -11193664, -7687416, 13236774, 10506355, 7464579, 9656445, 13059162, 10374397},
{7798556, 16710257, 3033922, 2874086, 28997861, 2835604, 32406664, -3839045, -641708, -101325},
},
{
{10861363, 11473154, 27284546, 1981175, -30064349, 12577861, 32867885, 14515107, -15438304, 10819380},
{4708026, 6336745, 20377586, 9066809, -11272109, 6594696, -25653668, 12483688, -12668491, 5581306},
{19563160, 16186464, -29386857, 4097519, 10237984, -4348115, 28542350, 13850243, -23678021, -15815942},
},
{
{-15371964, -12862754, 32573250, 4720197, -26436522, 5875511, -19188627, -15224819, -9818940, -12085777},
{-8549212, 109983, 15149363, 2178705, 22900618, 4543417, 3044240, -15689887, 1762328, 14866737},
{-18199695, -15951423, -10473290, 1707278, -17185920, 3916101, -28236412, 3959421, 27914454, 4383652},
},
{
{5153746, 9909285, 1723747, -2777874, 30523605, 5516873, 19480852, 5230134, -23952439, -15175766},
{-30269007, -3463509, 7665486, 10083793, 28475525, 1649722, 20654025, 16520125, 30598449, 7715701},
{28881845, 14381568, 9657904, 3680757, -20181635, 7843316, -31400660, 1370708, 29794553, -1409300},
},
{
{14499471, -2729599, -33191113, -4254652, 28494862, 14271267, 30290735, 10876454, -33154098, 2381726},
{-7195431, -2655363, -14730155, 462251, -27724326, 3941372, -6236617, 3696005, -32300832, 15351955},
{27431194, 8222322, 16448760, -3907995, -18707002, 11938355, -32961401, -2970515, 29551813, 10109425},
},
},
{
{
{-13657040, -13155431, -31283750, 11777098, 21447386, 6519384, -2378284, -1627556, 10092783, -4764171},
{27939166, 14210322, 4677035, 16277044, -22964462, -12398139, -32508754, 12005538, -17810127, 12803510},
{17228999, -15661624, -1233527, 300140, -1224870, -11714777, 30364213, -9038194, 18016357, 4397660},
},
{
{-10958843, -7690207, 4776341, -14954238, 27850028, -15602212, -26619106, 14544525, -17477504, 982639},
{29253598, 15796703, -2863982, -9908884, 10057023, 3163536, 7332899, -4120128, -21047696, 9934963},
{5793303, 16271923, -24131614, -10116404, 29188560, 1206517, -14747930, 4559895, -30123922, -10897950},
},
{
{-27643952, -11493006, 16282657, -11036493, 28414021, -15012264, 24191034, 4541697, -13338309, 5500568},
{12650548, -1497113, 9052871, 11355358, -17680037, -8400164, -17430592, 12264343, 10874051, 13524335},
{25556948, -3045990, 714651, 2510400, 23394682, -10415330, 33119038, 5080568, -22528059, 5376628},
},
{
{-26088264, -4011052, -17013699, -3537628, -6726793, 1920897, -22321305, -9447443, 4535768, 1569007},
{-2255422, 14606630, -21692440, -8039818, 28430649, 8775819, -30494562, 3044290, 31848280, 12543772},
{-22028579, 2943893, -31857513, 6777306, 13784462, -4292203, -27377195, -2062731, 7718482, 14474653},
},
{
{2385315, 2454213, -22631320, 46603, -4437935, -15680415, 656965, -7236665, 24316168, -5253567},
{13741529, 10911568, -33233417, -8603737, -20177830, -1033297, 33040651, -13424532, -20729456, 8321686},
{21060490, -2212744, 15712757, -4336099, 1639040, 10656336, 23845965, -11874838, -9984458, 608372},
},
{
{-13672732, -15087586, -10889693, -7557059, -6036909, 11305547, 1123968, -6780577, 27229399, 23887},
{-23244140, -294205, -11744728, 14712571, -29465699, -2029617, 12797024, -6440308, -1633405, 16678954},
{-29500620, 4770662, -16054387, 14001338, 7830047, 9564805, -1508144, -4795045, -17169265, 4904953},
},
{
{24059557, 14617003, 19037157, -15039908, 19766093, -14906429, 5169211, 16191880, 2128236, -4326833},
{-16981152, 4124966, -8540610, -10653797, 30336522, -14105247, -29806336, 916033, -6882542, -2986532},
{-22630907, 12419372, -7134229, -7473371, -16478904, 16739175, 285431, 2763829, 15736322, 4143876},
},
{
{2379352, 11839345, -4110402, -5988665, 11274298, 794957, 212801, -14594663, 23527084, -16458268},
{33431127, -11130478, -17838966, -15626900, 8909499, 8376530, -32625340, 4087881, -15188911, -14416214},
{1767683, 7197987, -13205226, -2022635, -13091350, 448826, 5799055, 4357868, -4774191, -16323038},
},
},
{
{
{6721966, 13833823, -23523388, -1551314, 26354293, -11863321, 23365147, -3949732, 7390890, 2759800},
{4409041, 2052381, 23373853, 10530217, 7676779, -12885954, 21302353, -4264057, 1244380, -12919645},
{-4421239, 7169619, 4982368, -2957590, 30256825, -2777540, 14086413, 9208236, 15886429, 16489664},
},
{
{1996075, 10375649, 14346367, 13311202, -6874135, -16438411, -13693198, 398369, -30606455, -712933},
{-25307465, 9795880, -2777414, 14878809, -33531835, 14780363, 13348553, 12076947, -30836462, 5113182},
{-17770784, 11797796, 31950843, 13929123, -25888302, 12288344, -30341101, -7336386, 13847711, 5387222},
},
{
{-18582163, -3416217, 17824843, -2340966, 22744343, -10442611, 8763061, 3617786, -19600662, 10370991},
{20246567, -14369378, 22358229, -543712, 18507283, -10413996, 14554437, -8746092, 32232924, 16763880},
{9648505, 10094563, 26416693, 14745928, -30374318, -6472621, 11094161, 15689506, 3140038, -16510092},
},
{
{-16160072, 5472695, 31895588, 4744994, 8823515, 10365685, -27224800, 9448613, -28774454, 366295},
{19153450, 11523972, -11096490, -6503142, -24647631, 5420647, 28344573, 8041113, 719605, 11671788},
{8678025, 2694440, -6808014, 2517372, 4964326, 11152271, -15432916, -15266516, 27000813, -10195553},
},
{
{-15157904, 7134312, 8639287, -2814877, -7235688, 10421742, 564065, 5336097, 6750977, -14521026},
{11836410, -3979488, 26297894, 16080799, 23455045, 15735944, 1695823, -8819122, 8169720, 16220347},
{-18115838, 8653647, 17578566, -6092619, -8025777, -16012763, -11144307, -2627664, -5990708, -14166033},
},
{
{-23308498, -10968312, 15213228, -10081214, -30853605, -11050004, 27884329, 2847284, 2655861, 1738395},
{-27537433, -14253021, -25336301, -8002780, -9370762, 8129821, 21651608, -3239336, -19087449, -11005278},
{1533110, 3437855, 23735889, 459276, 29970501, 11335377, 26030092, 5821408, 10478196, 8544890},
},
{
{32173121, -16129311, 24896207, 3921497, 22579056, -3410854, 19270449, 12217473, 17789017, -3395995},
{-30552961, -2228401, -15578829, -10147201, 13243889, 517024, 15479401, -3853233, 30460520, 1052596},
{-11614875, 13323618, 32618793, 8175907, -15230173, 12596687, 27491595, -4612359, 3179268, -9478891},
},
{
{31947069, -14366651, -4640583, -15339921, -15125977, -6039709, -14756777, -16411740, 19072640, -9511060},
{11685058, 11822410, 3158003, -13952594, 33402194, -4165066, 5977896, -5215017, 473099, 5040608},
{-20290863, 8198642, -27410132, 11602123, 1290375, -2799760, 28326862, 1721092, -19558642, -3131606},
},
},
{
{
{7881532, 10687937, 7578723, 7738378, -18951012, -2553952, 21820786, 8076149, -27868496, 11538389},
{-19935666, 3899861, 18283497, -6801568, -15728660, -11249211, 8754525, 7446702, -5676054, 5797016},
{-11295600, -3793569, -15782110, -7964573, 12708869, -8456199, 2014099, -9050574, -2369172, -5877341},
},
{
{-22472376, -11568741, -27682020, 1146375, 18956691, 16640559, 1192730, -3714199, 15123619, 10811505},
{14352098, -3419715, -18942044, 10822655, 32750596, 4699007, -70363, 15776356, -28886779, -11974553},
{-28241164, -8072475, -4978962, -5315317, 29416931, 1847569, -20654173, -16484855, 4714547, -9600655},
},
{
{15200332, 8368572, 19679101, 15970074, -31872674, 1959451, 24611599, -4543832, -11745876, 12340220},
{12876937, -10480056, 33134381, 6590940, -6307776, 14872440, 9613953, 8241152, 15370987, 9608631},
{-4143277, -12014408, 8446281, -391603, 4407738, 13629032, -7724868, 15866074, -28210621, -8814099},
},
{
{26660628, -15677655, 8393734, 358047, -7401291, 992988, -23904233, 858697, 20571223, 8420556},
{14620715, 13067227, -15447274, 8264467, 14106269, 15080814, 33531827, 12516406, -21574435, -12476749},
{236881, 10476226, 57258, -14677024, 6472998, 2466984, 17258519, 7256740, 8791136, 15069930},
},
{
{1276410, -9371918, 22949635, -16322807, -23493039, -5702186, 14711875, 4874229, -30663140, -2331391},
{5855666, 4990204, -13711848, 7294284, -7804282, 1924647, -1423175, -7912378, -33069337, 9234253},
{20590503, -9018988, 31529744, -7352666, -2706834, 10650548, 31559055, -11609587, 18979186, 13396066},
},
{
{24474287, 4968103, 22267082, 4407354, 24063882, -8325180, -18816887, 13594782, 33514650, 7021958},
{-11566906, -6565505, -21365085, 15928892, -26158305, 4315421, -25948728, -3916677, -21480480, 12868082},
{-28635013, 13504661, 19988037, -2132761, 21078225, 6443208, -21446107, 2244500, -12455797, -8089383},
},
{
{-30595528, 13793479, -5852820, 319136, -25723172, -6263899, 33086546, 8957937, -15233648, 5540521},
{-11630176, -11503902, -8119500, -7643073, 2620056, 1022908, -23710744, -1568984, -16128528, -14962807},
{23152971, 775386, 27395463, 14006635, -9701118, 4649512, 1689819, 892185, -11513277, -15205948},
},
{
{9770129, 9586738, 26496094, 4324120, 1556511, -3550024, 27453819, 4763127, -19179614, 5867134},
{-32765025, 1927590, 31726409, -4753295, 23962434, -16019500, 27846559, 5931263, -29749703, -16108455},
{27461885, -2977536, 22380810, 1815854, -23033753, -3031938, 7283490, -15148073, -19526700, 7734629},
},
},
{
{
{-8010264, -9590817, -11120403, 6196038, 29344158, -13430885, 7585295, -3176626, 18549497, 15302069},
{-32658337, -6171222, -7672793, -11051681, 6258878, 13504381, 10458790, -6418461, -8872242, 8424746},
{24687205, 8613276, -30667046, -3233545, 1863892, -1830544, 19206234, 7134917, -11284482, -828919},
},
{
{11334899, -9218022, 8025293, 12707519, 17523892, -10476071, 10243738, -14685461, -5066034, 16498837},
{8911542, 6887158, -9584260, -6958590, 11145641, -9543680, 17303925, -14124238, 6536641, 10543906},
{-28946384, 15479763, -17466835, 568876, -1497683, 11223454, -2669190, -16625574, -27235709, 8876771},
},
{
{-25742899, -12566864, -15649966, -846607, -33026686, -796288, -33481822, 15824474, -604426, -9039817},
{10330056, 70051, 7957388, -9002667, 9764902, 15609756, 27698697, -4890037, 1657394, 3084098},
{10477963, -7470260, 12119566, -13250805, 29016247, -5365589, 31280319, 14396151, -30233575, 15272409},
},
{
{-12288309, 3169463, 28813183, 16658753, 25116432, -5630466, -25173957, -12636138, -25014757, 1950504},
{-26180358, 9489187, 11053416, -14746161, -31053720, 5825630, -8384306, -8767532, 15341279, 8373727},
{28685821, 7759505, -14378516, -12002860, -31971820, 4079242, 298136, -10232602, -2878207, 15190420},
},
{
{-32932876, 13806336, -14337485, -15794431, -24004620, 10940928, 8669718, 2742393, -26033313, -6875003},
{-1580388, -11729417, -25979658, -11445023, -17411874, -10912854, 9291594, -16247779, -12154742, 6048605},
{-30305315, 14843444, 1539301, 11864366, 20201677, 1900163, 13934231, 5128323, 11213262, 9168384},
},
{
{-26280513, 11007847, 19408960, -940758, -18592965, -4328580, -5088060, -11105150, 20470157, -16398701},
{-23136053, 9282192, 14855179, -15390078, -7362815, -14408560, -22783952, 14461608, 14042978, 5230683},
{29969567, -2741594, -16711867, -8552442, 9175486, -2468974, 21556951, 3506042, -5933891, -12449708},
},
{
{-3144746, 8744661, 19704003, 4581278, -20430686, 6830683, -21284170, 8971513, -28539189, 15326563},
{-19464629, 10110288, -17262528, -3503892, -23500387, 1355669, -15523050, 15300988, -20514118, 9168260},
{-5353335, 4488613, -23803248, 16314347, 7780487, -15638939, -28948358, 9601605, 33087103, -9011387},
},
{
{-19443170, -15512900, -20797467, -12445323, -29824447, 10229461,
-27444329, -15000531, -5996870, 15664672},
{23294591, -16632613, -22650781, -8470978, 27844204, 11461195, 13099750, -2460356, 18151676, 13417686},
{-24722913, -4176517, -31150679, 5988919, -26858785, 6685065, 1661597, -12551441, 15271676, -15452665},
},
},
{
{
{11433042, -13228665, 8239631, -5279517, -1985436, -725718, -18698764, 2167544, -6921301, -13440182},
{-31436171, 15575146, 30436815, 12192228, -22463353, 9395379, -9917708, -8638997, 12215110, 12028277},
{14098400, 6555944, 23007258, 5757252, -15427832, -12950502, 30123440, 4617780, -16900089, -655628},
},
{
{-4026201, -15240835, 11893168, 13718664, -14809462, 1847385, -15819999, 10154009, 23973261, -12684474},
{-26531820, -3695990, -1908898, 2534301, -31870557, -16550355, 18341390, -11419951, 32013174, -10103539},
{-25479301, 10876443, -11771086, -14625140, -12369567, 1838104, 21911214, 6354752, 4425632, -837822},
},
{
{-10433389, -14612966, 22229858, -3091047, -13191166, 776729, -17415375, -12020462, 4725005, 14044970},
{19268650, -7304421, 1555349, 8692754, -21474059, -9910664, 6347390, -1411784, -19522291, -16109756},
{-24864089, 12986008, -10898878, -5558584, -11312371, -148526, 19541418, 8180106, 9282262, 10282508},
},
{
{-26205082, 4428547, -8661196, -13194263, 4098402, -14165257, 15522535, 8372215, 5542595, -10702683},
{-10562541, 14895633, 26814552, -16673850, -17480754, -2489360, -2781891, 6993761, -18093885, 10114655},
{-20107055, -929418, 31422704, 10427861, -7110749, 6150669, -29091755, -11529146, 25953725, -106158},
},
{
{-4234397, -8039292, -9119125, 3046000, 2101609, -12607294, 19390020, 6094296, -3315279, 12831125},
{-15998678, 7578152, 5310217, 14408357, -33548620, -224739, 31575954, 6326196, 7381791, -2421839},
{-20902779, 3296811, 24736065, -16328389, 18374254, 7318640, 6295303, 8082724, -15362489, 12339664},
},
{
{27724736, 2291157, 6088201, -14184798, 1792727, 5857634, 13848414, 15768922, 25091167, 14856294},
{-18866652, 8331043, 24373479, 8541013, -701998, -9269457, 12927300, -12695493, -22182473, -9012899},
{-11423429, -5421590, 11632845, 3405020, 30536730, -11674039, -27260765, 13866390, 30146206, 9142070},
},
{
{3924129, -15307516, -13817122, -10054960, 12291820, -668366, -27702774, 9326384, -8237858, 4171294},
{-15921940, 16037937, 6713787, 16606682, -21612135, 2790944, 26396185, 3731949, 345228, -5462949},
{-21327538, 13448259, 25284571, 1143661, 20614966, -8849387, 2031539, -12391231, -16253183, -13582083},
},
{
{31016211, -16722429, 26371392, -14451233, -5027349, 14854137, 17477601, 3842657, 28012650, -16405420},
{-5075835, 9368966, -8562079, -4600902, -15249953, 6970560, -9189873, 16292057, -8867157, 3507940},
{29439664, 3537914, 23333589, 6997794, -17555561, -11018068, -15209202, -15051267, -9164929, 6580396},
},
},
{
{
{-12185861, -7679788, 16438269, 10826160, -8696817, -6235611, 17860444, -9273846, -2095802, 9304567},
{20714564, -4336911, 29088195, 7406487, 11426967, -5095705, 14792667, -14608617, 5289421, -477127},
{-16665533, -10650790, -6160345, -13305760, 9192020, -1802462, 17271490, 12349094, 26939669, -3752294},
},
{
{-12889898, 9373458, 31595848, 16374215, 21471720, 13221525, -27283495, -12348559, -3698806, 117887},
{22263325, -6560050, 3984570, -11174646, -15114008, -566785, 28311253, 5358056, -23319780, 541964},
{16259219, 3261970, 2309254, -15534474, -16885711, -4581916, 24134070, -16705829, -13337066, -13552195},
},
{
{9378160, -13140186, -22845982, -12745264, 28198281, -7244098, -2399684, -717351, 690426, 14876244},
{24977353, -314384, -8223969, -13465086, 28432343, -1176353, -13068804, -12297348, -22380984, 6618999},
{-1538174, 11685646, 12944378, 13682314, -24389511, -14413193, 8044829, -13817328, 32239829, -5652762},
},
{
{-18603066, 4762990, -926250, 8885304, -28412480, -3187315, 9781647, -10350059, 32779359, 5095274},
{-33008130, -5214506, -32264887, -3685216, 9460461, -9327423, -24601656, 14506724, 21639561, -2630236},
{-16400943, -13112215, 25239338, 15531969, 3987758, -4499318, -1289502, -6863535, 17874574, 558605},
},
{
{-13600129, 10240081, 9171883, 16131053, -20869254, 9599700, 33499487, 5080151, 2085892, 5119761},
{-22205145, -2519528, -16381601, 414691, -25019550, 2170430, 30634760, -8363614, -31999993, -5759884},
{-6845704, 15791202, 8550074, -1312654, 29928809, -12092256, 27534430, -7192145, -22351378, 12961482},
},
{
{-24492060, -9570771, 10368194, 11582341, -23397293, -2245287, 16533930, 8206996, -30194652, -5159638},
{-11121496, -3382234, 2307366, 6362031, -135455, 8868177, -16835630, 7031275, 7589640, 8945490},
{-32152748, 8917967, 6661220, -11677616, -1192060, -15793393, 7251489, -11182180, 24099109, -14456170},
},
{
{5019558, -7907470, 4244127, -14714356, -26933272, 6453165, -19118182, -13289025, -6231896, -10280736},
{10853594, 10721687, 26480089, 5861829, -22995819, 1972175, -1866647, -10557898, -3363451, -6441124},
{-17002408, 5906790, 221599, -6563147, 7828208, -13248918, 24362661, -2008168, -13866408, 7421392},
},
{
{8139927, -6546497, 32257646, -5890546, 30375719, 1886181, -21175108, 15441252, 28826358, -4123029},
{6267086, 9695052, 7709135, -16603597, -32869068, -1886135, 14795160, -7840124, 13746021, -1742048},
{28584902, 7787108, -6732942, -15050729, 22846041, -7571236, -3181936, -363524, 4771362, -8419958},
},
},
{
{
{24949256, 6376279, -27466481, -8174608, -18646154, -9930606, 33543569, -12141695, 3569627, 11342593},
{26514989, 4740088, 27912651, 3697550, 19331575, -11472339, 6809886, 4608608, 7325975, -14801071},
{-11618399, -14554430, -24321212, 7655128, -1369274, 5214312, -27400540, 10258390, -17646694, -8186692},
},
{
{11431204, 15823007, 26570245, 14329124, 18029990, 4796082, -31446179, 15580664, 9280358, -3973687},
{-160783, -10326257, -22855316, -4304997, -20861367, -13621002, -32810901, -11181622, -15545091, 4387441},
{-20799378, 12194512, 3937617, -5805892, -27154820, 9340370, -24513992, 8548137, 20617071, -7482001},
},
{
{-938825, -3930586, -8714311, 16124718, 24603125, -6225393, -13775352, -11875822, 24345683, 10325460},
{-19855277, -1568885, -22202708, 8714034, 14007766, 6928528, 16318175, -1010689, 4766743, 3552007},
{-21751364, -16730916, 1351763, -803421, -4009670, 3950935, 3217514, 14481909, 10988822, -3994762},
},
{
{15564307, -14311570, 3101243, 5684148, 30446780, -8051356, 12677127, -6505343, -8295852, 13296005},
{-9442290, 6624296, -30298964, -11913677, -4670981, -2057379, 31521204, 9614054, -30000824, 12074674},
{4771191, -135239, 14290749, -13089852, 27992298, 14998318, -1413936, -1556716, 29832613, -16391035},
},
{
{7064884, -7541174, -19161962, -5067537, -18891269, -2912736, 25825242, 5293297, -27122660, 13101590},
{-2298563, 2439670, -7466610, 1719965, -27267541, -16328445, 32512469, -5317593, -30356070, -4190957},
{-30006540, 10162316, -33180176, 3981723, -16482138, -13070044, 14413974, 9515896, 19568978, 9628812},
},
{
{33053803, 199357, 15894591, 1583059, 27380243, -4580435, -17838894, -6106839, -6291786, 3437740},
{-18978877, 3884493, 19469877, 12726490, 15913552, 13614290, -22961733, 70104, 7463304, 4176122},
{-27124001, 10659917, 11482427, -16070381, 12771467, -6635117, -32719404, -5322751, 24216882, 5944158},
},
{
{8894125, 7450974, -2664149, -9765752, -28080517, -12389115, 19345746, 14680796, 11632993, 5847885},
{26942781, -2315317, 9129564, -4906607, 26024105, 11769399, -11518837, 6367194, -9727230, 4782140},
{19916461, -4828410, -22910704, -11414391, 25606324, -5972441, 33253853, 8220911, 6358847, -1873857},
},
{
{801428, -2081702, 16569428, 11065167, 29875704, 96627, 7908388, -4480480, -13538503, 1387155},
{19646058, 5720633, -11416706, 12814209, 11607948, 12749789, 14147075, 15156355, -21866831, 11835260},
{19299512, 1155910, 28703737, 14890794, 2925026, 7269399, 26121523, 15467869, -26560550, 5052483},
},
},
{
{
{-3017432, 10058206, 1980837, 3964243, 22160966, 12322533, -6431123, -12618185, 12228557, -7003677},
{32944382, 14922211, -22844894, 5188528, 21913450, -8719943, 4001465, 13238564, -6114803, 8653815},
{22865569, -4652735, 27603668, -12545395, 14348958, 8234005, 24808405, 5719875, 28483275, 2841751},
},
{
{-16420968, -1113305, -327719, -12107856, 21886282, -15552774, -1887966, -315658, 19932058, -12739203},
{-11656086, 10087521, -8864888, -5536143, -19278573, -3055912, 3999228, 13239134, -4777469, -13910208},
{1382174, -11694719, 17266790, 9194690, -13324356, 9720081, 20403944, 11284705, -14013818, 3093230},
},
{
{16650921, -11037932, -1064178, 1570629, -8329746, 7352753, -302424, 16271225, -24049421, -6691850},
{-21911077, -5927941, -4611316, -5560156, -31744103, -10785293, 24123614, 15193618, -21652117, -16739389},
{-9935934, -4289447, -25279823, 4372842, 2087473, 10399484, 31870908, 14690798, 17361620, 11864968},
},
{
{-11307610, 6210372, 13206574, 5806320, -29017692, -13967200, -12331205, -7486601, -25578460, -16240689},
{14668462, -12270235, 26039039, 15305210, 25515617, 4542480, 10453892, 6577524, 9145645, -6443880},
{5974874, 3053895, -9433049, -10385191, -31865124, 3225009, -7972642, 3936128, -5652273, -3050304},
},
{
{30625386, -4729400, -25555961, -12792866, -20484575, 7695099, 17097188, -16303496, -27999779, 1803632},
{-3553091, 9865099, -5228566, 4272701, -5673832, -16689700, 14911344, 12196514, -21405489, 7047412},
{20093277, 9920966, -11138194, -5343857, 13161587, 12044805, -32856851, 4124601, -32343828, -10257566},
},
{
{-20788824, 14084654, -13531713, 7842147, 19119038, -13822605, 4752377, -8714640, -21679658, 2288038},
{-26819236, -3283715, 29965059, 3039786, -14473765, 2540457, 29457502, 14625692, -24819617, 12570232},
{-1063558, -11551823, 16920318, 12494842, 1278292, -5869109, -21159943, -3498680, -11974704, 4724943},
},
{
{17960970, -11775534, -4140968, -9702530, -8876562, -1410617, -12907383, -8659932, -29576300, 1903856},
{23134274, -14279132, -10681997, -1611936, 20684485, 15770816, -12989750, 3190296, 26955097, 14109738},
{15308788, 5320727, -30113809, -14318877, 22902008, 7767164, 29425325, -11277562, 31960942, 11934971},
},
{
{-27395711, 8435796, 4109644, 12222639, -24627868, 14818669, 20638173, 4875028, 10491392, 1379718},
{-13159415, 9197841, 3875503, -8936108, -1383712, -5879801, 33518459, 16176658, 21432314, 12180697},
{-11787308, 11500838, 13787581, -13832590, -22430679, 10140205, 1465425, 12689540, -10301319, -13872883},
},
},
{
{
{5414091, -15386041, -21007664, 9643570, 12834970, 1186149, -2622916, -1342231, 26128231, 6032912},
{-26337395, -13766162, 32496025, -13653919, 17847801, -12669156, 3604025, 8316894, -25875034, -10437358},
{3296484, 6223048, 24680646, -12246460, -23052020, 5903205, -8862297, -4639164, 12376617, 3188849},
},
{
{29190488, -14659046, 27549113, -1183516, 3520066, -10697301, 32049515, -7309113, -16109234, -9852307},
{-14744486, -9309156, 735818, -598978, -20407687, -5057904, 25246078, -15795669, 18640741, -960977},
{-6928835, -16430795, 10361374, 5642961, 4910474, 12345252, -31638386, -494430, 10530747, 1053335},
},
{
{-29265967, -14186805, -13538216, -12117373, -19457059,
-10655384, -31462369, -2948985, 24018831, 15026644},
{-22592535, -3145277, -2289276, 5953843, -13440189, 9425631, 25310643, 13003497, -2314791, -15145616},
{-27419985, -603321, -8043984, -1669117, -26092265, 13987819, -27297622, 187899, -23166419, -2531735},
},
{
{-21744398, -13810475, 1844840, 5021428, -10434399, -15911473, 9716667, 16266922, -5070217, 726099},
{29370922, -6053998, 7334071, -15342259, 9385287, 2247707, -13661962, -4839461, 30007388, -15823341},
{-936379, 16086691, 23751945, -543318, -1167538, -5189036, 9137109, 730663, 9835848, 4555336},
},
{
{-23376435, 1410446, -22253753, -12899614, 30867635, 15826977, 17693930, 544696, -11985298, 12422646},
{31117226, -12215734, -13502838, 6561947, -9876867, -12757670, -5118685, -4096706, 29120153, 13924425},
{-17400879, -14233209, 19675799, -2734756, -11006962, -5858820, -9383939, -11317700, 7240931, -237388},
},
{
{-31361739, -11346780, -15007447, -5856218, -22453340, -12152771, 1222336, 4389483, 3293637, -15551743},
{-16684801, -14444245, 11038544, 11054958, -13801175, -3338533, -24319580, 7733547, 12796905, -6335822},
{-8759414, -10817836, -25418864, 10783769, -30615557, -9746811, -28253339, 3647836, 3222231, -11160462},
},
{
{18606113, 1693100, -25448386, -15170272, 4112353, 10045021, 23603893, -2048234, -7550776, 2484985},
{9255317, -3131197, -12156162, -1004256, 13098013, -9214866, 16377220, -2102812, -19802075, -3034702},
{-22729289, 7496160, -5742199, 11329249, 19991973, -3347502, -31718148, 9936966, -30097688, -10618797},
},
{
{21878590, -5001297, 4338336, 13643897, -3036865, 13160960, 19708896, 5415497, -7360503, -4109293},
{27736861, 10103576, 12500508, 8502413, -3413016, -9633558, 10436918, -1550276, -23659143, -8132100},
{19492550, -12104365, -29681976, -852630, -3208171, 12403437, 30066266, 8367329, 13243957, 8709688},
},
},
{
{
{12015105, 2801261, 28198131, 10151021, 24818120, -4743133, -11194191, -5645734, 5150968, 7274186},
{2831366, -12492146, 1478975, 6122054, 23825128, -12733586, 31097299, 6083058, 31021603, -9793610},
{-2529932, -2229646, 445613, 10720828, -13849527, -11505937, -23507731, 16354465, 15067285, -14147707},
},
{
{7840942, 14037873, -33364863, 15934016, -728213, -3642706, 21403988, 1057586, -19379462, -12403220},
{915865, -16469274, 15608285, -8789130, -24357026, 6060030, -17371319, 8410997, -7220461, 16527025},
{32922597, -556987, 20336074, -16184568, 10903705, -5384487, 16957574, 52992, 23834301, 6588044},
},
{
{32752030, 11232950, 3381995, -8714866, 22652988, -10744103, 17159699, 16689107, -20314580, -1305992},
{-4689649, 9166776, -25710296, -10847306, 11576752, 12733943, 7924251, -2752281, 1976123, -7249027},
{21251222, 16309901, -2983015, -6783122, 30810597, 12967303, 156041, -3371252, 12331345, -8237197},
},
{
{8651614, -4477032, -16085636, -4996994, 13002507, 2950805, 29054427, -5106970, 10008136, -4667901},
{31486080, 15114593, -14261250, 12951354, 14369431, -7387845, 16347321, -13662089, 8684155, -10532952},
{19443825, 11385320, 24468943, -9659068, -23919258, 2187569, -26263207, -6086921, 31316348, 14219878},
},
{
{-28594490, 1193785, 32245219, 11392485, 31092169, 15722801, 27146014, 6992409, 29126555, 9207390},
{32382935, 1110093, 18477781, 11028262, -27411763, -7548111, -4980517, 10843782, -7957600, -14435730},
{2814918, 7836403, 27519878, -7868156, -20894015, -11553689, -21494559, 8550130, 28346258, 1994730},
},
{
{-19578299, 8085545, -14000519, -3948622, 2785838, -16231307, -19516951, 7174894, 22628102, 8115180},
{-30405132, 955511, -11133838, -15078069, -32447087, -13278079, -25651578, 3317160, -9943017, 930272},
{-15303681, -6833769, 28856490, 1357446, 23421993, 1057177, 24091212, -1388970, -22765376, -10650715},
},
{
{-22751231, -5303997, -12907607, -12768866, -15811511, -7797053, -14839018, -16554220, -1867018, 8398970},
{-31969310, 2106403, -4736360, 1362501, 12813763, 16200670, 22981545, -6291273, 18009408, -15772772},
{-17220923, -9545221, -27784654, 14166835, 29815394, 7444469, 29551787, -3727419, 19288549, 1325865},
},
{
{15100157, -15835752, -23923978, -1005098, -26450192, 15509408, 12376730, -3479146, 33166107, -8042750},
{20909231, 13023121, -9209752, 16251778, -5778415, -8094914, 12412151, 10018715, 2213263, -13878373},
{32529814, -11074689, 30361439, -16689753, -9135940, 1513226, 22922121, 6382134, -5766928, 8371348},
},
},
{
{
{9923462, 11271500, 12616794, 3544722, -29998368, -1721626, 12891687, -8193132, -26442943, 10486144},
{-22597207, -7012665, 8587003, -8257861, 4084309, -12970062, 361726, 2610596, -23921530, -11455195},
{5408411, -1136691, -4969122, 10561668, 24145918, 14240566, 31319731, -4235541, 19985175, -3436086},
},
{
{-13994457, 16616821, 14549246, 3341099, 32155958, 13648976, -17577068, 8849297, 65030, 8370684},
{-8320926, -12049626, 31204563, 5839400, -20627288, -1057277, -19442942, 6922164, 12743482, -9800518},
{-2361371, 12678785, 28815050, 4759974, -23893047, 4884717, 23783145, 11038569, 18800704, 255233},
},
{
{-5269658, -1773886, 13957886, 7990715, 23132995, 728773, 13393847, 9066957, 19258688, -14753793},
{-2936654, -10827535, -10432089, 14516793, -3640786, 4372541, -31934921, 2209390, -1524053, 2055794},
{580882, 16705327, 5468415, -2683018, -30926419, -14696000, -7203346, -8994389, -30021019, 7394435},
},
{
{23838809, 1822728, -15738443, 15242727, 8318092, -3733104, -21672180, -3492205, -4821741, 14799921},
{13345610, 9759151, 3371034, -16137791, 16353039, 8577942, 31129804, 13496856, -9056018, 7402518},
{2286874, -4435931, -20042458, -2008336, -13696227, 5038122, 11006906, -15760352, 8205061, 1607563},
},
{
{14414086, -8002132, 3331830, -3208217, 22249151, -5594188, 18364661, -2906958, 30019587, -9029278},
{-27688051, 1585953, -10775053, 931069, -29120221, -11002319, -14410829, 12029093, 9944378, 8024},
{4368715, -3709630, 29874200, -15022983, -20230386, -11410704, -16114594, -999085, -8142388, 5640030},
},
{
{10299610, 13746483, 11661824, 16234854, 7630238, 5998374, 9809887, -16694564, 15219798, -14327783},
{27425505, -5719081, 3055006, 10660664, 23458024, 595578, -15398605, -1173195, -18342183, 9742717},
{6744077, 2427284, 26042789, 2720740, -847906, 1118974, 32324614, 7406442, 12420155, 1994844},
},
{
{14012521, -5024720, -18384453, -9578469, -26485342, -3936439, -13033478, -10909803, 24319929, -6446333},
{16412690, -4507367, 10772641, 15929391, -17068788, -4658621, 10555945, -10484049, -30102368, -4739048},
{22397382, -7767684, -9293161, -12792868, 17166287, -9755136, -27333065, 6199366, 21880021, -12250760},
},
{
{-4283307, 5368523, -31117018, 8163389, -30323063, 3209128, 16557151, 8890729, 8840445, 4957760},
{-15447727, 709327, -6919446, -10870178, -29777922, 6522332, -21720181, 12130072, -14796503, 5005757},
{-2114751, -14308128, 23019042, 15765735, -25269683, 6002752, 10183197, -13239326, -16395286, -2176112},
},
},
{
{
{-19025756, 1632005, 13466291, -7995100, -23640451, 16573537, -32013908, -3057104, 22208662, 2000468},
{3065073, -1412761, -25598674, -361432, -17683065, -5703415, -8164212, 11248527, -3691214, -7414184},
{10379208, -6045554, 8877319, 1473647, -29291284, -12507580, 16690915, 2553332, -3132688, 16400289},
},
{
{15716668, 1254266, -18472690, 7446274, -8448918, 6344164, -22097271, -7285580, 26894937, 9132066},
{24158887, 12938817, 11085297, -8177598, -28063478, -4457083, -30576463, 64452, -6817084, -2692882},
{13488534, 7794716, 22236231, 5989356, 25426474, -12578208, 2350710, -3418511, -4688006, 2364226},
},
{
{16335052, 9132434, 25640582, 6678888, 1725628, 8517937, -11807024, -11697457, 15445875, -7798101},
{29004207, -7867081, 28661402, -640412, -12794003, -7943086, 31863255, -4135540, -278050, -15759279},
{-6122061, -14866665, -28614905, 14569919, -10857999, -3591829, 10343412, -6976290, -29828287, -10815811},
},
{
{27081650, 3463984, 14099042, -4517604, 1616303, -6205604, 29542636, 15372179, 17293797, 960709},
{20263915, 11434237, -5765435, 11236810, 13505955, -10857102, -16111345, 6493122, -19384511, 7639714},
{-2830798, -14839232, 25403038, -8215196, -8317012, -16173699, 18006287, -16043750, 29994677, -15808121},
},
{
{9769828, 5202651, -24157398, -13631392, -28051003, -11561624, -24613141, -13860782, -31184575, 709464},
{12286395, 13076066, -21775189, -1176622, -25003198, 4057652, -32018128, -8890874, 16102007, 13205847},
{13733362, 5599946, 10557076, 3195751, -5557991, 8536970, -25540170, 8525972, 10151379, 10394400},
},
{
{4024660, -16137551, 22436262, 12276534, -9099015, -2686099, 19698229, 11743039, -33302334, 8934414},
{-15879800, -4525240, -8580747, -2934061, 14634845, -698278, -9449077, 3137094, -11536886, 11721158},
{17555939, -5013938, 8268606, 2331751, -22738815, 9761013, 9319229, 8835153, -9205489, -1280045},
},
{
{-461409, -7830014, 20614118, 16688288, -7514766, -4807119, 22300304, 505429, 6108462, -6183415},
{-5070281, 12367917, -30663534, 3234473, 32617080, -8422642, 29880583, -13483331, -26898490, -7867459},
{-31975283, 5726539, 26934134, 10237677, -3173717, -605053, 24199304, 3795095, 7592688, -14992079},
},
{
{21594432, -14964228, 17466408, -4077222, 32537084, 2739898, 6407723, 12018833, -28256052, 4298412},
{-20650503, -11961496, -27236275, 570498, 3767144, -1717540, 13891942, -1569194, 13717174, 10805743},
{-14676630, -15644296, 15287174, 11927123, 24177847, -8175568, -796431, 14860609, -26938930, -5863836},
},
},
{
{
{12962541, 5311799, -10060768, 11658280, 18855286, -7954201, 13286263, -12808704, -4381056, 9882022},
{18512079, 11319350, -20123124, 15090309, 18818594, 5271736, -22727904, 3666879, -23967430, -3299429},
{-6789020, -3146043, 16192429, 13241070, 15898607, -14206114, -10084880, -6661110, -2403099, 5276065},
},
{
{30169808, -5317648, 26306206, -11750859, 27814964, 7069267, 7152851, 3684982, 1449224, 13082861},
{10342826, 3098505, 2119311, 193222, 25702612, 12233820, 23697382, 15056736, -21016438, -8202000},
{-33150110, 3261608, 22745853, 7948688, 19370557, -15177665, -26171976, 6482814, -10300080, -11060101},
},
{
{32869458, -5408545, 25609743, 15678670, -10687769, -15471071, 26112421, 2521008, -22664288, 6904815},
{29506923, 4457497, 3377935, -9796444, -30510046, 12935080, 1561737, 3841096, -29003639, -6657642},
{10340844, -6630377, -18656632, -2278430, 12621151, -13339055, 30878497, -11824370, -25584551, 5181966},
},
{
{25940115, -12658025, 17324188, -10307374, -8671468, 15029094, 24396252, -16450922, -2322852, -12388574},
{-21765684, 9916823, -1300409, 4079498, -1028346, 11909559, 1782390, 12641087, 20603771, -6561742},
{-18882287, -11673380, 24849422, 11501709, 13161720, -4768874, 1925523, 11914390, 4662781, 7820689},
},
{
{12241050, -425982, 8132691, 9393934, 32846760, -1599620, 29749456, 12172924, 16136752, 15264020},
{-10349955, -14680563, -8211979, 2330220, -17662549, -14545780, 10658213, 6671822, 19012087, 3772772},
{3753511, -3421066, 10617074, 2028709, 14841030, -6721664, 28718732, -15762884, 20527771, 12988982},
},
{
{-14822485, -5797269, -3707987, 12689773, -898983, -10914866, -24183046, -10564943, 3299665, -12424953},
{-16777703, -15253301, -9642417, 4978983, 3308785, 8755439, 6943197, 6461331, -25583147, 8991218},
{-17226263, 1816362, -1673288, -6086439, 31783888, -8175991, -32948145, 7417950, -30242287, 1507265},
},
{
{29692663, 6829891, -10498800, 4334896, 20945975, -11906496, -28887608, 8209391, 14606362, -10647073},
{-3481570, 8707081, 32188102, 5672294, 22096700, 1711240, -33020695, 9761487, 4170404, -2085325},
{-11587470, 14855945, -4127778, -1531857, -26649089, 15084046, 22186522, 16002000, -14276837, -8400798},
},
{
{-4811456, 13761029, -31703877, -2483919, -3312471, 7869047, -7113572, -9620092, 13240845, 10965870},
{-7742563, -8256762, -14768334, -13656260, -23232383, 12387166, 4498947, 14147411, 29514390, 4302863},
{-13413405, -12407859, 20757302, -13801832, 14785143, 8976368, -5061276, -2144373, 17846988, -13971927},
},
},
{
{
{-2244452, -754728, -4597030, -1066309, -6247172, 1455299, -21647728, -9214789, -5222701, 12650267},
{-9906797, -16070310, 21134160, 12198166, -27064575, 708126, 387813, 13770293, -19134326, 10958663},
{22470984, 12369526, 23446014, -5441109, -21520802, -9698723, -11772496, -11574455, -25083830, 4271862},
},
{
{-25169565, -10053642, -19909332, 15361595, -5984358, 2159192, 75375, -4278529, -32526221, 8469673},
{15854970, 4148314, -8893890, 7259002, 11666551, 13824734, -30531198, 2697372, 24154791, -9460943},
{15446137, -15806644, 29759747, 14019369, 30811221, -9610191, -31582008, 12840104, 24913809, 9815020},
},
{
{-4709286, -5614269, -31841498, -12288893, -14443537, 10799414, -9103676, 13438769, 18735128, 9466238},
{11933045, 9281483, 5081055, -5183824, -2628162, -4905629, -7727821, -10896103, -22728655, 16199064},
{14576810, 379472, -26786533, -8317236, -29426508, -10812974, -102766, 1876699, 30801119, 2164795},
},
{
{15995086, 3199873, 13672555, 13712240, -19378835, -4647646, -13081610, -15496269, -13492807, 1268052},
{-10290614, -3659039, -3286592, 10948818, 23037027, 3794475, -3470338, -12600221, -17055369, 3565904},
{29210088, -9419337, -5919792, -4952785, 10834811, -13327726, -16512102, -10820713, -27162222, -14030531},
},
{
{-13161890, 15508588, 16663704, -8156150, -28349942, 9019123, -29183421, -3769423, 2244111, -14001979},
{-5152875, -3800936, -9306475, -6071583, 16243069, 14684434, -25673088, -16180800, 13491506, 4641841},
{10813417, 643330, -19188515, -728916, 30292062, -16600078, 27548447, -7721242, 14476989, -12767431},
},
{
{10292079, 9984945, 6481436, 8279905, -7251514, 7032743, 27282937, -1644259, -27912810, 12651324},
{-31185513, -813383, 22271204, 11835308, 10201545, 15351028, 17099662, 3988035, 21721536, -3148940},
{10202177, -6545839, -31373232, -9574638, -32150642, -8119683, -12906320, 3852694, 13216206, 14842320},
},
{
{-15815640, -10601066, -6538952, -7258995, -6984659, -6581778, -31500847, 13765824, -27434397, 9900184},
{14465505, -13833331, -32133984, -14738873, -27443187, 12990492, 33046193, 15796406, -7051866, -8040114},
{30924417, -8279620, 6359016, -12816335, 16508377, 9071735, -25488601, 15413635, 9524356, -7018878},
},
{
{12274201, -13175547, 32627641, -1785326, 6736625, 13267305, 5237659, -5109483, 15663516, 4035784},
{-2951309, 8903985, 17349946, 601635, -16432815, -4612556, -13732739, -15889334, -22258478, 4659091},
{-16916263, -4952973, -30393711, -15158821, 20774812, 15897498, 5736189, 15026997, -2178256, -13455585},
},
},
{
{
{-8858980, -2219056, 28571666, -10155518, -474467, -10105698, -3801496, 278095, 23440562, -290208},
{10226241, -5928702, 15139956, 120818, -14867693, 5218603, 32937275, 11551483, -16571960, -7442864},
{17932739, -12437276, -24039557, 10749060, 11316803, 7535897, 22503767, 5561594, -3646624, 3898661},
},
{
{7749907, -969567, -16339731, -16464, -25018111, 15122143, -1573531, 7152530, 21831162, 1245233},
{26958459, -14658026, 4314586, 8346991, -5677764, 11960072, -32589295, -620035, -30402091, -16716212},
{-12165896, 9166947, 33491384, 13673479, 29787085, 13096535, 6280834, 14587357, -22338025, 13987525},
},
{
{-24349909, 7778775, 21116000, 15572597, -4833266, -5357778, -4300898, -5124639, -7469781, -2858068},
{9681908, -6737123, -31951644, 13591838, -6883821, 386950, 31622781, 6439245, -14581012, 4091397},
{-8426427, 1470727, -28109679, -1596990, 3978627, -5123623, -19622683, 12092163, 29077877, -14741988},
},
{
{5269168, -6859726, -13230211, -8020715, 25932563, 1763552, -5606110, -5505881, -20017847, 2357889},
{32264008, -15407652, -5387735, -1160093, -2091322, -3946900, 23104804, -12869908, 5727338, 189038},
{14609123, -8954470, -6000566, -16622781, -14577387, -7743898, -26745169, 10942115, -25888931, -14884697},
},
{
{20513500, 5557931, -15604613, 7829531, 26413943, -2019404, -21378968, 7471781, 13913677, -5137875},
{-25574376, 11967826, 29233242, 12948236, -6754465, 4713227, -8940970, 14059180, 12878652, 8511905},
{-25656801, 3393631, -2955415, -7075526, -2250709, 9366908, -30223418, 6812974, 5568676, -3127656},
},
{
{11630004, 12144454, 2116339, 13606037, 27378885, 15676917, -17408753, -13504373, -14395196, 8070818},
{27117696, -10007378, -31282771, -5570088, 1127282, 12772488, -29845906, 10483306, -11552749, -1028714},
{10637467, -5688064, 5674781, 1072708, -26343588, -6982302, -1683975, 9177853, -27493162, 15431203},
},
{
{20525145, 10892566, -12742472, 12779443, -29493034, 16150075, -28240519, 14943142, -15056790, -7935931},
{-30024462, 5626926, -551567, -9981087, 753598, 11981191, 25244767, -3239766, -3356550, 9594024},
{-23752644, 2636870, -5163910, -10103818, 585134, 7877383, 11345683, -6492290, 13352335, -10977084},
},
{
{-1931799, -5407458, 3304649, -12884869, 17015806, -4877091, -29783850, -7752482, -13215537, -319204},
{20239939, 6607058, 6203985, 3483793, -18386976, -779229, -20723742, 15077870, -22750759, 14523817},
{27406042, -6041657, 27423596, -4497394, 4996214, 10002360, -28842031, -4545494, -30172742, -4805667},
},
},
{
{
{11374242, 12660715, 17861383, -12540833, 10935568, 1099227, -13886076, -9091740, -27727044, 11358504},
{-12730809, 10311867, 1510375, 10778093, -2119455, -9145702, 32676003, 11149336, -26123651, 4985768},
{-19096303, 341147, -6197485, -239033, 15756973, -8796662, -983043, 13794114, -19414307, -15621255},
},
{
{6490081, 11940286, 25495923, -7726360, 8668373, -8751316, 3367603, 6970005, -1691065, -9004790},
{1656497, 13457317, 15370807, 6364910, 13605745, 8362338, -19174622, -5475723, -16796596, -5031438},
{-22273315, -13524424, -64685, -4334223, -18605636, -10921968, -20571065, -7007978, -99853, -10237333},
},
{
{17747465, 10039260, 19368299, -4050591, -20630635, -16041286, 31992683, -15857976, -29260363, -5511971},
{31932027, -4986141, -19612382, 16366580, 22023614, 88450, 11371999, -3744247, 4882242, -10626905},
{29796507, 37186, 19818052, 10115756, -11829032, 3352736, 18551198, 3272828, -5190932, -4162409},
},
{
{12501286, 4044383, -8612957, -13392385, -32430052, 5136599, -19230378, -3529697, 330070, -3659409},
{6384877, 2899513, 17807477, 7663917, -2358888, 12363165, 25366522, -8573892, -271295, 12071499},
{-8365515, -4042521, 25133448, -4517355, -6211027, 2265927, -32769618, 1936675, -5159697, 3829363},
},
{
{28425966, -5835433, -577090, -4697198, -14217555, 6870930, 7921550, -6567787, 26333140, 14267664},
{-11067219, 11871231, 27385719, -10559544, -4585914, -11189312, 10004786, -8709488, -21761224, 8930324},
{-21197785, -16396035, 25654216, -1725397, 12282012, 11008919, 1541940, 4757911, -26491501, -16408940},
},
{
{13537262, -7759490, -20604840, 10961927, -5922820, -13218065, -13156584, 6217254, -15943699, 13814990},
{-17422573, 15157790, 18705543, 29619, 24409717, -260476, 27361681, 9257833, -1956526, -1776914},
{-25045300, -10191966, 15366585, 15166509, -13105086, 8423556, -29171540, 12361135, -18685978, 4578290},
},
{
{24579768, 3711570, 1342322, -11180126, -27005135, 14124956, -22544529, 14074919, 21964432, 8235257},
{-6528613, -2411497, 9442966, -5925588, 12025640, -1487420, -2981514, -1669206, 13006806, 2355433},
{-16304899, -13605259, -6632427, -5142349, 16974359, -10911083, 27202044, 1719366, 1141648, -12796236},
},
{
{-12863944, -13219986, -8318266, -11018091, -6810145, -4843894, 13475066, -3133972, 32674895, 13715045},
{11423335, -5468059, 32344216, 8962751, 24989809, 9241752, -13265253, 16086212, -28740881, -15642093},
{-1409668, 12530728, -6368726, 10847387, 19531186, -14132160, -11709148, 7791794, -27245943, 4383347},
},
},
{
{
{-28970898, 5271447, -1266009, -9736989, -12455236, 16732599, -4862407, -4906449, 27193557, 6245191},
{-15193956, 5362278, -1783893, 2695834, 4960227, 12840725, 23061898, 3260492, 22510453, 8577507},
{-12632451, 11257346, -32692994, 13548177, -721004, 10879011, 31168030, 13952092, -29571492, -3635906},
},
{
{3877321, -9572739, 32416692, 5405324, -11004407, -13656635, 3759769, 11935320, 5611860, 8164018},
{-16275802, 14667797, 15906460, 12155291, -22111149, -9039718, 32003002, -8832289, 5773085, -8422109},
{-23788118, -8254300, 1950875, 8937633, 18686727, 16459170, -905725, 12376320, 31632953, 190926},
},
{
{-24593607, -16138885, -8423991, 13378746, 14162407, 6901328, -8288749, 4508564, -25341555, -3627528},
{8884438, -5884009, 6023974, 10104341, -6881569, -4941533, 18722941, -14786005, -1672488, 827625},
{-32720583, -16289296, -32503547, 7101210, 13354605, 2659080, -1800575, -14108036, -24878478, 1541286},
},
{
{2901347, -1117687, 3880376, -10059388, -17620940, -3612781, -21802117, -3567481, 20456845, -1885033},
{27019610, 12299467, -13658288, -1603234, -12861660, -4861471, -19540150, -5016058, 29439641, 15138866},
{21536104, -6626420, -32447818, -10690208, -22408077, 5175814, -5420040, -16361163, 7779328, 109896},
},
{
{30279744, 14648750, -8044871, 6425558, 13639621, -743509, 28698390, 12180118, 23177719, -554075},
{26572847, 3405927, -31701700, 12890905, -19265668, 5335866, -6493768, 2378492, 4439158, -13279347},
{-22716706, 3489070, -9225266, -332753, 18875722, -1140095, 14819434, -12731527, -17717757, -5461437},
},
{
{-5056483, 16566551, 15953661, 3767752, -10436499, 15627060, -820954, 2177225, 8550082, -15114165},
{-18473302, 16596775, -381660, 15663611, 22860960, 15585581, -27844109, -3582739, -23260460, -8428588},
{-32480551, 15707275, -8205912, -5652081, 29464558, 2713815, -22725137, 15860482, -21902570, 1494193},
},
{
{-19562091, -14087393, -25583872, -9299552, 13127842, 759709, 21923482, 16529112, 8742704, 12967017},
{-28464899, 1553205, 32536856, -10473729, -24691605, -406174, -8914625, -2933896, -29903758, 15553883},
{21877909, 3230008, 9881174, 10539357, -4797115, 2841332, 11543572, 14513274, 19375923, -12647961},
},
{
{8832269, -14495485, 13253511, 5137575, 5037871, 4078777, 24880818, -6222716, 2862653, 9455043},
{29306751, 5123106, 20245049, -14149889, 9592566, 8447059, -2077124, -2990080, 15511449, 4789663},
{-20679756, 7004547, 8824831, -9434977, -4045704, -3750736, -5754762, 108893, 23513200, 16652362},
},
},
{
{
{-33256173, 4144782, -4476029, -6579123, 10770039, -7155542, -6650416, -12936300, -18319198, 10212860},
{2756081, 8598110, 7383731, -6859892, 22312759, -1105012, 21179801, 2600940, -9988298, -12506466},
{-24645692, 13317462, -30449259, -15653928, 21365574, -10869657, 11344424, 864440, -2499677, -16710063},
},
{
{-26432803, 6148329, -17184412, -14474154, 18782929, -275997, -22561534, 211300, 2719757, 4940997},
{-1323882, 3911313, -6948744, 14759765, -30027150, 7851207, 21690126, 8518463, 26699843, 5276295},
{-13149873, -6429067, 9396249, 365013, 24703301, -10488939, 1321586, 149635, -15452774, 7159369},
},
{
{9987780, -3404759, 17507962, 9505530, 9731535, -2165514, 22356009, 8312176, 22477218, -8403385},
{18155857, -16504990, 19744716, 9006923, 15154154, -10538976, 24256460, -4864995, -22548173, 9334109},
{2986088, -4911893, 10776628, -3473844, 10620590, -7083203, -21413845, 14253545, -22587149, 536906},
},
{
{4377756, 8115836, 24567078, 15495314, 11625074, 13064599, 7390551, 10589625, 10838060, -15420424},
{-19342404, 867880, 9277171, -3218459, -14431572, -1986443, 19295826, -15796950, 6378260, 699185},
{7895026, 4057113, -7081772, -13077756, -17886831, -323126, -716039, 15693155, -5045064, -13373962},
},
{
{-7737563, -5869402, -14566319, -7406919, 11385654, 13201616, 31730678, -10962840, -3918636, -9669325},
{10188286, -15770834, -7336361, 13427543, 22223443, 14896287, 30743455, 7116568, -21786507, 5427593},
{696102, 13206899, 27047647, -10632082, 15285305, -9853179, 10798490, -4578720, 19236243, 12477404},
},
{
{-11229439, 11243796, -17054270, -8040865, -788228, -8167967, -3897669, 11180504, -23169516, 7733644},
{17800790, -14036179, -27000429, -11766671, 23887827, 3149671, 23466177, -10538171, 10322027, 15313801},
{26246234, 11968874, 32263343, -5468728, 6830755, -13323031, -15794704, -101982, -24449242, 10890804},
},
{
{-31365647, 10271363, -12660625, -6267268, 16690207, -13062544, -14982212, 16484931, 25180797, -5334884},
{-586574, 10376444, -32586414, -11286356, 19801893, 10997610, 2276632, 9482883, 316878, 13820577},
{-9882808, -4510367, -2115506, 16457136, -11100081, 11674996, 30756178, -7515054, 30696930, -3712849},
},
{
{32988917, -9603412, 12499366, 7910787, -10617257, -11931514, -7342816, -9985397, -32349517, 7392473},
{-8855661, 15927861, 9866406, -3649411, -2396914, -16655781, -30409476, -9134995, 25112947, -2926644},
{-2504044, -436966, 25621774, -5678772, 15085042, -5479877, -24884878, -13526194, 5537438, -13914319},
},
},
{
{
{-11225584, 2320285, -9584280, 10149187, -33444663, 5808648, -14876251, -1729667, 31234590, 6090599},
{-9633316, 116426, 26083934, 2897444, -6364437, -2688086, 609721, 15878753, -6970405, -9034768},
{-27757857, 247744, -15194774, -9002551, 23288161, -10011936, -23869595, 6503646, 20650474, 1804084},
},
{
{-27589786, 15456424, 8972517, 8469608, 15640622, 4439847, 3121995, -10329713, 27842616, -202328},
{-15306973, 2839644, 22530074, 10026331, 4602058, 5048462, 28248656, 5031932, -11375082, 12714369},
{20807691, -7270825, 29286141, 11421711, -27876523, -13868230, -21227475, 1035546, -19733229, 12796920},
},
{
{12076899, -14301286, -8785001, -11848922, -25012791, 16400684, -17591495, -12899438, 3480665, -15182815},
{-32361549, 5457597, 28548107, 7833186, 7303070, -11953545, -24363064, -15921875, -33374054, 2771025},
{-21389266, 421932, 26597266, 6860826, 22486084, -6737172, -17137485, -4210226, -24552282, 15673397},
},
{
{-20184622, 2338216, 19788685, -9620956, -4001265, -8740893, -20271184, 4733254, 3727144, -12934448},
{6120119, 814863, -11794402, -622716, 6812205, -15747771, 2019594, 7975683, 31123697, -10958981},
{30069250, -11435332, 30434654, 2958439, 18399564, -976289, 12296869, 9204260, -16432438, 9648165},
},
{
{32705432, -1550977, 30705658, 7451065, -11805606, 9631813, 3305266, 5248604, -26008332, -11377501},
{17219865, 2375039, -31570947, -5575615, -19459679, 9219903, 294711, 15298639, 2662509, -16297073},
{-1172927, -7558695, -4366770, -4287744, -21346413, -8434326, 32087529, -1222777, 32247248, -14389861},
},
{
{14312628, 1221556, 17395390, -8700143, -4945741, -8684635, -28197744, -9637817, -16027623, -13378845},
{-1428825, -9678990, -9235681, 6549687, -7383069, -468664, 23046502, 9803137, 17597934, 2346211},
{18510800, 15337574, 26171504, 981392, -22241552, 7827556, -23491134, -11323352, 3059833, -11782870},
},
{
{10141598, 6082907, 17829293, -1947643, 9830092, 13613136, -25556636, -5544586, -33502212, 3592096},
{33114168, -15889352, -26525686, -13343397, 33076705, 8716171, 1151462, 1521897, -982665, -6837803},
{-32939165, -4255815, 23947181, -324178, -33072974, -12305637, -16637686, 3891704, 26353178, 693168},
},
{
{30374239, 1595580, -16884039, 13186931, 4600344, 406904, 9585294, -400668, 31375464, 14369965},
{-14370654, -7772529, 1510301, 6434173, -18784789, -6262728, 32732230, -13108839, 17901441, 16011505},
{18171223, -11934626, -12500402, 15197122, -11038147, -15230035, -19172240, -16046376, 8764035, 12309598},
},
},
{
{
{5975908, -5243188, -19459362, -9681747, -11541277, 14015782, -23665757, 1228319, 17544096, -10593782},
{5811932, -1715293, 3442887, -2269310, -18367348, -8359541, -18044043, -15410127, -5565381, 12348900},
{-31399660, 11407555, 25755363, 6891399, -3256938, 14872274, -24849353, 8141295, -10632534, -585479},
},
{
{-12675304, 694026, -5076145, 13300344, 14015258, -14451394, -9698672, -11329050, 30944593, 1130208},
{8247766, -6710942, -26562381, -7709309, -14401939, -14648910, 4652152, 2488540, 23550156, -271232},
{17294316, -3788438, 7026748, 15626851, 22990044, 113481, 2267737, -5908146, -408818, -137719},
},
{
{16091085, -16253926, 18599252, 7340678, 2137637, -1221657, -3364161, 14550936, 3260525, -7166271},
{-4910104, -13332887, 18550887, 10864893, -16459325, -7291596, -23028869, -13204905, -12748722, 2701326},
{-8574695, 16099415, 4629974, -16340524, -20786213, -6005432, -10018363, 9276971, 11329923, 1862132},
},
{
{14763076, -15903608, -30918270, 3689867, 3511892, 10313526, -21951088, 12219231, -9037963, -940300},
{8894987, -3446094, 6150753, 3013931, 301220, 15693451, -31981216, -2909717, -15438168, 11595570},
{15214962, 3537601, -26238722, -14058872, 4418657, -15230761, 13947276, 10730794, -13489462, -4363670},
},
{
{-2538306, 7682793, 32759013, 263109, -29984731, -7955452, -22332124, -10188635, 977108, 699994},
{-12466472, 4195084, -9211532, 550904, -15565337, 12917920, 19118110, -439841, -30534533, -14337913},
{31788461, -14507657, 4799989, 7372237, 8808585, -14747943, 9408237, -10051775, 12493932, -5409317},
},
{
{-25680606, 5260744, -19235809, -6284470, -3695942, 16566087, 27218280, 2607121, 29375955, 6024730},
{842132, -2794693, -4763381, -8722815, 26332018, -12405641, 11831880, 6985184, -9940361, 2854096},
{-4847262, -7969331, 2516242, -5847713, 9695691, -7221186, 16512645, 960770, 12121869, 16648078},
},
{
{-15218652, 14667096, -13336229, 2013717, 30598287, -464137, -31504922, -7882064, 20237806, 2838411},
{-19288047, 4453152, 15298546, -16178388, 22115043, -15972604, 12544294, -13470457, 1068881, -12499905},
{-9558883, -16518835, 33238498, 13506958, 30505848, -1114596, -8486907, -2630053, 12521378, 4845654},
},
{
{-28198521, 10744108, -2958380, 10199664, 7759311, -13088600, 3409348, -873400, -6482306, -12885870},
{-23561822, 6230156, -20382013, 10655314, -24040585, -11621172, 10477734, -1240216, -3113227, 13974498},
{12966261, 15550616, -32038948, -1615346, 21025980, -629444, 5642325, 7188737, 18895762, 12629579},
},
},
{
{
{14741879, -14946887, 22177208, -11721237, 1279741, 8058600, 11758140, 789443, 32195181, 3895677},
{10758205, 15755439, -4509950, 9243698, -4879422, 6879879, -2204575, -3566119, -8982069, 4429647},
{-2453894, 15725973, -20436342, -10410672, -5803908, -11040220, -7135870, -11642895, 18047436, -15281743},
},
{
{-25173001, -11307165, 29759956, 11776784, -22262383, -15820455,
10993114, -12850837, -17620701, -9408468},
{21987233, 700364, -24505048, 14972008, -7774265, -5718395, 32155026, 2581431, -29958985, 8773375},
{-25568350, 454463, -13211935, 16126715, 25240068, 8594567, 20656846, 12017935, -7874389, -13920155},
},
{
{6028182, 6263078, -31011806, -11301710, -818919, 2461772, -31841174, -5468042, -1721788, -2776725},
{-12278994, 16624277, 987579, -5922598, 32908203, 1248608, 7719845, -4166698, 28408820, 6816612},
{-10358094, -8237829, 19549651, -12169222, 22082623, 16147817, 20613181, 13982702, -10339570, 5067943},
},
{
{-30505967, -3821767, 12074681, 13582412, -19877972, 2443951, -19719286, 12746132, 5331210, -10105944},
{30528811, 3601899, -1957090, 4619785, -27361822, -15436388, 24180793, -12570394, 27679908, -1648928},
{9402404, -13957065, 32834043, 10838634, -26580150, -13237195, 26653274, -8685565, 22611444, -12715406},
},
{
{22190590, 1118029, 22736441, 15130463, -30460692, -5991321, 19189625, -4648942, 4854859, 6622139},
{-8310738, -2953450, -8262579, -3388049, -10401731, -271929, 13424426, -3567227, 26404409, 13001963},
{-31241838, -15415700, -2994250, 8939346, 11562230, -12840670, -26064365, -11621720, -15405155, 11020693},
},
{
{1866042, -7949489, -7898649, -10301010, 12483315, 13477547, 3175636, -12424163, 28761762, 1406734},
{-448555, -1777666, 13018551, 3194501, -9580420, -11161737, 24760585, -4347088, 25577411, -13378680},
{-24290378, 4759345, -690653, -1852816, 2066747, 10693769, -29595790, 9884936, -9368926, 4745410},
},
{
{-9141284, 6049714, -19531061, -4341411, -31260798, 9944276, -15462008, -11311852, 10931924, -11931931},
{-16561513, 14112680, -8012645, 4817318, -8040464, -11414606, -22853429, 10856641, -20470770, 13434654},
{22759489, -10073434, -16766264, -1871422, 13637442, -10168091, 1765144, -12654326, 28445307, -5364710},
},
{
{29875063, 12493613, 2795536, -3786330, 1710620, 15181182, -10195717, -8788675, 9074234, 1167180},
{-26205683, 11014233, -9842651, -2635485, -26908120, 7532294, -18716888, -9535498, 3843903, 9367684},
{-10969595, -6403711, 9591134, 9582310, 11349256, 108879, 16235123, 8601684, -139197, 4242895},
},
},
{
{
{22092954, -13191123, -2042793, -11968512, 32186753, -11517388, -6574341, 2470660, -27417366, 16625501},
{-11057722, 3042016, 13770083, -9257922, 584236, -544855, -7770857, 2602725, -27351616, 14247413},
{6314175, -10264892, -32772502, 15957557, -10157730, 168750, -8618807, 14290061, 27108877, -1180880},
},
{
{-8586597, -7170966, 13241782, 10960156, -32991015, -13794596, 33547976, -11058889, -27148451, 981874},
{22833440, 9293594, -32649448, -13618667, -9136966, 14756819, -22928859, -13970780, -10479804, -16197962},
{-7768587, 3326786, -28111797, 10783824, 19178761, 14905060, 22680049, 13906969, -15933690, 3797899},
},
{
{21721356, -4212746, -12206123, 9310182, -3882239, -13653110, 23740224, -2709232, 20491983, -8042152},
{9209270, -15135055, -13256557, -6167798, -731016, 15289673, 25947805, 15286587, 30997318, -6703063},
{7392032, 16618386, 23946583, -8039892, -13265164, -1533858, -14197445, -2321576, 17649998, -250080},
},
{
{-9301088, -14193827, 30609526, -3049543, -25175069, -1283752, -15241566, -9525724, -2233253, 7662146},
{-17558673, 1763594, -33114336, 15908610, -30040870, -12174295, 7335080, -8472199, -3174674, 3440183},
{-19889700, -5977008, -24111293, -9688870, 10799743, -16571957, 40450, -4431835, 4862400, 1133},
},
{
{-32856209, -7873957, -5422389, 14860950, -16319031, 7956142, 7258061, 311861, -30594991, -7379421},
{-3773428, -1565936, 28985340, 7499440, 24445838, 9325937, 29727763, 16527196, 18278453, 15405622},
{-4381906, 8508652, -19898366, -3674424, -5984453, 15149970, -13313598, 843523, -21875062, 13626197},
},
{
{2281448, -13487055, -10915418, -2609910, 1879358, 16164207, -10783882, 3953792, 13340839, 15928663},
{31727126, -7179855, -18437503, -8283652, 2875793, -16390330, -25269894, -7014826, -23452306, 5964753},
{4100420, -5959452, -17179337, 6017714, -18705837, 12227141, -26684835, 11344144, 2538215, -7570755},
},
{
{-9433605, 6123113, 11159803, -2156608, 30016280, 14966241, -20474983, 1485421, -629256, -15958862},
{-26804558, 4260919, 11851389, 9658551, -32017107, 16367492, -20205425, -13191288, 11659922, -11115118},
{26180396, 10015009, -30844224, -8581293, 5418197, 9480663, 2231568, -10170080, 33100372, -1306171},
},
{
{15121113, -5201871, -10389905, 15427821, -27509937, -15992507, 21670947, 4486675, -5931810, -14466380},
{16166486, -9483733, -11104130, 6023908, -31926798, -1364923, 2340060, -16254968, -10735770, -10039824},
{28042865, -3557089, -12126526, 12259706, -3717498, -6945899, 6766453, -8689599, 18036436, 5803270},
},
},
{
{
{-817581, 6763912, 11803561, 1585585, 10958447, -2671165, 23855391, 4598332, -6159431, -14117438},
{-31031306, -14256194, 17332029, -2383520, 31312682, -5967183, 696309, 50292, -20095739, 11763584},
{-594563, -2514283, -32234153, 12643980, 12650761, 14811489, 665117, -12613632, -19773211, -10713562},
},
{
{30464590, -11262872, -4127476, -12734478, 19835327, -7105613, -24396175, 2075773, -17020157, 992471},
{18357185, -6994433, 7766382, 16342475, -29324918, 411174, 14578841, 8080033, -11574335, -10601610},
{19598397, 10334610, 12555054, 2555664, 18821899, -10339780, 21873263, 16014234, 26224780, 16452269},
},
{
{-30223925, 5145196, 5944548, 16385966, 3976735, 2009897, -11377804, -7618186, -20533829, 3698650},
{14187449, 3448569, -10636236, -10810935, -22663880, -3433596, 7268410, -10890444, 27394301, 12015369},
{19695761, 16087646, 28032085, 12999827, 6817792, 11427614, 20244189, -1312777, -13259127, -3402461},
},
{
{30860103, 12735208, -1888245, -4699734, -16974906, 2256940, -8166013, 12298312, -8550524, -10393462},
{-5719826, -11245325, -1910649, 15569035, 26642876, -7587760, -5789354, -15118654, -4976164, 12651793},
{-2848395, 9953421, 11531313, -5282879, 26895123, -12697089, -13118820, -16517902, 9768698, -2533218},
},
{
{-24719459, 1894651, -287698, -4704085, 15348719, -8156530, 32767513, 12765450, 4940095, 10678226},
{18860224, 15980149, -18987240, -1562570, -26233012, -11071856, -7843882, 13944024, -24372348, 16582019},
{-15504260, 4970268, -29893044, 4175593, -20993212, -2199756, -11704054, 15444560, -11003761, 7989037},
},
{
{31490452, 5568061, -2412803, 2182383, -32336847, 4531686, -32078269, 6200206, -19686113, -14800171},
{-17308668, -15879940, -31522777, -2831, -32887382, 16375549, 8680158, -16371713, 28550068, -6857132},
{-28126887, -5688091, 16837845, -1820458, -6850681, 12700016, -30039981, 4364038, 1155602, 5988841},
},
{
{21890435, -13272907, -12624011, 12154349, -7831873, 15300496, 23148983, -4470481, 24618407, 8283181},
{-33136107, -10512751, 9975416, 6841041, -31559793, 16356536, 3070187, -7025928, 1466169, 10740210},
{-1509399, -15488185, -13503385, -10655916, 32799044, 909394, -13938903, -5779719, -32164649, -15327040},
},
{
{3960823, -14267803, -28026090, -15918051, -19404858, 13146868, 15567327, 951507, -3260321, -573935},
{24740841, 5052253, -30094131, 8961361, 25877428, 6165135, -24368180, 14397372, -7380369, -6144105},
{-28888365, 3510803, -28103278, -1158478, -11238128, -10631454, -15441463, -14453128, -1625486, -6494814},
},
},
{
{
{793299, -9230478, 8836302, -6235707, -27360908, -2369593, 33152843, -4885251, -9906200, -621852},
{5666233, 525582, 20782575, -8038419, -24538499, 14657740, 16099374, 1468826, -6171428, -15186581},
{-4859255, -3779343, -2917758, -6748019, 7778750, 11688288, -30404353, -9871238, -1558923, -9863646},
},
{
{10896332, -7719704, 824275, 472601, -19460308, 3009587, 25248958, 14783338, -30581476, -15757844},
{10566929, 12612572, -31944212, 11118703, -12633376, 12362879, 21752402, 8822496, 24003793, 14264025},
{27713862, -7355973, -11008240, 9227530, 27050101, 2504721, 23886875, -13117525, 13958495, -5732453},
},
{
{-23481610, 4867226, -27247128, 3900521, 29838369, -8212291, -31889399, -10041781, 7340521, -15410068},
{4646514, -8011124, -22766023, -11532654, 23184553, 8566613, 31366726, -1381061, -15066784, -10375192},
{-17270517, 12723032, -16993061, 14878794, 21619651, -6197576, 27584817, 3093888, -8843694, 3849921},
},
{
{-9064912, 2103172, 25561640, -15125738, -5239824, 9582958, 32477045, -9017955, 5002294, -15550259},
{-12057553, -11177906, 21115585, -13365155, 8808712, -12030708, 16489530, 13378448, -25845716, 12741426},
{-5946367, 10645103, -30911586, 15390284, -3286982, -7118677, 24306472, 15852464, 28834118, -7646072},
},
{
{-17335748, -9107057, -24531279, 9434953, -8472084, -583362, -13090771, 455841, 20461858, 5491305},
{13669248, -16095482, -12481974, -10203039, -14569770,
-11893198, -24995986, 11293807, -28588204, -9421832},
{28497928, 6272777, -33022994, 14470570, 8906179, -1225630, 18504674, -14165166, 29867745, -8795943},
},
{
{-16207023, 13517196, -27799630, -13697798, 24009064, -6373891, -6367600, -13175392, 22853429, -4012011},
{24191378, 16712145, -13931797, 15217831, 14542237, 1646131, 18603514, -11037887, 12876623, -2112447},
{17902668, 4518229, -411702, -2829247, 26878217, 5258055, -12860753, 608397, 16031844, 3723494},
},
{
{-28632773, 12763728, -20446446, 7577504, 33001348, -13017745, 17558842, -7872890, 23896954, -4314245},
{-20005381, -12011952, 31520464, 605201, 2543521, 5991821, -2945064, 7229064, -9919646, -8826859},
{28816045, 298879, -28165016, -15920938, 19000928, -1665890, -12680833, -2949325, -18051778, -2082915},
},
{
{16000882, -344896, 3493092, -11447198, -29504595, -13159789, 12577740, 16041268, -19715240, 7847707},
{10151868, 10572098, 27312476, 7922682, 14825339, 4723128, -32855931, -6519018, -10020567, 3852848},
{-11430470, 15697596, -21121557, -4420647, 5386314, 15063598, 16514493, -15932110, 29330899, -15076224},
},
},
{
{
{-25499735, -4378794, -15222908, -6901211, 16615731, 2051784, 3303702, 15490, -27548796, 12314391},
{15683520, -6003043, 18109120, -9980648, 15337968, -5997823, -16717435, 15921866, 16103996, -3731215},
{-23169824, -10781249, 13588192, -1628807, -3798557, -1074929, -19273607, 5402699, -29815713, -9841101},
},
{
{23190676, 2384583, -32714340, 3462154, -29903655, -1529132, -11266856, 8911517, -25205859, 2739713},
{21374101, -3554250, -33524649, 9874411, 15377179, 11831242, -33529904, 6134907, 4931255, 11987849},
{-7732, -2978858, -16223486, 7277597, 105524, -322051, -31480539, 13861388, -30076310, 10117930},
},
{
{-29501170, -10744872, -26163768, 13051539, -25625564, 5089643, -6325503, 6704079, 12890019, 15728940},
{-21972360, -11771379, -951059, -4418840, 14704840, 2695116, 903376, -10428139, 12885167, 8311031},
{-17516482, 5352194, 10384213, -13811658, 7506451, 13453191, 26423267, 4384730, 1888765, -5435404},
},
{
{-25817338, -3107312, -13494599, -3182506, 30896459,
-13921729, -32251644, -12707869, -19464434, -3340243},
{-23607977, -2665774, -526091, 4651136, 5765089, 4618330, 6092245, 14845197, 17151279, -9854116},
{-24830458, -12733720, -15165978, 10367250, -29530908, -265356, 22825805, -7087279, -16866484, 16176525},
},
{
{-23583256, 6564961, 20063689, 3798228, -4740178, 7359225, 2006182, -10363426, -28746253, -10197509},
{-10626600, -4486402, -13320562, -5125317, 3432136, -6393229, 23632037, -1940610, 32808310, 1099883},
{15030977, 5768825, -27451236, -2887299, -6427378, -15361371, -15277896, -6809350, 2051441, -15225865},
},
{
{-3362323, -7239372, 7517890, 9824992, 23555850, 295369, 5148398, -14154188, -22686354, 16633660},
{4577086, -16752288, 13249841, -15304328, 19958763, -14537274, 18559670, -10759549, 8402478, -9864273},
{-28406330, -1051581, -26790155, -907698, -17212414, -11030789, 9453451, -14980072, 17983010, 9967138},
},
{
{-25762494, 6524722, 26585488, 9969270, 24709298, 1220360, -1677990, 7806337, 17507396, 3651560},
{-10420457, -4118111, 14584639, 15971087, -15768321, 8861010, 26556809, -5574557, -18553322, -11357135},
{2839101, 14284142, 4029895, 3472686, 14402957, 12689363, -26642121, 8459447, -5605463, -7621941},
},
{
{-4839289, -3535444, 9744961, 2871048, 25113978, 3187018, -25110813, -849066, 17258084, -7977739},
{18164541, -10595176, -17154882, -1542417, 19237078, -9745295, 23357533, -15217008, 26908270, 12150756},
{-30264870, -7647865, 5112249, -7036672, -1499807, -6974257, 43168, -5537701, -32302074, 16215819},
},
},
{
{
{-6898905, 9824394, -12304779, -4401089, -31397141, -6276835, 32574489, 12532905, -7503072, -8675347},
{-27343522, -16515468, -27151524, -10722951, 946346, 16291093, 254968, 7168080, 21676107, -1943028},
{21260961, -8424752, -16831886, -11920822, -23677961, 3968121, -3651949, -6215466, -3556191, -7913075},
},
{
{16544754, 13250366, -16804428, 15546242, -4583003, 12757258, -2462308, -8680336, -18907032, -9662799},
{-2415239, -15577728, 18312303, 4964443, -15272530, -12653564, 26820651, 16690659, 25459437, -4564609},
{-25144690, 11425020, 28423002, -11020557, -6144921, -15826224, 9142795, -2391602, -6432418, -1644817},
},
{
{-23104652, 6253476, 16964147, -3768872, -25113972, -12296437, -27457225, -16344658, 6335692, 7249989},
{-30333227, 13979675, 7503222, -12368314, -11956721, -4621693, -30272269, 2682242, 25993170, -12478523},
{4364628, 5930691, 32304656, -10044554, -8054781, 15091131, 22857016, -10598955, 31820368, 15075278},
},
{
{31879134, -8918693, 17258761, 90626, -8041836, -4917709, 24162788, -9650886, -17970238, 12833045},
{19073683, 14851414, -24403169, -11860168, 7625278, 11091125, -19619190, 2074449, -9413939, 14905377},
{24483667, -11935567, -2518866, -11547418, -1553130, 15355506, -25282080, 9253129, 27628530, -7555480},
},
{
{17597607, 8340603, 19355617, 552187, 26198470, -3176583, 4593324, -9157582, -14110875, 15297016},
{510886, 14337390, -31785257, 16638632, 6328095, 2713355, -20217417, -11864220, 8683221, 2921426},
{18606791, 11874196, 27155355, -5281482, -24031742, 6265446, -25178240, -1278924, 4674690, 13890525},
},
{
{13609624, 13069022, -27372361, -13055908, 24360586, 9592974, 14977157, 9835105, 4389687, 288396},
{9922506, -519394, 13613107, 5883594, -18758345, -434263, -12304062, 8317628, 23388070, 16052080},
{12720016, 11937594, -31970060, -5028689, 26900120, 8561328, -20155687, -11632979, -14754271, -10812892},
},
{
{15961858, 14150409, 26716931, -665832, -22794328, 13603569, 11829573, 7467844, -28822128, 929275},
{11038231, -11582396, -27310482, -7316562, -10498527, -16307831, -23479533, -9371869, -21393143, 2465074},
{20017163, -4323226, 27915242, 1529148, 12396362, 15675764, 13817261, -9658066, 2463391, -4622140},
},
{
{-16358878, -12663911, -12065183, 4996454, -1256422, 1073572, 9583558, 12851107, 4003896, 12673717},
{-1731589, -15155870, -3262930, 16143082, 19294135, 13385325, 14741514, -9103726, 7903886, 2348101},
{24536016, -16515207, 12715592, -3862155, 1511293, 10047386, -3842346, -7129159, -28377538, 10048127},
},
},
{
{
{-12622226, -6204820, 30718825, 2591312, -10617028, 12192840, 18873298, -7297090, -32297756, 15221632},
{-26478122, -11103864, 11546244, -1852483, 9180880, 7656409, -21343950, 2095755, 29769758, 6593415},
{-31994208, -2907461, 4176912, 3264766, 12538965, -868111, 26312345, -6118678, 30958054, 8292160},
},
{
{31429822, -13959116, 29173532, 15632448, 12174511, -2760094, 32808831, 3977186, 26143136, -3148876},
{22648901, 1402143, -22799984, 13746059, 7936347, 365344, -8668633, -1674433, -3758243, -2304625},
{-15491917, 8012313, -2514730, -12702462, -23965846, -10254029, -1612713, -1535569, -16664475, 8194478},
},
{
{27338066, -7507420, -7414224, 10140405, -19026427, -6589889, 27277191, 8855376, 28572286, 3005164},
{26287124, 4821776, 25476601, -4145903, -3764513, -15788984, -18008582, 1182479, -26094821, -13079595},
{-7171154, 3178080, 23970071, 6201893, -17195577, -4489192, -21876275, -13982627, 32208683, -1198248},
},
{
{-16657702, 2817643, -10286362, 14811298, 6024667, 13349505, -27315504, -10497842, -27672585, -11539858},
{15941029, -9405932, -21367050, 8062055, 31876073, -238629, -15278393, -1444429, 15397331, -4130193},
{8934485, -13485467, -23286397, -13423241, -32446090, 14047986, 31170398, -1441021, -27505566, 15087184},
},
{
{-18357243, -2156491, 24524913, -16677868, 15520427, -6360776, -15502406, 11461896, 16788528, -5868942},
{-1947386, 16013773, 21750665, 3714552, -17401782, -16055433, -3770287, -10323320, 31322514, -11615635},
{21426655, -5650218, -13648287, -5347537, -28812189, -4920970, -18275391, -14621414, 13040862, -12112948},
},
{
{11293895, 12478086, -27136401, 15083750, -29307421, 14748872, 14555558, -13417103, 1613711, 4896935},
{-25894883, 15323294, -8489791, -8057900, 25967126, -13425460, 2825960, -4897045, -23971776, -11267415},
{-15924766, -5229880, -17443532, 6410664, 3622847, 10243618, 20615400, 12405433, -23753030, -8436416},
},
{
{-7091295, 12556208, -20191352, 9025187, -17072479, 4333801, 4378436, 2432030, 23097949, -566018},
{4565804, -16025654, 20084412, -7842817, 1724999, 189254, 24767264, 10103221, -18512313, 2424778},
{366633, -11976806, 8173090, -6890119, 30788634, 5745705, -7168678, 1344109, -3642553, 12412659},
},
{
{-24001791, 7690286, 14929416, -168257, -32210835, -13412986, 24162697, -15326504, -3141501, 11179385},
{18289522, -14724954, 8056945, 16430056, -21729724, 7842514, -6001441, -1486897, -18684645, -11443503},
{476239, 6601091, -6152790, -9723375, 17503545, -4863900, 27672959, 13403813, 11052904, 5219329},
},
},
{
{
{20678546, -8375738, -32671898, 8849123, -5009758, 14574752, 31186971, -3973730, 9014762, -8579056},
{-13644050, -10350239, -15962508, 5075808, -1514661, -11534600, -33102500, 9160280, 8473550, -3256838},
{24900749, 14435722, 17209120, -15292541, -22592275, 9878983, -7689309, -16335821, -24568481, 11788948},
},
{
{-3118155, -11395194, -13802089, 14797441, 9652448, -6845904, -20037437, 10410733, -24568470, -1458691},
{-15659161, 16736706, -22467150, 10215878, -9097177, 7563911, 11871841, -12505194, -18513325, 8464118},
{-23400612, 8348507, -14585951, -861714, -3950205, -6373419, 14325289, 8628612, 33313881, -8370517},
},
{
{-20186973, -4967935, 22367356, 5271547, -1097117, -4788838, -24805667, -10236854, -8940735, -5818269},
{-6948785, -1795212, -32625683, -16021179, 32635414, -7374245, 15989197, -12838188, 28358192, -4253904},
{-23561781, -2799059, -32351682, -1661963, -9147719, 10429267, -16637684, 4072016, -5351664, 5596589},
},
{
{-28236598, -3390048, 12312896, 6213178, 3117142, 16078565, 29266239, 2557221, 1768301, 15373193},
{-7243358, -3246960, -4593467, -7553353, -127927, -912245, -1090902, -4504991, -24660491, 3442910},
{-30210571, 5124043, 14181784, 8197961, 18964734, -11939093, 22597931, 7176455, -18585478, 13365930},
},
{
{-7877390, -1499958, 8324673, 4690079, 6261860, 890446, 24538107, -8570186, -9689599, -3031667},
{25008904, -10771599, -4305031, -9638010, 16265036, 15721635, 683793, -11823784, 15723479, -15163481},
{-9660625, 12374379, -27006999, -7026148, -7724114, -12314514, 11879682, 5400171, 519526, -1235876},
},
{
{22258397, -16332233, -7869817, 14613016, -22520255, -2950923, -20353881, 7315967, 16648397, 7605640},
{-8081308, -8464597, -8223311, 9719710, 19259459, -15348212, 23994942, -5281555, -9468848, 4763278},
{-21699244, 9220969, -15730624, 1084137, -25476107, -2852390, 31088447, -7764523, -11356529, 728112},
},
{
{26047220, -11751471, -6900323, -16521798, 24092068, 9158119, -4273545, -12555558, -29365436, -5498272},
{17510331, -322857, 5854289, 8403524, 17133918, -3112612, -28111007, 12327945, 10750447, 10014012},
{-10312768, 3936952, 9156313, -8897683, 16498692, -994647, -27481051, -666732, 3424691, 7540221},
},
{
{30322361, -6964110, 11361005, -4143317, 7433304, 4989748, -7071422, -16317219, -9244265, 15258046},
{13054562, -2779497, 19155474, 469045, -12482797, 4566042, 5631406, 2711395, 1062915, -5136345},
{-19240248, -11254599, -29509029, -7499965, -5835763, 13005411, -6066489, 12194497, 32960380, 1459310},
},
},
{
{
{19852034, 7027924, 23669353, 10020366, 8586503, -6657907, 394197, -6101885, 18638003, -11174937},
{31395534, 15098109, 26581030, 8030562, -16527914, -5007134, 9012486, -7584354, -6643087, -5442636},
{-9192165, -2347377, -1997099, 4529534, 25766844, 607986, -13222, 9677543, -32294889, -6456008},
},
{
{-2444496, -149937, 29348902, 8186665, 1873760, 12489863, -30934579, -7839692, -7852844, -8138429},
{-15236356, -15433509, 7766470, 746860, 26346930, -10221762, -27333451, 10754588, -9431476, 5203576},
{31834314, 14135496, -770007, 5159118, 20917671, -16768096, -7467973, -7337524, 31809243, 7347066},
},
{
{-9606723, -11874240, 20414459, 13033986, 13716524, -11691881, 19797970, -12211255, 15192876, -2087490},
{-12663563, -2181719, 1168162, -3804809, 26747877, -14138091, 10609330, 12694420, 33473243, -13382104},
{33184999, 11180355, 15832085, -11385430, -1633671, 225884, 15089336, -11023903, -6135662, 14480053},
},
{
{31308717, -5619998, 31030840, -1897099, 15674547, -6582883, 5496208, 13685227, 27595050, 8737275},
{-20318852, -15150239, 10933843, -16178022, 8335352, -7546022, -31008351, -12610604, 26498114, 66511},
{22644454, -8761729, -16671776, 4884562, -3105614, -13559366, 30540766, -4286747, -13327787, -7515095},
},
{
{-28017847, 9834845, 18617207, -2681312, -3401956, -13307506, 8205540, 13585437, -17127465, 15115439},
{23711543, -672915, 31206561, -8362711, 6164647, -9709987, -33535882, -1426096, 8236921, 16492939},
{-23910559, -13515526, -26299483, -4503841, 25005590, -7687270, 19574902, 10071562, 6708380, -6222424},
},
{
{2101391, -4930054, 19702731, 2367575, -15427167, 1047675, 5301017, 9328700, 29955601, -11678310},
{3096359, 9271816, -21620864, -15521844, -14847996, -7592937, -25892142, -12635595, -9917575, 6216608},
{-32615849, 338663, -25195611, 2510422, -29213566, -13820213, 24822830, -6146567, -26767480, 7525079},
},
{
{-23066649, -13985623, 16133487, -7896178, -3389565, 778788, -910336, -2782495, -19386633, 11994101},
{21691500, -13624626, -641331, -14367021, 3285881, -3483596, -25064666, 9718258, -7477437, 13381418},
{18445390, -4202236, 14979846, 11622458, -1727110, -3582980, 23111648, -6375247, 28535282, 15779576},
},
{
{30098053, 3089662, -9234387, 16662135, -21306940, 11308411, -14068454, 12021730, 9955285, -16303356},
{9734894, -14576830, -7473633, -9138735, 2060392, 11313496, -18426029, 9924399, 20194861, 13380996},
{-26378102, -7965207, -22167821, 15789297, -18055342, -6168792, -1984914, 15707771, 26342023, 10146099},
},
},
{
{
{-26016874, -219943, 21339191, -41388, 19745256, -2878700, -29637280, 2227040, 21612326, -545728},
{-13077387, 1184228, 23562814, -5970442, -20351244, -6348714, 25764461, 12243797, -20856566, 11649658},
{-10031494, 11262626, 27384172, 2271902, 26947504, -15997771, 39944, 6114064, 33514190, 2333242},
},
{
{-21433588, -12421821, 8119782, 7219913, -21830522, -9016134, -6679750, -12670638, 24350578, -13450001},
{-4116307, -11271533, -23886186, 4843615, -30088339, 690623, -31536088, -10406836, 8317860, 12352766},
{18200138, -14475911, -33087759, -2696619, -23702521, -9102511, -23552096, -2287550, 20712163, 6719373},
},
{
{26656208, 6075253, -7858556, 1886072, -28344043, 4262326, 11117530, -3763210, 26224235, -3297458},
{-17168938, -14854097, -3395676, -16369877, -19954045, 14050420, 21728352, 9493610, 18620611, -16428628},
{-13323321, 13325349, 11432106, 5964811, 18609221, 6062965, -5269471, -9725556, -30701573, -16479657},
},
{
{-23860538, -11233159, 26961357, 1640861, -32413112, -16737940, 12248509, -5240639, 13735342, 1934062},
{25089769, 6742589, 17081145, -13406266, 21909293, -16067981, -15136294, -3765346, -21277997, 5473616},
{31883677, -7961101, 1083432, -11572403, 22828471, 13290673, -7125085, 12469656, 29111212, -5451014},
},
{
{24244947, -15050407, -26262976, 2791540, -14997599, 16666678, 24367466, 6388839, -10295587, 452383},
{-25640782, -3417841, 5217916, 16224624, 19987036, -4082269, -24236251, -5915248, 15766062, 8407814},
{-20406999, 13990231, 15495425, 16395525, 5377168, 15166495, -8917023, -4388953, -8067909, 2276718},
},
{
{30157918, 12924066, -17712050, 9245753, 19895028, 3368142, -23827587, 5096219, 22740376, -7303417},
{2041139, -14256350, 7783687, 13876377, -25946985, -13352459, 24051124, 13742383, -15637599, 13295222},
{33338237, -8505733, 12532113, 7977527, 9106186, -1715251, -17720195, -4612972, -4451357, -14669444},
},
{
{-20045281, 5454097, -14346548, 6447146, 28862071, 1883651, -2469266, -4141880, 7770569, 9620597},
{23208068, 7979712, 33071466, 8149229, 1758231, -10834995, 30945528, -1694323, -33502340, -14767970},
{1439958, -16270480, -1079989, -793782, 4625402, 10647766, -5043801, 1220118, 30494170, -11440799},
},
{
{-5037580, -13028295, -2970559, -3061767, 15640974, -6701666, -26739026, 926050, -1684339, -13333647},
{13908495, -3549272, 30919928, -6273825, -21521863, 7989039, 9021034, 9078865, 3353509, 4033511},
{-29663431, -15113610, 32259991, -344482, 24295849, -12912123, 23161163, 8839127, 27485041, 7356032},
},
},
{
{
{9661027, 705443, 11980065, -5370154, -1628543, 14661173, -6346142, 2625015, 28431036, -16771834},
{-23839233, -8311415, -25945511, 7480958, -17681669, -8354183, -22545972, 14150565, 15970762, 4099461},
{29262576, 16756590, 26350592, -8793563, 8529671, -11208050, 13617293, -9937143, 11465739, 8317062},
},
{
{-25493081, -6962928, 32500200, -9419051, -23038724, -2302222, 14898637, 3848455, 20969334, -5157516},
{-20384450, -14347713, -18336405, 13884722, -33039454, 2842114, -21610826, -3649888, 11177095, 14989547},
{-24496721, -11716016, 16959896, 2278463, 12066309, 10137771, 13515641, 2581286, -28487508, 9930240},
},
{
{-17751622, -2097826, 16544300, -13009300, -15914807, -14949081, 18345767, -13403753, 16291481, -5314038},
{-33229194, 2553288, 32678213, 9875984, 8534129, 6889387, -9676774, 6957617, 4368891, 9788741},
{16660756, 7281060, -10830758, 12911820, 20108584, -8101676, -21722536, -8613148, 16250552, -11111103},
},
{
{-19765507, 2390526, -16551031, 14161980, 1905286, 6414907, 4689584, 10604807, -30190403, 4782747},
{-1354539, 14736941, -7367442, -13292886, 7710542, -14155590, -9981571, 4383045, 22546403, 437323},
{31665577, -12180464, -16186830, 1491339, -18368625, 3294682, 27343084, 2786261, -30633590, -14097016},
},
{
{-14467279, -683715, -33374107, 7448552, 19294360, 14334329, -19690631, 2355319, -19284671, -6114373},
{15121312, -15796162, 6377020, -6031361, -10798111, -12957845, 18952177, 15496498, -29380133, 11754228},
{-2637277, -13483075, 8488727, -14303896, 12728761, -1622493, 7141596, 11724556, 22761615, -10134141},
},
{
{16918416, 11729663, -18083579, 3022987, -31015732, -13339659, -28741185, -12227393, 32851222, 11717399},
{11166634, 7338049, -6722523, 4531520, -29468672, -7302055, 31474879, 3483633, -1193175, -4030831},
{-185635, 9921305, 31456609, -13536438, -12013818, 13348923, 33142652, 6546660, -19985279, -3948376},
},
{
{-32460596, 11266712, -11197107, -7899103, 31703694, 3855903, -8537131, -12833048, -30772034, -15486313},
{-18006477, 12709068, 3991746, -6479188, -21491523, -10550425, -31135347, -16049879, 10928917, 3011958},
{-6957757, -15594337, 31696059, 334240, 29576716, 14796075, -30831056, -12805180, 18008031, 10258577},
},
{
{-22448644, 15655569, 7018479, -4410003, -30314266, -1201591, -1853465, 1367120, 25127874, 6671743},
{29701166, -14373934, -10878120, 9279288, -17568, 13127210, 21382910, 11042292, 25838796, 4642684},
{-20430234, 14955537, -24126347, 8124619, -5369288, -5990470, 30468147, -13900640, 18423289, 4177476},
},
},
};
void TableLookup(GePre *preCompute, int32_t pos, int8_t e)
{
GePre negate;
// Prevent side-channel attack: Do not use conditional statements to ensure that the execution time is constant.
// -negative = 11111111 if e is negative, or 0 if e is not
// (-negative & e) << 1 = 2e if e is negative, or 0 if e is positive
// absolute value = e - 2e (e negative) or e (e positive)
uint8_t negative = (uint8_t)e >> 7; // shift 7 to check negative
// range of e is -7 to 8, left shift won't cause sign change
uint8_t abs = (uint8_t)(e - ((uint8_t)(-negative & (uint8_t)e) << 1));
// set base result
CURVE25519_FP_SET(preCompute->yplusx, 1);
CURVE25519_FP_SET(preCompute->yminusx, 1);
CURVE25519_FP_SET(preCompute->xy2d, 0);
// only copy the corrsponding position
ConditionalMove(preCompute, &CURVE25519PRE_COMPUTE[pos][0], abs == 1); // 1 of 8
ConditionalMove(preCompute, &CURVE25519PRE_COMPUTE[pos][1], abs == 2); // 2 of 8
ConditionalMove(preCompute, &CURVE25519PRE_COMPUTE[pos][2], abs == 3); // 3 of 8
ConditionalMove(preCompute, &CURVE25519PRE_COMPUTE[pos][3], abs == 4); // 4 of 8
ConditionalMove(preCompute, &CURVE25519PRE_COMPUTE[pos][4], abs == 5); // 5 of 8
ConditionalMove(preCompute, &CURVE25519PRE_COMPUTE[pos][5], abs == 6); // 6 of 8
ConditionalMove(preCompute, &CURVE25519PRE_COMPUTE[pos][6], abs == 7); // 7 of 8
ConditionalMove(preCompute, &CURVE25519PRE_COMPUTE[pos][7], abs == 8); // 8 of 8
CURVE25519_FP_COPY(negate.yminusx, preCompute->yplusx);
CURVE25519_FP_COPY(negate.yplusx, preCompute->yminusx);
CURVE25519_FP_NEGATE(negate.xy2d, preCompute->xy2d);
ConditionalMove(preCompute, &negate, negative);
}
#endif /* HITLS_CRYPTO_CURVE25519 */
|
2301_79861745/bench_create
|
crypto/curve25519/src/curve25519_table.c
|
C
|
unknown
| 96,121
|
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_X25519
#include "securec.h"
#include "curve25519_local.h"
// X25519 alternative implementation, faster but require int128
#if (defined(__SIZEOF_INT128__) && (__SIZEOF_INT128__ == 16))
#define CURVE25519_51BITS_MASK 0x7ffffffffffff
#define CURVE25519_51BITS 51
static void Fp51DataToPoly(Fp51 *out, const uint8_t in[32])
{
uint64_t h[5];
CURVE25519_BYTES7_LOAD(h, in);
CURVE25519_BYTES6_LOAD(h + 1, in + 7);
h[1] <<= 5;
CURVE25519_BYTES7_LOAD(h + 2, in + 13);
h[2] <<= 2;
CURVE25519_BYTES6_LOAD(h + 3, in + 20);
h[3] <<= 7;
CURVE25519_BYTES6_LOAD(h + 4, in + 26);
h[4] &= 0x7fffffffffff; // 41 bits mask = 0x7fffffffffff
h[4] <<= 4;
h[1] |= h[0] >> CURVE25519_51BITS;
h[0] &= CURVE25519_51BITS_MASK;
h[2] |= h[1] >> CURVE25519_51BITS;
h[1] &= CURVE25519_51BITS_MASK;
h[3] |= h[2] >> CURVE25519_51BITS;
h[2] &= CURVE25519_51BITS_MASK;
h[4] |= h[3] >> CURVE25519_51BITS;
h[3] &= CURVE25519_51BITS_MASK;
out->data[0] = h[0];
out->data[1] = h[1];
out->data[2] = h[2];
out->data[3] = h[3];
out->data[4] = h[4];
}
static void Fp51UnloadTo8Bits(uint8_t out[32], uint64_t h[5])
{
// load from uint64 to uint8, load 8 bits at a time
out[0] = (uint8_t)h[0];
out[1] = (uint8_t)(h[0] >> 8);
out[2] = (uint8_t)(h[0] >> 16);
out[3] = (uint8_t)(h[0] >> 24);
out[4] = (uint8_t)(h[0] >> 32);
out[5] = (uint8_t)(h[0] >> 40);
// load from position 48 from h[1] and (8-5)=3 bits from h[1] to out[6]
out[6] = (uint8_t)((h[0] >> 48) | (uint8_t)(h[1] << 3));
out[7] = (uint8_t)(h[1] >> 5);
out[8] = (uint8_t)(h[1] >> 13);
out[9] = (uint8_t)(h[1] >> 21);
out[10] = (uint8_t)(h[1] >> 29);
out[11] = (uint8_t)(h[1] >> 37);
// load from position 45 from h[1] and (8-2)=6 bits from h[2] to out[12]
out[12] = (uint8_t)((h[1] >> 45) | (uint8_t)(h[2] << 6));
out[13] = (uint8_t)(h[2] >> 2);
out[14] = (uint8_t)(h[2] >> 10);
out[15] = (uint8_t)(h[2] >> 18);
out[16] = (uint8_t)(h[2] >> 26);
out[17] = (uint8_t)(h[2] >> 34);
out[18] = (uint8_t)(h[2] >> 42);
// load from position 50 from h[2] and (8-1)=7 bits from h[3] to out[19]
out[19] = (uint8_t)((h[2] >> 50) | (uint8_t)(h[3] << 1));
out[20] = (uint8_t)(h[3] >> 7);
out[21] = (uint8_t)(h[3] >> 15);
out[22] = (uint8_t)(h[3] >> 23);
out[23] = (uint8_t)(h[3] >> 31);
out[24] = (uint8_t)(h[3] >> 39);
// load from position 47 from h[3] and (4-4)=4 bits from h[4] to out[25]
out[25] = (uint8_t)((h[3] >> 47) | (uint8_t)(h[4] << 4));
out[26] = (uint8_t)(h[4] >> 4);
out[27] = (uint8_t)(h[4] >> 12);
out[28] = (uint8_t)(h[4] >> 20);
out[29] = (uint8_t)(h[4] >> 28);
out[30] = (uint8_t)(h[4] >> 36);
out[31] = (uint8_t)(h[4] >> 44);
}
static void Fp51PolyToData(const Fp51 *in, uint8_t out[32])
{
uint64_t h[5];
h[0] = in->data[0];
h[1] = in->data[1];
h[2] = in->data[2];
h[3] = in->data[3];
h[4] = in->data[4];
uint64_t carry;
carry = (h[0] + 19) >> CURVE25519_51BITS; // plus 19 then calculate carry
carry = (h[1] + carry) >> CURVE25519_51BITS;
carry = (h[2] + carry) >> CURVE25519_51BITS;
carry = (h[3] + carry) >> CURVE25519_51BITS;
carry = (h[4] + carry) >> CURVE25519_51BITS;
h[0] += 19 * carry; // process carry h[4] -> h[0], h[0] += 19 * carry
h[1] += h[0] >> CURVE25519_51BITS;
h[0] &= CURVE25519_51BITS_MASK;
h[2] += h[1] >> CURVE25519_51BITS;
h[1] &= CURVE25519_51BITS_MASK;
h[3] += h[2] >> CURVE25519_51BITS;
h[2] &= CURVE25519_51BITS_MASK;
h[4] += h[3] >> CURVE25519_51BITS;
h[3] &= CURVE25519_51BITS_MASK;
h[4] &= CURVE25519_51BITS_MASK;
Fp51UnloadTo8Bits(out, h);
}
void Fp51ProcessCarry(__uint128_t in[5])
{
in[1] += (uint64_t)(in[0] >> CURVE25519_51BITS);
in[0] = (uint64_t)in[0] & CURVE25519_51BITS_MASK;
in[2] += (uint64_t)(in[1] >> CURVE25519_51BITS);
in[1] = (uint64_t)in[1] & CURVE25519_51BITS_MASK;
in[3] += (uint64_t)(in[2] >> CURVE25519_51BITS);
in[2] = (uint64_t)in[2] & CURVE25519_51BITS_MASK;
in[4] += (uint64_t)(in[3] >> CURVE25519_51BITS);
in[3] = (uint64_t)in[3] & CURVE25519_51BITS_MASK;
in[0] += (uint64_t)(in[4] >> CURVE25519_51BITS) * 19;
in[4] = (uint64_t)in[4] & CURVE25519_51BITS_MASK;
in[1] += in[0] >> CURVE25519_51BITS;
in[0] &= CURVE25519_51BITS_MASK;
}
void Fp51Mul(Fp51 *out, const Fp51 *f, const Fp51 *g)
{
__uint128_t h[5];
// h[0] = f0g0 + 19*f1g4 + 19*f2g3 + 19*f3g2 + 19*f4g1
h[0] = (__uint128_t)f->data[0] * g->data[0] + (__uint128_t)f->data[1] * g->data[4] * 19 +
(__uint128_t)f->data[2] * g->data[3] * 19 + (__uint128_t)f->data[3] * g->data[2] * 19 + // 19*f2g3 + 19*f3g2
(__uint128_t)f->data[4] * g->data[1] * 19; // 19*f4g1
// h[1] = f0g1 + f1g0 + 19*f2g4 + 19*f3g3 + 19*f4g2
h[1] = (__uint128_t)f->data[0] * g->data[1] + (__uint128_t)f->data[1] * g->data[0] +
(__uint128_t)f->data[2] * g->data[4] * 19 + (__uint128_t)f->data[3] * g->data[3] * 19 + // 19*f2g4 + 19*f3g3
(__uint128_t)f->data[4] * g->data[2] * 19; // 19*f4g2
// h[2] = f0g2 + f1g1 + f2g0 + 19*f3g4 + 19*f4g3
h[2] = (__uint128_t)f->data[0] * g->data[2] + (__uint128_t)f->data[1] * g->data[1] +
(__uint128_t)f->data[2] * g->data[0] + (__uint128_t)f->data[3] * g->data[4] * 19 + // f2g0 + 19*f3g4
(__uint128_t)f->data[4] * g->data[3] * 19; // 19*f4g3
// h[3] = f0g3 + f1g2 + f2g1 + f3g0 + 19*f4g4
h[3] = (__uint128_t)f->data[0] * g->data[3] + (__uint128_t)f->data[1] * g->data[2] +
(__uint128_t)f->data[2] * g->data[1] + (__uint128_t)f->data[3] * g->data[0] + // f2g1 + f3g0
(__uint128_t)f->data[4] * g->data[4] * 19; // 19*f4g4
// h[4] = f0g4 + f1g3 + f2g2 + f3g1 + f4g0
h[4] = (__uint128_t)f->data[0] * g->data[4] + (__uint128_t)f->data[1] * g->data[3] +
(__uint128_t)f->data[2] * g->data[2] + (__uint128_t)f->data[3] * g->data[1] + // f2g2 + f3g1
(__uint128_t)f->data[4] * g->data[0]; // f4g0
Fp51ProcessCarry(h);
out->data[0] = (uint64_t)h[0];
out->data[1] = (uint64_t)h[1];
out->data[2] = (uint64_t)h[2];
out->data[3] = (uint64_t)h[3];
out->data[4] = (uint64_t)h[4];
}
void Fp51Square(Fp51 *out, const Fp51 *in)
{
__uint128_t h[5];
uint64_t in0mul2 = in->data[0] * 2;
uint64_t in1mul2 = in->data[1] * 2;
uint64_t in2mul2 = in->data[2] * 2;
uint64_t in3mul19 = in->data[3] * 19;
uint64_t in4mul19 = in->data[4] * 19;
// h0 = in0^2 + 38 * in1 * in4 + 38 * in2 * in3
h[0] = (__uint128_t)in->data[0] * in->data[0] + (__uint128_t)in1mul2 * in4mul19 +
(__uint128_t)in2mul2 * in3mul19;
// h1 = 2 * in0 * in1 + 19 * in3^2 + 38 * in2 * in4
h[1] = (__uint128_t)in0mul2 * in->data[1] + (__uint128_t)in->data[3] * in3mul19 +
(__uint128_t)in2mul2 * in4mul19;
// h2 = 2 * in0 * in2 + in1^2 + 38 * in3 * in4
h[2] = (__uint128_t)in0mul2 * in->data[2] + (__uint128_t)in->data[1] * in->data[1] +
(__uint128_t)(in->data[3] * 2) * in4mul19; // 2 * 19 * in3 * in4
// h3 = 2 * in0 * in3 + 19 * in4^2 + 2 * in1 * in2
h[3] = (__uint128_t)in0mul2 * in->data[3] + (__uint128_t)in->data[4] * in4mul19 +
(__uint128_t)in1mul2 * in->data[2]; // 2 * in1 * in2
// h4 = 2 * in0 * in4 + 2 * in1 * in3 + in2^2
h[4] = (__uint128_t)in0mul2 * in->data[4] + (__uint128_t)in1mul2 * in->data[3] +
(__uint128_t)in->data[2] * in->data[2]; // in2^2
Fp51ProcessCarry(h);
out->data[0] = (uint64_t)h[0];
out->data[1] = (uint64_t)h[1];
out->data[2] = (uint64_t)h[2];
out->data[3] = (uint64_t)h[3];
out->data[4] = (uint64_t)h[4];
}
void Fp51MulScalar(Fp51 *out, const Fp51 *in, const uint32_t scalar)
{
__uint128_t h[5];
h[0] = in->data[0] * (__uint128_t)scalar;
h[1] = in->data[1] * (__uint128_t)scalar;
h[2] = in->data[2] * (__uint128_t)scalar;
h[3] = in->data[3] * (__uint128_t)scalar;
h[4] = in->data[4] * (__uint128_t)scalar;
Fp51ProcessCarry(h);
out->data[0] = (uint64_t)h[0];
out->data[1] = (uint64_t)h[1];
out->data[2] = (uint64_t)h[2];
out->data[3] = (uint64_t)h[3];
out->data[4] = (uint64_t)h[4];
}
/* out = in1 ^ (4 * 2 ^ (2 * times)) * in2 */
static inline void Fp51MultiSquare(Fp51 *in1, Fp51 *in2, Fp51 *out, int32_t times)
{
int32_t i;
Fp51 temp1, temp2;
Fp51Square(&temp1, in1);
Fp51Square(&temp2, &temp1);
for (i = 0; i < times; i++) {
Fp51Square(&temp1, &temp2);
Fp51Square(&temp2, &temp1);
}
Fp51Mul(out, in2, &temp2);
}
/* out = a ^ -1 */
static void Fp51Invert(Fp51 *out, const Fp51 *a)
{
Fp51 a0; /* save a^1 */
Fp51 a1; /* save a^2 */
Fp51 a2; /* save a^11 */
Fp51 a3; /* save a^(2^5-1) */
Fp51 a4; /* save a^(2^10-1) */
Fp51 a5; /* save a^(2^20-1) */
Fp51 a6; /* save a^(2^40-1) */
Fp51 a7; /* save a^(2^50-1) */
Fp51 a8; /* save a^(2^100-1) */
Fp51 a9; /* save a^(2^200-1) */
Fp51 a10; /* save a^(2^250-1) */
Fp51 temp1, temp2;
/* We know a×b=1(mod p), then a and b are inverses of mod p, i.e. a=b^(-1), b=a^(-1);
* According to Fermat's little theorem a^(p-1)=1(mod p), so a*a^(p-2)=1(mod p);
* So the inverse element of a is a^(-1) = a^(p-2)(mod p)
* Here it is, p=2^255-19, thus we need to compute a^(2^255-21)(mod(2^255-19))
*/
/* a^1 */
CURVE25519_FP51_COPY(a0.data, a->data);
/* a^2 */
Fp51Square(&a1, &a0);
/* a^4 */
Fp51Square(&temp1, &a1);
/* a^8 */
Fp51Square(&temp2, &temp1);
/* a^9 */
Fp51Mul(&temp1, &a0, &temp2);
/* a^11 */
Fp51Mul(&a2, &a1, &temp1);
/* a^22 */
Fp51Square(&temp2, &a2);
/* a^(2^5-1) = a^(9+22) */
Fp51Mul(&a3, &temp1, &temp2);
/* a^(2^10-1) = a^(2^10-2^5) * a^(2^5-1) */
Fp51Square(&temp1, &a3);
Fp51Square(&temp2, &temp1);
Fp51Square(&temp1, &temp2);
Fp51Square(&temp2, &temp1);
Fp51Square(&temp1, &temp2);
Fp51Mul(&a4, &a3, &temp1);
/* a^(2^20-1) = a^(2^20-2^10) * a^(2^10-1) */
Fp51MultiSquare(&a4, &a4, &a5, 4); // (2 * 2) ^ 4
/* a^(2^40-1) = a^(2^40-2^20) * a^(2^20-1) */
Fp51MultiSquare(&a5, &a5, &a6, 9); // (2 * 2) ^ 9
/* a^(2^50-1) = a^(2^50-2^10) * a^(2^10-1) */
Fp51MultiSquare(&a6, &a4, &a7, 4); // (2 * 2) ^ 4
/* a^(2^100-1) = a^(2^100-2^50) * a^(2^50-1) */
Fp51MultiSquare(&a7, &a7, &a8, 24); // (2 * 2) ^ 24
/* a^(2^200-1) = a^(2^200-2^100) * a^(2^100-1) */
Fp51MultiSquare(&a8, &a8, &a9, 49); // (2 * 2) ^ 49
/* a^(2^250-1) = a^(2^250-2^50) * a^(2^50-1) */
Fp51MultiSquare(&a9, &a7, &a10, 24); // (2 * 2) ^ 24
/* a^(2^5*(2^250-1)) = (a^(2^250-1))^5 */
Fp51Square(&temp1, &a10);
Fp51Square(&temp2, &temp1);
Fp51Square(&temp1, &temp2);
Fp51Square(&temp2, &temp1);
Fp51Square(&temp1, &temp2);
/* The output: a^(2^255-21) = a(2^5*(2^250-1)+11) = a^(2^5*(2^250-1)) * a^11 */
Fp51Mul(out, &a2, &temp1);
}
void ScalarMultiPoint(uint8_t out[32], const uint8_t scalar[32], const uint8_t point[32])
{
uint8_t k[32];
const uint8_t *u = point;
int32_t t;
uint32_t swap;
uint32_t kTemp;
Fp51 x1, x2, x3;
Fp51 z2, z3;
Fp51 t1, t2;
/* Decord the scalar into k */
CURVE25519_DECODE_LITTLE_ENDIAN(k, scalar);
/* Reference RFC 7748 section 5: The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 */
Fp51DataToPoly(&x1, u);
CURVE25519_FP51_SET(x2.data, 1);
CURVE25519_FP51_SET(z2.data, 0);
CURVE25519_FP51_COPY(x3.data, x1.data);
CURVE25519_FP51_SET(z3.data, 1);
swap = 0;
/* "bits" parameter set to 255 for x25519 */ /* For t = bits-1(254) down to 0: */
for (t = 254; t >= 0; t--) {
/* t >> 3: calculation the index of bit; t & 7: Obtains the corresponding bit in the byte */
kTemp = (k[(uint32_t)t >> 3] >> ((uint32_t)t & 7)) & 1; /* kTemp = (k >> t) & 1 */
swap ^= kTemp; /* swap ^= kTemp */
CURVE25519_FP51_CSWAP(swap, x2.data, x3.data); /* (x_2, x_3) = cswap(swap, x_2, x_3) */
CURVE25519_FP51_CSWAP(swap, z2.data, z3.data); /* (z_2, z_3) = cswap(swap, z_2, z_3) */
swap = kTemp; /* swap = kTemp */
CURVE25519_FP51_SUB(t1.data, x3.data, z3.data); /* x3 = D */
CURVE25519_FP51_SUB(t2.data, x2.data, z2.data); /* t2 = B */
CURVE25519_FP51_ADD(x2.data, x2.data, z2.data); /* t1 = A */
CURVE25519_FP51_ADD(z2.data, x3.data, z3.data); /* x2 = C */
Fp51Mul(&z3, &t1, &x2);
Fp51Mul(&z2, &z2, &t2);
Fp51Square(&t1, &t2);
Fp51Square(&t2, &x2);
CURVE25519_FP51_ADD(x3.data, z3.data, z2.data);
CURVE25519_FP51_SUB(z2.data, z3.data, z2.data);
Fp51Mul(&x2, &t2, &t1);
CURVE25519_FP51_SUB(t2.data, t2.data, t1.data);
Fp51Square(&z2, &z2);
Fp51MulScalar(&z3, &t2, 121666); // z2 *= 121665 + 1 = 121666
Fp51Square(&x3, &x3);
CURVE25519_FP51_ADD(t1.data, t1.data, z3.data);
Fp51Mul(&z3, &x1, &z2);
Fp51Mul(&z2, &t2, &t1);
}
CURVE25519_FP51_CSWAP(swap, x2.data, x3.data);
CURVE25519_FP51_CSWAP(swap, z2.data, z3.data);
/* Return x2 * (z2 ^ (p - 2)) */
Fp51Invert(&t1, &z2);
Fp51Mul(&t2, &x2, &t1);
Fp51PolyToData(&t2, out);
BSL_SAL_CleanseData(k, sizeof(k));
}
#else
void FpMulScalar(Fp25 out, const Fp25 p, const int32_t scalar)
{
int64_t s = (int64_t)scalar;
uint64_t over;
uint64_t result[10];
uint64_t mul19;
uint64_t t1;
uint64_t signMask1;
uint64_t signMask2;
/* Could be more than 32 bits but not be more than 64 bits */
CURVE25519_FP_MUL_SCALAR(result, p, s);
/* Process Carry */
/* the radix 2^25.5 representation:
* f0+2^26*f1+2^51*f2+2^77*f3+2^102*f4+2^128*f5+2^153*f6+2^179*f7+2^204*f8+2^230*f9 */
over = result[9] + (1 << 24); /* carry chain: index 9->0; 2^25 progressiv, left shift by 24 bits */
signMask1 = MASK_HIGH64(25) & (-((over) >> 63)); /* 2^25 progressiv, shift 63 for sign */
t1 = (over >> 25) | signMask1;
mul19 = (t1 + (t1 << 1) + (t1 << 4)); /* 19 = 1 + 2^1 + 2^4 */
result[0] += mul19; /* carry chain: index 9->0 */
result[9] -= CURVE25519_MASK_HIGH_39 & over;
/* carry chain: index 1->2; 2^25 progressiv(26->51) */
/* carry chain: index 1->2; 2^25 progressiv, left shift by 24 bits */
PROCESS_CARRY(result[1], result[2], signMask1, over, 24);
/* carry chain: index 3->4; 2^25 progressiv(77->102) */
/* carry chain: index 3->4; 2^25 progressiv, left shift by 24 bits */
PROCESS_CARRY(result[3], result[4], signMask1, over, 24);
/* carry chain: index 5->6; 2^25 progressiv(128->153) */
/* carry chain: index 5->6; 2^25 progressiv, left shift by 24 bits */
PROCESS_CARRY(result[5], result[6], signMask1, over, 24);
/* carry chain: index 7->8; 2^25 progressiv(179->204) */
/* carry chain: index 7->8; 2^25 progressiv, left shift by 24 bits */
PROCESS_CARRY(result[7], result[8], signMask1, over, 24);
/* carry chain: index 0->1; 2^26 progressiv(0->26) */
/* carry chain: index 0->1; 2^26 progressiv, left shift by 25 bits */
PROCESS_CARRY(result[0], result[1], signMask2, over, 25);
/* carry chain: index 2->3; 2^26 progressiv(51->77) */
/* carry chain: index 2->3; 2^26 progressiv, left shift by 25 bits */
PROCESS_CARRY(result[2], result[3], signMask2, over, 25);
/* carry chain: index 4->5; 2^26 progressiv(102->128) */
/* carry chain: index 4->5; 2^26 progressiv, left shift by 25 bits */
PROCESS_CARRY(result[4], result[5], signMask2, over, 25);
/* carry chain: index 6->7; 2^26 progressiv(153->179) */
/* carry chain: index 6->7; 2^26 progressiv, left shift by 25 bits */
PROCESS_CARRY(result[6], result[7], signMask2, over, 25);
/* carry chain: index 8->9; 2^26 progressiv(204->230) */
/* carry chain: index 8->9; 2^26 progressiv, left shift by 25 bits */
PROCESS_CARRY(result[8], result[9], signMask2, over, 25);
/* The result would not be more than 32 bits */
out[0] = (int32_t)result[0]; // 0
out[1] = (int32_t)result[1]; // 1
out[2] = (int32_t)result[2]; // 2
out[3] = (int32_t)result[3]; // 3
out[4] = (int32_t)result[4]; // 4
out[5] = (int32_t)result[5]; // 5
out[6] = (int32_t)result[6]; // 6
out[7] = (int32_t)result[7]; // 7
out[8] = (int32_t)result[8]; // 8
out[9] = (int32_t)result[9]; // 9
(void)memset_s(result, sizeof(result), 0, sizeof(result));
}
void ScalarMultiPoint(uint8_t out[32], const uint8_t scalar[32], const uint8_t point[32])
{
uint8_t k[32];
const uint8_t *u = point;
int32_t t;
uint32_t swap;
uint32_t kTemp;
Fp25 x1, x2, x3, z2, z3, t1, t2, t3;
/* Decord the scalar into k */
CURVE25519_DECODE_LITTLE_ENDIAN(k, scalar);
/* Reference RFC 7748 section 5:The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 */
DataToPolynomial(x1, u);
CURVE25519_FP_SET(x2, 1);
CURVE25519_FP_SET(z2, 0);
CURVE25519_FP_COPY(x3, x1);
CURVE25519_FP_SET(z3, 1);
swap = 0;
/* "bits" parameter set to 255 for x25519 */ /* For t = bits-1(254) down to 0: */
for (t = 254; t >= 0; t--) {
/* t >> 3: calculation the index of bit; t & 7: Obtains the corresponding bit in the byte */
kTemp = (k[(uint32_t)t >> 3] >> ((uint32_t)t & 7)) & 1; /* kTemp = (k >> t) & 1 */
swap ^= kTemp; /* swap ^= kTemp */
CURVE25519_FP_CSWAP(swap, x2, x3); /* (x_2, x_3) = cswap(swap, x_2, x_3) */
CURVE25519_FP_CSWAP(swap, z2, z3); /* (z_2, z_3) = cswap(swap, z_2, z_3) */
swap = kTemp; /* swap = kTemp */
CURVE25519_FP_ADD(t1, x2, z2); /* t1 = A */
CURVE25519_FP_SUB(t2, x2, z2); /* t2 = B */
CURVE25519_FP_ADD(x2, x3, z3); /* x2 = C */
CURVE25519_FP_SUB(x3, x3, z3); /* x3 = D */
FpMul(z2, x3, t1); /* z2 = DA */
FpMul(z3, x2, t2); /* z3 = CB */
FpSquareDoubleCore(t1, t1, false); /* t1 = AA */
FpSquareDoubleCore(t2, t2, false); /* t2 = BB */
CURVE25519_FP_SUB(t3, t1, t2); /* t3 = E = AA - BB */
CURVE25519_FP_ADD(x3, z2, z3); /* x3 = DA + CB */
FpSquareDoubleCore(x3, x3, false); /* x3 = (DA + CB)^2 */
CURVE25519_FP_SUB(z3, z2, z3); /* z3 = DA - CB */
FpSquareDoubleCore(z3, z3, false); /* z3 = (DA - CB)^2 */
FpMul(z3, x1, z3); /* z3 = x1 * (DA - CB)^2 */
FpMul(x2, t1, t2); /* x2 = AA * BB */
FpMul(t1, t3, t1); /* t1 = E * AA */
FpSquareDoubleCore(z2, t3, false); /* z2 = E^2 */
/* Reference RFC 7748 section 5:The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 */
FpMulScalar(z2, z2, 121665); /* z2 = a24 * E^2 */
CURVE25519_FP_ADD(z2, t1, z2); /* z2 = E * (AA + a24 * E) */
}
CURVE25519_FP_CSWAP(swap, x2, x3);
CURVE25519_FP_CSWAP(swap, z2, z3);
/* Return x2 * (z2 ^ (p - 2)) */
FpInvert(t1, z2);
FpMul(t2, x2, t1);
PolynomialToData(out, t2);
}
#endif // uint128
#endif /* HITLS_CRYPTO_X25519 */
|
2301_79861745/bench_create
|
crypto/curve25519/src/noasm_curve25519_fp51_ops.c
|
C
|
unknown
| 20,251
|
/*
* 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 X25519_ASM_H
#define X25519_ASM_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_X25519
#include "curve25519_local.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* Function description: out = f * g (mod p), p = 2 ^ 255 - 19, which is the modulus of curve25519 field.
* Function prototype: void Fp51Mul(Fp51 *out, const Fp51 *f, const Fp51 *g);
* Input register: rdi: out; rsi: f; rdx: g; fp51 is an array of [u64; 5].
* rdi: out, array pointer of output parameter fp51.
* rsi: pointer f of the input source data fp51 array.
* rdx: pointer g of the input source data fp51 array.
* Modify the register as follows: rax, rbx, rcx, rdx, rsp, rbp, rsi, rdi, r8-r15.
* Output register: None
* Function/Macro Call: None
*/
void Fp51Mul(Fp51 *out, const Fp51 *f, const Fp51 *g);
/**
* Function description: out = f ^ 2 (mod p), p = 2 ^ 255 - 19, which is the modulus of curve25519 field.
* Function prototype: void Fp51Square(Fp51 *out, const Fp51 *f);
* Input register: rdi: out; rsi: f; fp51 is an array of [u64; 5]
* rdi: out, array pointer of output parameter fp51.
* rsi: pointer f of the input source data fp51 array.
* Modify the register as follows: rax, rbx, rcx, rdx, rsp, rbp, rsi, rdi, r8-r15.
* Output register: None
* Function/Macro Call: None
*/
void Fp51Square(Fp51 *out, const Fp51 *f);
/**
* Function description: out = f * 121666 (mod p), p = 2 ^ 255 - 19, which is the modulus of curve25519 field.
* Function prototype: void Fp51MulScalar(Fp51 *out, const Fp51 *f, const uint32_t scalar);
* Input register: rdi: out; rsi: f; fp51 is an array of [u64; 5]
* rdi: out, array pointer of output parameter fp51.
* rsi: pointer f of the input source data fp51 array.
* Modify the register as follows: rax, rbx, rcx, rdx, rsp, rbp, rsi, rdi, r8-r15.
* Output register: None
* Function/Macro Call: None
*/
void Fp51MulScalar(Fp51 *out, const Fp51 *in);
#ifdef HITLS_CRYPTO_X25519_X8664
typedef uint64_t Fp64[4];
/**
* Function description: out = f * g (mod p), p = 2 ^ 255 - 19, which is the modulus of curve25519 field.
* Function prototype: void Fp64Mul(Fp64 h, const Fp64 f, const Fp64 g);
* Input register: rdi: out; rsi: f; rdx: g; Fp64 is an array of [u64; 4].
* rdi: out, array pointer of output parameter Fp64.
* rsi: pointer f of the input source data Fp64 array.
* rdx: pointer g of the input source data Fp64 array.
* Modify the register as follows: rax, rbx, rcx, rdx, rsp, rbp, rsi, rdi, r8-r15.
* Output register: None
* Function/Macro Call: None
*/
void Fp64Mul(Fp64 out, const Fp64 f, const Fp64 g);
/**
* Function description: out = f ^ 2 (mod p), p = 2 ^ 255 - 19, which is the modulus of curve25519 field.
* Function prototype: void Fp64Sqr(Fp64 h, const Fp64 f);
* Input register: rdi: out; rsi: f; Fp64 is an array of [u64; 4]
* rdi: out, array pointer of output parameter Fp64.
* rsi: pointer f of the input source data Fp64 array.
* Modify the register as follows: rax, rbx, rcx, rdx, rsp, rbp, rsi, rdi, r8-r15.
* Output register: None
* Function/Macro Call: None
*/
void Fp64Sqr(Fp64 out, const Fp64 f);
/**
* Function description: out = f * 121666 (mod p), p = 2 ^ 255 - 19, which is the modulus of curve25519 field.
* Function prototype: void Fp64MulScalar(Fp64 h, Fp64 f);
* Input register: rdi: out; rsi: f; Fp64 is an array of [u64; 4]
* rdi: out, array pointer of output parameter Fp64.
* rsi: pointer f of the input source data Fp64 array.
* Modify the register as follows: rax, rbx, rcx, rdx, rsp, rbp, rsi, rdi, r8-r15.
* Output register: None
* Function/Macro Call: None
*/
void Fp64MulScalar(Fp64 out, Fp64 f);
/**
* Function description: out = f + g (mod p), p = 2 ^ 255 - 19, which is the modulus of curve25519 field.
* Function prototype: void Fp64Add(Fp64 h, const Fp64 f, const Fp64 g);
* Input register: rdi: out; rsi: f; Fp64 is an array of [u64; 4]
* rdi: out, array pointer of output parameter Fp64.
* rsi: pointer f of the input source data Fp64 array.
* rdx: pointer g of the input source data Fp64 array.
* Modify the register as follows: rax, rcx, r8-r11.
* Output register: None
* Function/Macro Call: None
*/
void Fp64Add(Fp64 out, const Fp64 f, const Fp64 g);
/**
* Function description: out = f - g (mod p), p = 2 ^ 255 - 19, which is the modulus of curve25519 field.
* Function prototype: void Fp64Sub(Fp64 h, const Fp64 f, const Fp64 g);
* Input register: rdi: out; rsi: f; Fp64 is an array of [u64; 4]
* rdi: out, array pointer of output parameter Fp64.
* rsi: pointer f of the input source data Fp64 array.
* rdx: pointer g of the input source data Fp64 array.
* Modify the register as follows: rax, rcx, r8-r11.
* Output register: None
* Function/Macro Call: None
*/
void Fp64Sub(Fp64 out, const Fp64 f, const Fp64 g);
/**
* Function description: data conversion.
* Function prototype: void Fp64PolyToData(uint8_t *out, const Fp64 f);
* Input register: rdi: out; rsi: f; Fp64 is an array of [u64; 4]
* rdi: out, array pointer of output parameter Fp64.
* rsi: pointer f of the input source data Fp64 array.
* Modify the register as follows: rax, rcx, r8-r11.
* Output register: None
* Function/Macro Call: None
*/
void Fp64PolyToData(uint8_t *out, const Fp64 f);
#endif
#ifdef __cplusplus
}
#endif
#endif /* HITLS_CRYPTO_X25519 */
#endif // X25519_ASM_H
|
2301_79861745/bench_create
|
crypto/curve25519/src/x25519_asm.h
|
C
|
unknown
| 6,217
|
/*
* 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_DH_H
#define CRYPT_DH_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_DH
#include <stdint.h>
#include "crypt_types.h"
#include "crypt_algid.h"
#include "bsl_params.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
#ifndef CRYPT_DH_TRY_CNT_MAX
#define CRYPT_DH_TRY_CNT_MAX 100
#endif
/* DH key parameter */
typedef struct DH_Para CRYPT_DH_Para;
/* DH key context */
typedef struct DH_Ctx CRYPT_DH_Ctx;
/**
* @ingroup dh
* @brief dh Allocate the context of dh.
*
* @retval (CRYPT_DH_Ctx *) Pointer to the memory space of the allocated context
* @retval NULL Invalid null pointer
*/
CRYPT_DH_Ctx *CRYPT_DH_NewCtx(void);
/**
* @ingroup dh
* @brief dh Allocate the context of dh.
*
* @param libCtx [IN] Library context
*
* @retval (CRYPT_DH_Ctx *) Pointer to the memory space of the allocated context
* @retval NULL Invalid null pointer
*/
CRYPT_DH_Ctx *CRYPT_DH_NewCtxEx(void *libCtx);
/**
* @ingroup dh
* @brief Copy the DH context. After the duplicated context is used up, call CRYPT_DH_FreeCtx to release the memory.
*
* @param ctx [IN] Source DH context
*
* @return CRYPT_DH_Ctx DH context pointer
* If the operation fails, null is returned.
*/
CRYPT_DH_Ctx *CRYPT_DH_DupCtx(CRYPT_DH_Ctx *ctx);
/**
* @ingroup dh
* @brief dh Release context structure of dh key
*
* @param ctx [IN] Indicates the pointer to the context structure to be released. The ctx is set NULL by the invoker.
*/
void CRYPT_DH_FreeCtx(CRYPT_DH_Ctx *ctx);
/**
* @ingroup dh
* @brief dh Allocate key parameter structure space
*
* @param para [IN] DH External parameter
*
* @retval (CRYPT_DH_Para *) Pointer to the memory space of the allocated context
* @retval NULL Invalid null pointer
*/
CRYPT_DH_Para *CRYPT_DH_NewPara(const CRYPT_DhPara *para);
/**
* @ingroup dh
* @brief Release dh 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_DH_FreePara(CRYPT_DH_Para *dhPara);
/**
* @ingroup dh
* @brief Set the data of the key parameter structure to the key structure.
*
* @param ctx [IN] Key structure for setting related parameters. The key specification is 1024-8192 bits.
* @param para [IN] Key parameters
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input.
* @retval CRYPT_DH_PARA_ERROR The key parameter data is incorrect.
* @retval CRYPT_MEM_ALLOC_FAIL Internal Memory Allocation Error
* @retval BN error code: An error occurred in the internal BigNum calculation.
* @retval CRYPT_SUCCESS Set successfully.
*/
int32_t CRYPT_DH_SetPara(CRYPT_DH_Ctx *ctx, const CRYPT_DhPara *para);
/**
* @ingroup dh
* @brief Obtain the key structure parameters.
*
* @param ctx [IN] Key structure
* @param para [OUT] Obtained key parameter.
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input.
* @retval CRYPT_DH_PARA_ERROR The key parameter data is incorrect.
* @retval BN error code: An error occurred in the internal BigNum calculation.
* @retval CRYPT_SUCCESS Set successfully.
*/
int32_t CRYPT_DH_GetPara(const CRYPT_DH_Ctx *ctx, CRYPT_DhPara *para);
/**
* @ingroup dh
* @brief Set a parameter based on the parameter ID.
*
* @param id [IN] Parameter ID
*
* @retval (CRYPT_DH_Para *) Pointer to the memory space of the allocated context
* @retval NULL Invalid null pointer
*/
CRYPT_DH_Para *CRYPT_DH_NewParaById(CRYPT_PKEY_ParaId id);
/**
* @ingroup dh
* @brief Obtain the parameter ID.
*
* @param ctx [IN] Key structure
*
* @retval ID. If the context is invalid, CRYPT_PKEY_PARAID_MAX is returned.
*/
CRYPT_PKEY_ParaId CRYPT_DH_GetParaId(const CRYPT_DH_Ctx *ctx);
/**
* @ingroup dh
* @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_DH_GetBits(const CRYPT_DH_Ctx *ctx);
/**
* @ingroup dh
* @brief Generate the DH key pair.
*
* @param ctx [IN] dh Context structure
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_DH_PARA_ERROR The key parameter data is incorrect.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval CRYPT_DH_RAND_GENRATE_ERROR Unable to generate results within the specified number of attempts
* @retval BN error code: An error occurred in the internal BigNum calculation.
* @retval CRYPT_SUCCESS The key pair is successfully generated.
*/
int32_t CRYPT_DH_Gen(CRYPT_DH_Ctx *ctx);
/**
* @ingroup dh
* @brief DH key exchange
*
* @param ctx [IN] dh Context structure
* @param pubKey [IN] Public key data
* @param shareKey [OUT] Shared key
* @param shareKeyLen [IN/OUT] The input parameter is the length of the shareKey,
* and the output parameter is the valid length of the shareKey.
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_DH_BUFF_LEN_NOT_ENOUGH The buffer length is insufficient.
* @retval CRYPT_DH_KEYINFO_ERROR The key information is incorrect.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS Key exchange succeeded.
*/
int32_t CRYPT_DH_ComputeShareKey(const CRYPT_DH_Ctx *ctx, const CRYPT_DH_Ctx *pubKey,
uint8_t *shareKey, uint32_t *shareKeyLen);
/**
* @ingroup dh
* @brief DH Set the private key.
*
* @param ctx [OUT] dh Context structure
* @param prv [IN] Private key
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_DH_PARA_ERROR The key parameter is incorrect.
* @retval CRYPT_DH_KEYINFO_ERROR The key information is incorrect.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS Set successfully.
*/
int32_t CRYPT_DH_SetPrvKey(CRYPT_DH_Ctx *ctx, const CRYPT_DhPrv *prv);
/**
* @ingroup dh
* @brief DH Set the public key data.
*
* @param ctx [OUT] dh Context structure
* @param pub [IN] Public key data
*
* @retval CRYPT_NULL_INPUT Error null pointer input
* @retval CRYPT_DH_PARA_ERROR The key parameter data is incorrect.
* @retval CRYPT_DH_KEYINFO_ERROR The key information is incorrect.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS Set successfully.
*/
int32_t CRYPT_DH_SetPubKey(CRYPT_DH_Ctx *ctx, const CRYPT_DhPub *pub);
/**
* @ingroup dh
* @brief DH Obtain the private key data.
*
* @param ctx [IN] dh Context structure
* @param prv [OUT] Private key data
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_DH_BUFF_LEN_NOT_ENOUGH The buffer length is insufficient.
* @retval CRYPT_DH_KEYINFO_ERROR The key information is incorrect.
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS obtained successfully.
*/
int32_t CRYPT_DH_GetPrvKey(const CRYPT_DH_Ctx *ctx, CRYPT_DhPrv *prv);
/**
* @ingroup dh
* @brief DH Obtain the public key data.
*
* @param ctx [IN] dh Context structure
* @param pub [OUT] Public key data
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_DH_BUFF_LEN_NOT_ENOUGH The buffer length is insufficient.
* @retval CRYPT_DH_KEYINFO_ERROR The key information is incorrect.
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS Obtained successfully.
*/
int32_t CRYPT_DH_GetPubKey(const CRYPT_DH_Ctx *ctx, CRYPT_DhPub *pub);
#ifdef HITLS_BSL_PARAMS
/**
* @ingroup dh
* @brief DH Set the private key.
*
* @param ctx [OUT] dh Context structure
* @param para [IN] Private key
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_DH_PARA_ERROR The key parameter is incorrect.
* @retval CRYPT_DH_KEYINFO_ERROR The key information is incorrect.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS Set successfully.
*/
int32_t CRYPT_DH_SetPrvKeyEx(CRYPT_DH_Ctx *ctx, const BSL_Param *para);
/**
* @ingroup dh
* @brief DH Set the public key data.
*
* @param ctx [OUT] dh Context structure
* @param para [IN] Public key data
*
* @retval CRYPT_NULL_INPUT Error null pointer input
* @retval CRYPT_DH_PARA_ERROR The key parameter data is incorrect.
* @retval CRYPT_DH_KEYINFO_ERROR The key information is incorrect.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS Set successfully.
*/
int32_t CRYPT_DH_SetPubKeyEx(CRYPT_DH_Ctx *ctx, const BSL_Param *para);
/**
* @ingroup dh
* @brief DH Obtain the private key data.
*
* @param ctx [IN] dh Context structure
* @param para [OUT] Private key data
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_DH_BUFF_LEN_NOT_ENOUGH The buffer length is insufficient.
* @retval CRYPT_DH_KEYINFO_ERROR The key information is incorrect.
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS obtained successfully.
*/
int32_t CRYPT_DH_GetPrvKeyEx(const CRYPT_DH_Ctx *ctx, BSL_Param *para);
/**
* @ingroup dh
* @brief DH Obtain the public key data.
*
* @param ctx [IN] dh Context structure
* @param para [OUT] Public key data
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_DH_BUFF_LEN_NOT_ENOUGH The buffer length is insufficient.
* @retval CRYPT_DH_KEYINFO_ERROR The key information is incorrect.
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS Obtained successfully.
*/
int32_t CRYPT_DH_GetPubKeyEx(const CRYPT_DH_Ctx *ctx, BSL_Param *para);
/**
* @ingroup dh
* @brief Set the data of the key parameter structure to the key structure.
*
* @param ctx [IN] Key structure for setting related parameters. The key specification is 1024-8192 bits.
* @param para [IN] Key parameters
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input.
* @retval CRYPT_DH_PARA_ERROR The key parameter data is incorrect.
* @retval CRYPT_MEM_ALLOC_FAIL Internal Memory Allocation Error
* @retval BN error code: An error occurred in the internal BigNum calculation.
* @retval CRYPT_SUCCESS Set successfully.
*/
int32_t CRYPT_DH_SetParaEx(CRYPT_DH_Ctx *ctx, const BSL_Param *para);
/**
* @ingroup dh
* @brief Obtain the key structure parameters.
*
* @param ctx [IN] Key structure
* @param para [OUT] Obtained key parameter.
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input.
* @retval CRYPT_DH_PARA_ERROR The key parameter data is incorrect.
* @retval BN error code: An error occurred in the internal BigNum calculation.
* @retval CRYPT_SUCCESS Set successfully.
*/
int32_t CRYPT_DH_GetParaEx(const CRYPT_DH_Ctx *ctx, BSL_Param *para);
#endif
/**
* @ingroup dh
* @brief dh Compare public keys and parameters
*
* @param a [IN] dh Context structure
* @param b [IN] dh Context structure
*
* @return CRYPT_SUCCESS is the same
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_DH_KEYINFO_ERROR The key information is incorrect.
* @retval CRYPT_DH_PUBKEY_NOT_EQUAL Public Keys are not equal
* @retval CRYPT_DH_PARA_ERROR The parameter data is incorrect.
* @retval CRYPT_DH_PARA_NOT_EQUAL The parameters are not equal.
*/
int32_t CRYPT_DH_Cmp(const CRYPT_DH_Ctx *a, const CRYPT_DH_Ctx *b);
/**
* @ingroup dh
* @brief DH control interface
*
* @param ctx [IN] dh Context structure
* @param opt [IN] Operation mode
* @param val [IN] Parameter
* @param len [IN] val length
*
* @retval CRYPT_NULL_INPUT Error null pointer input
* @retval CRYPT_SUCCESS obtained successfully.
*/
int32_t CRYPT_DH_Ctrl(CRYPT_DH_Ctx *ctx, int32_t opt, void *val, uint32_t len);
/**
* @ingroup dh
* @brief dh get security bits
*
* @param ctx [IN] dh Context structure
*
* @retval security bits
*/
int32_t CRYPT_DH_GetSecBits(const CRYPT_DH_Ctx *ctx);
#ifdef HITLS_CRYPTO_DH_CHECK
/**
* @ingroup dh
* @brief check the key pair consistency
*
* @param checkType [IN] check type
* @param pkey1 [IN] dh key context structure
* @param pkey2 [IN] dh key context structure
*
* @retval CRYPT_SUCCESS check success.
* Others. For details, see error code in errno.
*/
int32_t CRYPT_DH_Check(uint32_t checkType, const CRYPT_DH_Ctx *pkey1, const CRYPT_DH_Ctx *pkey2);
#endif // HITLS_CRYPTO_DH_CHECK
#ifdef __cplusplus
}
#endif
#endif // HITLS_CRYPTO_DH
#endif // CRYPT_DH_H
|
2301_79861745/bench_create
|
crypto/dh/include/crypt_dh.h
|
C
|
unknown
| 13,923
|
/*
* 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_DH
#include "crypt_errno.h"
#include "securec.h"
#include "bsl_sal.h"
#include "bsl_err_internal.h"
#include "crypt_bn.h"
#include "crypt_utils.h"
#include "crypt_dh.h"
#include "dh_local.h"
#include "sal_atomic.h"
#include "crypt_local_types.h"
#include "crypt_params_key.h"
CRYPT_DH_Ctx *CRYPT_DH_NewCtx(void)
{
CRYPT_DH_Ctx *ctx = BSL_SAL_Malloc(sizeof(CRYPT_DH_Ctx));
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
(void)memset_s(ctx, sizeof(CRYPT_DH_Ctx), 0, sizeof(CRYPT_DH_Ctx));
BSL_SAL_ReferencesInit(&(ctx->references));
return ctx;
}
CRYPT_DH_Ctx *CRYPT_DH_NewCtxEx(void *libCtx)
{
CRYPT_DH_Ctx *ctx = CRYPT_DH_NewCtx();
if (ctx == NULL) {
return NULL;
}
ctx->libCtx = libCtx;
return ctx;
}
static CRYPT_DH_Para *ParaMemGet(uint32_t bits)
{
CRYPT_DH_Para *para = BSL_SAL_Calloc(1u, sizeof(CRYPT_DH_Para));
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
para->p = BN_Create(bits);
para->g = BN_Create(bits);
para->id = CRYPT_PKEY_PARAID_MAX;
if (para->p == NULL || para->g == NULL) {
CRYPT_DH_FreePara(para);
BSL_ERR_PUSH_ERROR(CRYPT_DH_CREATE_PARA_FAIL);
return NULL;
}
return para;
}
static int32_t NewParaCheck(const CRYPT_DhPara *para)
{
if (para == NULL || para->p == NULL || para->g == NULL ||
para->pLen == 0 || para->gLen == 0 || (para->q == NULL &&
para->qLen != 0)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (para->pLen > BN_BITS_TO_BYTES(DH_MAX_PBITS)) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR);
return CRYPT_DH_PARA_ERROR;
}
if (para->gLen > para->pLen) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR);
return CRYPT_DH_PARA_ERROR;
}
if (para->q == NULL) {
return CRYPT_SUCCESS;
}
if (para->qLen > para->pLen) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR);
return CRYPT_DH_PARA_ERROR;
}
return CRYPT_SUCCESS;
}
CRYPT_DH_Para *CRYPT_DH_NewPara(const CRYPT_DhPara *para)
{
if (NewParaCheck(para) != CRYPT_SUCCESS) {
return NULL;
}
uint32_t modBits = BN_BYTES_TO_BITS(para->pLen);
CRYPT_DH_Para *retPara = ParaMemGet(modBits);
if (retPara == NULL) {
return NULL;
}
int32_t ret = BN_Bin2Bn(retPara->p, para->p, para->pLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
ret = BN_Bin2Bn(retPara->g, para->g, para->gLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
if (para->q == NULL) {
return retPara; // The parameter q does not exist, this function is ended early.
}
retPara->q = BN_Create(modBits);
if (retPara->q == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_CREATE_PARA_FAIL);
goto ERR;
}
ret = BN_Bin2Bn(retPara->q, para->q, para->qLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
retPara->id = CRYPT_PKEY_PARAID_MAX; // No ID is passed in this function. Assign a invalid ID temporarily.
return retPara;
ERR:
CRYPT_DH_FreePara(retPara);
return NULL;
}
void CRYPT_DH_FreePara(CRYPT_DH_Para *dhPara)
{
if (dhPara == NULL) {
return;
}
BN_Destroy(dhPara->p);
BN_Destroy(dhPara->q);
BN_Destroy(dhPara->g);
BSL_SAL_FREE(dhPara);
}
void CRYPT_DH_FreeCtx(CRYPT_DH_Ctx *ctx)
{
if (ctx == NULL) {
return;
}
int val = 0;
BSL_SAL_AtomicDownReferences(&(ctx->references), &val);
if (val > 0) {
return;
}
CRYPT_DH_FreePara(ctx->para);
BN_Destroy(ctx->x);
BN_Destroy(ctx->y);
BSL_SAL_ReferencesFree(&(ctx->references));
BSL_SAL_FREE(ctx);
}
static int32_t ParaQCheck(BN_BigNum *q, BN_BigNum *r)
{
// 1. Determine the length.
if (BN_Bits(q) < DH_MIN_QBITS) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR);
return CRYPT_DH_PARA_ERROR;
}
// 2. Parity and even judgment
if (BN_GetBit(q, 0) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR);
return CRYPT_DH_PARA_ERROR;
}
// 3. Compare q and r.
if (BN_Cmp(q, r) >= 0) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR);
return CRYPT_DH_PARA_ERROR;
}
// 4. Check the pq multiple relationship.
BN_Optimizer *opt = BN_OptimizerCreate();
if (opt == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
int32_t ret = BN_Div(NULL, r, r, q, opt);
BN_OptimizerDestroy(opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// (p - 1) % q == 0
if (!BN_IsZero(r)) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR);
return CRYPT_DH_PARA_ERROR;
}
return CRYPT_SUCCESS;
}
static int32_t ParaDataCheck(const CRYPT_DH_Para *para)
{
int32_t ret;
const BN_BigNum *p = para->p;
const BN_BigNum *g = para->g;
// 1. Determine the length.
uint32_t pBits = BN_Bits(p);
if (pBits < DH_MIN_PBITS || pBits > DH_MAX_PBITS) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR);
return CRYPT_DH_PARA_ERROR;
}
// 2. P parity and g value judgment
// p is an odd number
if (BN_GetBit(p, 0) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR);
return CRYPT_DH_PARA_ERROR;
}
// g != 0 && g != 1
if (BN_IsZero(g) || BN_IsOne(g)) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR);
return CRYPT_DH_PARA_ERROR;
}
BN_BigNum *r = BN_Create(pBits + 1);
if (r == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
// r = p - 1
ret = BN_SubLimb(r, p, 1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
// g < p - 1
if (BN_Cmp(g, r) >= 0) {
ret = CRYPT_DH_PARA_ERROR;
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
if (para->q != NULL) {
ret = ParaQCheck(para->q, r);
}
EXIT:
BN_Destroy(r);
return ret;
}
static CRYPT_DH_Para *ParaDup(const CRYPT_DH_Para *para)
{
CRYPT_DH_Para *ret = BSL_SAL_Malloc(sizeof(CRYPT_DH_Para));
if (ret == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
ret->p = BN_Dup(para->p);
ret->q = BN_Dup(para->q);
ret->g = BN_Dup(para->g);
ret->id = para->id;
if (ret->p == NULL || ret->g == NULL) {
CRYPT_DH_FreePara(ret);
BSL_ERR_PUSH_ERROR(CRYPT_DH_CREATE_PARA_FAIL);
return NULL;
}
if (para->q != NULL && ret->q == NULL) {
CRYPT_DH_FreePara(ret);
BSL_ERR_PUSH_ERROR(CRYPT_DH_CREATE_PARA_FAIL);
return NULL;
}
return ret;
}
CRYPT_DH_Ctx *CRYPT_DH_DupCtx(CRYPT_DH_Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return NULL;
}
CRYPT_DH_Ctx *newKeyCtx = BSL_SAL_Calloc(1, sizeof(CRYPT_DH_Ctx));
if (newKeyCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
// If x, y and para is not empty, copy the value.
GOTO_ERR_IF_SRC_NOT_NULL(newKeyCtx->x, ctx->x, BN_Dup(ctx->x), CRYPT_MEM_ALLOC_FAIL);
GOTO_ERR_IF_SRC_NOT_NULL(newKeyCtx->y, ctx->y, BN_Dup(ctx->y), CRYPT_MEM_ALLOC_FAIL);
GOTO_ERR_IF_SRC_NOT_NULL(newKeyCtx->para, ctx->para, ParaDup(ctx->para), CRYPT_MEM_ALLOC_FAIL);
newKeyCtx->libCtx = ctx->libCtx;
BSL_SAL_ReferencesInit(&(newKeyCtx->references));
return newKeyCtx;
ERR:
CRYPT_DH_FreeCtx(newKeyCtx);
return NULL;
}
static int32_t DhSetPara(CRYPT_DH_Ctx *ctx, CRYPT_DH_Para *para)
{
int32_t ret = ParaDataCheck(para);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BN_Destroy(ctx->x);
BN_Destroy(ctx->y);
CRYPT_DH_FreePara(ctx->para);
ctx->x = NULL;
ctx->y = NULL;
ctx->para = para;
return CRYPT_SUCCESS;
}
int32_t CRYPT_DH_SetPara(CRYPT_DH_Ctx *ctx, const CRYPT_DhPara *para)
{
if (ctx == NULL || para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_DH_Para *dhPara = CRYPT_DH_NewPara(para);
if (dhPara == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_NEW_PARA_FAIL);
return CRYPT_EAL_ERR_NEW_PARA_FAIL;
}
int32_t ret = DhSetPara(ctx, dhPara);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
CRYPT_DH_FreePara(dhPara);
}
return ret;
}
int32_t CRYPT_DH_GetPara(const CRYPT_DH_Ctx *ctx, CRYPT_DhPara *para)
{
if (ctx == NULL || para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR);
return CRYPT_DH_PARA_ERROR;
}
int32_t ret = BN_Bn2Bin(ctx->para->p, para->p, &(para->pLen));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (ctx->para->q == NULL) {
para->q = NULL;
para->qLen = 0;
} else {
ret = BN_Bn2Bin(ctx->para->q, para->q, &(para->qLen));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
ret = BN_Bn2Bin(ctx->para->g, para->g, &(para->gLen));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
static int32_t PubCheck(const BN_BigNum *y, const BN_BigNum *minP)
{
// y != 0, y != 1
if (BN_IsZero(y) || BN_IsOne(y)) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_KEYINFO_ERROR);
return CRYPT_DH_KEYINFO_ERROR;
}
// y < p - 1
if (BN_Cmp(y, minP) >= 0) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_KEYINFO_ERROR);
return CRYPT_DH_KEYINFO_ERROR;
}
return CRYPT_SUCCESS;
}
// Get p-2 or q-1
static int32_t GetXLimb(BN_BigNum *xLimb, const BN_BigNum *p, const BN_BigNum *q)
{
if (q != NULL) {
// xLimb = q - 1
return BN_SubLimb(xLimb, q, 1);
}
// xLimb = p - 2
return BN_SubLimb(xLimb, p, 2);
}
static void RefreshCtx(CRYPT_DH_Ctx *dhCtx, BN_BigNum *x, BN_BigNum *y, int32_t ret)
{
if (ret == CRYPT_SUCCESS) {
BN_Destroy(dhCtx->x);
BN_Destroy(dhCtx->y);
dhCtx->x = x;
dhCtx->y = y;
} else {
BN_Destroy(x);
BN_Destroy(y);
}
}
/* SP800-56Ar3 5_6_1_1_4 Key-Pair Generation by Testing Candidates */
static int32_t DH_GenSp80056ATestCandidates(CRYPT_DH_Ctx *ctx)
{
int32_t ret;
uint32_t bits = BN_Bits(ctx->para->p);
uint32_t qbits = BN_Bits(ctx->para->q);
/* If s is not the maximum security strength that can be support by (p, q, g), then return an error. */
uint32_t s = (uint32_t)CRYPT_DH_GetSecBits(ctx);
if (bits == 0 || qbits == 0 || s == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR);
return CRYPT_DH_PARA_ERROR;
}
/* 2*s <= n <= len(q), set n = 2*s */
uint32_t n = 2 * s;
BN_BigNum *x = BN_Create(bits);
BN_BigNum *y = BN_Create(bits);
BN_BigNum *twoPowN = BN_Create(n);
BN_Mont *mont = BN_MontCreate(ctx->para->p);
BN_BigNum *m = ctx->para->q;
BN_Optimizer *opt = BN_OptimizerCreate();
if (x == NULL || y == NULL || mont == NULL || opt == NULL || twoPowN == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
goto ERR;
}
ret = BN_SetLimb(twoPowN, 1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
ret = BN_Lshift(twoPowN, twoPowN, n);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
/* Set M = min(2^N, q), the minimum of 2^N and q. */
if (BN_Cmp(twoPowN, m) < 0) {
m = twoPowN;
}
for (int32_t cnt = 0; cnt < CRYPT_DH_TRY_CNT_MAX; cnt++) {
/* c in the interval [0, 2N - 1] */
ret = BN_RandRangeEx(ctx->libCtx, x, twoPowN);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
/* x = c + 1 */
ret = BN_AddLimb(x, x, 1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
/* If c > M - 2, (i.e. c + 1 >= M) continue */
if (BN_Cmp(x, m) >= 0) {
continue;
}
ret = BN_MontExpConsttime(y, ctx->para->g, x, mont, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
goto ERR; // The function exits successfully.
}
ret = CRYPT_DH_RAND_GENERATE_ERROR;
BSL_ERR_PUSH_ERROR(ret);
ERR:
RefreshCtx(ctx, x, y, ret);
BN_Destroy(twoPowN);
BN_MontDestroy(mont);
BN_OptimizerDestroy(opt);
return ret;
}
static int32_t DH_GenSp80056ASafePrime(CRYPT_DH_Ctx *ctx)
{
int32_t ret;
uint32_t bits = BN_Bits(ctx->para->p);
BN_BigNum *x = BN_Create(bits);
BN_BigNum *y = BN_Create(bits);
BN_BigNum *minP = BN_Create(bits);
BN_BigNum *xLimb = BN_Create(bits);
BN_Mont *mont = BN_MontCreate(ctx->para->p);
BN_Optimizer *opt = BN_OptimizerCreate();
if (x == NULL || y == NULL || minP == NULL || xLimb == NULL || mont == NULL || opt == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BN_SubLimb(minP, ctx->para->p, 1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = GetXLimb(xLimb, ctx->para->p, ctx->para->q);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
for (int32_t cnt = 0; cnt < CRYPT_DH_TRY_CNT_MAX; cnt++) {
/* Generate private key x for [1, q-1] or [1, p-2] */
ret = BN_RandRangeEx(ctx->libCtx, x, xLimb);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BN_AddLimb(x, x, 1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
/* Calculate the public key y. */
ret = BN_MontExpConsttime(y, ctx->para->g, x, mont, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
/* Check whether the public key meets the requirements. If not, try to generate the key again. */
// y != 0, y != 1, y < p - 1
if (BN_IsZero(y) || BN_IsOne(y) || BN_Cmp(y, minP) >= 0) {
continue;
}
goto EXIT; // The function exits successfully.
}
ret = CRYPT_DH_RAND_GENERATE_ERROR;
BSL_ERR_PUSH_ERROR(ret);
EXIT:
RefreshCtx(ctx, x, y, ret);
BN_Destroy(minP);
BN_Destroy(xLimb);
BN_MontDestroy(mont);
BN_OptimizerDestroy(opt);
return ret;
}
int32_t CRYPT_DH_Gen(CRYPT_DH_Ctx *ctx)
{
if (ctx == NULL || ctx->para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR);
return CRYPT_DH_PARA_ERROR;
}
int32_t s = CRYPT_DH_GetSecBits(ctx);
if (ctx->para->q != NULL && s != 0) {
return DH_GenSp80056ATestCandidates(ctx);
}
return DH_GenSp80056ASafePrime(ctx);
}
static int32_t ComputeShareKeyInputCheck(const CRYPT_DH_Ctx *ctx, const CRYPT_DH_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->para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR);
return CRYPT_DH_PARA_ERROR;
}
if (ctx->x == NULL || pubKey->y == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_KEYINFO_ERROR);
return CRYPT_DH_KEYINFO_ERROR;
}
if (BN_Bytes(ctx->para->p) > *shareKeyLen) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_BUFF_LEN_NOT_ENOUGH);
return CRYPT_DH_BUFF_LEN_NOT_ENOUGH;
}
return CRYPT_SUCCESS;
}
static void CheckAndFillZero(uint8_t *shareKey, uint32_t *shareKeyLen, uint32_t bytes)
{
int32_t i;
if (*shareKeyLen == bytes) { // (*shareKeyLen > bytes) is not possible
return;
}
uint32_t fill = bytes - *shareKeyLen;
for (i = (int32_t)*shareKeyLen - 1; i >= 0; i--) {
shareKey[i + (int32_t)fill] = shareKey[i];
}
for (i = 0; i < (int32_t)fill; i++) {
shareKey[i] = 0;
}
*shareKeyLen = bytes;
}
int32_t CRYPT_DH_ComputeShareKey(const CRYPT_DH_Ctx *ctx, const CRYPT_DH_Ctx *pubKey,
uint8_t *shareKey, uint32_t *shareKeyLen)
{
uint32_t bytes = 0;
int32_t ret = ComputeShareKeyInputCheck(ctx, pubKey, shareKey, shareKeyLen);
if (ret != CRYPT_SUCCESS) {
return ret;
}
uint32_t bits = BN_Bits(ctx->para->p);
BN_BigNum *tmp = BN_Create(bits);
BN_Mont *mont = BN_MontCreate(ctx->para->p);
BN_Optimizer *opt = BN_OptimizerCreate();
if (tmp == NULL || mont == NULL || opt == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BN_SubLimb(tmp, ctx->para->p, 1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
/* Check whether the public key meets the requirements. */
ret = PubCheck(pubKey->y, tmp);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BN_MontExpConsttime(tmp, pubKey->y, ctx->x, mont, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BN_Bn2Bin(tmp, shareKey, shareKeyLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
// no need to filled zero in the leading.
if ((ctx->flags & CRYPT_DH_NO_PADZERO) == 0) {
bytes = BN_BITS_TO_BYTES(bits);
CheckAndFillZero(shareKey, shareKeyLen, bytes);
}
EXIT:
BN_Destroy(tmp);
BN_MontDestroy(mont);
BN_OptimizerDestroy(opt);
return ret;
}
static int32_t PrvLenCheck(const CRYPT_DH_Ctx *ctx, const CRYPT_DhPrv *prv)
{
if (ctx->para->q != NULL) {
if (BN_Bytes(ctx->para->q) < prv->len) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_KEYINFO_ERROR);
return CRYPT_DH_KEYINFO_ERROR;
}
} else {
if (BN_Bytes(ctx->para->p) < prv->len) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_KEYINFO_ERROR);
return CRYPT_DH_KEYINFO_ERROR;
}
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_DH_SetPrvKey(CRYPT_DH_Ctx *ctx, const CRYPT_DhPrv *prv)
{
if (ctx == NULL || prv == NULL || prv->data == NULL || prv->len == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR);
return CRYPT_DH_PARA_ERROR;
}
int32_t ret = PrvLenCheck(ctx, prv);
if (ret != CRYPT_SUCCESS) {
return ret;
}
BN_BigNum *bnX = BN_Create(BN_BYTES_TO_BITS(prv->len));
BN_BigNum *xLimb = BN_Create(BN_Bits(ctx->para->p) + 1);
if (bnX == NULL || xLimb == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
GOTO_ERR_IF(GetXLimb(xLimb, ctx->para->p, ctx->para->q), ret);
GOTO_ERR_IF(BN_Bin2Bn(bnX, prv->data, prv->len), ret);
// Satisfy x <= q - 1 or x <= p - 2
if (BN_Cmp(bnX, xLimb) > 0) {
ret = CRYPT_DH_KEYINFO_ERROR;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
// x != 0
if (BN_IsZero(bnX)) {
ret = CRYPT_DH_KEYINFO_ERROR;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
BN_Destroy(xLimb);
BN_Destroy(ctx->x);
ctx->x = bnX;
return ret;
ERR:
BN_Destroy(bnX);
BN_Destroy(xLimb);
return ret;
}
// No parameter information is required for setting the public key.
// Therefore, the validity of the public key is not checked during the setting.
// The validity of the public key is checked during the calculation of the shared key.
int32_t CRYPT_DH_SetPubKey(CRYPT_DH_Ctx *ctx, const CRYPT_DhPub *pub)
{
if (ctx == NULL || pub == NULL || pub->data == NULL || pub->len == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (pub->len > BN_BITS_TO_BYTES(DH_MAX_PBITS)) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_KEYINFO_ERROR);
return CRYPT_DH_KEYINFO_ERROR;
}
BN_BigNum *bnY = BN_Create(BN_BYTES_TO_BITS(pub->len));
if (bnY == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
int32_t ret = BN_Bin2Bn(bnY, pub->data, pub->len);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
BN_Destroy(ctx->y);
ctx->y = bnY;
return ret;
ERR:
BN_Destroy(bnY);
return ret;
}
int32_t CRYPT_DH_GetPrvKey(const CRYPT_DH_Ctx *ctx, CRYPT_DhPrv *prv)
{
if (ctx == NULL || prv == NULL || prv->data == NULL || prv->len == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->x == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_KEYINFO_ERROR);
return CRYPT_DH_KEYINFO_ERROR;
}
if (ctx->para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR);
return CRYPT_DH_PARA_ERROR;
}
if (ctx->para->q != NULL) {
if (BN_Bytes(ctx->para->q) > prv->len) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_BUFF_LEN_NOT_ENOUGH);
return CRYPT_DH_BUFF_LEN_NOT_ENOUGH;
}
} else {
if (BN_Bytes(ctx->para->p) > prv->len) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_BUFF_LEN_NOT_ENOUGH);
return CRYPT_DH_BUFF_LEN_NOT_ENOUGH;
}
}
int32_t ret = BN_Bn2Bin(ctx->x, prv->data, &(prv->len));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
int32_t CRYPT_DH_GetPubKey(const CRYPT_DH_Ctx *ctx, CRYPT_DhPub *pub)
{
if (ctx == NULL || pub == NULL || pub->data == NULL || pub->len == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->para == NULL || ctx->para->p == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR);
return CRYPT_DH_PARA_ERROR;
}
if (ctx->y == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_KEYINFO_ERROR);
return CRYPT_DH_KEYINFO_ERROR;
}
uint32_t pubLen = BN_Bytes(ctx->para->p);
if (pubLen > pub->len) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_BUFF_LEN_NOT_ENOUGH);
return CRYPT_DH_BUFF_LEN_NOT_ENOUGH;
}
// RFC 8446 requires the dh public value should be encoded as a big-endian integer and padded to
// the left with zeros to the size of p in bytes.
int32_t ret = BN_Bn2BinFixZero(ctx->y, pub->data, pubLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
pub->len = pubLen;
return ret;
}
#ifdef HITLS_BSL_PARAMS
int32_t CRYPT_DH_SetParaEx(CRYPT_DH_Ctx *ctx, const BSL_Param *para)
{
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_DhPara dhPara = {0};
(void)GetConstParamValue(para, CRYPT_PARAM_DH_P, &(dhPara.p), &(dhPara.pLen));
(void)GetConstParamValue(para, CRYPT_PARAM_DH_Q, &(dhPara.q), &(dhPara.qLen));
(void)GetConstParamValue(para, CRYPT_PARAM_DH_G, &(dhPara.g), &(dhPara.gLen));
return CRYPT_DH_SetPara(ctx, &dhPara);
}
int32_t CRYPT_DH_GetParaEx(const CRYPT_DH_Ctx *ctx, BSL_Param *para)
{
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_DhPara dhPara = {0};
BSL_Param *paramP = GetParamValue(para, CRYPT_PARAM_DH_P, &(dhPara.p), &(dhPara.pLen));
BSL_Param *paramQ = GetParamValue(para, CRYPT_PARAM_DH_Q, &(dhPara.q), &(dhPara.qLen));
BSL_Param *paramG = GetParamValue(para, CRYPT_PARAM_DH_G, &(dhPara.g), &(dhPara.gLen));
int32_t ret = CRYPT_DH_GetPara(ctx, &dhPara);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
paramP->useLen = dhPara.pLen;
paramQ->useLen = dhPara.qLen;
paramG->useLen = dhPara.gLen;
return CRYPT_SUCCESS;
}
int32_t CRYPT_DH_SetPrvKeyEx(CRYPT_DH_Ctx *ctx, const BSL_Param *para)
{
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_DhPrv prv = {0};
(void)GetConstParamValue(para, CRYPT_PARAM_DH_PRVKEY, &prv.data, &prv.len);
return CRYPT_DH_SetPrvKey(ctx, &prv);
}
int32_t CRYPT_DH_SetPubKeyEx(CRYPT_DH_Ctx *ctx, const BSL_Param *para)
{
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_DhPub pub = {0};
if (GetConstParamValue(para, CRYPT_PARAM_DH_PUBKEY, &pub.data, &pub.len) == NULL) {
(void)GetConstParamValue(para, CRYPT_PARAM_PKEY_ENCODE_PUBKEY, (uint8_t **)&pub.data, &pub.len);
}
return CRYPT_DH_SetPubKey(ctx, &pub);
}
int32_t CRYPT_DH_GetPrvKeyEx(const CRYPT_DH_Ctx *ctx, BSL_Param *para)
{
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_DhPrv prv = {0};
BSL_Param *paramPrv = GetParamValue(para, CRYPT_PARAM_DH_PRVKEY, &prv.data, &(prv.len));
int32_t ret = CRYPT_DH_GetPrvKey(ctx, &prv);
if (ret != CRYPT_SUCCESS) {
return ret;
}
paramPrv->useLen = prv.len;
return CRYPT_SUCCESS;
}
int32_t CRYPT_DH_GetPubKeyEx(const CRYPT_DH_Ctx *ctx, BSL_Param *para)
{
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_DhPub pub = {0};
BSL_Param *paramPub = GetParamValue(para, CRYPT_PARAM_DH_PUBKEY, &pub.data, &(pub.len));
if (paramPub == NULL) {
paramPub = GetParamValue(para, CRYPT_PARAM_PKEY_ENCODE_PUBKEY, &pub.data, &(pub.len));
}
int32_t ret = CRYPT_DH_GetPubKey(ctx, &pub);
if (ret != CRYPT_SUCCESS) {
return ret;
}
paramPub->useLen = pub.len;
return ret;
}
#endif
uint32_t CRYPT_DH_GetBits(const CRYPT_DH_Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return 0;
}
if (ctx->para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return 0;
}
return BN_Bits(ctx->para->p);
}
static uint32_t CRYPT_DH_GetPrvKeyLen(const CRYPT_DH_Ctx *ctx)
{
return BN_Bytes(ctx->x);
}
static uint32_t CRYPT_DH_GetPubKeyLen(const CRYPT_DH_Ctx *ctx)
{
if (ctx->para != NULL) {
return BN_Bytes(ctx->para->p);
}
if (ctx->y != NULL) {
return BN_Bytes(ctx->y);
}
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return 0;
}
static uint32_t CRYPT_DH_GetSharedKeyLen(const CRYPT_DH_Ctx *ctx)
{
if (ctx->para != NULL) {
return BN_Bytes(ctx->para->p);
}
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return 0;
}
#ifdef HITLS_CRYPTO_DH_CHECK
static int32_t DhKeyPairCheck(const CRYPT_DH_Ctx *pub, const CRYPT_DH_Ctx *prv)
{
int32_t ret;
if (prv == NULL || pub == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (prv->para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR);
return CRYPT_DH_PARA_ERROR;
}
ret = CRYPT_FFC_KeyPairCheck(prv->x, pub->y, prv->para->p, prv->para->g);
if (ret == CRYPT_PAIRWISE_CHECK_FAIL) {
ret = CRYPT_DH_PAIRWISE_CHECK_FAIL;
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
/*
* SP800-56a 5.6.2.1.2
* for check an FFC key pair.
*/
static int32_t DhPrvKeyCheck(const CRYPT_DH_Ctx *pkey)
{
if (pkey == NULL || pkey->para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret = CRYPT_FFC_PrvCheck(pkey->x, pkey->para->p, pkey->para->q);
if (ret == CRYPT_INVALID_KEY) {
ret = CRYPT_DH_INVALID_PRVKEY;
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
int32_t CRYPT_DH_Check(uint32_t checkType, const CRYPT_DH_Ctx *pkey1, const CRYPT_DH_Ctx *pkey2)
{
switch (checkType) {
case CRYPT_PKEY_CHECK_KEYPAIR:
return DhKeyPairCheck(pkey1, pkey2);
case CRYPT_PKEY_CHECK_PRVKEY:
return DhPrvKeyCheck(pkey1);
default:
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
}
#endif // HITLS_CRYPTO_DH_CHECK
int32_t CRYPT_DH_Cmp(const CRYPT_DH_Ctx *a, const CRYPT_DH_Ctx *b)
{
RETURN_RET_IF(a == NULL || b == NULL, CRYPT_NULL_INPUT);
RETURN_RET_IF(a->y == NULL || b->y == NULL, CRYPT_DH_KEYINFO_ERROR);
RETURN_RET_IF(BN_Cmp(a->y, b->y) != 0, CRYPT_DH_PUBKEY_NOT_EQUAL);
// para must be both null and non-null.
RETURN_RET_IF((a->para == NULL) != (b->para == NULL), CRYPT_DH_PARA_ERROR);
if (a->para != NULL) {
RETURN_RET_IF(BN_Cmp(a->para->p, b->para->p) != 0 ||
BN_Cmp(a->para->q, b->para->q) != 0 ||
BN_Cmp(a->para->g, b->para->g) != 0,
CRYPT_DH_PARA_NOT_EQUAL);
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_DH_SetParamById(CRYPT_DH_Ctx *ctx, CRYPT_PKEY_ParaId id)
{
CRYPT_DH_Para *para = CRYPT_DH_NewParaById(id);
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_NEW_PARA_FAIL);
return CRYPT_EAL_ERR_NEW_PARA_FAIL;
}
int32_t ret = DhSetPara(ctx, para);
if (ret != CRYPT_SUCCESS) {
CRYPT_DH_FreePara(para);
}
return ret;
}
static int32_t CRYPT_DH_GetLen(const CRYPT_DH_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 CRYPT_DH_SetFlag(CRYPT_DH_Ctx *ctx, const void *val, uint32_t len)
{
if (val == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (len != sizeof(uint32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_SET_FLAG_LEN_ERROR);
return CRYPT_DH_SET_FLAG_LEN_ERROR;
}
uint32_t flag = *(const uint32_t *)val;
if (flag == 0 || flag >= CRYPT_DH_MAXFLAG) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_FLAG_NOT_SUPPORT_ERROR);
return CRYPT_DH_FLAG_NOT_SUPPORT_ERROR;
}
ctx->flags |= flag;
return CRYPT_SUCCESS;
}
int32_t CRYPT_DH_Ctrl(CRYPT_DH_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_DH_GetLen(ctx, (GetLenFunc)CRYPT_DH_GetParaId, val, len);
case CRYPT_CTRL_GET_BITS:
return CRYPT_DH_GetLen(ctx, (GetLenFunc)CRYPT_DH_GetBits, val, len);
case CRYPT_CTRL_GET_SECBITS:
return CRYPT_DH_GetLen(ctx, (GetLenFunc)CRYPT_DH_GetSecBits, val, len);
case CRYPT_CTRL_GET_PUBKEY_LEN:
return GetUintCtrl(ctx, val, len, (GetUintCallBack)CRYPT_DH_GetPubKeyLen);
case CRYPT_CTRL_GET_PRVKEY_LEN:
return GetUintCtrl(ctx, val, len, (GetUintCallBack)CRYPT_DH_GetPrvKeyLen);
case CRYPT_CTRL_GET_SHARED_KEY_LEN:
return GetUintCtrl(ctx, val, len, (GetUintCallBack)CRYPT_DH_GetSharedKeyLen);
case CRYPT_CTRL_SET_PARA_BY_ID:
return CRYPT_DH_SetParamById(ctx, *(CRYPT_PKEY_ParaId *)val);
case CRYPT_CTRL_SET_DH_FLAG:
return CRYPT_DH_SetFlag(ctx, val, len);
case CRYPT_CTRL_UP_REFERENCES:
if (val == NULL || len != (uint32_t)sizeof(int)) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
return BSL_SAL_AtomicUpReferences(&(ctx->references), (int *)val);
default:
break;
}
BSL_ERR_PUSH_ERROR(CRYPT_DH_UNSUPPORTED_CTRL_OPTION);
return CRYPT_DH_UNSUPPORTED_CTRL_OPTION;
}
/**
* @ingroup dh
* @brief dh get security bits
*
* @param ctx [IN] dh Context structure
*
* @retval security bits
*/
int32_t CRYPT_DH_GetSecBits(const CRYPT_DH_Ctx *ctx)
{
if (ctx == NULL || ctx->para == NULL || ctx->para->p == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return 0;
}
if (ctx->para->q == NULL) {
return BN_SecBits(BN_Bits(ctx->para->p), -1);
}
return BN_SecBits(BN_Bits(ctx->para->p), BN_Bits(ctx->para->q));
}
#endif /* HITLS_CRYPTO_DH */
|
2301_79861745/bench_create
|
crypto/dh/src/dh_core.c
|
C
|
unknown
| 32,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 DH_LOCAL_H
#define DH_LOCAL_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_DH
#include "crypt_bn.h"
#include "crypt_dh.h"
#include "sal_atomic.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
#define DH_MIN_PBITS 768 // Minimum DH specification: 768 bits
#define DH_MAX_PBITS 8192 // Maximum DH specification: 8192 bits
#define DH_MIN_QBITS 160 // Minimum specification of DH parameter Q: 160 bits
/* DH key parameter */
struct DH_Para {
BN_BigNum *p;
BN_BigNum *q;
BN_BigNum *g;
CRYPT_PKEY_ParaId id;
};
/* DH key context */
struct DH_Ctx {
BN_BigNum *x; // Private key
BN_BigNum *y; // Public key
CRYPT_DH_Para *para; // key parameter
BSL_SAL_RefCount references;
void *libCtx;
uint32_t flags;
};
#ifdef __cplusplus
}
#endif
#endif // HITLS_CRYPTO_DH
#endif // CRYPT_DH_H
|
2301_79861745/bench_create
|
crypto/dh/src/dh_local.h
|
C
|
unknown
| 1,389
|
/*
* 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_DH
#include "bsl_err_internal.h"
#include "crypt_bn.h"
#include "crypt_errno.h"
#include "crypt_types.h"
#include "crypt_params_key.h"
#include "dh_local.h"
#include "crypt_dh.h"
static uint8_t g_rfc3526_2409_primeG[] = { 0x02 };
static uint8_t g_rfc7919G[] = { 0x02 };
static uint8_t g_rfc2409_prime768P[] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34,
0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74,
0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37,
0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6,
0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x3A, 0x36, 0x20, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
};
static uint8_t g_rfc2409_prime1024P[] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34,
0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74,
0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37,
0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6,
0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,
0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6,
0x49, 0x28, 0x66, 0x51, 0xEC, 0xE6, 0x53, 0x81, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
};
static uint8_t g_rfc3526_prime1536P[] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34,
0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74,
0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37,
0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6,
0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,
0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6,
0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05,
0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F,
0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB,
0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04,
0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x23, 0x73, 0x27, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
static uint8_t g_rfc3526_prime2048P[] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34,
0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74,
0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37,
0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6,
0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,
0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6,
0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05,
0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F,
0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB,
0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04,
0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B,
0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F,
0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18,
0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10,
0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAC, 0xAA, 0x68, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
static uint8_t g_rfc3526_prime3072P[] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34,
0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74,
0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37,
0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6,
0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,
0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6,
0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05,
0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F,
0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB,
0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04,
0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B,
0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F,
0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18,
0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10,
0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAA, 0xC4, 0x2D, 0xAD, 0x33, 0x17, 0x0D, 0x04, 0x50, 0x7A, 0x33,
0xA8, 0x55, 0x21, 0xAB, 0xDF, 0x1C, 0xBA, 0x64, 0xEC, 0xFB, 0x85, 0x04, 0x58, 0xDB, 0xEF, 0x0A,
0x8A, 0xEA, 0x71, 0x57, 0x5D, 0x06, 0x0C, 0x7D, 0xB3, 0x97, 0x0F, 0x85, 0xA6, 0xE1, 0xE4, 0xC7,
0xAB, 0xF5, 0xAE, 0x8C, 0xDB, 0x09, 0x33, 0xD7, 0x1E, 0x8C, 0x94, 0xE0, 0x4A, 0x25, 0x61, 0x9D,
0xCE, 0xE3, 0xD2, 0x26, 0x1A, 0xD2, 0xEE, 0x6B, 0xF1, 0x2F, 0xFA, 0x06, 0xD9, 0x8A, 0x08, 0x64,
0xD8, 0x76, 0x02, 0x73, 0x3E, 0xC8, 0x6A, 0x64, 0x52, 0x1F, 0x2B, 0x18, 0x17, 0x7B, 0x20, 0x0C,
0xBB, 0xE1, 0x17, 0x57, 0x7A, 0x61, 0x5D, 0x6C, 0x77, 0x09, 0x88, 0xC0, 0xBA, 0xD9, 0x46, 0xE2,
0x08, 0xE2, 0x4F, 0xA0, 0x74, 0xE5, 0xAB, 0x31, 0x43, 0xDB, 0x5B, 0xFC, 0xE0, 0xFD, 0x10, 0x8E,
0x4B, 0x82, 0xD1, 0x20, 0xA9, 0x3A, 0xD2, 0xCA, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
static uint8_t g_rfc3526_prime4096P[] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34,
0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74,
0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37,
0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6,
0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,
0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6,
0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05,
0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F,
0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB,
0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04,
0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B,
0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F,
0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18,
0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10,
0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAA, 0xC4, 0x2D, 0xAD, 0x33, 0x17, 0x0D, 0x04, 0x50, 0x7A, 0x33,
0xA8, 0x55, 0x21, 0xAB, 0xDF, 0x1C, 0xBA, 0x64, 0xEC, 0xFB, 0x85, 0x04, 0x58, 0xDB, 0xEF, 0x0A,
0x8A, 0xEA, 0x71, 0x57, 0x5D, 0x06, 0x0C, 0x7D, 0xB3, 0x97, 0x0F, 0x85, 0xA6, 0xE1, 0xE4, 0xC7,
0xAB, 0xF5, 0xAE, 0x8C, 0xDB, 0x09, 0x33, 0xD7, 0x1E, 0x8C, 0x94, 0xE0, 0x4A, 0x25, 0x61, 0x9D,
0xCE, 0xE3, 0xD2, 0x26, 0x1A, 0xD2, 0xEE, 0x6B, 0xF1, 0x2F, 0xFA, 0x06, 0xD9, 0x8A, 0x08, 0x64,
0xD8, 0x76, 0x02, 0x73, 0x3E, 0xC8, 0x6A, 0x64, 0x52, 0x1F, 0x2B, 0x18, 0x17, 0x7B, 0x20, 0x0C,
0xBB, 0xE1, 0x17, 0x57, 0x7A, 0x61, 0x5D, 0x6C, 0x77, 0x09, 0x88, 0xC0, 0xBA, 0xD9, 0x46, 0xE2,
0x08, 0xE2, 0x4F, 0xA0, 0x74, 0xE5, 0xAB, 0x31, 0x43, 0xDB, 0x5B, 0xFC, 0xE0, 0xFD, 0x10, 0x8E,
0x4B, 0x82, 0xD1, 0x20, 0xA9, 0x21, 0x08, 0x01, 0x1A, 0x72, 0x3C, 0x12, 0xA7, 0x87, 0xE6, 0xD7,
0x88, 0x71, 0x9A, 0x10, 0xBD, 0xBA, 0x5B, 0x26, 0x99, 0xC3, 0x27, 0x18, 0x6A, 0xF4, 0xE2, 0x3C,
0x1A, 0x94, 0x68, 0x34, 0xB6, 0x15, 0x0B, 0xDA, 0x25, 0x83, 0xE9, 0xCA, 0x2A, 0xD4, 0x4C, 0xE8,
0xDB, 0xBB, 0xC2, 0xDB, 0x04, 0xDE, 0x8E, 0xF9, 0x2E, 0x8E, 0xFC, 0x14, 0x1F, 0xBE, 0xCA, 0xA6,
0x28, 0x7C, 0x59, 0x47, 0x4E, 0x6B, 0xC0, 0x5D, 0x99, 0xB2, 0x96, 0x4F, 0xA0, 0x90, 0xC3, 0xA2,
0x23, 0x3B, 0xA1, 0x86, 0x51, 0x5B, 0xE7, 0xED, 0x1F, 0x61, 0x29, 0x70, 0xCE, 0xE2, 0xD7, 0xAF,
0xB8, 0x1B, 0xDD, 0x76, 0x21, 0x70, 0x48, 0x1C, 0xD0, 0x06, 0x91, 0x27, 0xD5, 0xB0, 0x5A, 0xA9,
0x93, 0xB4, 0xEA, 0x98, 0x8D, 0x8F, 0xDD, 0xC1, 0x86, 0xFF, 0xB7, 0xDC, 0x90, 0xA6, 0xC0, 0x8F,
0x4D, 0xF4, 0x35, 0xC9, 0x34, 0x06, 0x31, 0x99, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
static uint8_t g_rfc3526_prime6144P[] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34,
0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74,
0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37,
0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6,
0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,
0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6,
0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05,
0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F,
0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB,
0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04,
0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B,
0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F,
0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18,
0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10,
0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAA, 0xC4, 0x2D, 0xAD, 0x33, 0x17, 0x0D, 0x04, 0x50, 0x7A, 0x33,
0xA8, 0x55, 0x21, 0xAB, 0xDF, 0x1C, 0xBA, 0x64, 0xEC, 0xFB, 0x85, 0x04, 0x58, 0xDB, 0xEF, 0x0A,
0x8A, 0xEA, 0x71, 0x57, 0x5D, 0x06, 0x0C, 0x7D, 0xB3, 0x97, 0x0F, 0x85, 0xA6, 0xE1, 0xE4, 0xC7,
0xAB, 0xF5, 0xAE, 0x8C, 0xDB, 0x09, 0x33, 0xD7, 0x1E, 0x8C, 0x94, 0xE0, 0x4A, 0x25, 0x61, 0x9D,
0xCE, 0xE3, 0xD2, 0x26, 0x1A, 0xD2, 0xEE, 0x6B, 0xF1, 0x2F, 0xFA, 0x06, 0xD9, 0x8A, 0x08, 0x64,
0xD8, 0x76, 0x02, 0x73, 0x3E, 0xC8, 0x6A, 0x64, 0x52, 0x1F, 0x2B, 0x18, 0x17, 0x7B, 0x20, 0x0C,
0xBB, 0xE1, 0x17, 0x57, 0x7A, 0x61, 0x5D, 0x6C, 0x77, 0x09, 0x88, 0xC0, 0xBA, 0xD9, 0x46, 0xE2,
0x08, 0xE2, 0x4F, 0xA0, 0x74, 0xE5, 0xAB, 0x31, 0x43, 0xDB, 0x5B, 0xFC, 0xE0, 0xFD, 0x10, 0x8E,
0x4B, 0x82, 0xD1, 0x20, 0xA9, 0x21, 0x08, 0x01, 0x1A, 0x72, 0x3C, 0x12, 0xA7, 0x87, 0xE6, 0xD7,
0x88, 0x71, 0x9A, 0x10, 0xBD, 0xBA, 0x5B, 0x26, 0x99, 0xC3, 0x27, 0x18, 0x6A, 0xF4, 0xE2, 0x3C,
0x1A, 0x94, 0x68, 0x34, 0xB6, 0x15, 0x0B, 0xDA, 0x25, 0x83, 0xE9, 0xCA, 0x2A, 0xD4, 0x4C, 0xE8,
0xDB, 0xBB, 0xC2, 0xDB, 0x04, 0xDE, 0x8E, 0xF9, 0x2E, 0x8E, 0xFC, 0x14, 0x1F, 0xBE, 0xCA, 0xA6,
0x28, 0x7C, 0x59, 0x47, 0x4E, 0x6B, 0xC0, 0x5D, 0x99, 0xB2, 0x96, 0x4F, 0xA0, 0x90, 0xC3, 0xA2,
0x23, 0x3B, 0xA1, 0x86, 0x51, 0x5B, 0xE7, 0xED, 0x1F, 0x61, 0x29, 0x70, 0xCE, 0xE2, 0xD7, 0xAF,
0xB8, 0x1B, 0xDD, 0x76, 0x21, 0x70, 0x48, 0x1C, 0xD0, 0x06, 0x91, 0x27, 0xD5, 0xB0, 0x5A, 0xA9,
0x93, 0xB4, 0xEA, 0x98, 0x8D, 0x8F, 0xDD, 0xC1, 0x86, 0xFF, 0xB7, 0xDC, 0x90, 0xA6, 0xC0, 0x8F,
0x4D, 0xF4, 0x35, 0xC9, 0x34, 0x02, 0x84, 0x92, 0x36, 0xC3, 0xFA, 0xB4, 0xD2, 0x7C, 0x70, 0x26,
0xC1, 0xD4, 0xDC, 0xB2, 0x60, 0x26, 0x46, 0xDE, 0xC9, 0x75, 0x1E, 0x76, 0x3D, 0xBA, 0x37, 0xBD,
0xF8, 0xFF, 0x94, 0x06, 0xAD, 0x9E, 0x53, 0x0E, 0xE5, 0xDB, 0x38, 0x2F, 0x41, 0x30, 0x01, 0xAE,
0xB0, 0x6A, 0x53, 0xED, 0x90, 0x27, 0xD8, 0x31, 0x17, 0x97, 0x27, 0xB0, 0x86, 0x5A, 0x89, 0x18,
0xDA, 0x3E, 0xDB, 0xEB, 0xCF, 0x9B, 0x14, 0xED, 0x44, 0xCE, 0x6C, 0xBA, 0xCE, 0xD4, 0xBB, 0x1B,
0xDB, 0x7F, 0x14, 0x47, 0xE6, 0xCC, 0x25, 0x4B, 0x33, 0x20, 0x51, 0x51, 0x2B, 0xD7, 0xAF, 0x42,
0x6F, 0xB8, 0xF4, 0x01, 0x37, 0x8C, 0xD2, 0xBF, 0x59, 0x83, 0xCA, 0x01, 0xC6, 0x4B, 0x92, 0xEC,
0xF0, 0x32, 0xEA, 0x15, 0xD1, 0x72, 0x1D, 0x03, 0xF4, 0x82, 0xD7, 0xCE, 0x6E, 0x74, 0xFE, 0xF6,
0xD5, 0x5E, 0x70, 0x2F, 0x46, 0x98, 0x0C, 0x82, 0xB5, 0xA8, 0x40, 0x31, 0x90, 0x0B, 0x1C, 0x9E,
0x59, 0xE7, 0xC9, 0x7F, 0xBE, 0xC7, 0xE8, 0xF3, 0x23, 0xA9, 0x7A, 0x7E, 0x36, 0xCC, 0x88, 0xBE,
0x0F, 0x1D, 0x45, 0xB7, 0xFF, 0x58, 0x5A, 0xC5, 0x4B, 0xD4, 0x07, 0xB2, 0x2B, 0x41, 0x54, 0xAA,
0xCC, 0x8F, 0x6D, 0x7E, 0xBF, 0x48, 0xE1, 0xD8, 0x14, 0xCC, 0x5E, 0xD2, 0x0F, 0x80, 0x37, 0xE0,
0xA7, 0x97, 0x15, 0xEE, 0xF2, 0x9B, 0xE3, 0x28, 0x06, 0xA1, 0xD5, 0x8B, 0xB7, 0xC5, 0xDA, 0x76,
0xF5, 0x50, 0xAA, 0x3D, 0x8A, 0x1F, 0xBF, 0xF0, 0xEB, 0x19, 0xCC, 0xB1, 0xA3, 0x13, 0xD5, 0x5C,
0xDA, 0x56, 0xC9, 0xEC, 0x2E, 0xF2, 0x96, 0x32, 0x38, 0x7F, 0xE8, 0xD7, 0x6E, 0x3C, 0x04, 0x68,
0x04, 0x3E, 0x8F, 0x66, 0x3F, 0x48, 0x60, 0xEE, 0x12, 0xBF, 0x2D, 0x5B, 0x0B, 0x74, 0x74, 0xD6,
0xE6, 0x94, 0xF9, 0x1E, 0x6D, 0xCC, 0x40, 0x24, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
static uint8_t g_rfc3526_prime8192P[] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34,
0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74,
0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37,
0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6,
0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,
0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6,
0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05,
0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F,
0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB,
0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04,
0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B,
0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F,
0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18,
0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10,
0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAA, 0xC4, 0x2D, 0xAD, 0x33, 0x17, 0x0D, 0x04, 0x50, 0x7A, 0x33,
0xA8, 0x55, 0x21, 0xAB, 0xDF, 0x1C, 0xBA, 0x64, 0xEC, 0xFB, 0x85, 0x04, 0x58, 0xDB, 0xEF, 0x0A,
0x8A, 0xEA, 0x71, 0x57, 0x5D, 0x06, 0x0C, 0x7D, 0xB3, 0x97, 0x0F, 0x85, 0xA6, 0xE1, 0xE4, 0xC7,
0xAB, 0xF5, 0xAE, 0x8C, 0xDB, 0x09, 0x33, 0xD7, 0x1E, 0x8C, 0x94, 0xE0, 0x4A, 0x25, 0x61, 0x9D,
0xCE, 0xE3, 0xD2, 0x26, 0x1A, 0xD2, 0xEE, 0x6B, 0xF1, 0x2F, 0xFA, 0x06, 0xD9, 0x8A, 0x08, 0x64,
0xD8, 0x76, 0x02, 0x73, 0x3E, 0xC8, 0x6A, 0x64, 0x52, 0x1F, 0x2B, 0x18, 0x17, 0x7B, 0x20, 0x0C,
0xBB, 0xE1, 0x17, 0x57, 0x7A, 0x61, 0x5D, 0x6C, 0x77, 0x09, 0x88, 0xC0, 0xBA, 0xD9, 0x46, 0xE2,
0x08, 0xE2, 0x4F, 0xA0, 0x74, 0xE5, 0xAB, 0x31, 0x43, 0xDB, 0x5B, 0xFC, 0xE0, 0xFD, 0x10, 0x8E,
0x4B, 0x82, 0xD1, 0x20, 0xA9, 0x21, 0x08, 0x01, 0x1A, 0x72, 0x3C, 0x12, 0xA7, 0x87, 0xE6, 0xD7,
0x88, 0x71, 0x9A, 0x10, 0xBD, 0xBA, 0x5B, 0x26, 0x99, 0xC3, 0x27, 0x18, 0x6A, 0xF4, 0xE2, 0x3C,
0x1A, 0x94, 0x68, 0x34, 0xB6, 0x15, 0x0B, 0xDA, 0x25, 0x83, 0xE9, 0xCA, 0x2A, 0xD4, 0x4C, 0xE8,
0xDB, 0xBB, 0xC2, 0xDB, 0x04, 0xDE, 0x8E, 0xF9, 0x2E, 0x8E, 0xFC, 0x14, 0x1F, 0xBE, 0xCA, 0xA6,
0x28, 0x7C, 0x59, 0x47, 0x4E, 0x6B, 0xC0, 0x5D, 0x99, 0xB2, 0x96, 0x4F, 0xA0, 0x90, 0xC3, 0xA2,
0x23, 0x3B, 0xA1, 0x86, 0x51, 0x5B, 0xE7, 0xED, 0x1F, 0x61, 0x29, 0x70, 0xCE, 0xE2, 0xD7, 0xAF,
0xB8, 0x1B, 0xDD, 0x76, 0x21, 0x70, 0x48, 0x1C, 0xD0, 0x06, 0x91, 0x27, 0xD5, 0xB0, 0x5A, 0xA9,
0x93, 0xB4, 0xEA, 0x98, 0x8D, 0x8F, 0xDD, 0xC1, 0x86, 0xFF, 0xB7, 0xDC, 0x90, 0xA6, 0xC0, 0x8F,
0x4D, 0xF4, 0x35, 0xC9, 0x34, 0x02, 0x84, 0x92, 0x36, 0xC3, 0xFA, 0xB4, 0xD2, 0x7C, 0x70, 0x26,
0xC1, 0xD4, 0xDC, 0xB2, 0x60, 0x26, 0x46, 0xDE, 0xC9, 0x75, 0x1E, 0x76, 0x3D, 0xBA, 0x37, 0xBD,
0xF8, 0xFF, 0x94, 0x06, 0xAD, 0x9E, 0x53, 0x0E, 0xE5, 0xDB, 0x38, 0x2F, 0x41, 0x30, 0x01, 0xAE,
0xB0, 0x6A, 0x53, 0xED, 0x90, 0x27, 0xD8, 0x31, 0x17, 0x97, 0x27, 0xB0, 0x86, 0x5A, 0x89, 0x18,
0xDA, 0x3E, 0xDB, 0xEB, 0xCF, 0x9B, 0x14, 0xED, 0x44, 0xCE, 0x6C, 0xBA, 0xCE, 0xD4, 0xBB, 0x1B,
0xDB, 0x7F, 0x14, 0x47, 0xE6, 0xCC, 0x25, 0x4B, 0x33, 0x20, 0x51, 0x51, 0x2B, 0xD7, 0xAF, 0x42,
0x6F, 0xB8, 0xF4, 0x01, 0x37, 0x8C, 0xD2, 0xBF, 0x59, 0x83, 0xCA, 0x01, 0xC6, 0x4B, 0x92, 0xEC,
0xF0, 0x32, 0xEA, 0x15, 0xD1, 0x72, 0x1D, 0x03, 0xF4, 0x82, 0xD7, 0xCE, 0x6E, 0x74, 0xFE, 0xF6,
0xD5, 0x5E, 0x70, 0x2F, 0x46, 0x98, 0x0C, 0x82, 0xB5, 0xA8, 0x40, 0x31, 0x90, 0x0B, 0x1C, 0x9E,
0x59, 0xE7, 0xC9, 0x7F, 0xBE, 0xC7, 0xE8, 0xF3, 0x23, 0xA9, 0x7A, 0x7E, 0x36, 0xCC, 0x88, 0xBE,
0x0F, 0x1D, 0x45, 0xB7, 0xFF, 0x58, 0x5A, 0xC5, 0x4B, 0xD4, 0x07, 0xB2, 0x2B, 0x41, 0x54, 0xAA,
0xCC, 0x8F, 0x6D, 0x7E, 0xBF, 0x48, 0xE1, 0xD8, 0x14, 0xCC, 0x5E, 0xD2, 0x0F, 0x80, 0x37, 0xE0,
0xA7, 0x97, 0x15, 0xEE, 0xF2, 0x9B, 0xE3, 0x28, 0x06, 0xA1, 0xD5, 0x8B, 0xB7, 0xC5, 0xDA, 0x76,
0xF5, 0x50, 0xAA, 0x3D, 0x8A, 0x1F, 0xBF, 0xF0, 0xEB, 0x19, 0xCC, 0xB1, 0xA3, 0x13, 0xD5, 0x5C,
0xDA, 0x56, 0xC9, 0xEC, 0x2E, 0xF2, 0x96, 0x32, 0x38, 0x7F, 0xE8, 0xD7, 0x6E, 0x3C, 0x04, 0x68,
0x04, 0x3E, 0x8F, 0x66, 0x3F, 0x48, 0x60, 0xEE, 0x12, 0xBF, 0x2D, 0x5B, 0x0B, 0x74, 0x74, 0xD6,
0xE6, 0x94, 0xF9, 0x1E, 0x6D, 0xBE, 0x11, 0x59, 0x74, 0xA3, 0x92, 0x6F, 0x12, 0xFE, 0xE5, 0xE4,
0x38, 0x77, 0x7C, 0xB6, 0xA9, 0x32, 0xDF, 0x8C, 0xD8, 0xBE, 0xC4, 0xD0, 0x73, 0xB9, 0x31, 0xBA,
0x3B, 0xC8, 0x32, 0xB6, 0x8D, 0x9D, 0xD3, 0x00, 0x74, 0x1F, 0xA7, 0xBF, 0x8A, 0xFC, 0x47, 0xED,
0x25, 0x76, 0xF6, 0x93, 0x6B, 0xA4, 0x24, 0x66, 0x3A, 0xAB, 0x63, 0x9C, 0x5A, 0xE4, 0xF5, 0x68,
0x34, 0x23, 0xB4, 0x74, 0x2B, 0xF1, 0xC9, 0x78, 0x23, 0x8F, 0x16, 0xCB, 0xE3, 0x9D, 0x65, 0x2D,
0xE3, 0xFD, 0xB8, 0xBE, 0xFC, 0x84, 0x8A, 0xD9, 0x22, 0x22, 0x2E, 0x04, 0xA4, 0x03, 0x7C, 0x07,
0x13, 0xEB, 0x57, 0xA8, 0x1A, 0x23, 0xF0, 0xC7, 0x34, 0x73, 0xFC, 0x64, 0x6C, 0xEA, 0x30, 0x6B,
0x4B, 0xCB, 0xC8, 0x86, 0x2F, 0x83, 0x85, 0xDD, 0xFA, 0x9D, 0x4B, 0x7F, 0xA2, 0xC0, 0x87, 0xE8,
0x79, 0x68, 0x33, 0x03, 0xED, 0x5B, 0xDD, 0x3A, 0x06, 0x2B, 0x3C, 0xF5, 0xB3, 0xA2, 0x78, 0xA6,
0x6D, 0x2A, 0x13, 0xF8, 0x3F, 0x44, 0xF8, 0x2D, 0xDF, 0x31, 0x0E, 0xE0, 0x74, 0xAB, 0x6A, 0x36,
0x45, 0x97, 0xE8, 0x99, 0xA0, 0x25, 0x5D, 0xC1, 0x64, 0xF3, 0x1C, 0xC5, 0x08, 0x46, 0x85, 0x1D,
0xF9, 0xAB, 0x48, 0x19, 0x5D, 0xED, 0x7E, 0xA1, 0xB1, 0xD5, 0x10, 0xBD, 0x7E, 0xE7, 0x4D, 0x73,
0xFA, 0xF3, 0x6B, 0xC3, 0x1E, 0xCF, 0xA2, 0x68, 0x35, 0x90, 0x46, 0xF4, 0xEB, 0x87, 0x9F, 0x92,
0x40, 0x09, 0x43, 0x8B, 0x48, 0x1C, 0x6C, 0xD7, 0x88, 0x9A, 0x00, 0x2E, 0xD5, 0xEE, 0x38, 0x2B,
0xC9, 0x19, 0x0D, 0xA6, 0xFC, 0x02, 0x6E, 0x47, 0x95, 0x58, 0xE4, 0x47, 0x56, 0x77, 0xE9, 0xAA,
0x9E, 0x30, 0x50, 0xE2, 0x76, 0x56, 0x94, 0xDF, 0xC8, 0x1F, 0x56, 0xE8, 0x80, 0xB9, 0x6E, 0x71,
0x60, 0xC9, 0x80, 0xDD, 0x98, 0xED, 0xD3, 0xDF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
static uint8_t g_rfc7919_ffdhe2048P[] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A,
0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95,
0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9,
0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A,
0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0,
0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35,
0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72,
0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A,
0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB,
0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4,
0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70,
0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61,
0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83,
0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05,
0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA,
0x88, 0x6B, 0x42, 0x38, 0x61, 0x28, 0x5C, 0x97, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
static uint8_t g_rfc7919_ffdhe2048Q[] = {
0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xD6, 0xFC, 0x2A, 0x2C, 0x51, 0x5D, 0xA5, 0x4D,
0x57, 0xEE, 0x2B, 0x10, 0x13, 0x9E, 0x9E, 0x78, 0xEC, 0x5C, 0xE2, 0xC1, 0xE7, 0x16, 0x9B, 0x4A,
0xD4, 0xF0, 0x9B, 0x20, 0x8A, 0x32, 0x19, 0xFD, 0xE6, 0x49, 0xCE, 0xE7, 0x12, 0x4D, 0x9F, 0x7C,
0xBE, 0x97, 0xF1, 0xB1, 0xB1, 0x86, 0x3A, 0xEC, 0x7B, 0x40, 0xD9, 0x01, 0x57, 0x62, 0x30, 0xBD,
0x69, 0xEF, 0x8F, 0x6A, 0xEA, 0xFE, 0xB2, 0xB0, 0x92, 0x19, 0xFA, 0x8F, 0xAF, 0x83, 0x37, 0x68,
0x42, 0xB1, 0xB2, 0xAA, 0x9E, 0xF6, 0x8D, 0x79, 0xDA, 0xAB, 0x89, 0xAF, 0x3F, 0xAB, 0xE4, 0x9A,
0xCC, 0x27, 0x86, 0x38, 0x70, 0x73, 0x45, 0xBB, 0xF1, 0x53, 0x44, 0xED, 0x79, 0xF7, 0xF4, 0x39,
0x0E, 0xF8, 0xAC, 0x50, 0x9B, 0x56, 0xF3, 0x9A, 0x98, 0x56, 0x65, 0x27, 0xA4, 0x1D, 0x3C, 0xBD,
0x5E, 0x05, 0x58, 0xC1, 0x59, 0x92, 0x7D, 0xB0, 0xE8, 0x84, 0x54, 0xA5, 0xD9, 0x64, 0x71, 0xFD,
0xDC, 0xB5, 0x6D, 0x5B, 0xB0, 0x6B, 0xFA, 0x34, 0x0E, 0xA7, 0xA1, 0x51, 0xEF, 0x1C, 0xA6, 0xFA,
0x57, 0x2B, 0x76, 0xF3, 0xB1, 0xB9, 0x5D, 0x8C, 0x85, 0x83, 0xD3, 0xE4, 0x77, 0x05, 0x36, 0xB8,
0x4F, 0x01, 0x7E, 0x70, 0xE6, 0xFB, 0xF1, 0x76, 0x60, 0x1A, 0x02, 0x66, 0x94, 0x1A, 0x17, 0xB0,
0xC8, 0xB9, 0x7F, 0x4E, 0x74, 0xC2, 0xC1, 0xFF, 0xC7, 0x27, 0x89, 0x19, 0x77, 0x79, 0x40, 0xC1,
0xE1, 0xFF, 0x1D, 0x8D, 0xA6, 0x37, 0xD6, 0xB9, 0x9D, 0xDA, 0xFE, 0x5E, 0x17, 0x61, 0x10, 0x02,
0xE2, 0xC7, 0x78, 0xC1, 0xBE, 0x8B, 0x41, 0xD9, 0x63, 0x79, 0xA5, 0x13, 0x60, 0xD9, 0x77, 0xFD,
0x44, 0x35, 0xA1, 0x1C, 0x30, 0x94, 0x2E, 0x4B, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
static uint8_t g_rfc7919_ffdhe3072P[] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A,
0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95,
0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9,
0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A,
0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0,
0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35,
0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72,
0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A,
0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB,
0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4,
0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70,
0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61,
0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83,
0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05,
0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA,
0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B,
0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07,
0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C,
0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44,
0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF,
0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D,
0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E,
0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C,
0x25, 0xE4, 0x1D, 0x2B, 0x66, 0xC6, 0x2E, 0x37, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
static uint8_t g_rfc7919_ffdhe3072Q[] = {
0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xD6, 0xFC, 0x2A, 0x2C, 0x51, 0x5D, 0xA5, 0x4D,
0x57, 0xEE, 0x2B, 0x10, 0x13, 0x9E, 0x9E, 0x78, 0xEC, 0x5C, 0xE2, 0xC1, 0xE7, 0x16, 0x9B, 0x4A,
0xD4, 0xF0, 0x9B, 0x20, 0x8A, 0x32, 0x19, 0xFD, 0xE6, 0x49, 0xCE, 0xE7, 0x12, 0x4D, 0x9F, 0x7C,
0xBE, 0x97, 0xF1, 0xB1, 0xB1, 0x86, 0x3A, 0xEC, 0x7B, 0x40, 0xD9, 0x01, 0x57, 0x62, 0x30, 0xBD,
0x69, 0xEF, 0x8F, 0x6A, 0xEA, 0xFE, 0xB2, 0xB0, 0x92, 0x19, 0xFA, 0x8F, 0xAF, 0x83, 0x37, 0x68,
0x42, 0xB1, 0xB2, 0xAA, 0x9E, 0xF6, 0x8D, 0x79, 0xDA, 0xAB, 0x89, 0xAF, 0x3F, 0xAB, 0xE4, 0x9A,
0xCC, 0x27, 0x86, 0x38, 0x70, 0x73, 0x45, 0xBB, 0xF1, 0x53, 0x44, 0xED, 0x79, 0xF7, 0xF4, 0x39,
0x0E, 0xF8, 0xAC, 0x50, 0x9B, 0x56, 0xF3, 0x9A, 0x98, 0x56, 0x65, 0x27, 0xA4, 0x1D, 0x3C, 0xBD,
0x5E, 0x05, 0x58, 0xC1, 0x59, 0x92, 0x7D, 0xB0, 0xE8, 0x84, 0x54, 0xA5, 0xD9, 0x64, 0x71, 0xFD,
0xDC, 0xB5, 0x6D, 0x5B, 0xB0, 0x6B, 0xFA, 0x34, 0x0E, 0xA7, 0xA1, 0x51, 0xEF, 0x1C, 0xA6, 0xFA,
0x57, 0x2B, 0x76, 0xF3, 0xB1, 0xB9, 0x5D, 0x8C, 0x85, 0x83, 0xD3, 0xE4, 0x77, 0x05, 0x36, 0xB8,
0x4F, 0x01, 0x7E, 0x70, 0xE6, 0xFB, 0xF1, 0x76, 0x60, 0x1A, 0x02, 0x66, 0x94, 0x1A, 0x17, 0xB0,
0xC8, 0xB9, 0x7F, 0x4E, 0x74, 0xC2, 0xC1, 0xFF, 0xC7, 0x27, 0x89, 0x19, 0x77, 0x79, 0x40, 0xC1,
0xE1, 0xFF, 0x1D, 0x8D, 0xA6, 0x37, 0xD6, 0xB9, 0x9D, 0xDA, 0xFE, 0x5E, 0x17, 0x61, 0x10, 0x02,
0xE2, 0xC7, 0x78, 0xC1, 0xBE, 0x8B, 0x41, 0xD9, 0x63, 0x79, 0xA5, 0x13, 0x60, 0xD9, 0x77, 0xFD,
0x44, 0x35, 0xA1, 0x1C, 0x30, 0x8F, 0xE7, 0xEE, 0x6F, 0x1A, 0xAD, 0x9D, 0xB2, 0x8C, 0x81, 0xAD,
0xDE, 0x1A, 0x7A, 0x6F, 0x7C, 0xCE, 0x01, 0x1C, 0x30, 0xDA, 0x37, 0xE4, 0xEB, 0x73, 0x64, 0x83,
0xBD, 0x6C, 0x8E, 0x93, 0x48, 0xFB, 0xFB, 0xF7, 0x2C, 0xC6, 0x58, 0x7D, 0x60, 0xC3, 0x6C, 0x8E,
0x57, 0x7F, 0x09, 0x84, 0xC2, 0x89, 0xC9, 0x38, 0x5A, 0x09, 0x86, 0x49, 0xDE, 0x21, 0xBC, 0xA2,
0x7A, 0x7E, 0xA2, 0x29, 0x71, 0x6B, 0xA6, 0xE9, 0xB2, 0x79, 0x71, 0x0F, 0x38, 0xFA, 0xA5, 0xFF,
0xAE, 0x57, 0x41, 0x55, 0xCE, 0x4E, 0xFB, 0x4F, 0x74, 0x36, 0x95, 0xE2, 0x91, 0x1B, 0x1D, 0x06,
0xD5, 0xE2, 0x90, 0xCB, 0xCD, 0x86, 0xF5, 0x6D, 0x0E, 0xDF, 0xCD, 0x21, 0x6A, 0xE2, 0x24, 0x27,
0x05, 0x5E, 0x68, 0x35, 0xFD, 0x29, 0xEE, 0xF7, 0x9E, 0x0D, 0x90, 0x77, 0x1F, 0xEA, 0xCE, 0xBE,
0x12, 0xF2, 0x0E, 0x95, 0xB3, 0x63, 0x17, 0x1B, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
static uint8_t g_rfc7919_ffdhe4096P[] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A,
0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95,
0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9,
0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A,
0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0,
0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35,
0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72,
0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A,
0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB,
0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4,
0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70,
0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61,
0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83,
0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05,
0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA,
0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B,
0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07,
0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C,
0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44,
0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF,
0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D,
0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E,
0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C,
0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, 0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB,
0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, 0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18,
0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, 0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A,
0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, 0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32,
0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, 0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38,
0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, 0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C,
0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, 0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF,
0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, 0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1,
0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x65, 0x5F, 0x6A, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
static uint8_t g_rfc7919_ffdhe4096Q[] = {
0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xD6, 0xFC, 0x2A, 0x2C, 0x51, 0x5D, 0xA5, 0x4D,
0x57, 0xEE, 0x2B, 0x10, 0x13, 0x9E, 0x9E, 0x78, 0xEC, 0x5C, 0xE2, 0xC1, 0xE7, 0x16, 0x9B, 0x4A,
0xD4, 0xF0, 0x9B, 0x20, 0x8A, 0x32, 0x19, 0xFD, 0xE6, 0x49, 0xCE, 0xE7, 0x12, 0x4D, 0x9F, 0x7C,
0xBE, 0x97, 0xF1, 0xB1, 0xB1, 0x86, 0x3A, 0xEC, 0x7B, 0x40, 0xD9, 0x01, 0x57, 0x62, 0x30, 0xBD,
0x69, 0xEF, 0x8F, 0x6A, 0xEA, 0xFE, 0xB2, 0xB0, 0x92, 0x19, 0xFA, 0x8F, 0xAF, 0x83, 0x37, 0x68,
0x42, 0xB1, 0xB2, 0xAA, 0x9E, 0xF6, 0x8D, 0x79, 0xDA, 0xAB, 0x89, 0xAF, 0x3F, 0xAB, 0xE4, 0x9A,
0xCC, 0x27, 0x86, 0x38, 0x70, 0x73, 0x45, 0xBB, 0xF1, 0x53, 0x44, 0xED, 0x79, 0xF7, 0xF4, 0x39,
0x0E, 0xF8, 0xAC, 0x50, 0x9B, 0x56, 0xF3, 0x9A, 0x98, 0x56, 0x65, 0x27, 0xA4, 0x1D, 0x3C, 0xBD,
0x5E, 0x05, 0x58, 0xC1, 0x59, 0x92, 0x7D, 0xB0, 0xE8, 0x84, 0x54, 0xA5, 0xD9, 0x64, 0x71, 0xFD,
0xDC, 0xB5, 0x6D, 0x5B, 0xB0, 0x6B, 0xFA, 0x34, 0x0E, 0xA7, 0xA1, 0x51, 0xEF, 0x1C, 0xA6, 0xFA,
0x57, 0x2B, 0x76, 0xF3, 0xB1, 0xB9, 0x5D, 0x8C, 0x85, 0x83, 0xD3, 0xE4, 0x77, 0x05, 0x36, 0xB8,
0x4F, 0x01, 0x7E, 0x70, 0xE6, 0xFB, 0xF1, 0x76, 0x60, 0x1A, 0x02, 0x66, 0x94, 0x1A, 0x17, 0xB0,
0xC8, 0xB9, 0x7F, 0x4E, 0x74, 0xC2, 0xC1, 0xFF, 0xC7, 0x27, 0x89, 0x19, 0x77, 0x79, 0x40, 0xC1,
0xE1, 0xFF, 0x1D, 0x8D, 0xA6, 0x37, 0xD6, 0xB9, 0x9D, 0xDA, 0xFE, 0x5E, 0x17, 0x61, 0x10, 0x02,
0xE2, 0xC7, 0x78, 0xC1, 0xBE, 0x8B, 0x41, 0xD9, 0x63, 0x79, 0xA5, 0x13, 0x60, 0xD9, 0x77, 0xFD,
0x44, 0x35, 0xA1, 0x1C, 0x30, 0x8F, 0xE7, 0xEE, 0x6F, 0x1A, 0xAD, 0x9D, 0xB2, 0x8C, 0x81, 0xAD,
0xDE, 0x1A, 0x7A, 0x6F, 0x7C, 0xCE, 0x01, 0x1C, 0x30, 0xDA, 0x37, 0xE4, 0xEB, 0x73, 0x64, 0x83,
0xBD, 0x6C, 0x8E, 0x93, 0x48, 0xFB, 0xFB, 0xF7, 0x2C, 0xC6, 0x58, 0x7D, 0x60, 0xC3, 0x6C, 0x8E,
0x57, 0x7F, 0x09, 0x84, 0xC2, 0x89, 0xC9, 0x38, 0x5A, 0x09, 0x86, 0x49, 0xDE, 0x21, 0xBC, 0xA2,
0x7A, 0x7E, 0xA2, 0x29, 0x71, 0x6B, 0xA6, 0xE9, 0xB2, 0x79, 0x71, 0x0F, 0x38, 0xFA, 0xA5, 0xFF,
0xAE, 0x57, 0x41, 0x55, 0xCE, 0x4E, 0xFB, 0x4F, 0x74, 0x36, 0x95, 0xE2, 0x91, 0x1B, 0x1D, 0x06,
0xD5, 0xE2, 0x90, 0xCB, 0xCD, 0x86, 0xF5, 0x6D, 0x0E, 0xDF, 0xCD, 0x21, 0x6A, 0xE2, 0x24, 0x27,
0x05, 0x5E, 0x68, 0x35, 0xFD, 0x29, 0xEE, 0xF7, 0x9E, 0x0D, 0x90, 0x77, 0x1F, 0xEA, 0xCE, 0xBE,
0x12, 0xF2, 0x0E, 0x95, 0xB3, 0x4F, 0x0F, 0x78, 0xB7, 0x37, 0xA9, 0x61, 0x8B, 0x26, 0xFA, 0x7D,
0xBC, 0x98, 0x74, 0xF2, 0x72, 0xC4, 0x2B, 0xDB, 0x56, 0x3E, 0xAF, 0xA1, 0x6B, 0x4F, 0xB6, 0x8C,
0x3B, 0xB1, 0xE7, 0x8E, 0xAA, 0x81, 0xA0, 0x02, 0x43, 0xFA, 0xAD, 0xD2, 0xBF, 0x18, 0xE6, 0x3D,
0x38, 0x9A, 0xE4, 0x43, 0x77, 0xDA, 0x18, 0xC5, 0x76, 0xB5, 0x0F, 0x00, 0x96, 0xCF, 0x34, 0x19,
0x54, 0x83, 0xB0, 0x05, 0x48, 0xC0, 0x98, 0x62, 0x36, 0xE3, 0xBC, 0x7C, 0xB8, 0xD6, 0x80, 0x1C,
0x04, 0x94, 0xCC, 0xD1, 0x99, 0xE5, 0xC5, 0xBD, 0x0D, 0x0E, 0xDC, 0x9E, 0xB8, 0xA0, 0x00, 0x1E,
0x15, 0x27, 0x67, 0x54, 0xFC, 0xC6, 0x85, 0x66, 0x05, 0x41, 0x48, 0xE6, 0xE7, 0x64, 0xBE, 0xE7,
0xC7, 0x64, 0xDA, 0xAD, 0x3F, 0xC4, 0x52, 0x35, 0xA6, 0xDA, 0xD4, 0x28, 0xFA, 0x20, 0xC1, 0x70,
0xE3, 0x45, 0x00, 0x3F, 0x2F, 0x32, 0xAF, 0xB5, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
static uint8_t g_rfc7919_ffdhe6144P[] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A,
0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95,
0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9,
0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A,
0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0,
0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35,
0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72,
0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A,
0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB,
0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4,
0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70,
0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61,
0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83,
0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05,
0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA,
0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B,
0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07,
0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C,
0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44,
0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF,
0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D,
0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E,
0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C,
0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, 0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB,
0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, 0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18,
0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, 0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A,
0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, 0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32,
0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, 0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38,
0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, 0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C,
0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, 0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF,
0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, 0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1,
0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x0D, 0xD9, 0x02, 0x0B, 0xFD, 0x64, 0xB6, 0x45, 0x03, 0x6C, 0x7A,
0x4E, 0x67, 0x7D, 0x2C, 0x38, 0x53, 0x2A, 0x3A, 0x23, 0xBA, 0x44, 0x42, 0xCA, 0xF5, 0x3E, 0xA6,
0x3B, 0xB4, 0x54, 0x32, 0x9B, 0x76, 0x24, 0xC8, 0x91, 0x7B, 0xDD, 0x64, 0xB1, 0xC0, 0xFD, 0x4C,
0xB3, 0x8E, 0x8C, 0x33, 0x4C, 0x70, 0x1C, 0x3A, 0xCD, 0xAD, 0x06, 0x57, 0xFC, 0xCF, 0xEC, 0x71,
0x9B, 0x1F, 0x5C, 0x3E, 0x4E, 0x46, 0x04, 0x1F, 0x38, 0x81, 0x47, 0xFB, 0x4C, 0xFD, 0xB4, 0x77,
0xA5, 0x24, 0x71, 0xF7, 0xA9, 0xA9, 0x69, 0x10, 0xB8, 0x55, 0x32, 0x2E, 0xDB, 0x63, 0x40, 0xD8,
0xA0, 0x0E, 0xF0, 0x92, 0x35, 0x05, 0x11, 0xE3, 0x0A, 0xBE, 0xC1, 0xFF, 0xF9, 0xE3, 0xA2, 0x6E,
0x7F, 0xB2, 0x9F, 0x8C, 0x18, 0x30, 0x23, 0xC3, 0x58, 0x7E, 0x38, 0xDA, 0x00, 0x77, 0xD9, 0xB4,
0x76, 0x3E, 0x4E, 0x4B, 0x94, 0xB2, 0xBB, 0xC1, 0x94, 0xC6, 0x65, 0x1E, 0x77, 0xCA, 0xF9, 0x92,
0xEE, 0xAA, 0xC0, 0x23, 0x2A, 0x28, 0x1B, 0xF6, 0xB3, 0xA7, 0x39, 0xC1, 0x22, 0x61, 0x16, 0x82,
0x0A, 0xE8, 0xDB, 0x58, 0x47, 0xA6, 0x7C, 0xBE, 0xF9, 0xC9, 0x09, 0x1B, 0x46, 0x2D, 0x53, 0x8C,
0xD7, 0x2B, 0x03, 0x74, 0x6A, 0xE7, 0x7F, 0x5E, 0x62, 0x29, 0x2C, 0x31, 0x15, 0x62, 0xA8, 0x46,
0x50, 0x5D, 0xC8, 0x2D, 0xB8, 0x54, 0x33, 0x8A, 0xE4, 0x9F, 0x52, 0x35, 0xC9, 0x5B, 0x91, 0x17,
0x8C, 0xCF, 0x2D, 0xD5, 0xCA, 0xCE, 0xF4, 0x03, 0xEC, 0x9D, 0x18, 0x10, 0xC6, 0x27, 0x2B, 0x04,
0x5B, 0x3B, 0x71, 0xF9, 0xDC, 0x6B, 0x80, 0xD6, 0x3F, 0xDD, 0x4A, 0x8E, 0x9A, 0xDB, 0x1E, 0x69,
0x62, 0xA6, 0x95, 0x26, 0xD4, 0x31, 0x61, 0xC1, 0xA4, 0x1D, 0x57, 0x0D, 0x79, 0x38, 0xDA, 0xD4,
0xA4, 0x0E, 0x32, 0x9C, 0xD0, 0xE4, 0x0E, 0x65, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
static uint8_t g_rfc7919_ffdhe6144Q[] = {
0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xD6, 0xFC, 0x2A, 0x2C, 0x51, 0x5D, 0xA5, 0x4D,
0x57, 0xEE, 0x2B, 0x10, 0x13, 0x9E, 0x9E, 0x78, 0xEC, 0x5C, 0xE2, 0xC1, 0xE7, 0x16, 0x9B, 0x4A,
0xD4, 0xF0, 0x9B, 0x20, 0x8A, 0x32, 0x19, 0xFD, 0xE6, 0x49, 0xCE, 0xE7, 0x12, 0x4D, 0x9F, 0x7C,
0xBE, 0x97, 0xF1, 0xB1, 0xB1, 0x86, 0x3A, 0xEC, 0x7B, 0x40, 0xD9, 0x01, 0x57, 0x62, 0x30, 0xBD,
0x69, 0xEF, 0x8F, 0x6A, 0xEA, 0xFE, 0xB2, 0xB0, 0x92, 0x19, 0xFA, 0x8F, 0xAF, 0x83, 0x37, 0x68,
0x42, 0xB1, 0xB2, 0xAA, 0x9E, 0xF6, 0x8D, 0x79, 0xDA, 0xAB, 0x89, 0xAF, 0x3F, 0xAB, 0xE4, 0x9A,
0xCC, 0x27, 0x86, 0x38, 0x70, 0x73, 0x45, 0xBB, 0xF1, 0x53, 0x44, 0xED, 0x79, 0xF7, 0xF4, 0x39,
0x0E, 0xF8, 0xAC, 0x50, 0x9B, 0x56, 0xF3, 0x9A, 0x98, 0x56, 0x65, 0x27, 0xA4, 0x1D, 0x3C, 0xBD,
0x5E, 0x05, 0x58, 0xC1, 0x59, 0x92, 0x7D, 0xB0, 0xE8, 0x84, 0x54, 0xA5, 0xD9, 0x64, 0x71, 0xFD,
0xDC, 0xB5, 0x6D, 0x5B, 0xB0, 0x6B, 0xFA, 0x34, 0x0E, 0xA7, 0xA1, 0x51, 0xEF, 0x1C, 0xA6, 0xFA,
0x57, 0x2B, 0x76, 0xF3, 0xB1, 0xB9, 0x5D, 0x8C, 0x85, 0x83, 0xD3, 0xE4, 0x77, 0x05, 0x36, 0xB8,
0x4F, 0x01, 0x7E, 0x70, 0xE6, 0xFB, 0xF1, 0x76, 0x60, 0x1A, 0x02, 0x66, 0x94, 0x1A, 0x17, 0xB0,
0xC8, 0xB9, 0x7F, 0x4E, 0x74, 0xC2, 0xC1, 0xFF, 0xC7, 0x27, 0x89, 0x19, 0x77, 0x79, 0x40, 0xC1,
0xE1, 0xFF, 0x1D, 0x8D, 0xA6, 0x37, 0xD6, 0xB9, 0x9D, 0xDA, 0xFE, 0x5E, 0x17, 0x61, 0x10, 0x02,
0xE2, 0xC7, 0x78, 0xC1, 0xBE, 0x8B, 0x41, 0xD9, 0x63, 0x79, 0xA5, 0x13, 0x60, 0xD9, 0x77, 0xFD,
0x44, 0x35, 0xA1, 0x1C, 0x30, 0x8F, 0xE7, 0xEE, 0x6F, 0x1A, 0xAD, 0x9D, 0xB2, 0x8C, 0x81, 0xAD,
0xDE, 0x1A, 0x7A, 0x6F, 0x7C, 0xCE, 0x01, 0x1C, 0x30, 0xDA, 0x37, 0xE4, 0xEB, 0x73, 0x64, 0x83,
0xBD, 0x6C, 0x8E, 0x93, 0x48, 0xFB, 0xFB, 0xF7, 0x2C, 0xC6, 0x58, 0x7D, 0x60, 0xC3, 0x6C, 0x8E,
0x57, 0x7F, 0x09, 0x84, 0xC2, 0x89, 0xC9, 0x38, 0x5A, 0x09, 0x86, 0x49, 0xDE, 0x21, 0xBC, 0xA2,
0x7A, 0x7E, 0xA2, 0x29, 0x71, 0x6B, 0xA6, 0xE9, 0xB2, 0x79, 0x71, 0x0F, 0x38, 0xFA, 0xA5, 0xFF,
0xAE, 0x57, 0x41, 0x55, 0xCE, 0x4E, 0xFB, 0x4F, 0x74, 0x36, 0x95, 0xE2, 0x91, 0x1B, 0x1D, 0x06,
0xD5, 0xE2, 0x90, 0xCB, 0xCD, 0x86, 0xF5, 0x6D, 0x0E, 0xDF, 0xCD, 0x21, 0x6A, 0xE2, 0x24, 0x27,
0x05, 0x5E, 0x68, 0x35, 0xFD, 0x29, 0xEE, 0xF7, 0x9E, 0x0D, 0x90, 0x77, 0x1F, 0xEA, 0xCE, 0xBE,
0x12, 0xF2, 0x0E, 0x95, 0xB3, 0x4F, 0x0F, 0x78, 0xB7, 0x37, 0xA9, 0x61, 0x8B, 0x26, 0xFA, 0x7D,
0xBC, 0x98, 0x74, 0xF2, 0x72, 0xC4, 0x2B, 0xDB, 0x56, 0x3E, 0xAF, 0xA1, 0x6B, 0x4F, 0xB6, 0x8C,
0x3B, 0xB1, 0xE7, 0x8E, 0xAA, 0x81, 0xA0, 0x02, 0x43, 0xFA, 0xAD, 0xD2, 0xBF, 0x18, 0xE6, 0x3D,
0x38, 0x9A, 0xE4, 0x43, 0x77, 0xDA, 0x18, 0xC5, 0x76, 0xB5, 0x0F, 0x00, 0x96, 0xCF, 0x34, 0x19,
0x54, 0x83, 0xB0, 0x05, 0x48, 0xC0, 0x98, 0x62, 0x36, 0xE3, 0xBC, 0x7C, 0xB8, 0xD6, 0x80, 0x1C,
0x04, 0x94, 0xCC, 0xD1, 0x99, 0xE5, 0xC5, 0xBD, 0x0D, 0x0E, 0xDC, 0x9E, 0xB8, 0xA0, 0x00, 0x1E,
0x15, 0x27, 0x67, 0x54, 0xFC, 0xC6, 0x85, 0x66, 0x05, 0x41, 0x48, 0xE6, 0xE7, 0x64, 0xBE, 0xE7,
0xC7, 0x64, 0xDA, 0xAD, 0x3F, 0xC4, 0x52, 0x35, 0xA6, 0xDA, 0xD4, 0x28, 0xFA, 0x20, 0xC1, 0x70,
0xE3, 0x45, 0x00, 0x3F, 0x2F, 0x06, 0xEC, 0x81, 0x05, 0xFE, 0xB2, 0x5B, 0x22, 0x81, 0xB6, 0x3D,
0x27, 0x33, 0xBE, 0x96, 0x1C, 0x29, 0x95, 0x1D, 0x11, 0xDD, 0x22, 0x21, 0x65, 0x7A, 0x9F, 0x53,
0x1D, 0xDA, 0x2A, 0x19, 0x4D, 0xBB, 0x12, 0x64, 0x48, 0xBD, 0xEE, 0xB2, 0x58, 0xE0, 0x7E, 0xA6,
0x59, 0xC7, 0x46, 0x19, 0xA6, 0x38, 0x0E, 0x1D, 0x66, 0xD6, 0x83, 0x2B, 0xFE, 0x67, 0xF6, 0x38,
0xCD, 0x8F, 0xAE, 0x1F, 0x27, 0x23, 0x02, 0x0F, 0x9C, 0x40, 0xA3, 0xFD, 0xA6, 0x7E, 0xDA, 0x3B,
0xD2, 0x92, 0x38, 0xFB, 0xD4, 0xD4, 0xB4, 0x88, 0x5C, 0x2A, 0x99, 0x17, 0x6D, 0xB1, 0xA0, 0x6C,
0x50, 0x07, 0x78, 0x49, 0x1A, 0x82, 0x88, 0xF1, 0x85, 0x5F, 0x60, 0xFF, 0xFC, 0xF1, 0xD1, 0x37,
0x3F, 0xD9, 0x4F, 0xC6, 0x0C, 0x18, 0x11, 0xE1, 0xAC, 0x3F, 0x1C, 0x6D, 0x00, 0x3B, 0xEC, 0xDA,
0x3B, 0x1F, 0x27, 0x25, 0xCA, 0x59, 0x5D, 0xE0, 0xCA, 0x63, 0x32, 0x8F, 0x3B, 0xE5, 0x7C, 0xC9,
0x77, 0x55, 0x60, 0x11, 0x95, 0x14, 0x0D, 0xFB, 0x59, 0xD3, 0x9C, 0xE0, 0x91, 0x30, 0x8B, 0x41,
0x05, 0x74, 0x6D, 0xAC, 0x23, 0xD3, 0x3E, 0x5F, 0x7C, 0xE4, 0x84, 0x8D, 0xA3, 0x16, 0xA9, 0xC6,
0x6B, 0x95, 0x81, 0xBA, 0x35, 0x73, 0xBF, 0xAF, 0x31, 0x14, 0x96, 0x18, 0x8A, 0xB1, 0x54, 0x23,
0x28, 0x2E, 0xE4, 0x16, 0xDC, 0x2A, 0x19, 0xC5, 0x72, 0x4F, 0xA9, 0x1A, 0xE4, 0xAD, 0xC8, 0x8B,
0xC6, 0x67, 0x96, 0xEA, 0xE5, 0x67, 0x7A, 0x01, 0xF6, 0x4E, 0x8C, 0x08, 0x63, 0x13, 0x95, 0x82,
0x2D, 0x9D, 0xB8, 0xFC, 0xEE, 0x35, 0xC0, 0x6B, 0x1F, 0xEE, 0xA5, 0x47, 0x4D, 0x6D, 0x8F, 0x34,
0xB1, 0x53, 0x4A, 0x93, 0x6A, 0x18, 0xB0, 0xE0, 0xD2, 0x0E, 0xAB, 0x86, 0xBC, 0x9C, 0x6D, 0x6A,
0x52, 0x07, 0x19, 0x4E, 0x68, 0x72, 0x07, 0x32, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
static uint8_t g_rfc7919_ffdhe8192P[] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A,
0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95,
0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9,
0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A,
0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0,
0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35,
0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72,
0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A,
0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB,
0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4,
0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70,
0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61,
0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83,
0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05,
0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA,
0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B,
0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07,
0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C,
0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44,
0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF,
0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D,
0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E,
0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C,
0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, 0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB,
0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, 0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18,
0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, 0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A,
0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, 0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32,
0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, 0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38,
0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, 0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C,
0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, 0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF,
0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, 0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1,
0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x0D, 0xD9, 0x02, 0x0B, 0xFD, 0x64, 0xB6, 0x45, 0x03, 0x6C, 0x7A,
0x4E, 0x67, 0x7D, 0x2C, 0x38, 0x53, 0x2A, 0x3A, 0x23, 0xBA, 0x44, 0x42, 0xCA, 0xF5, 0x3E, 0xA6,
0x3B, 0xB4, 0x54, 0x32, 0x9B, 0x76, 0x24, 0xC8, 0x91, 0x7B, 0xDD, 0x64, 0xB1, 0xC0, 0xFD, 0x4C,
0xB3, 0x8E, 0x8C, 0x33, 0x4C, 0x70, 0x1C, 0x3A, 0xCD, 0xAD, 0x06, 0x57, 0xFC, 0xCF, 0xEC, 0x71,
0x9B, 0x1F, 0x5C, 0x3E, 0x4E, 0x46, 0x04, 0x1F, 0x38, 0x81, 0x47, 0xFB, 0x4C, 0xFD, 0xB4, 0x77,
0xA5, 0x24, 0x71, 0xF7, 0xA9, 0xA9, 0x69, 0x10, 0xB8, 0x55, 0x32, 0x2E, 0xDB, 0x63, 0x40, 0xD8,
0xA0, 0x0E, 0xF0, 0x92, 0x35, 0x05, 0x11, 0xE3, 0x0A, 0xBE, 0xC1, 0xFF, 0xF9, 0xE3, 0xA2, 0x6E,
0x7F, 0xB2, 0x9F, 0x8C, 0x18, 0x30, 0x23, 0xC3, 0x58, 0x7E, 0x38, 0xDA, 0x00, 0x77, 0xD9, 0xB4,
0x76, 0x3E, 0x4E, 0x4B, 0x94, 0xB2, 0xBB, 0xC1, 0x94, 0xC6, 0x65, 0x1E, 0x77, 0xCA, 0xF9, 0x92,
0xEE, 0xAA, 0xC0, 0x23, 0x2A, 0x28, 0x1B, 0xF6, 0xB3, 0xA7, 0x39, 0xC1, 0x22, 0x61, 0x16, 0x82,
0x0A, 0xE8, 0xDB, 0x58, 0x47, 0xA6, 0x7C, 0xBE, 0xF9, 0xC9, 0x09, 0x1B, 0x46, 0x2D, 0x53, 0x8C,
0xD7, 0x2B, 0x03, 0x74, 0x6A, 0xE7, 0x7F, 0x5E, 0x62, 0x29, 0x2C, 0x31, 0x15, 0x62, 0xA8, 0x46,
0x50, 0x5D, 0xC8, 0x2D, 0xB8, 0x54, 0x33, 0x8A, 0xE4, 0x9F, 0x52, 0x35, 0xC9, 0x5B, 0x91, 0x17,
0x8C, 0xCF, 0x2D, 0xD5, 0xCA, 0xCE, 0xF4, 0x03, 0xEC, 0x9D, 0x18, 0x10, 0xC6, 0x27, 0x2B, 0x04,
0x5B, 0x3B, 0x71, 0xF9, 0xDC, 0x6B, 0x80, 0xD6, 0x3F, 0xDD, 0x4A, 0x8E, 0x9A, 0xDB, 0x1E, 0x69,
0x62, 0xA6, 0x95, 0x26, 0xD4, 0x31, 0x61, 0xC1, 0xA4, 0x1D, 0x57, 0x0D, 0x79, 0x38, 0xDA, 0xD4,
0xA4, 0x0E, 0x32, 0x9C, 0xCF, 0xF4, 0x6A, 0xAA, 0x36, 0xAD, 0x00, 0x4C, 0xF6, 0x00, 0xC8, 0x38,
0x1E, 0x42, 0x5A, 0x31, 0xD9, 0x51, 0xAE, 0x64, 0xFD, 0xB2, 0x3F, 0xCE, 0xC9, 0x50, 0x9D, 0x43,
0x68, 0x7F, 0xEB, 0x69, 0xED, 0xD1, 0xCC, 0x5E, 0x0B, 0x8C, 0xC3, 0xBD, 0xF6, 0x4B, 0x10, 0xEF,
0x86, 0xB6, 0x31, 0x42, 0xA3, 0xAB, 0x88, 0x29, 0x55, 0x5B, 0x2F, 0x74, 0x7C, 0x93, 0x26, 0x65,
0xCB, 0x2C, 0x0F, 0x1C, 0xC0, 0x1B, 0xD7, 0x02, 0x29, 0x38, 0x88, 0x39, 0xD2, 0xAF, 0x05, 0xE4,
0x54, 0x50, 0x4A, 0xC7, 0x8B, 0x75, 0x82, 0x82, 0x28, 0x46, 0xC0, 0xBA, 0x35, 0xC3, 0x5F, 0x5C,
0x59, 0x16, 0x0C, 0xC0, 0x46, 0xFD, 0x82, 0x51, 0x54, 0x1F, 0xC6, 0x8C, 0x9C, 0x86, 0xB0, 0x22,
0xBB, 0x70, 0x99, 0x87, 0x6A, 0x46, 0x0E, 0x74, 0x51, 0xA8, 0xA9, 0x31, 0x09, 0x70, 0x3F, 0xEE,
0x1C, 0x21, 0x7E, 0x6C, 0x38, 0x26, 0xE5, 0x2C, 0x51, 0xAA, 0x69, 0x1E, 0x0E, 0x42, 0x3C, 0xFC,
0x99, 0xE9, 0xE3, 0x16, 0x50, 0xC1, 0x21, 0x7B, 0x62, 0x48, 0x16, 0xCD, 0xAD, 0x9A, 0x95, 0xF9,
0xD5, 0xB8, 0x01, 0x94, 0x88, 0xD9, 0xC0, 0xA0, 0xA1, 0xFE, 0x30, 0x75, 0xA5, 0x77, 0xE2, 0x31,
0x83, 0xF8, 0x1D, 0x4A, 0x3F, 0x2F, 0xA4, 0x57, 0x1E, 0xFC, 0x8C, 0xE0, 0xBA, 0x8A, 0x4F, 0xE8,
0xB6, 0x85, 0x5D, 0xFE, 0x72, 0xB0, 0xA6, 0x6E, 0xDE, 0xD2, 0xFB, 0xAB, 0xFB, 0xE5, 0x8A, 0x30,
0xFA, 0xFA, 0xBE, 0x1C, 0x5D, 0x71, 0xA8, 0x7E, 0x2F, 0x74, 0x1E, 0xF8, 0xC1, 0xFE, 0x86, 0xFE,
0xA6, 0xBB, 0xFD, 0xE5, 0x30, 0x67, 0x7F, 0x0D, 0x97, 0xD1, 0x1D, 0x49, 0xF7, 0xA8, 0x44, 0x3D,
0x08, 0x22, 0xE5, 0x06, 0xA9, 0xF4, 0x61, 0x4E, 0x01, 0x1E, 0x2A, 0x94, 0x83, 0x8F, 0xF8, 0x8C,
0xD6, 0x8C, 0x8B, 0xB7, 0xC5, 0xC6, 0x42, 0x4C, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
static uint8_t g_rfc7919_ffdhe8192Q[] = {
0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xD6, 0xFC, 0x2A, 0x2C, 0x51, 0x5D, 0xA5, 0x4D,
0x57, 0xEE, 0x2B, 0x10, 0x13, 0x9E, 0x9E, 0x78, 0xEC, 0x5C, 0xE2, 0xC1, 0xE7, 0x16, 0x9B, 0x4A,
0xD4, 0xF0, 0x9B, 0x20, 0x8A, 0x32, 0x19, 0xFD, 0xE6, 0x49, 0xCE, 0xE7, 0x12, 0x4D, 0x9F, 0x7C,
0xBE, 0x97, 0xF1, 0xB1, 0xB1, 0x86, 0x3A, 0xEC, 0x7B, 0x40, 0xD9, 0x01, 0x57, 0x62, 0x30, 0xBD,
0x69, 0xEF, 0x8F, 0x6A, 0xEA, 0xFE, 0xB2, 0xB0, 0x92, 0x19, 0xFA, 0x8F, 0xAF, 0x83, 0x37, 0x68,
0x42, 0xB1, 0xB2, 0xAA, 0x9E, 0xF6, 0x8D, 0x79, 0xDA, 0xAB, 0x89, 0xAF, 0x3F, 0xAB, 0xE4, 0x9A,
0xCC, 0x27, 0x86, 0x38, 0x70, 0x73, 0x45, 0xBB, 0xF1, 0x53, 0x44, 0xED, 0x79, 0xF7, 0xF4, 0x39,
0x0E, 0xF8, 0xAC, 0x50, 0x9B, 0x56, 0xF3, 0x9A, 0x98, 0x56, 0x65, 0x27, 0xA4, 0x1D, 0x3C, 0xBD,
0x5E, 0x05, 0x58, 0xC1, 0x59, 0x92, 0x7D, 0xB0, 0xE8, 0x84, 0x54, 0xA5, 0xD9, 0x64, 0x71, 0xFD,
0xDC, 0xB5, 0x6D, 0x5B, 0xB0, 0x6B, 0xFA, 0x34, 0x0E, 0xA7, 0xA1, 0x51, 0xEF, 0x1C, 0xA6, 0xFA,
0x57, 0x2B, 0x76, 0xF3, 0xB1, 0xB9, 0x5D, 0x8C, 0x85, 0x83, 0xD3, 0xE4, 0x77, 0x05, 0x36, 0xB8,
0x4F, 0x01, 0x7E, 0x70, 0xE6, 0xFB, 0xF1, 0x76, 0x60, 0x1A, 0x02, 0x66, 0x94, 0x1A, 0x17, 0xB0,
0xC8, 0xB9, 0x7F, 0x4E, 0x74, 0xC2, 0xC1, 0xFF, 0xC7, 0x27, 0x89, 0x19, 0x77, 0x79, 0x40, 0xC1,
0xE1, 0xFF, 0x1D, 0x8D, 0xA6, 0x37, 0xD6, 0xB9, 0x9D, 0xDA, 0xFE, 0x5E, 0x17, 0x61, 0x10, 0x02,
0xE2, 0xC7, 0x78, 0xC1, 0xBE, 0x8B, 0x41, 0xD9, 0x63, 0x79, 0xA5, 0x13, 0x60, 0xD9, 0x77, 0xFD,
0x44, 0x35, 0xA1, 0x1C, 0x30, 0x8F, 0xE7, 0xEE, 0x6F, 0x1A, 0xAD, 0x9D, 0xB2, 0x8C, 0x81, 0xAD,
0xDE, 0x1A, 0x7A, 0x6F, 0x7C, 0xCE, 0x01, 0x1C, 0x30, 0xDA, 0x37, 0xE4, 0xEB, 0x73, 0x64, 0x83,
0xBD, 0x6C, 0x8E, 0x93, 0x48, 0xFB, 0xFB, 0xF7, 0x2C, 0xC6, 0x58, 0x7D, 0x60, 0xC3, 0x6C, 0x8E,
0x57, 0x7F, 0x09, 0x84, 0xC2, 0x89, 0xC9, 0x38, 0x5A, 0x09, 0x86, 0x49, 0xDE, 0x21, 0xBC, 0xA2,
0x7A, 0x7E, 0xA2, 0x29, 0x71, 0x6B, 0xA6, 0xE9, 0xB2, 0x79, 0x71, 0x0F, 0x38, 0xFA, 0xA5, 0xFF,
0xAE, 0x57, 0x41, 0x55, 0xCE, 0x4E, 0xFB, 0x4F, 0x74, 0x36, 0x95, 0xE2, 0x91, 0x1B, 0x1D, 0x06,
0xD5, 0xE2, 0x90, 0xCB, 0xCD, 0x86, 0xF5, 0x6D, 0x0E, 0xDF, 0xCD, 0x21, 0x6A, 0xE2, 0x24, 0x27,
0x05, 0x5E, 0x68, 0x35, 0xFD, 0x29, 0xEE, 0xF7, 0x9E, 0x0D, 0x90, 0x77, 0x1F, 0xEA, 0xCE, 0xBE,
0x12, 0xF2, 0x0E, 0x95, 0xB3, 0x4F, 0x0F, 0x78, 0xB7, 0x37, 0xA9, 0x61, 0x8B, 0x26, 0xFA, 0x7D,
0xBC, 0x98, 0x74, 0xF2, 0x72, 0xC4, 0x2B, 0xDB, 0x56, 0x3E, 0xAF, 0xA1, 0x6B, 0x4F, 0xB6, 0x8C,
0x3B, 0xB1, 0xE7, 0x8E, 0xAA, 0x81, 0xA0, 0x02, 0x43, 0xFA, 0xAD, 0xD2, 0xBF, 0x18, 0xE6, 0x3D,
0x38, 0x9A, 0xE4, 0x43, 0x77, 0xDA, 0x18, 0xC5, 0x76, 0xB5, 0x0F, 0x00, 0x96, 0xCF, 0x34, 0x19,
0x54, 0x83, 0xB0, 0x05, 0x48, 0xC0, 0x98, 0x62, 0x36, 0xE3, 0xBC, 0x7C, 0xB8, 0xD6, 0x80, 0x1C,
0x04, 0x94, 0xCC, 0xD1, 0x99, 0xE5, 0xC5, 0xBD, 0x0D, 0x0E, 0xDC, 0x9E, 0xB8, 0xA0, 0x00, 0x1E,
0x15, 0x27, 0x67, 0x54, 0xFC, 0xC6, 0x85, 0x66, 0x05, 0x41, 0x48, 0xE6, 0xE7, 0x64, 0xBE, 0xE7,
0xC7, 0x64, 0xDA, 0xAD, 0x3F, 0xC4, 0x52, 0x35, 0xA6, 0xDA, 0xD4, 0x28, 0xFA, 0x20, 0xC1, 0x70,
0xE3, 0x45, 0x00, 0x3F, 0x2F, 0x06, 0xEC, 0x81, 0x05, 0xFE, 0xB2, 0x5B, 0x22, 0x81, 0xB6, 0x3D,
0x27, 0x33, 0xBE, 0x96, 0x1C, 0x29, 0x95, 0x1D, 0x11, 0xDD, 0x22, 0x21, 0x65, 0x7A, 0x9F, 0x53,
0x1D, 0xDA, 0x2A, 0x19, 0x4D, 0xBB, 0x12, 0x64, 0x48, 0xBD, 0xEE, 0xB2, 0x58, 0xE0, 0x7E, 0xA6,
0x59, 0xC7, 0x46, 0x19, 0xA6, 0x38, 0x0E, 0x1D, 0x66, 0xD6, 0x83, 0x2B, 0xFE, 0x67, 0xF6, 0x38,
0xCD, 0x8F, 0xAE, 0x1F, 0x27, 0x23, 0x02, 0x0F, 0x9C, 0x40, 0xA3, 0xFD, 0xA6, 0x7E, 0xDA, 0x3B,
0xD2, 0x92, 0x38, 0xFB, 0xD4, 0xD4, 0xB4, 0x88, 0x5C, 0x2A, 0x99, 0x17, 0x6D, 0xB1, 0xA0, 0x6C,
0x50, 0x07, 0x78, 0x49, 0x1A, 0x82, 0x88, 0xF1, 0x85, 0x5F, 0x60, 0xFF, 0xFC, 0xF1, 0xD1, 0x37,
0x3F, 0xD9, 0x4F, 0xC6, 0x0C, 0x18, 0x11, 0xE1, 0xAC, 0x3F, 0x1C, 0x6D, 0x00, 0x3B, 0xEC, 0xDA,
0x3B, 0x1F, 0x27, 0x25, 0xCA, 0x59, 0x5D, 0xE0, 0xCA, 0x63, 0x32, 0x8F, 0x3B, 0xE5, 0x7C, 0xC9,
0x77, 0x55, 0x60, 0x11, 0x95, 0x14, 0x0D, 0xFB, 0x59, 0xD3, 0x9C, 0xE0, 0x91, 0x30, 0x8B, 0x41,
0x05, 0x74, 0x6D, 0xAC, 0x23, 0xD3, 0x3E, 0x5F, 0x7C, 0xE4, 0x84, 0x8D, 0xA3, 0x16, 0xA9, 0xC6,
0x6B, 0x95, 0x81, 0xBA, 0x35, 0x73, 0xBF, 0xAF, 0x31, 0x14, 0x96, 0x18, 0x8A, 0xB1, 0x54, 0x23,
0x28, 0x2E, 0xE4, 0x16, 0xDC, 0x2A, 0x19, 0xC5, 0x72, 0x4F, 0xA9, 0x1A, 0xE4, 0xAD, 0xC8, 0x8B,
0xC6, 0x67, 0x96, 0xEA, 0xE5, 0x67, 0x7A, 0x01, 0xF6, 0x4E, 0x8C, 0x08, 0x63, 0x13, 0x95, 0x82,
0x2D, 0x9D, 0xB8, 0xFC, 0xEE, 0x35, 0xC0, 0x6B, 0x1F, 0xEE, 0xA5, 0x47, 0x4D, 0x6D, 0x8F, 0x34,
0xB1, 0x53, 0x4A, 0x93, 0x6A, 0x18, 0xB0, 0xE0, 0xD2, 0x0E, 0xAB, 0x86, 0xBC, 0x9C, 0x6D, 0x6A,
0x52, 0x07, 0x19, 0x4E, 0x67, 0xFA, 0x35, 0x55, 0x1B, 0x56, 0x80, 0x26, 0x7B, 0x00, 0x64, 0x1C,
0x0F, 0x21, 0x2D, 0x18, 0xEC, 0xA8, 0xD7, 0x32, 0x7E, 0xD9, 0x1F, 0xE7, 0x64, 0xA8, 0x4E, 0xA1,
0xB4, 0x3F, 0xF5, 0xB4, 0xF6, 0xE8, 0xE6, 0x2F, 0x05, 0xC6, 0x61, 0xDE, 0xFB, 0x25, 0x88, 0x77,
0xC3, 0x5B, 0x18, 0xA1, 0x51, 0xD5, 0xC4, 0x14, 0xAA, 0xAD, 0x97, 0xBA, 0x3E, 0x49, 0x93, 0x32,
0xE5, 0x96, 0x07, 0x8E, 0x60, 0x0D, 0xEB, 0x81, 0x14, 0x9C, 0x44, 0x1C, 0xE9, 0x57, 0x82, 0xF2,
0x2A, 0x28, 0x25, 0x63, 0xC5, 0xBA, 0xC1, 0x41, 0x14, 0x23, 0x60, 0x5D, 0x1A, 0xE1, 0xAF, 0xAE,
0x2C, 0x8B, 0x06, 0x60, 0x23, 0x7E, 0xC1, 0x28, 0xAA, 0x0F, 0xE3, 0x46, 0x4E, 0x43, 0x58, 0x11,
0x5D, 0xB8, 0x4C, 0xC3, 0xB5, 0x23, 0x07, 0x3A, 0x28, 0xD4, 0x54, 0x98, 0x84, 0xB8, 0x1F, 0xF7,
0x0E, 0x10, 0xBF, 0x36, 0x1C, 0x13, 0x72, 0x96, 0x28, 0xD5, 0x34, 0x8F, 0x07, 0x21, 0x1E, 0x7E,
0x4C, 0xF4, 0xF1, 0x8B, 0x28, 0x60, 0x90, 0xBD, 0xB1, 0x24, 0x0B, 0x66, 0xD6, 0xCD, 0x4A, 0xFC,
0xEA, 0xDC, 0x00, 0xCA, 0x44, 0x6C, 0xE0, 0x50, 0x50, 0xFF, 0x18, 0x3A, 0xD2, 0xBB, 0xF1, 0x18,
0xC1, 0xFC, 0x0E, 0xA5, 0x1F, 0x97, 0xD2, 0x2B, 0x8F, 0x7E, 0x46, 0x70, 0x5D, 0x45, 0x27, 0xF4,
0x5B, 0x42, 0xAE, 0xFF, 0x39, 0x58, 0x53, 0x37, 0x6F, 0x69, 0x7D, 0xD5, 0xFD, 0xF2, 0xC5, 0x18,
0x7D, 0x7D, 0x5F, 0x0E, 0x2E, 0xB8, 0xD4, 0x3F, 0x17, 0xBA, 0x0F, 0x7C, 0x60, 0xFF, 0x43, 0x7F,
0x53, 0x5D, 0xFE, 0xF2, 0x98, 0x33, 0xBF, 0x86, 0xCB, 0xE8, 0x8E, 0xA4, 0xFB, 0xD4, 0x22, 0x1E,
0x84, 0x11, 0x72, 0x83, 0x54, 0xFA, 0x30, 0xA7, 0x00, 0x8F, 0x15, 0x4A, 0x41, 0xC7, 0xFC, 0x46,
0x6B, 0x46, 0x45, 0xDB, 0xE2, 0xE3, 0x21, 0x26, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
typedef struct {
CRYPT_PKEY_ParaId id;
const CRYPT_Data *p;
const CRYPT_Data *q;
const CRYPT_Data *g;
} DH_PARA_VECTOR;
static const CRYPT_Data G_VECTOR_RFC_3526_2409 = {
.data = (uint8_t *)g_rfc3526_2409_primeG,
.len = sizeof(g_rfc3526_2409_primeG)
};
static const CRYPT_Data G_VECTOR_RFC_7919 = {
.data = (uint8_t *)g_rfc7919G,
.len = sizeof(g_rfc7919G)
};
static const CRYPT_Data Q_VECTOR_RFC_3526_2409 = {
.data = NULL,
.len = 0
};
static const CRYPT_Data Q_VECTOR_RFC_7919_2048 = {
.data = (uint8_t *)g_rfc7919_ffdhe2048Q,
.len = sizeof(g_rfc7919_ffdhe2048Q)
};
static const CRYPT_Data Q_VECTOR_RFC_7919_3072 = {
.data = (uint8_t *)g_rfc7919_ffdhe3072Q,
.len = sizeof(g_rfc7919_ffdhe3072Q)
};
static const CRYPT_Data Q_VECTOR_RFC_7919_4096 = {
.data = (uint8_t *)g_rfc7919_ffdhe4096Q,
.len = sizeof(g_rfc7919_ffdhe4096Q)
};
static const CRYPT_Data Q_VECTOR_RFC_7919_6144 = {
.data = (uint8_t *)g_rfc7919_ffdhe6144Q,
.len = sizeof(g_rfc7919_ffdhe6144Q)
};
static const CRYPT_Data Q_VECTOR_RFC_7919_8192 = {
.data = (uint8_t *)g_rfc7919_ffdhe8192Q,
.len = sizeof(g_rfc7919_ffdhe8192Q)
};
static const CRYPT_Data P_VECTORS_RFC2409_768 = {
.data = (uint8_t *)g_rfc2409_prime768P,
.len = sizeof(g_rfc2409_prime768P)
};
static const CRYPT_Data P_VECTORS_RFC2409_1024 = {
.data = (uint8_t *)g_rfc2409_prime1024P,
.len = sizeof(g_rfc2409_prime1024P)
};
static const CRYPT_Data P_VECTORS_RFC3526_1536 = {
.data = (uint8_t *)g_rfc3526_prime1536P,
.len = sizeof(g_rfc3526_prime1536P)
};
static const CRYPT_Data P_VECTORS_RFC3526_2048 = {
.data = (uint8_t *)g_rfc3526_prime2048P,
.len = sizeof(g_rfc3526_prime2048P)
};
static const CRYPT_Data P_VECTORS_RFC3526_3072 = {
.data = (uint8_t *)g_rfc3526_prime3072P,
.len = sizeof(g_rfc3526_prime3072P)
};
static const CRYPT_Data P_VECTORS_RFC3526_4096 = {
.data = (uint8_t *)g_rfc3526_prime4096P,
.len = sizeof(g_rfc3526_prime4096P)
};
static const CRYPT_Data P_VECTORS_RFC3526_6144 = {
.data = (uint8_t *)g_rfc3526_prime6144P,
.len = sizeof(g_rfc3526_prime6144P)
};
static const CRYPT_Data P_VECTORS_RFC3526_8192 = {
.data = (uint8_t *)g_rfc3526_prime8192P,
.len = sizeof(g_rfc3526_prime8192P)
};
static const CRYPT_Data P_VECTORS_RFC7919_2048 = {
.data = (uint8_t *)g_rfc7919_ffdhe2048P,
.len = sizeof(g_rfc7919_ffdhe2048P)
};
static const CRYPT_Data P_VECTORS_RFC7919_3072 = {
.data = (uint8_t *)g_rfc7919_ffdhe3072P,
.len = sizeof(g_rfc7919_ffdhe3072P)
};
static const CRYPT_Data P_VECTORS_RFC7919_4096 = {
.data = (uint8_t *)g_rfc7919_ffdhe4096P,
.len = sizeof(g_rfc7919_ffdhe4096P)
};
static const CRYPT_Data P_VECTORS_RFC7919_6144 = {
.data = (uint8_t *)g_rfc7919_ffdhe6144P,
.len = sizeof(g_rfc7919_ffdhe6144P)
};
static const CRYPT_Data P_VECTORS_RFC7919_8192 = {
.data = (uint8_t *)g_rfc7919_ffdhe8192P,
.len = sizeof(g_rfc7919_ffdhe8192P)
};
static const DH_PARA_VECTOR DH_PARA_VECTORS[] = {
{
.id = CRYPT_DH_RFC2409_768,
.p = &P_VECTORS_RFC2409_768,
.g = &G_VECTOR_RFC_3526_2409,
.q = &Q_VECTOR_RFC_3526_2409,
},
{
.id = CRYPT_DH_RFC2409_1024,
.p = &P_VECTORS_RFC2409_1024,
.g = &G_VECTOR_RFC_3526_2409,
.q = &Q_VECTOR_RFC_3526_2409,
},
{
.id = CRYPT_DH_RFC3526_1536,
.p = &P_VECTORS_RFC3526_1536,
.g = &G_VECTOR_RFC_3526_2409,
.q = &Q_VECTOR_RFC_3526_2409,
},
{
.id = CRYPT_DH_RFC3526_2048,
.p = &P_VECTORS_RFC3526_2048,
.g = &G_VECTOR_RFC_3526_2409,
.q = &Q_VECTOR_RFC_3526_2409,
},
{
.id = CRYPT_DH_RFC3526_3072,
.p = &P_VECTORS_RFC3526_3072,
.g = &G_VECTOR_RFC_3526_2409,
.q = &Q_VECTOR_RFC_3526_2409,
},
{
.id = CRYPT_DH_RFC3526_4096,
.p = &P_VECTORS_RFC3526_4096,
.g = &G_VECTOR_RFC_3526_2409,
.q = &Q_VECTOR_RFC_3526_2409,
},
{
.id = CRYPT_DH_RFC3526_6144,
.p = &P_VECTORS_RFC3526_6144,
.g = &G_VECTOR_RFC_3526_2409,
.q = &Q_VECTOR_RFC_3526_2409,
},
{
.id = CRYPT_DH_RFC3526_8192,
.p = &P_VECTORS_RFC3526_8192,
.g = &G_VECTOR_RFC_3526_2409,
.q = &Q_VECTOR_RFC_3526_2409,
},
{
.id = CRYPT_DH_RFC7919_2048,
.p = &P_VECTORS_RFC7919_2048,
.g = &G_VECTOR_RFC_7919,
.q = &Q_VECTOR_RFC_7919_2048,
},
{
.id = CRYPT_DH_RFC7919_3072,
.p = &P_VECTORS_RFC7919_3072,
.g = &G_VECTOR_RFC_7919,
.q = &Q_VECTOR_RFC_7919_3072,
},
{
.id = CRYPT_DH_RFC7919_4096,
.p = &P_VECTORS_RFC7919_4096,
.g = &G_VECTOR_RFC_7919,
.q = &Q_VECTOR_RFC_7919_4096,
},
{
.id = CRYPT_DH_RFC7919_6144,
.p = &P_VECTORS_RFC7919_6144,
.g = &G_VECTOR_RFC_7919,
.q = &Q_VECTOR_RFC_7919_6144,
},
{
.id = CRYPT_DH_RFC7919_8192,
.p = &P_VECTORS_RFC7919_8192,
.g = &G_VECTOR_RFC_7919,
.q = &Q_VECTOR_RFC_7919_8192,
}
};
static const DH_PARA_VECTOR *DhIdIsVaild(uint32_t id)
{
for (uint32_t i = 0; i < sizeof(DH_PARA_VECTORS) / sizeof(DH_PARA_VECTORS[0]); i++) {
if (id == DH_PARA_VECTORS[i].id) {
return &DH_PARA_VECTORS[i];
}
}
return NULL;
}
CRYPT_DH_Para *CRYPT_DH_NewParaById(CRYPT_PKEY_ParaId id)
{
CRYPT_DH_Para *retPara = NULL;
const DH_PARA_VECTOR *vector = DhIdIsVaild(id);
if (vector == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID);
return NULL;
}
CRYPT_DhPara para;
para.p = vector->p->data;
para.pLen = vector->p->len;
para.q = vector->q->data;
para.qLen = vector->q->len;
para.g = vector->g->data;
para.gLen = vector->g->len;
retPara = CRYPT_DH_NewPara(¶);
if (retPara == NULL) {
goto ERR;
}
retPara->id = id;
static const uint32_t list[] = {
CRYPT_DH_RFC3526_1536, CRYPT_DH_RFC3526_2048, CRYPT_DH_RFC3526_3072,
CRYPT_DH_RFC3526_4096, CRYPT_DH_RFC3526_6144, CRYPT_DH_RFC3526_8192,
};
for (uint32_t i = 0; i < sizeof(list) / sizeof(list[0]); i++) {
if (id == list[i]) {
/**
* NIST.SP.800-56Ar3
* Appendix D
* Finite Field Cryptography Groups for Key Establishment: The following safe-prime
* groups are defined in RFC 3526 and RFC 7919 for use with key-agreement schemes that
* employ either the FFC DH or FFC MQV primitives.
* The domain parameters for these groups have the form ( p, q = (p − 1)/2, g = 2 ); the explicit
* values for p are provided in the RFCs
*/
retPara->q = BN_Dup(retPara->p);
if (retPara->q == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_CREATE_PARA_FAIL);
goto ERR;
}
// Shift to the right by 1 bit: q = (p-1)/2
if (BN_Rshift(retPara->q, retPara->q, 1) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_CREATE_PARA_FAIL);
goto ERR;
}
break;
}
}
return retPara;
ERR:
CRYPT_DH_FreePara(retPara);
return NULL;
}
CRYPT_PKEY_ParaId CRYPT_DH_GetParaId(const CRYPT_DH_Ctx *ctx)
{
if (ctx == NULL || ctx->para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_ALGID);
return CRYPT_PKEY_PARAID_MAX;
}
return ctx->para->id;
}
#endif /* HITLS_CRYPTO_DH */
|
2301_79861745/bench_create
|
crypto/dh/src/dh_para.c
|
C
|
unknown
| 67,041
|
/*
* 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_DRBG_H
#define CRYPT_DRBG_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_DRBG
#include <stdint.h>
#include <stdbool.h>
#include "crypt_types.h"
#include "crypt_local_types.h"
#ifdef __cplusplus
extern "C" {
#endif
// hlcheck : health testing
// pr : prediction_resistance
typedef struct DrbgCtx DRBG_Ctx;
#define DRBG_MAX_LEN (0x7ffffff0)
#define DRBG_MAX_REQUEST (1 << 16)
#ifndef DRBG_MAX_RESEED_INTERVAL
#define DRBG_MAX_RESEED_INTERVAL (10000)
#endif
/* Default reseed intervals */
# define DRBG_RESEED_INTERVAL (1 << 8)
# define DRBG_TIME_INTERVAL (60 * 60) /* 1 hour */
#ifndef DRBG_MAX_REQUEST_SM3
#define DRBG_MAX_REQUEST_SM3 (1 << 5)
#endif
#ifndef DRBG_MAX_REQUEST_SM4
#define DRBG_MAX_REQUEST_SM4 (1 << 4)
#endif
#ifndef DRBG_RESEED_INTERVAL_GM1
#define DRBG_RESEED_INTERVAL_GM1 (1 << 20)
#endif
#ifndef DRBG_RESEED_TIME_GM1
#define DRBG_RESEED_TIME_GM1 (600)
#endif
#ifndef DRBG_RESEED_INTERVAL_GM2
#define DRBG_RESEED_INTERVAL_GM2 (1 << 10)
#endif
#ifndef DRBG_RESEED_TIME_GM2
#define DRBG_RESEED_TIME_GM2 (60)
#endif
#ifndef HITLS_CRYPTO_DRBG_GM_LEVEL
#define HITLS_CRYPTO_DRBG_GM_LEVEL 2
#endif
#ifndef HITLS_CRYPTO_RESEED_INTERVAL_GM
#if HITLS_CRYPTO_DRBG_GM_LEVEL == 1
#define HITLS_CRYPTO_RESEED_INTERVAL_GM DRBG_RESEED_INTERVAL_GM1
#else
#define HITLS_CRYPTO_RESEED_INTERVAL_GM DRBG_RESEED_INTERVAL_GM2
#endif
#endif
#ifdef HITLS_CRYPTO_ENTROPY
#ifndef HITLS_SEED_DRBG_INIT_RAND_ALG
#ifdef HITLS_CRYPTO_AES
#define HITLS_SEED_DRBG_INIT_RAND_ALG CRYPT_RAND_AES256_CTR
#else
#error "HITLS_SEED_DRBG_INIT_RAND_ALG configuration error."
#endif
#endif
#endif
#ifndef HITLS_CRYPTO_DRBG_RESEED_TIME_GM
#if HITLS_CRYPTO_DRBG_GM_LEVEL == 1
#define HITLS_CRYPTO_DRBG_RESEED_TIME_GM DRBG_RESEED_TIME_GM1
#else
#define HITLS_CRYPTO_DRBG_RESEED_TIME_GM DRBG_RESEED_TIME_GM2
#endif
#endif
#define DRBG_HASH_MAX_MDSIZE (64)
#define RAND_TYPE_MD 1
#define RAND_TYPE_MAC 2
#define RAND_TYPE_AES 3
#define RAND_TYPE_AES_DF 4
#define RAND_TYPE_SM4_DF 5
typedef struct {
CRYPT_RAND_AlgId drbgId;
int32_t depId;
uint32_t type;
} DrbgIdMap;
/**
* @ingroup drbg
* @brief Apply for a context for the DRBG.
* @brief This API does not support multiple threads.
*
* @param libCtx Library context
* @param algId Algorithm ID for the DRBG
* @param param DRBG parameters
*
* @retval DRBG_Ctx* Success
* @retval NULL Failure
*/
DRBG_Ctx *DRBG_New(void *libCtx, int32_t algId, BSL_Param *param);
/**
* @ingroup drbg
* @brief Release the DRBG context.
* @brief This API does not support multiple threads.
*
* @param ctx DRBG context
*
* @retval None
*/
void DRBG_Free(DRBG_Ctx *ctx);
/**
* @ingroup drbg
* @brief Instantiating a DRBG based on personalization string.
* @brief This API does not support multiple threads.
*
* @param ctx DRBG context
* @param person Personalization string. The personalization string can be NULL.
* @param persLen Personalization string length,
* @param param DRBG parameters,Not in use yet
*
* @retval CRYPT_SUCCESS Instantiation succeeded.
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_DRBG_ERR_STATE The DRBG status is incorrect.
* @retval CRYPT_DRBG_FAIL_GET_ENTROPY Failed to obtain the entropy.
* @retval CRYPT_DRBG_FAIL_GET_NONCE Failed to obtain the nonce.
* @retval Hash function error code: Failed to invoke the hash function.
*/
int32_t DRBG_Instantiate(DRBG_Ctx *ctx, const uint8_t *person, uint32_t persLen, BSL_Param *param);
/**
* @ingroup drbg
* @brief Reseeding the DRBG.
* @brief The additional input can be NULL. This API does not support multiple threads.
*
* @param ctx DRBG context
* @param adin Additional input. The data can be empty.
* @param adinLen Additional input length
* @param param DRBG parameters,Not in use yet
*
* @retval CRYPT_SUCCESS Instantiation succeeded.
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_DRBG_ERR_STATE The DRBG status is incorrect.
* @retval CRYPT_DRBG_FAIL_GET_ENTROPY Failed to obtain the entropy.
* @retval Hash function error code: Failed to invoke the hash function.
*/
int32_t DRBG_Reseed(DRBG_Ctx *ctx, const uint8_t *adin, uint32_t adinLen, BSL_Param *param);
/**
* @ingroup drbg
* @brief Generating pseudorandom bits using a DRBG.
* @brief The additional input can be null. The user specifies the additional obfuscation data.
* This API does not support multiple threads.
* @brief External invoking must have a recovery mechanism after the status is abnormal.
*
* @param ctx DRBG context
* @param out Output BUF
* @param outLen Output length
* @param adin Additional input. The data can be empty.
* @param adinLen Additional input length
* @param param DRBG parameters,involve:
* pr Predicted resistance. If this parameter is set to true, reseed is executed each time.
*
* @retval CRYPT_SUCCESS Instantiation succeeded.
* @retval CRYPT_NULL_INPUT Invalid null pointer
* @retval CRYPT_DRBG_ERR_STATE The DRBG status is incorrect.
* @retval Hash function error code: Failed to invoke the hash function.
*/
int32_t DRBG_GenerateBytes(DRBG_Ctx *ctx, uint8_t *out, uint32_t outLen,
const uint8_t *adin, uint32_t adinLen, BSL_Param *param);
/**
* @ingroup drbg
* @brief Remove the DRBG instantiation
* @brief This API does not support multiple threads.
*
* @param ctx DRBG context
*
* @retval CRYPT_SUCCESS Removed successfully.
* @retval CRYPT_NULL_INPUT Invalid null pointer
*/
int32_t DRBG_Uninstantiate(DRBG_Ctx *ctx);
/**
* @ingroup drbg
* @brief get or set drbg param
*
* @param ctx [IN] drbg context
* @param cmd [IN] Option information
* @param val [IN/OUT] Data to be set/obtained
* @param valLen [IN] Length of the data marked as "val"
*
* @retval #CRYPT_SUCCESS.
* For other error codes, see crypt_errno.h.
*/
int32_t DRBG_Ctrl(DRBG_Ctx *ctx, int32_t cmd, void *val, uint32_t valLen);
/**
* @ingroup drbg
* @brief Get the map corresponding to the algid.
*
* @param id enum of CRYPT_RAND_AlgId
*
* @retval DrbgIdMap
* @retval NULL Invalid arguments
*/
const DrbgIdMap *DRBG_GetIdMap(CRYPT_RAND_AlgId id);
#ifdef __cplusplus
}
#endif
#endif // HITLS_CRYPTO_DRBG
#endif // CRYPT_DRBG_H
|
2301_79861745/bench_create
|
crypto/drbg/include/crypt_drbg.h
|
C
|
unknown
| 7,080
|
/*
* 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_DRBG
#include <stdlib.h>
#include <stdbool.h>
#include <securec.h>
#include "crypt_types.h"
#include "crypt_errno.h"
#include "crypt_utils.h"
#include "crypt_ealinit.h"
#include "eal_entropy.h"
#include "bsl_err_internal.h"
#include "drbg_local.h"
#include "crypt_drbg_local.h"
#include "bsl_params.h"
#include "crypt_params_key.h"
#define DRBG_NONCE_FROM_ENTROPY (2)
// According to the definition of DRBG_Ctx, ctx->seedMeth is not NULL
static void DRBG_CleanEntropy(DRBG_Ctx *ctx, CRYPT_Data *entropy)
{
CRYPT_RandSeedMethod *seedMeth = NULL;
if (ctx == NULL || CRYPT_IsDataNull(entropy)) {
return;
}
seedMeth = &ctx->seedMeth;
if (seedMeth->cleanEntropy != NULL) {
seedMeth->cleanEntropy(ctx->seedCtx, entropy);
}
entropy->data = NULL;
entropy->len = 0;
return;
}
// According to the definition of DRBG_Ctx, ctx->seedMeth is not NULL
static int32_t DRBG_GetEntropy(DRBG_Ctx *ctx, CRYPT_Data *entropy, bool addEntropy)
{
int32_t ret;
CRYPT_RandSeedMethod *seedMeth = NULL;
CRYPT_Range entropyRange = ctx->entropyRange;
uint32_t strength = ctx->strength;
seedMeth = &ctx->seedMeth;
if (addEntropy) {
strength += strength / DRBG_NONCE_FROM_ENTROPY;
entropyRange.min += ctx->nonceRange.min;
entropyRange.max += ctx->nonceRange.max;
}
if (seedMeth->getEntropy == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DRBG_FAIL_GET_ENTROPY);
return CRYPT_DRBG_FAIL_GET_ENTROPY;
}
// CPRNG is implemented by hooks, in DRBG, the CPRNG is not verified,
// but only the entropy source pointer and its length are verified.
ret = seedMeth->getEntropy(ctx->seedCtx, entropy, strength, &entropyRange);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_DRBG_FAIL_GET_ENTROPY);
return CRYPT_DRBG_FAIL_GET_ENTROPY;
}
if (CRYPT_CHECK_DATA_INVALID(entropy)) {
goto ERR;
}
if (!CRYPT_IN_RANGE(entropy->len, &entropyRange)) {
goto ERR;
}
return CRYPT_SUCCESS;
ERR:
DRBG_CleanEntropy(ctx, entropy);
BSL_ERR_PUSH_ERROR(CRYPT_DRBG_FAIL_GET_ENTROPY);
return CRYPT_DRBG_FAIL_GET_ENTROPY;
}
// According to the definition of DRBG_Ctx, ctx->seedMeth is not NULL
static void DRBG_CleanNonce(DRBG_Ctx *ctx, CRYPT_Data *nonce)
{
CRYPT_RandSeedMethod *seedMeth = NULL;
if (ctx == NULL || CRYPT_IsDataNull(nonce)) {
return;
}
seedMeth = &ctx->seedMeth;
if (seedMeth->cleanNonce != NULL) {
seedMeth->cleanNonce(ctx->seedCtx, nonce);
}
nonce->data = NULL;
nonce->len = 0;
return;
}
// According to the definition of DRBG_Ctx, ctx->seedMeth is not NULL
static int32_t DRBG_GetNonce(DRBG_Ctx *ctx, CRYPT_Data *nonce, bool *addEntropy)
{
int32_t ret;
CRYPT_RandSeedMethod *seedMeth = NULL;
seedMeth = &ctx->seedMeth;
// Allowed nonce which entered by the user can be NULL.
// In this case, set *addEntropy to true to obtain the nonce from the entropy.
if (seedMeth->getNonce == NULL || ctx->nonceRange.max == 0) {
if (ctx->nonceRange.min > 0) {
*addEntropy = true;
}
return CRYPT_SUCCESS;
}
ret = seedMeth->getNonce(ctx->seedCtx, nonce, ctx->strength, &ctx->nonceRange);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_DRBG_FAIL_GET_NONCE);
return CRYPT_DRBG_FAIL_GET_NONCE;
}
if (CRYPT_CHECK_DATA_INVALID(nonce)) {
goto ERR;
}
if (!CRYPT_IN_RANGE(nonce->len, &ctx->nonceRange)) {
goto ERR;
}
return CRYPT_SUCCESS;
ERR:
DRBG_CleanNonce(ctx, nonce);
BSL_ERR_PUSH_ERROR(CRYPT_DRBG_FAIL_GET_NONCE);
return CRYPT_DRBG_FAIL_GET_NONCE;
}
#ifdef HITLS_CRYPTO_DRBG_CTR
#define RAND_AES128_KEYLEN 16
#define RAND_AES192_KEYLEN 24
#define RAND_AES256_KEYLEN 32
#define RAND_SM4_KEYLEN 16
static int32_t GetCipherKeyLen(int32_t id, uint32_t *keyLen)
{
switch (id) {
case CRYPT_CIPHER_AES128_CTR:
*keyLen = RAND_AES128_KEYLEN;
break;
case CRYPT_CIPHER_AES192_CTR:
*keyLen = RAND_AES192_KEYLEN;
break;
case CRYPT_CIPHER_AES256_CTR:
*keyLen = RAND_AES256_KEYLEN;
break;
case CRYPT_CIPHER_SM4_CTR:
*keyLen = RAND_SM4_KEYLEN;
break;
default:
BSL_ERR_PUSH_ERROR(CRYPT_DRBG_ALG_NOT_SUPPORT);
return CRYPT_DRBG_ALG_NOT_SUPPORT;
}
return CRYPT_SUCCESS;
}
#endif
static int32_t DRBG_Restart(DRBG_Ctx *ctx)
{
if (ctx->state == DRBG_STATE_ERROR) {
(void)DRBG_Uninstantiate(ctx);
}
if (ctx->state == DRBG_STATE_UNINITIALISED) {
int32_t ret = DRBG_Instantiate(ctx, NULL, 0, NULL);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
return CRYPT_SUCCESS;
}
DRBG_Ctx *DRBG_New(void *libCtx, int32_t algId, BSL_Param *param)
{
int32_t ret;
(void)libCtx;
CRYPT_RandSeedMethod seedMethArray = {0};
CRYPT_RandSeedMethod *seedMeth = &seedMethArray;
void *seedCtx = NULL;
const BSL_Param *temp = NULL;
if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_RAND_SEED_GETENTROPY)) != NULL) {
GOTO_ERR_IF(BSL_PARAM_GetPtrValue(temp, CRYPT_PARAM_RAND_SEED_GETENTROPY, BSL_PARAM_TYPE_FUNC_PTR,
(void **)&(seedMethArray.getEntropy), NULL), ret);
}
if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_RAND_SEED_CLEANENTROPY)) != NULL) {
GOTO_ERR_IF(BSL_PARAM_GetPtrValue(temp, CRYPT_PARAM_RAND_SEED_CLEANENTROPY, BSL_PARAM_TYPE_FUNC_PTR,
(void **)&(seedMethArray.cleanEntropy), NULL), ret);
}
if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_RAND_SEED_GETNONCE)) != NULL) {
GOTO_ERR_IF(BSL_PARAM_GetPtrValue(temp, CRYPT_PARAM_RAND_SEED_GETNONCE, BSL_PARAM_TYPE_FUNC_PTR,
(void **)&(seedMethArray.getNonce), NULL), ret);
}
if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_RAND_SEED_CLEANNONCE)) != NULL) {
GOTO_ERR_IF(BSL_PARAM_GetPtrValue(temp, CRYPT_PARAM_RAND_SEED_CLEANNONCE, BSL_PARAM_TYPE_FUNC_PTR,
(void **)&(seedMethArray.cleanNonce), NULL), ret);
}
if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_RAND_SEEDCTX)) != NULL) {
GOTO_ERR_IF(BSL_PARAM_GetPtrValue(temp, CRYPT_PARAM_RAND_SEEDCTX, BSL_PARAM_TYPE_CTX_PTR, &seedCtx, NULL), ret);
}
DRBG_Ctx *drbg = NULL;
EAL_RandMethLookup lu = { 0 };
if (EAL_RandFindMethod(algId, &lu) != CRYPT_SUCCESS) {
return NULL;
}
switch (lu.type) {
#ifdef HITLS_CRYPTO_DRBG_HASH
case RAND_TYPE_MD:
drbg = DRBG_NewHashCtx((const EAL_MdMethod *)(lu.method), algId == CRYPT_RAND_SM3, seedMeth, seedCtx);
break;
#endif
#ifdef HITLS_CRYPTO_DRBG_HMAC
case RAND_TYPE_MAC:
drbg = DRBG_NewHmacCtx(libCtx, (const EAL_MacMethod *)(lu.method), lu.methodId, seedMeth, seedCtx);
break;
#endif
#ifdef HITLS_CRYPTO_DRBG_CTR
case RAND_TYPE_SM4_DF:
case RAND_TYPE_AES:
case RAND_TYPE_AES_DF: {
bool isUsedDF = (lu.type == RAND_TYPE_AES_DF || lu.type == RAND_TYPE_SM4_DF) ? true : false;
uint32_t keyLen;
if (GetCipherKeyLen(lu.methodId, &keyLen) != CRYPT_SUCCESS) {
return NULL;
}
drbg = DRBG_NewCtrCtx((const EAL_SymMethod *)(lu.method), keyLen, algId == CRYPT_RAND_SM4_CTR_DF, isUsedDF,
seedMeth, seedCtx);
break;
}
#endif
default:
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_ALGID);
return NULL;
}
return drbg;
ERR:
return NULL;
}
void DRBG_Free(DRBG_Ctx *ctx)
{
if (ctx == NULL || ctx->meth == NULL || ctx->meth->free == NULL) {
return;
}
void (*ctxFree)(DRBG_Ctx *ctx) = ctx->meth->free;
DRBG_Uninstantiate(ctx);
ctxFree(ctx);
return;
}
int32_t DRBG_Instantiate(DRBG_Ctx *ctx, const uint8_t *person, uint32_t persLen, BSL_Param *param)
{
(void) param;
int32_t ret;
CRYPT_Data entropy = {NULL, 0};
CRYPT_Data nonce = {NULL, 0};
CRYPT_Data pers = {(uint8_t *)(uintptr_t)person, persLen};
bool addEntropy = false;
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (CRYPT_CHECK_DATA_INVALID(&pers)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (persLen > ctx->maxPersLen) {
BSL_ERR_PUSH_ERROR(CRYPT_DRBG_INVALID_LEN);
return CRYPT_DRBG_INVALID_LEN;
}
if (ctx->state != DRBG_STATE_UNINITIALISED) {
BSL_ERR_PUSH_ERROR(CRYPT_DRBG_ERR_STATE);
return CRYPT_DRBG_ERR_STATE;
}
ctx->state = DRBG_STATE_ERROR;
ret = DRBG_GetNonce(ctx, &nonce, &addEntropy);
if (ret != CRYPT_SUCCESS) {
goto ERR_NONCE;
}
ret = DRBG_GetEntropy(ctx, &entropy, addEntropy);
if (ret != CRYPT_SUCCESS) {
goto ERR_ENTROPY;
}
ret = ctx->meth->instantiate(ctx, &entropy, &nonce, &pers);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR_ENTROPY;
}
ctx->state = DRBG_STATE_READY;
ctx->reseedCtr = 1;
#if defined(HITLS_CRYPTO_DRBG_GM)
if (ctx->reseedIntervalTime != 0) {
ctx->lastReseedTime = BSL_SAL_CurrentSysTimeGet();
}
#endif
ERR_ENTROPY:
DRBG_CleanEntropy(ctx, &entropy);
ERR_NONCE:
DRBG_CleanNonce(ctx, &nonce);
return ret;
}
static inline bool DRBG_IsNeedReseed(const DRBG_Ctx *ctx, bool pr)
{
if (pr) {
return true;
}
if (ctx->reseedCtr > ctx->reseedInterval) {
return true;
}
#if defined(HITLS_CRYPTO_DRBG_GM)
if (ctx->reseedIntervalTime != 0) {
int64_t time = BSL_SAL_CurrentSysTimeGet();
return ((time - ctx->lastReseedTime) > ctx->reseedIntervalTime) ? true : false;
}
#endif
return false;
}
int32_t DRBG_Reseed(DRBG_Ctx *ctx, const uint8_t *adin, uint32_t adinLen, BSL_Param *param)
{
(void) param;
int32_t ret;
CRYPT_Data entropy = {NULL, 0};
CRYPT_Data adinData = {(uint8_t*)(uintptr_t)adin, adinLen};
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (CRYPT_CHECK_BUF_INVALID(adin, adinLen)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (adinLen > ctx->maxAdinLen) {
BSL_ERR_PUSH_ERROR(CRYPT_DRBG_INVALID_LEN);
return CRYPT_DRBG_INVALID_LEN;
}
if (ctx->state != DRBG_STATE_READY) {
if (DRBG_Restart(ctx) != CRYPT_SUCCESS) {
return CRYPT_DRBG_ERR_STATE;
}
}
ctx->state = DRBG_STATE_ERROR;
ret = DRBG_GetEntropy(ctx, &entropy, false);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
ret = ctx->meth->reseed(ctx, &entropy, &adinData);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
ctx->reseedCtr = 1;
#if defined(HITLS_CRYPTO_DRBG_GM)
if (ctx->reseedIntervalTime != 0) {
ctx->lastReseedTime = BSL_SAL_CurrentSysTimeGet();
}
#endif
ctx->state = DRBG_STATE_READY;
ERR:
DRBG_CleanEntropy(ctx, &entropy);
return ret;
}
int32_t DRBG_Generate(DRBG_Ctx *ctx, uint8_t *out, uint32_t outLen,
const uint8_t *adin, uint32_t adinLen, bool pr)
{
int32_t ret;
CRYPT_Data adinData = {(uint8_t*)(uintptr_t)adin, adinLen};
if (CRYPT_CHECK_BUF_INVALID(adin, adinLen)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (outLen > ctx->maxRequest || adinLen > ctx->maxAdinLen) {
BSL_ERR_PUSH_ERROR(CRYPT_DRBG_INVALID_LEN);
return CRYPT_DRBG_INVALID_LEN;
}
if (ctx->state != DRBG_STATE_READY) {
if (DRBG_Restart(ctx) != CRYPT_SUCCESS) {
return CRYPT_DRBG_ERR_STATE;
}
}
if (DRBG_IsNeedReseed(ctx, pr)) {
ret = DRBG_Reseed(ctx, adin, adinLen, NULL);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
adinData.data = NULL;
adinData.len = 0;
}
ret = ctx->meth->generate(ctx, out, outLen, &adinData);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ctx->reseedCtr++;
return ret;
}
int32_t DRBG_GenerateBytes(DRBG_Ctx *ctx, uint8_t *out, uint32_t outLen,
const uint8_t *adin, uint32_t adinLen, BSL_Param *param)
{
if (ctx == NULL || out == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret;
bool pr = ctx->predictionResistance;
const BSL_Param *temp = NULL;
if ((temp = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_RAND_PR)) != NULL) {
uint32_t boolSize = sizeof(bool);
ret = BSL_PARAM_GetValue(temp, CRYPT_PARAM_RAND_PR, BSL_PARAM_TYPE_BOOL, (void *)&pr, &boolSize);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
uint32_t block = ctx->maxRequest;
if (block == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
for (uint32_t leftLen = outLen; leftLen > 0; leftLen -= block, out += block) {
block = leftLen > block ? block : leftLen;
ret = DRBG_Generate(ctx, out, block, adin, adinLen, pr);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
return CRYPT_SUCCESS;
}
int32_t DRBG_Uninstantiate(DRBG_Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
ctx->meth->uninstantiate(ctx);
ctx->reseedCtr = 0;
ctx->state = DRBG_STATE_UNINITIALISED;
return CRYPT_SUCCESS;
}
#if defined(HITLS_CRYPTO_DRBG_GM)
static int32_t DRBG_SetGmlevel(DRBG_Ctx *ctx, const void *val, uint32_t len)
{
if (val == NULL || len != sizeof(uint32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
if (*(const uint32_t *)val == 1) {
ctx->reseedInterval = DRBG_RESEED_INTERVAL_GM1;
ctx->reseedIntervalTime = DRBG_RESEED_TIME_GM1;
} else {
ctx->reseedInterval = DRBG_RESEED_INTERVAL_GM2;
ctx->reseedIntervalTime = DRBG_RESEED_TIME_GM2;
}
return CRYPT_SUCCESS;
}
static int32_t DRBG_SetReseedIntervalTime(DRBG_Ctx *ctx, const void *val, uint32_t len)
{
if (val == NULL || len != sizeof(uint64_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
ctx->reseedIntervalTime = *(const uint64_t *)val;
return CRYPT_SUCCESS;
}
static int32_t DRBG_GetReseedIntervalTime(DRBG_Ctx *ctx, void *val, uint32_t len)
{
if (val == NULL || len != sizeof(uint64_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
*(uint64_t *)val = ctx->reseedIntervalTime;
return CRYPT_SUCCESS;
}
#endif // HITLS_CRYPTO_DRBG_GM
static int32_t DRBG_SetReseedInterval(DRBG_Ctx *ctx, const void *val, uint32_t len)
{
if (val == NULL || len != sizeof(uint32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
ctx->reseedInterval = *(const uint32_t *)val;
return CRYPT_SUCCESS;
}
static int32_t DRBG_GetReseedInterval(DRBG_Ctx *ctx, void *val, uint32_t len)
{
if (val == NULL || len != sizeof(uint32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
*(uint32_t *)val = ctx->reseedInterval;
return CRYPT_SUCCESS;
}
static int32_t DRBG_SetPredictionResistance(DRBG_Ctx *ctx, const void *val, uint32_t len)
{
if (val == NULL || len != sizeof(bool)) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
ctx->predictionResistance = *(const bool *)val;
return CRYPT_SUCCESS;
}
int32_t DRBG_Ctrl(DRBG_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) {
#if defined(HITLS_CRYPTO_DRBG_GM)
case CRYPT_CTRL_SET_GM_LEVEL:
return DRBG_SetGmlevel(ctx, val, len);
case CRYPT_CTRL_SET_RESEED_TIME:
return DRBG_SetReseedIntervalTime(ctx, val, len);
case CRYPT_CTRL_GET_RESEED_TIME:
return DRBG_GetReseedIntervalTime(ctx, val, len);
#endif // HITLS_CRYPTO_DRBG_GM
case CRYPT_CTRL_SET_RESEED_INTERVAL:
return DRBG_SetReseedInterval(ctx, val, len);
case CRYPT_CTRL_GET_RESEED_INTERVAL:
return DRBG_GetReseedInterval(ctx, val, len);
case CRYPT_CTRL_SET_PREDICTION_RESISTANCE:
return DRBG_SetPredictionResistance(ctx, val, len);
default:
break;
}
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
static const DrbgIdMap DRBG_METHOD_MAP[] = {
#if defined(HITLS_CRYPTO_DRBG_HASH)
{ CRYPT_RAND_SHA1, CRYPT_MD_SHA1, RAND_TYPE_MD },
{ CRYPT_RAND_SHA224, CRYPT_MD_SHA224, RAND_TYPE_MD },
{ CRYPT_RAND_SHA256, CRYPT_MD_SHA256, RAND_TYPE_MD },
{ CRYPT_RAND_SHA384, CRYPT_MD_SHA384, RAND_TYPE_MD },
{ CRYPT_RAND_SHA512, CRYPT_MD_SHA512, RAND_TYPE_MD },
#ifdef HITLS_CRYPTO_DRBG_GM
{ CRYPT_RAND_SM3, CRYPT_MD_SM3, RAND_TYPE_MD },
#endif
#endif
#if defined(HITLS_CRYPTO_DRBG_HMAC)
{ CRYPT_RAND_HMAC_SHA1, CRYPT_MAC_HMAC_SHA1, RAND_TYPE_MAC },
{ CRYPT_RAND_HMAC_SHA224, CRYPT_MAC_HMAC_SHA224, RAND_TYPE_MAC },
{ CRYPT_RAND_HMAC_SHA256, CRYPT_MAC_HMAC_SHA256, RAND_TYPE_MAC },
{ CRYPT_RAND_HMAC_SHA384, CRYPT_MAC_HMAC_SHA384, RAND_TYPE_MAC },
{ CRYPT_RAND_HMAC_SHA512, CRYPT_MAC_HMAC_SHA512, RAND_TYPE_MAC },
#endif
#if defined(HITLS_CRYPTO_DRBG_CTR)
{ CRYPT_RAND_AES128_CTR, CRYPT_CIPHER_AES128_CTR, RAND_TYPE_AES },
{ CRYPT_RAND_AES192_CTR, CRYPT_CIPHER_AES192_CTR, RAND_TYPE_AES },
{ CRYPT_RAND_AES256_CTR, CRYPT_CIPHER_AES256_CTR, RAND_TYPE_AES },
{ CRYPT_RAND_AES128_CTR_DF, CRYPT_CIPHER_AES128_CTR, RAND_TYPE_AES_DF },
{ CRYPT_RAND_AES192_CTR_DF, CRYPT_CIPHER_AES192_CTR, RAND_TYPE_AES_DF },
{ CRYPT_RAND_AES256_CTR_DF, CRYPT_CIPHER_AES256_CTR, RAND_TYPE_AES_DF },
#ifdef HITLS_CRYPTO_DRBG_GM
{ CRYPT_RAND_SM4_CTR_DF, CRYPT_CIPHER_SM4_CTR, RAND_TYPE_SM4_DF }
#endif
#endif
};
const DrbgIdMap *DRBG_GetIdMap(CRYPT_RAND_AlgId id)
{
uint32_t num = sizeof(DRBG_METHOD_MAP) / sizeof(DRBG_METHOD_MAP[0]);
for (uint32_t i = 0; i < num; i++) {
if (DRBG_METHOD_MAP[i].drbgId == id) {
return &DRBG_METHOD_MAP[i];
}
}
return NULL;
}
#endif /* HITLS_CRYPTO_DRBG */
|
2301_79861745/bench_create
|
crypto/drbg/src/drbg.c
|
C
|
unknown
| 19,347
|
/*
* 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_DRBG_CTR
#include <stdlib.h>
#include <securec.h>
#include "crypt_errno.h"
#include "crypt_local_types.h"
#include "crypt_utils.h"
#include "bsl_sal.h"
#include "crypt_types.h"
#include "bsl_err_internal.h"
#include "drbg_local.h"
#define DRBG_CTR_MAX_KEYLEN (32)
#define AES_BLOCK_LEN (16)
#define DRBG_CTR_MAX_SEEDLEN (48)
#define DRBG_CTR_MIN_ENTROPYLEN (32)
typedef struct {
uint8_t k[DRBG_CTR_MAX_KEYLEN]; // DRBG_CTR_MAX_KEYLEN 32
uint8_t v[AES_BLOCK_LEN]; // AES_BLOCK_LEN 16 (blockLen)
uint8_t kx[DRBG_CTR_MAX_SEEDLEN]; // DRBG_CTR_MAX_SEEDLEN 48
uint32_t keyLen;
uint32_t seedLen;
const EAL_SymMethod *ciphMeth;
void *ctrCtx;
void *dfCtx;
bool isUsedDf;
} DRBG_CtrCtx;
static void DRBG_CtrXor(CRYPT_Data *dst, const CRYPT_Data *src)
{
uint32_t xorlen;
if (CRYPT_IsDataNull(dst) || CRYPT_IsDataNull(src)) {
return;
}
xorlen = (dst->len > src->len) ? src->len : dst->len;
DATA_XOR(dst->data, src->data, dst->data, xorlen);
}
static void DRBG_CtrInc(uint8_t *v, uint32_t len)
{
uint32_t i;
uint8_t *p = v + len - 1;
for (i = 0; i < len; i++, p--) {
(*p)++;
if (*p != 0) {
break;
}
}
}
int32_t DRBG_CtrUpdate(DRBG_Ctx *drbg, const CRYPT_Data *in1, const CRYPT_Data *in2)
{
DRBG_CtrCtx *ctx = (DRBG_CtrCtx *)drbg->ctx;
const EAL_SymMethod *ciphMeth = ctx->ciphMeth;
int32_t ret;
uint8_t tempData[DRBG_CTR_MAX_SEEDLEN];
CRYPT_Data temp;
uint32_t offset;
if ((ret = ciphMeth->setEncryptKey(ctx->ctrCtx, ctx->k, ctx->keyLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
/**
While (len (temp) < seedlen) do
If ctr_len < blocklen
inc = (rightmost (V, ctr_len) + 1) mod 2ctr_len .
V = leftmost (V, blocklen-ctr_len) || inc.
Else V = (V+1) mod 2blocklen .
output_block = Block_Encrypt (Key, V).
temp = temp || output_block.
*/
for (offset = 0; offset < ctx->seedLen; offset += AES_BLOCK_LEN) {
DRBG_CtrInc(ctx->v, AES_BLOCK_LEN);
if ((ret = ciphMeth->encryptBlock(ctx->ctrCtx, ctx->v, tempData + offset, AES_BLOCK_LEN)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
}
// temp = temp ⊕ provided_data
temp.data = tempData;
temp.len = ctx->seedLen;
DRBG_CtrXor(&temp, in1);
DRBG_CtrXor(&temp, in2);
// Key = leftmost (temp, keylen). V = rightmost (temp, blocklen).
if (memcpy_s(ctx->k, DRBG_CTR_MAX_KEYLEN, temp.data, ctx->keyLen) != EOK) {
BSL_ERR_PUSH_ERROR(CRYPT_SECUREC_FAIL);
ret = CRYPT_SECUREC_FAIL;
goto EXIT;
}
// The length to be copied of ctx->V is AES_BLOCK_LEN, which is also the array length.
// The lower bits of temp.data are used for ctx->K, and the upper bits are used for ctx->V.
(void)memcpy_s(ctx->v, AES_BLOCK_LEN, temp.data + ctx->keyLen, AES_BLOCK_LEN);
EXIT:
ciphMeth->cipherDeInitCtx(ctx->ctrCtx);
return ret;
}
// BCC implementation, BCC is CBC-MAC: CBC encryption + IV(0) + last ciphertext returned.
static int32_t DRBG_CtrBCCUpdateBlock(DRBG_Ctx *drbg, const uint8_t *in, uint8_t *out, uint32_t len)
{
DRBG_CtrCtx *ctx = (DRBG_CtrCtx *)drbg->ctx;
int32_t ret;
/**
4. For i = 1 to n do
4.1 input_block = chaining_value ⊕ blocki.
4.2 chaining_value = Block_Encrypt (Key, input_block).
*/
DATA_XOR(out, in, out, len);
if ((ret = ctx->ciphMeth->encryptBlock(ctx->dfCtx, out, out, AES_BLOCK_LEN)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
ctx->ciphMeth->cipherDeInitCtx(ctx->dfCtx);
}
return ret;
}
static int32_t DRBG_CtrBCCInit(DRBG_Ctx *drbg)
{
DRBG_CtrCtx *ctx = (DRBG_CtrCtx *)drbg->ctx;
uint8_t *out = ctx->kx;
int32_t ret = CRYPT_SUCCESS;
uint8_t in[16] = { 0 };
uint32_t offset = 0;
while (offset < ctx->seedLen) {
if ((ret = DRBG_CtrBCCUpdateBlock(drbg, in, out + offset, AES_BLOCK_LEN)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
in[3]++; // Each cycle is incremented by 1 at the 3rd position.
offset += AES_BLOCK_LEN;
}
return ret;
}
static int32_t DRBG_CtrBCCUpdateKX(DRBG_Ctx *drbg, const uint8_t *in)
{
DRBG_CtrCtx *ctx = (DRBG_CtrCtx *)drbg->ctx;
uint8_t *out = ctx->kx;
int32_t ret = CRYPT_SUCCESS;
uint32_t offset = 0;
while (offset < ctx->seedLen) {
if ((ret = DRBG_CtrBCCUpdateBlock(drbg, in, out + offset, AES_BLOCK_LEN)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
offset += AES_BLOCK_LEN;
}
return ret;
}
// Temporary block storage used by ctr_df
static int32_t DRBG_CtrBCCUpdate(DRBG_Ctx *drbg, const CRYPT_Data *in, uint8_t temp[16], uint32_t *tempLen)
{
uint32_t dataLeft;
uint32_t offset = 0;
uint32_t tempPos = *tempLen;
int32_t ret = CRYPT_SUCCESS;
if (CRYPT_IsDataNull(in) || in->len == 0) {
return ret;
}
dataLeft = in->len;
do {
const uint32_t left = AES_BLOCK_LEN - tempPos;
const uint32_t cpyLen = (left > dataLeft) ? dataLeft : left;
if (memcpy_s(temp + tempPos, left, in->data + offset, cpyLen) != EOK) {
BSL_ERR_PUSH_ERROR(CRYPT_SECUREC_FAIL);
return CRYPT_SECUREC_FAIL;
}
if (left == cpyLen) {
if ((ret = DRBG_CtrBCCUpdateKX(drbg, temp)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
tempPos = 0;
} else {
tempPos += cpyLen;
}
dataLeft -= cpyLen;
offset += cpyLen;
} while (dataLeft > 0);
*tempLen = tempPos;
return ret;
}
static int32_t DRBG_CtrBCCFinal(DRBG_Ctx *drbg, uint8_t temp[16], uint32_t tempLen)
{
int32_t ret;
uint32_t i;
for (i = tempLen; i < AES_BLOCK_LEN; i++) {
temp[i] = 0;
}
if ((ret = DRBG_CtrBCCUpdateKX(drbg, temp)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
static int32_t BlockCipherDfCal(DRBG_Ctx *drbg, CRYPT_Data *out)
{
DRBG_CtrCtx *ctx = (DRBG_CtrCtx *)drbg->ctx;
const EAL_SymMethod *ciphMeth = ctx->ciphMeth;
int32_t ret;
uint32_t kOffset = 0;
uint32_t vOffset = ctx->keyLen;
/* Set up key K */
if ((ret = ciphMeth->setEncryptKey(ctx->ctrCtx, ctx->kx, ctx->keyLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
while (kOffset < ctx->seedLen) {
ret = ciphMeth->encryptBlock(ctx->ctrCtx, ctx->kx + vOffset, ctx->kx + kOffset, AES_BLOCK_LEN);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
vOffset = kOffset;
kOffset += AES_BLOCK_LEN;
}
out->data = ctx->kx;
out->len = ctx->seedLen;
EXIT:
ciphMeth->cipherDeInitCtx(ctx->ctrCtx);
return ret;
}
static int32_t BlockCipherDf(DRBG_Ctx *drbg, const CRYPT_Data *in1, const CRYPT_Data *in2,
const CRYPT_Data *in3, CRYPT_Data *out)
{
DRBG_CtrCtx *ctx = (DRBG_CtrCtx *)drbg->ctx;
int32_t ret;
uint32_t tempLen = 8;
uint8_t temp[16] = { 0 };
uint32_t l;
BSL_SAL_CleanseData(ctx->kx, sizeof(ctx->kx));
if ((ret = DRBG_CtrBCCInit(drbg)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
/**
2. L = len (input_string)/8.
3. N = number_of_bits_to_return/8.
4. S = L || N || input_string || 0x80.
5. While (len (S) mod outlen) ≠ 0, do
S = S || 0x00.
6. temp = the Null string.
9. While len (temp) < keylen + outlen, do
9.1 IV = i || 0^(outlen - len (i))
9.2 temp = temp || BCC (K, (IV || S)).
9.3 i = i + 1.
*/
l = (in1 ? in1->len : 0) + (in2 ? in2->len : 0) + (in3 ? in3->len : 0);
temp[0] = (uint8_t)((l >> 24) & 0xff);
temp[1] = (uint8_t)((l >> 16) & 0xff);
temp[2] = (uint8_t)((l >> 8) & 0xff);
temp[3] = (uint8_t)(l & 0xff);
temp[4] = 0;
temp[5] = 0;
temp[6] = 0;
temp[7] = (uint8_t)ctx->seedLen;
if ((ret = DRBG_CtrBCCUpdate(drbg, in1, temp, &tempLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if ((ret = DRBG_CtrBCCUpdate(drbg, in2, temp, &tempLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if ((ret = DRBG_CtrBCCUpdate(drbg, in3, temp, &tempLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
temp[tempLen++] = 0x80;
if ((ret = DRBG_CtrBCCFinal(drbg, temp, tempLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
/**
13. While len (temp) < number_of_bits_to_return, do
13.1 X = Block_Encrypt (K, X).
13.2 temp = temp || X.
*/
if ((ret = BlockCipherDfCal(drbg, out)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
static int32_t DRBG_CtrSetDfKey(DRBG_Ctx *drbg)
{
DRBG_CtrCtx *ctx = (DRBG_CtrCtx *)drbg->ctx;
const EAL_SymMethod *ciphMeth = ctx->ciphMeth;
int32_t ret = CRYPT_SUCCESS;
BSL_SAL_CleanseData(ctx->ctrCtx, ciphMeth->ctxSize);
if (ctx->isUsedDf) {
/* df initialisation */
const uint8_t dfKey[32] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
};
BSL_SAL_CleanseData(ctx->dfCtx, ciphMeth->ctxSize);
/* Set key schedule for dfKey */
if ((ret = ctx->ciphMeth->setEncryptKey(ctx->dfCtx, dfKey, ctx->keyLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
}
return ret;
}
int32_t DRBG_CtrInstantiate(DRBG_Ctx *drbg, const CRYPT_Data *entropy, const CRYPT_Data *nonce, const CRYPT_Data *pers)
{
DRBG_CtrCtx *ctx = (DRBG_CtrCtx *)drbg->ctx;
CRYPT_Data seedMaterial;
int32_t ret;
if ((ret = DRBG_CtrSetDfKey(drbg)) != CRYPT_SUCCESS) {
return ret;
}
/**
* 4. Key = 0(keylen)
* 5. V = 0(blocklen)
*/
BSL_SAL_CleanseData(ctx->k, sizeof(ctx->k));
BSL_SAL_CleanseData(ctx->v, sizeof(ctx->v));
/* seed_material = entropy_input ⊕ personalization_string.
(Key, V) = CTR_DRBG_Update (seed_material, Key, V).
*/
if (!ctx->isUsedDf) {
if ((ret = DRBG_CtrUpdate(drbg, entropy, pers)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
// seed_material = entropy_input || nonce || personalization_string.
if ((ret = BlockCipherDf(drbg, entropy, nonce, pers, &seedMaterial)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
ctx->ciphMeth->cipherDeInitCtx(ctx->dfCtx);
return ret;
}
if ((ret = DRBG_CtrUpdate(drbg, &seedMaterial, NULL)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
int32_t DRBG_CtrReseed(DRBG_Ctx *drbg, const CRYPT_Data *entropy, const CRYPT_Data *adin)
{
DRBG_CtrCtx *ctx = (DRBG_CtrCtx *)drbg->ctx;
CRYPT_Data seedMaterial;
int32_t ret;
if (!ctx->isUsedDf) {
if ((ret = DRBG_CtrUpdate(drbg, entropy, adin)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
// seed_material = entropy_input || additional_input.
if ((ret = BlockCipherDf(drbg, entropy, adin, NULL, &seedMaterial)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if ((ret = DRBG_CtrUpdate(drbg, &seedMaterial, NULL)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
static int32_t DRBG_CtrGenerateBlock(DRBG_Ctx *drbg, uint8_t *out, uint32_t outLen)
{
DRBG_CtrCtx *ctx = (DRBG_CtrCtx *)drbg->ctx;
int32_t ret;
DRBG_CtrInc(ctx->v, outLen);
if ((ret = ctx->ciphMeth->encryptBlock(ctx->ctrCtx, ctx->v, out, outLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
ctx->ciphMeth->cipherDeInitCtx(ctx->ctrCtx);
}
return ret;
}
static int32_t DRBG_CtrGenerateBlocks(DRBG_Ctx *drbg, uint8_t *out, uint32_t outLen)
{
DRBG_CtrCtx *ctx = (DRBG_CtrCtx *)drbg->ctx;
uint32_t offset = 0;
uint32_t tmpOutLen = outLen;
int32_t ret;
if ((ret = ctx->ciphMeth->setEncryptKey(ctx->ctrCtx, ctx->k, ctx->keyLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
while (tmpOutLen >= AES_BLOCK_LEN) {
if ((ret = DRBG_CtrGenerateBlock(drbg, out + offset, AES_BLOCK_LEN)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
tmpOutLen -= AES_BLOCK_LEN;
offset += AES_BLOCK_LEN;
}
if (tmpOutLen > 0) {
uint8_t temp[AES_BLOCK_LEN];
if ((ret = DRBG_CtrGenerateBlock(drbg, temp, AES_BLOCK_LEN)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// tmpOutLen indicates the length of the out remaining. In the last part of DRBG generation,
// truncate the length of tmpOutLen and assign it to the out remaining.
(void)memcpy_s(out + offset, tmpOutLen, temp, tmpOutLen);
}
return ret;
}
int32_t DRBG_CtrGenerate(DRBG_Ctx *drbg, uint8_t *out, uint32_t outLen, const CRYPT_Data *adin)
{
DRBG_CtrCtx *ctx = (DRBG_CtrCtx *)drbg->ctx;
int32_t ret;
/**
If (additional_input ≠ Null), then
temp = len (additional_input)
If (temp < seedlen), then
additional_input = additional_input || 0^(seedlen - temp).
(Key, V) = CTR_DRBG_Update (additional_input, Key, V)
Else additional_input = 0seedlen.
*/
if (adin != NULL && adin->data != NULL && adin->len != 0) {
if (!ctx->isUsedDf) {
if ((ret = DRBG_CtrUpdate(drbg, adin, NULL)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
} else {
// additional_input = Block_Cipher_df (additional_input, seedlen).
if ((ret = BlockCipherDf(drbg, adin, NULL, NULL, (CRYPT_Data *)(uintptr_t)adin)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if ((ret = DRBG_CtrUpdate(drbg, adin, NULL)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
}
/**
3. temp = Null.
4. While (len (temp) < requested_number_of_bits) do:
4.1 If ctr_len < blocklen
4.1.1 inc = (rightmost (V, ctr_len) + 1) mod 2ctr_len .
4.1.2 V = leftmost (V, blocklen-ctr_len) || inc.
Else V = (V+1) mod 2blocklen .
4.2 output_block = Block_Encrypt (Key, V).
4.3 temp = temp || output_block.
5. returned_bits = leftmost (temp, requested_number_of_bits).
*/
if ((ret = DRBG_CtrGenerateBlocks(drbg, out, outLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// (Key, V) = CTR_DRBG_Update (additional_input, Key, V).
if ((ret = DRBG_CtrUpdate(drbg, adin, NULL)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
void DRBG_CtrUnInstantiate(DRBG_Ctx *drbg)
{
DRBG_CtrCtx *ctx = (DRBG_CtrCtx*)drbg->ctx;
ctx->ciphMeth->cipherDeInitCtx(ctx->ctrCtx);
ctx->ciphMeth->cipherDeInitCtx(ctx->dfCtx);
BSL_SAL_CleanseData((void *)(ctx->k), sizeof(ctx->k));
BSL_SAL_CleanseData((void *)(ctx->v), sizeof(ctx->v));
BSL_SAL_CleanseData((void *)(ctx->kx), sizeof(ctx->kx));
}
DRBG_Ctx *DRBG_CtrDup(DRBG_Ctx *drbg)
{
if (drbg == NULL) {
return NULL;
}
DRBG_CtrCtx *ctx = (DRBG_CtrCtx*)drbg->ctx;
DRBG_Ctx *newDrbg = DRBG_NewCtrCtx(ctx->ciphMeth, ctx->keyLen, drbg->isGm, ctx->isUsedDf, &(drbg->seedMeth),
drbg->seedCtx);
if (newDrbg == NULL) {
return NULL;
}
newDrbg->libCtx = drbg->libCtx;
return newDrbg;
}
void DRBG_CtrFree(DRBG_Ctx *drbg)
{
if (drbg == NULL) {
return;
}
DRBG_CtrUnInstantiate(drbg);
DRBG_CtrCtx *ctx = (DRBG_CtrCtx*)drbg->ctx;
BSL_SAL_FREE(ctx->dfCtx);
BSL_SAL_FREE(drbg);
return;
}
static void DRBG_InitializeRanges(DRBG_Ctx *drbg, DRBG_CtrCtx *ctx, bool isUsedDf, uint32_t keyLen)
{
// NIST.SP.800-90Ar1, Section 10.3.1 Table 3 defined those initial value.
if (isUsedDf) {
// shift rightwards by 3, converting from bit length to byte length
drbg->entropyRange.min = (drbg->isGm) ? DRBG_CTR_MIN_ENTROPYLEN : keyLen;
drbg->entropyRange.max = DRBG_MAX_LEN;
drbg->maxPersLen = DRBG_MAX_LEN;
drbg->maxAdinLen = DRBG_MAX_LEN;
// NIST.SP.800-90Ar1, Section 8.6.7 defined, a nonce needs (security_strength/2) bits of entropy at least.
drbg->nonceRange.min = drbg->entropyRange.min / DRBG_NONCE_FROM_ENTROPY;
drbg->nonceRange.max = DRBG_MAX_LEN;
} else {
drbg->entropyRange.min = ctx->seedLen;
drbg->entropyRange.max = ctx->seedLen;
drbg->maxPersLen = ctx->seedLen;
drbg->maxAdinLen = ctx->seedLen;
drbg->nonceRange.min = 0;
drbg->nonceRange.max = 0;
}
}
DRBG_Ctx *DRBG_NewCtrCtx(const EAL_SymMethod *ciphMeth, const uint32_t keyLen, bool isGm, const bool isUsedDf,
const CRYPT_RandSeedMethod *seedMeth, void *seedCtx)
{
static DRBG_Method meth = {
DRBG_CtrInstantiate,
DRBG_CtrGenerate,
DRBG_CtrReseed,
DRBG_CtrUnInstantiate,
DRBG_CtrDup,
DRBG_CtrFree
};
if (ciphMeth == NULL || keyLen == 0 || seedMeth == NULL) {
return NULL;
}
DRBG_Ctx *drbg = (DRBG_Ctx*)BSL_SAL_Malloc(sizeof(DRBG_Ctx) + sizeof(DRBG_CtrCtx) + ciphMeth->ctxSize);
if (drbg == NULL) {
return NULL;
}
void *dfCtx = (void*)BSL_SAL_Malloc(ciphMeth->ctxSize); // have 2 contexts
if (dfCtx == NULL) {
BSL_SAL_FREE(drbg);
return NULL;
}
DRBG_CtrCtx *ctx = (DRBG_CtrCtx*)(drbg + 1);
ctx->ctrCtx = (void*)(ctx + 1);
ctx->dfCtx = dfCtx;
ctx->ciphMeth = ciphMeth;
drbg->state = DRBG_STATE_UNINITIALISED;
drbg->isGm = isGm;
drbg->reseedInterval = (drbg->isGm) ? HITLS_CRYPTO_RESEED_INTERVAL_GM : DRBG_MAX_RESEED_INTERVAL;
#if defined(HITLS_CRYPTO_DRBG_GM)
drbg->reseedIntervalTime = (drbg->isGm) ? HITLS_CRYPTO_DRBG_RESEED_TIME_GM : 0;
#endif
ctx->keyLen = keyLen;
ctx->seedLen = AES_BLOCK_LEN + keyLen;
ctx->isUsedDf = isUsedDf;
drbg->meth = &meth;
drbg->ctx = ctx;
drbg->seedMeth = *seedMeth;
drbg->seedCtx = seedCtx;
drbg->strength = keyLen * 8;
drbg->maxRequest = (drbg->isGm) ? DRBG_MAX_REQUEST_SM4 : DRBG_MAX_REQUEST;
DRBG_InitializeRanges(drbg, ctx, isUsedDf, keyLen);
drbg->predictionResistance = false;
return drbg;
}
#endif
|
2301_79861745/bench_create
|
crypto/drbg/src/drbg_ctr.c
|
C
|
unknown
| 19,544
|
/*
* 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_DRBG_HASH
#include <stdlib.h>
#include <securec.h>
#include "crypt_errno.h"
#include "crypt_local_types.h"
#include "crypt_utils.h"
#include "bsl_sal.h"
#include "crypt_types.h"
#include "bsl_err_internal.h"
#include "drbg_local.h"
#define DRBG_HASH_MAX_SEEDLEN (111)
typedef enum {
DRBG_SHA1MDSIZE = 20,
DRBG_SHA224MDSIZE = 28,
DRBG_SHA256MDSIZE = 32,
DRBG_SHA384MDSIZE = 48,
DRBG_SHA512MDSIZE = 64,
DRBG_SM3MDSIZE = 32,
} DRBG_MdSize;
typedef struct {
uint8_t v[DRBG_HASH_MAX_SEEDLEN];
uint8_t c[DRBG_HASH_MAX_SEEDLEN];
uint32_t seedLen;
const EAL_MdMethod *md;
void *mdCtx;
} DRBG_HashCtx;
// This function performs the ctx->V += xxx operation.
static void DRBG_HashAddV(uint8_t *v, uint32_t vLen, uint8_t *src, uint32_t srcLen)
{
uint8_t *d = v + vLen - 1;
uint8_t *s = src + srcLen - 1;
uint8_t c = 0;
uint32_t r;
while (s >= src) {
r = (uint32_t)(*d) + (*s) + c;
*d = (uint8_t)(r & 0xff);
c = (r > 0xff) ? 1 : 0;
d--;
s--;
}
while (d >= v && c > 0) {
r = (uint32_t)(*d) + c;
*d = (uint8_t)(r & 0xff);
c = (r > 0xff) ? 1 : 0;
d--;
}
return;
}
static int32_t DRBG_UpdateDataInHashDf(DRBG_HashCtx *ctx,
const CRYPT_Data *in1, const CRYPT_Data *in2,
const CRYPT_Data *in3, const CRYPT_Data *in4)
{
const EAL_MdMethod *meth = ctx->md;
void *mdCtx = ctx->mdCtx;
int32_t ret = CRYPT_SUCCESS;
if (!CRYPT_IsDataNull(in1)) {
ret = meth->update(mdCtx, in1->data, in1->len);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
if (!CRYPT_IsDataNull(in2)) {
ret = meth->update(mdCtx, in2->data, in2->len);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
if (!CRYPT_IsDataNull(in3)) {
ret = meth->update(mdCtx, in3->data, in3->len);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
if (!CRYPT_IsDataNull(in4)) {
ret = meth->update(mdCtx, in4->data, in4->len);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
}
return ret;
}
static void DRBG_HashDfValuesAssig(uint8_t values[5], uint32_t len)
{
// The value of values is the same as that of counter || no_of_bits_to_return in Hash_df Process
// in section 10.3.1 in NIST 800-90a.
values[0] = 0x1;
// len is shifted leftward by 3, then byte-to-bit. Shift rightwards by 24 bits to get the highest 8 bits.
values[1] = (uint8_t)(((len << 3) >> 24) & 0xff);
// 2nd, len is shifted leftward by 3, then byte-to-bit. Shift rightwards by 16 bits to get the second 8 bits.
values[2] = (uint8_t)(((len << 3) >> 16) & 0xff);
// 3rd, len is shifted leftward by 3, then byte-to-bit. Shift rightwards by 8 bits to get the third 8 bits.
values[3] = (uint8_t)(((len << 3) >> 8) & 0xff);
values[4] = (uint8_t)((len << 3) & 0xff); // 4th, len is shifted leftward by 3, then byte-to-bit.
}
static int32_t DRBG_HashDf(DRBG_HashCtx *ctx, uint8_t *out, uint32_t outLen, const CRYPT_Data *in1,
const CRYPT_Data *in2, const CRYPT_Data *in3, const CRYPT_Data *in4)
{
const EAL_MdMethod *meth = ctx->md;
void *mdCtx = ctx->mdCtx;
uint32_t mdSize = meth->mdSize;
uint8_t *buf = out;
uint32_t len = outLen;
int32_t ret;
// The temp is the same as that of counter || no_of_bits_to_return in Hash_df Process
// in section 10.3.1 in NIST 800-90a.
uint8_t temp[5];
// len = floor(no_of_bits_to_return / outlen)
DRBG_HashDfValuesAssig(temp, len);
do {
// temp = temp || Hash (counter || no_of_bits_to_return || input_string).
if ((ret = meth->init(mdCtx, NULL)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// 5 indicates the maximum length of temp. For details, see the temp statement.
if ((ret = meth->update(mdCtx, temp, 5)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
if ((ret = DRBG_UpdateDataInHashDf(ctx, in1, in2, in3, in4)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
uint8_t tmpOut[DRBG_HASH_MAX_MDSIZE];
uint32_t tmpOutLen = DRBG_HASH_MAX_MDSIZE;
if (len < mdSize) {
if ((ret = meth->final(mdCtx, tmpOut, &tmpOutLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
// tmpOutLen is the maximum supported MD length,
// and len is the actual length, which must be smaller than tmpOutLen.
// Only the len length needs to be truncated as the output.
(void)memcpy_s(buf, len, tmpOut, len);
break;
}
if ((ret = meth->final(mdCtx, buf, &tmpOutLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
buf += mdSize;
len -= mdSize;
temp[0]++;
} while (len > 0);
EXIT:
meth->deinit(mdCtx);
return ret;
}
static int32_t DRBG_Hashgen(DRBG_HashCtx *ctx, uint8_t *out, uint32_t outLen)
{
uint8_t data[DRBG_HASH_MAX_SEEDLEN];
const EAL_MdMethod *md = ctx->md;
void *mdCtx = ctx->mdCtx;
int32_t ret = CRYPT_SUCCESS;
uint32_t mdSize = md->mdSize;
uint32_t tmpLen = mdSize;
uint32_t len = outLen;
uint8_t *buf = out;
// The length of the V array is the longest seedLen. Therefore, there is no failure.
(void)memcpy_s(data, sizeof(data), ctx->v, ctx->seedLen);
while (len > 0) {
uint8_t n = 1;
if ((ret = md->init(mdCtx, NULL)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if ((ret = md->update(mdCtx, data, ctx->seedLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
if (len >= mdSize) {
if ((ret = md->final(mdCtx, buf, &tmpLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
} else {
uint8_t temp[DRBG_HASH_MAX_SEEDLEN];
uint32_t tempLen = DRBG_HASH_MAX_SEEDLEN;
if ((ret = md->final(mdCtx, temp, &tempLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
(void)memcpy_s(buf, len, temp, len);
break;
}
buf += mdSize;
len -= mdSize;
DRBG_HashAddV(data, ctx->seedLen, &n, 1);
}
EXIT:
// Clear MD data.
md->deinit(mdCtx);
return ret;
}
int32_t DRBG_HashInstantiate(DRBG_Ctx *drbg, const CRYPT_Data *entropy,
const CRYPT_Data *nonce, const CRYPT_Data *pers)
{
DRBG_HashCtx *ctx = (DRBG_HashCtx*)drbg->ctx;
CRYPT_Data seed = {ctx->v, (uint32_t)(ctx->seedLen)};
int32_t ret;
uint8_t c = 0;
CRYPT_Data temp = {&c, 1};
/**
1. seed_material = entropy || nonce || pers
2. seed = Hash_df(seed_material)
3. V = seed
4. C = Hash_df(0x00 || V)
*/
ret = DRBG_HashDf(ctx, ctx->v, ctx->seedLen, entropy, nonce, pers, NULL);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = DRBG_HashDf(ctx, ctx->c, ctx->seedLen, &temp, &seed, NULL, NULL);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
static int32_t DRBG_HashAdinInHashGenerate(DRBG_HashCtx *ctx, const CRYPT_Data *adin)
{
void *mdCtx = ctx->mdCtx;
const EAL_MdMethod *md = ctx->md;
uint32_t mdSize = md->mdSize;
int32_t ret;
uint8_t temp = 0x2;
uint8_t w[DRBG_HASH_MAX_MDSIZE];
uint32_t wLen = DRBG_HASH_MAX_MDSIZE;
ret = md->init(mdCtx, NULL);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = md->update(mdCtx, &temp, 1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = md->update(mdCtx, ctx->v, ctx->seedLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = md->update(mdCtx, adin->data, adin->len);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = md->final(mdCtx, w, &wLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
DRBG_HashAddV(ctx->v, ctx->seedLen, w, mdSize);
EXIT:
// Clear MD data.
md->deinit(mdCtx);
return ret;
}
int32_t DRBG_HashGenerate(DRBG_Ctx *drbg, uint8_t *out, uint32_t outLen, const CRYPT_Data *adin)
{
DRBG_HashCtx *ctx = (DRBG_HashCtx*)drbg->ctx;
const EAL_MdMethod *md = ctx->md;
void *mdCtx = ctx->mdCtx;
uint32_t mdSize = md->mdSize;
uint8_t h[DRBG_HASH_MAX_MDSIZE];
uint32_t len = outLen;
int32_t ret;
uint32_t reseedCtrBe;
/* if adin :
w = HASH(0x02 || V || adin)
V = (V + w) mod 2^seedLen
*/
if (!CRYPT_IsDataNull(adin)) {
ret = DRBG_HashAdinInHashGenerate(ctx, adin);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
// Hashgen(V, out, len)
ret = DRBG_Hashgen(ctx, out, len);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// H = HASH(0x03 || V)
uint8_t temp = 0x3;
ret = md->init(mdCtx, NULL);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = md->update(mdCtx, &temp, 1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = md->update(mdCtx, ctx->v, ctx->seedLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = md->final(mdCtx, h, &mdSize);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
// V = (V + H + C + reseed_counter) mod 2^seedlen
DRBG_HashAddV(ctx->v, ctx->seedLen, h, mdSize);
DRBG_HashAddV(ctx->v, ctx->seedLen, ctx->c, ctx->seedLen);
reseedCtrBe = CRYPT_HTONL((uint32_t)(drbg->reseedCtr));
DRBG_HashAddV(ctx->v, ctx->seedLen, (uint8_t*)&reseedCtrBe, sizeof(reseedCtrBe));
EXIT:
// Clear MD data.
md->deinit(mdCtx);
return ret;
}
int32_t DRBG_HashReseed(DRBG_Ctx *drbg, const CRYPT_Data *entropy, const CRYPT_Data *adin)
{
int32_t ret;
DRBG_HashCtx *ctx = (DRBG_HashCtx*)drbg->ctx;
CRYPT_Data v = {ctx->v, ctx->seedLen};
uint8_t c = 0x1;
CRYPT_Data temp = {&c, 1};
/**
seed_material = 0x01 || V || entropy_input || additional_input.
seed = Hash_Df(seed_material) // The memory of C is reused.
V = seed
C = Hash_Df(0x00 || V)
*/
if (drbg->isGm) {
ret = DRBG_HashDf(ctx, ctx->c, ctx->seedLen, &temp, entropy, &v, adin);
} else {
ret = DRBG_HashDf(ctx, ctx->c, ctx->seedLen, &temp, &v, entropy, adin);
}
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// The length of the C array is the longest seedLen. Therefore, there is no failure.
(void)memcpy_s(ctx->v, sizeof(ctx->v), ctx->c, ctx->seedLen);
c = 0x0;
ret = DRBG_HashDf(ctx, ctx->c, ctx->seedLen, &temp, &v, NULL, NULL);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
void DRBG_HashUnInstantiate(DRBG_Ctx *drbg)
{
DRBG_HashCtx *ctx = (DRBG_HashCtx*)drbg->ctx;
ctx->md->deinit(ctx->mdCtx);
BSL_SAL_CleanseData((void *)(ctx->c), sizeof(ctx->c));
BSL_SAL_CleanseData((void *)(ctx->v), sizeof(ctx->v));
}
DRBG_Ctx *DRBG_HashDup(DRBG_Ctx *drbg)
{
if (drbg == NULL) {
return NULL;
}
DRBG_HashCtx *ctx = (DRBG_HashCtx*)drbg->ctx;
DRBG_Ctx *newDrbg = DRBG_NewHashCtx(ctx->md, drbg->isGm, &(drbg->seedMeth), drbg->seedCtx);
if (newDrbg == NULL) {
return NULL;
}
newDrbg->libCtx = drbg->libCtx;
return newDrbg;
}
void DRBG_HashFree(DRBG_Ctx *drbg)
{
if (drbg == NULL) {
return;
}
DRBG_HashUnInstantiate(drbg);
DRBG_HashCtx *ctx = (DRBG_HashCtx*)drbg->ctx;
ctx->md->freeCtx(ctx->mdCtx);
BSL_SAL_FREE(drbg);
return;
}
static int32_t DRBG_NewHashCtxBase(uint32_t mdSize, DRBG_Ctx *drbg, DRBG_HashCtx *ctx)
{
switch (mdSize) {
case DRBG_SHA1MDSIZE:
drbg->strength = 128; // 128 is the standard content length of nist 800-90a.
ctx->seedLen = 55; // 55 is the standard content length of nist 800-90a.
return CRYPT_SUCCESS;
case DRBG_SHA224MDSIZE:
drbg->strength = 192; // 192 is the standard content length of nist 800-90a.
ctx->seedLen = 55; // 55 is the standard content length of nist 800-90a.
return CRYPT_SUCCESS;
case DRBG_SHA256MDSIZE:
drbg->strength = 256; // 256 is the standard content length of nist 800-90a.
ctx->seedLen = 55; // 55 is the standard content length of nist 800-90a.
return CRYPT_SUCCESS;
case DRBG_SHA384MDSIZE:
case DRBG_SHA512MDSIZE:
drbg->strength = 256; // 256 is the standard content length of nist 800-90a.
ctx->seedLen = 111; // 111 is the standard content length of nist 800-90a.
return CRYPT_SUCCESS;
default:
BSL_ERR_PUSH_ERROR(CRYPT_DRBG_ALG_NOT_SUPPORT);
return CRYPT_DRBG_ALG_NOT_SUPPORT;
}
}
DRBG_Ctx *DRBG_NewHashCtx(const EAL_MdMethod *md, bool isGm, const CRYPT_RandSeedMethod *seedMeth, void *seedCtx)
{
DRBG_Ctx *drbg = NULL;
DRBG_HashCtx *ctx = NULL;
static DRBG_Method meth = {
DRBG_HashInstantiate,
DRBG_HashGenerate,
DRBG_HashReseed,
DRBG_HashUnInstantiate,
DRBG_HashDup,
DRBG_HashFree
};
if (md == NULL || md->newCtx == NULL || md->freeCtx == NULL || seedMeth == NULL) {
return NULL;
}
drbg = (DRBG_Ctx*)BSL_SAL_Malloc(sizeof(DRBG_Ctx) + sizeof(DRBG_HashCtx));
if (drbg == NULL) {
return NULL;
}
ctx = (DRBG_HashCtx*)(drbg + 1);
ctx->md = md;
ctx->mdCtx = md->newCtx(NULL, md->id);
if (ctx->mdCtx == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
BSL_SAL_FREE(drbg);
return NULL;
}
if (DRBG_NewHashCtxBase(md->mdSize, drbg, ctx) != CRYPT_SUCCESS) {
BSL_SAL_FREE(drbg);
md->freeCtx(ctx->mdCtx);
ctx->mdCtx = NULL;
return NULL;
}
drbg->state = DRBG_STATE_UNINITIALISED;
drbg->isGm = isGm;
drbg->reseedInterval = (drbg->isGm) ? HITLS_CRYPTO_RESEED_INTERVAL_GM : DRBG_MAX_RESEED_INTERVAL;
#if defined(HITLS_CRYPTO_DRBG_GM)
drbg->reseedIntervalTime = (drbg->isGm) ? HITLS_CRYPTO_DRBG_RESEED_TIME_GM : 0;
#endif
drbg->meth = &meth;
drbg->ctx = ctx;
drbg->seedMeth = *seedMeth;
drbg->seedCtx = seedCtx;
// Shift right by 3, from bit length to byte length
drbg->entropyRange.min = drbg->strength >> 3;
drbg->entropyRange.max = DRBG_MAX_LEN;
drbg->nonceRange.min = drbg->entropyRange.min / DRBG_NONCE_FROM_ENTROPY;
drbg->nonceRange.max = DRBG_MAX_LEN;
drbg->maxPersLen = DRBG_MAX_LEN;
drbg->maxAdinLen = DRBG_MAX_LEN;
drbg->maxRequest = (drbg->isGm) ? DRBG_MAX_REQUEST_SM3 : DRBG_MAX_REQUEST;
drbg->predictionResistance = false;
return drbg;
}
#endif
|
2301_79861745/bench_create
|
crypto/drbg/src/drbg_hash.c
|
C
|
unknown
| 16,203
|
/*
* 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_DRBG_HMAC
#include <stdlib.h>
#include <securec.h>
#include "crypt_errno.h"
#include "crypt_local_types.h"
#include "crypt_utils.h"
#include "bsl_sal.h"
#include "crypt_types.h"
#include "bsl_err_internal.h"
#include "drbg_local.h"
#define DRBG_HMAC_MAX_MDLEN (64)
typedef enum {
DRBG_HMAC_SHA1SIZE = 20,
DRBG_HMAC_SHA224SIZE = 28,
DRBG_HMAC_SHA256SIZE = 32,
DRBG_HMAC_SHA384SIZE = 48,
DRBG_HMAC_SHA512SIZE = 64,
} DRBG_HmacSize;
typedef struct {
uint8_t k[DRBG_HMAC_MAX_MDLEN];
uint8_t v[DRBG_HMAC_MAX_MDLEN];
uint32_t blockLen;
const EAL_MacMethod *hmacMeth;
CRYPT_MAC_AlgId macId;
void *hmacCtx;
} DRBG_HmacCtx;
static int32_t Hmac(DRBG_HmacCtx *ctx, uint8_t mark, const CRYPT_Data *provData[], int32_t provDataLen)
{
int32_t ret;
uint32_t ctxKLen = sizeof(ctx->k);
uint32_t ctxVLen = sizeof(ctx->v);
// K = HMAC (K, V || mark || provided_data). mark can be 0x00 or 0x01,
// provided_data = in1 || in2 || in3, private_data can be NULL
if ((ret = ctx->hmacMeth->init(ctx->hmacCtx, ctx->k, ctx->blockLen, NULL)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
if ((ret = ctx->hmacMeth->update(ctx->hmacCtx, ctx->v, ctx->blockLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
if ((ret = ctx->hmacMeth->update(ctx->hmacCtx, &mark, 1)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
for (int32_t i = 0; i < provDataLen; i++) {
if ((ret = ctx->hmacMeth->update(ctx->hmacCtx, provData[i]->data, provData[i]->len)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
}
if ((ret = ctx->hmacMeth->final(ctx->hmacCtx, ctx->k, &ctxKLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
// V = HMAC (K, V).
if ((ret = ctx->hmacMeth->init(ctx->hmacCtx, ctx->k, ctx->blockLen, NULL)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
if ((ret = ctx->hmacMeth->update(ctx->hmacCtx, ctx->v, ctx->blockLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
if ((ret = ctx->hmacMeth->final(ctx->hmacCtx, ctx->v, &ctxVLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
EXIT:
// clear hmacCtx
ctx->hmacMeth->deinit(ctx->hmacCtx);
return ret;
}
/**
* Ref: NIST.SP.800-90Ar1 https://nvlpubs.nist.gov/nistpubs/specialpublications/nist.sp.800-90ar1.pdf
* Section: 10.1.2.2 HMAC_DRBG Update Process
*/
static int32_t DRBG_HmacUpdate(DRBG_Ctx *drbg, const CRYPT_Data *provData[], int32_t provDataLen)
{
DRBG_HmacCtx *ctx = (DRBG_HmacCtx *)drbg->ctx;
int32_t ret;
// K = HMAC (K, V || 0x00 || provided_data). V = HMAC (K, V), provided_data have 3 input
ret = Hmac(ctx, 0x00, provData, provDataLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
// If (provided_data = Null), then return K and V. It's not an error, it's algorithmic.
if (provDataLen == 0) {
return ret;
}
// K = HMAC (K, V || 0x01 || provided_data). V = HMAC (K, V)
ret = Hmac(ctx, 0x01, provData, provDataLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
/**
* Ref: NIST.SP.800-90Ar1 https://nvlpubs.nist.gov/nistpubs/specialpublications/nist.sp.800-90ar1.pdf
* Section: 10.1.2.3 Instantiation of HMAC_DRBG
*/
int32_t DRBG_HmacInstantiate(DRBG_Ctx *drbg, const CRYPT_Data *entropyInput, const CRYPT_Data *nonce,
const CRYPT_Data *perstr)
{
DRBG_HmacCtx *ctx = (DRBG_HmacCtx *)drbg->ctx;
int32_t ret;
const CRYPT_Data *provData[3] = {0}; // We only need 3 at most.
int32_t index = 0;
if (!CRYPT_IsDataNull(entropyInput)) {
provData[index++] = entropyInput;
}
if (!CRYPT_IsDataNull(nonce)) {
provData[index++] = nonce;
}
if (!CRYPT_IsDataNull(perstr)) {
provData[index++] = perstr;
}
// Key = 0x00 00...00.
(void)memset_s(ctx->k, sizeof(ctx->k), 0, ctx->blockLen);
// V = 0x01 01...01.
(void)memset_s(ctx->v, sizeof(ctx->v), 1, ctx->blockLen);
// seed_material = entropy_input || nonce || personalization_string.
// (Key, V) = HMAC_DRBG_Update (seed_material, Key, V).
ret = DRBG_HmacUpdate(drbg, provData, index);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
/**
* Ref: NIST.SP.800-90Ar1 https://nvlpubs.nist.gov/nistpubs/specialpublications/nist.sp.800-90ar1.pdf
* Section: 10.1.2.4 HMAC_DRBG Reseed Process
*/
int32_t DRBG_HmacReseed(DRBG_Ctx *drbg, const CRYPT_Data *entropyInput, const CRYPT_Data *adin)
{
int32_t ret;
// seed_material = entropy_input || additional_input.
const CRYPT_Data *seedMaterial[2] = {0}; // This stage only needs 2 at most.
int32_t index = 0;
if (!CRYPT_IsDataNull(entropyInput)) {
seedMaterial[index++] = entropyInput;
}
if (!CRYPT_IsDataNull(adin)) {
seedMaterial[index++] = adin;
}
// (Key, V) = HMAC_DRBG_Update (seed_material, Key, V).
ret = DRBG_HmacUpdate(drbg, seedMaterial, index);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
/**
* Ref: NIST.SP.800-90Ar1 https://nvlpubs.nist.gov/nistpubs/specialpublications/nist.sp.800-90ar1.pdf
* Section: 10.1.2.5 HMAC_DRBG Generate Process
*/
int32_t DRBG_HmacGenerate(DRBG_Ctx *drbg, uint8_t *out, uint32_t outLen, const CRYPT_Data *adin)
{
DRBG_HmacCtx *ctx = (DRBG_HmacCtx *)drbg->ctx;
const EAL_MacMethod *hmacMeth = ctx->hmacMeth;
const uint8_t *temp = ctx->v;
uint32_t tmpLen = ctx->blockLen;
uint32_t len = outLen;
uint8_t *buf = out;
int32_t ret;
uint32_t ctxVLen;
int32_t hasAdin = CRYPT_IsDataNull(adin) ? 0 : 1;
// If additional_input ≠ Null, then (Key, V) = HMAC_DRBG_Update (additional_input, Key, V).
if (hasAdin == 1) {
if ((ret = DRBG_HmacUpdate(drbg, &adin, hasAdin)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
}
/**
While (len (temp) < requested_number_of_bits) do:
V = HMAC (Key, V).
temp = temp || V.
*/
while (len > 0) {
if ((ret = hmacMeth->init(ctx->hmacCtx, ctx->k, ctx->blockLen, NULL)) != CRYPT_SUCCESS ||
(ret = hmacMeth->update(ctx->hmacCtx, temp, ctx->blockLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
if (len <= ctx->blockLen) {
break;
}
if ((ret = hmacMeth->final(ctx->hmacCtx, buf, &tmpLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
temp = buf;
buf += ctx->blockLen;
len -= ctx->blockLen;
}
ctxVLen = sizeof(ctx->v);
if ((ret = hmacMeth->final(ctx->hmacCtx, ctx->v, &ctxVLen)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
// Intercepts the len-length V-value as an output, and because of len <= blockLen,
// length of V is always greater than blockLen,Therefore, this problem does not exist.
(void)memcpy_s(buf, len, ctx->v, len);
// (Key, V) = HMAC_DRBG_Update (additional_input, Key, V).
if ((ret = DRBG_HmacUpdate(drbg, &adin, hasAdin)) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
EXIT:
// clear hmacCtx
hmacMeth->deinit(ctx->hmacCtx);
return ret;
}
void DRBG_HmacUnInstantiate(DRBG_Ctx *drbg)
{
DRBG_HmacCtx *ctx = (DRBG_HmacCtx*)drbg->ctx;
ctx->hmacMeth->deinit(ctx->hmacCtx);
BSL_SAL_CleanseData((void *)(ctx->k), sizeof(ctx->k));
BSL_SAL_CleanseData((void *)(ctx->v), sizeof(ctx->v));
}
DRBG_Ctx *DRBG_HmacDup(DRBG_Ctx *drbg)
{
if (drbg == NULL) {
return NULL;
}
DRBG_HmacCtx *ctx = (DRBG_HmacCtx*)drbg->ctx;
DRBG_Ctx *newDrbg = DRBG_NewHmacCtx(drbg->libCtx, ctx->hmacMeth, ctx->macId, &(drbg->seedMeth), drbg->seedCtx);
if (newDrbg == NULL) {
return NULL;
}
newDrbg->libCtx = drbg->libCtx;
return newDrbg;
}
void DRBG_HmacFree(DRBG_Ctx *drbg)
{
if (drbg == NULL) {
return;
}
DRBG_HmacUnInstantiate(drbg);
DRBG_HmacCtx *ctx = (DRBG_HmacCtx*)drbg->ctx;
ctx->hmacMeth->freeCtx(ctx->hmacCtx);
BSL_SAL_FREE(drbg);
return;
}
static int32_t DRBG_NewHmacCtxBase(uint32_t hmacSize, DRBG_Ctx *drbg)
{
switch (hmacSize) {
case DRBG_HMAC_SHA1SIZE:
drbg->strength = 128; // nist 800-90a specified the length must be 128
return CRYPT_SUCCESS;
case DRBG_HMAC_SHA224SIZE:
drbg->strength = 192; // nist 800-90a specified the length must be 192
return CRYPT_SUCCESS;
case DRBG_HMAC_SHA256SIZE:
case DRBG_HMAC_SHA384SIZE:
case DRBG_HMAC_SHA512SIZE:
drbg->strength = 256; // nist 800-90a specified the length must be 256
return CRYPT_SUCCESS;
default:
BSL_ERR_PUSH_ERROR(CRYPT_DRBG_ALG_NOT_SUPPORT);
return CRYPT_DRBG_ALG_NOT_SUPPORT;
}
}
DRBG_Ctx *DRBG_NewHmacCtx(void *libCtx, const EAL_MacMethod *hmacMeth, CRYPT_MAC_AlgId macId,
const CRYPT_RandSeedMethod *seedMeth, void *seedCtx)
{
DRBG_Ctx *drbg = NULL;
DRBG_HmacCtx *ctx = NULL;
static DRBG_Method meth = {
DRBG_HmacInstantiate,
DRBG_HmacGenerate,
DRBG_HmacReseed,
DRBG_HmacUnInstantiate,
DRBG_HmacDup,
DRBG_HmacFree
};
if (hmacMeth == NULL || seedMeth == NULL) {
return NULL;
}
drbg = (DRBG_Ctx*)BSL_SAL_Malloc(sizeof(DRBG_Ctx) + sizeof(DRBG_HmacCtx));
if (drbg == NULL) {
return NULL;
}
ctx = (DRBG_HmacCtx*)(drbg + 1);
ctx->hmacMeth = hmacMeth;
ctx->macId = macId;
void *macCtx = hmacMeth->newCtx(libCtx, ctx->macId);
if (macCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
BSL_SAL_FREE(drbg);
return NULL;
}
ctx->hmacCtx = macCtx;
uint32_t tempLen = 0;
int32_t ret = hmacMeth->ctrl(ctx->hmacCtx, CRYPT_CTRL_GET_MACLEN, &tempLen, sizeof(uint32_t));
if (ret != CRYPT_SUCCESS) {
hmacMeth->freeCtx(ctx->hmacCtx);
BSL_SAL_FREE(drbg);
return NULL;
}
ctx->blockLen = tempLen;
if (DRBG_NewHmacCtxBase(ctx->blockLen, drbg) != CRYPT_SUCCESS) {
hmacMeth->freeCtx(ctx->hmacCtx);
BSL_SAL_FREE(drbg);
return NULL;
}
drbg->state = DRBG_STATE_UNINITIALISED;
drbg->reseedInterval = DRBG_MAX_RESEED_INTERVAL;
drbg->meth = &meth;
drbg->ctx = ctx;
drbg->seedMeth = *seedMeth;
drbg->seedCtx = seedCtx;
// shift rightwards by 3, converting from bit length to byte length
drbg->entropyRange.min = drbg->strength >> 3;
drbg->entropyRange.max = DRBG_MAX_LEN;
drbg->nonceRange.min = drbg->entropyRange.min / DRBG_NONCE_FROM_ENTROPY;
drbg->nonceRange.max = DRBG_MAX_LEN;
drbg->maxPersLen = DRBG_MAX_LEN;
drbg->maxAdinLen = DRBG_MAX_LEN;
drbg->maxRequest = DRBG_MAX_REQUEST;
drbg->libCtx = libCtx;
drbg->predictionResistance = false;
return drbg;
}
#endif
|
2301_79861745/bench_create
|
crypto/drbg/src/drbg_hmac.c
|
C
|
unknown
| 11,780
|
/*
* 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 DRBG_LOCAL_H
#define DRBG_LOCAL_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_DRBG
#include <stdint.h>
#include "crypt_drbg.h"
#ifdef __cplusplus
extern "C" {
#endif
// Relationship between the number of NONCE and ENTROPY
#define DRBG_NONCE_FROM_ENTROPY (2)
typedef enum {
DRBG_STATE_UNINITIALISED,
DRBG_STATE_READY,
DRBG_STATE_ERROR,
} DRBG_State;
typedef struct {
int32_t (*instantiate)(DRBG_Ctx *ctx, const CRYPT_Data *entropy,
const CRYPT_Data *nonce, const CRYPT_Data *pers);
int32_t (*generate)(DRBG_Ctx *ctx, uint8_t *out, uint32_t outLen, const CRYPT_Data *adin);
int32_t (*reseed)(DRBG_Ctx *ctx, const CRYPT_Data *entropy, const CRYPT_Data *adin);
void (*uninstantiate)(DRBG_Ctx *ctx);
DRBG_Ctx* (*dup)(DRBG_Ctx *ctx);
void (*free)(DRBG_Ctx *ctx);
} DRBG_Method;
struct DrbgCtx {
bool isGm;
DRBG_State state; /* DRBG state */
uint32_t reseedCtr; /* reseed counter */
uint32_t reseedInterval; /* reseed interval times */
#if defined(HITLS_CRYPTO_DRBG_GM)
uint64_t lastReseedTime; /* last reseed time, uint: second */
uint64_t reseedIntervalTime; /* Time threshold for reseed, uint: second */
#endif
uint32_t strength; /* Algorithm strength */
uint32_t maxRequest; /* Maximum number of bytes per request, which is determined by the algorithm. */
CRYPT_Range entropyRange; /* entropy size range */
CRYPT_Range nonceRange; /* nonce size range */
uint32_t maxPersLen; /* Maximum private data length */
uint32_t maxAdinLen; /* Maximum additional data length */
DRBG_Method *meth; /* Internal different mode method */
void *ctx; /* Mode Context */
/* seed function, which is related to the entropy source and DRBG generation.
When seedMeth and seedCtx are empty, the default entropy source is used. */
CRYPT_RandSeedMethod seedMeth;
void *seedCtx; /* Seed context */
void *libCtx; /* Library context */
bool predictionResistance;
};
#ifdef HITLS_CRYPTO_DRBG_HMAC
/**
* @ingroup drbg
* @brief Apply for a context for the HMAC_DRBG.
* @brief This API does not support multiple threads.
*
* @param libCtx Library context
* @param hmacMeth HMAC method
* @param mdMeth hash algid
* @param seedMeth DRBG seed hook
* @param seedCtx DRBG seed context
*
* @retval DRBG_Ctx* Success
* @retval NULL failure
*/
DRBG_Ctx *DRBG_NewHmacCtx(void *libCtx, const EAL_MacMethod *hmacMeth, CRYPT_MAC_AlgId macId,
const CRYPT_RandSeedMethod *seedMeth, void *seedCtx);
#endif
#ifdef HITLS_CRYPTO_DRBG_HASH
/**
* @ingroup drbg
* @brief Apply for a context for the Hash_DRBG.
* @brief This API does not support multiple threads.
*
* @param md HASH method
* @param isGm is sm3
* @param seedMeth DRBG seed hook
* @param seedCtx DRBG seed context
*
* @retval DRBG_Ctx* Success
* @retval NULL failure
*/
DRBG_Ctx *DRBG_NewHashCtx(const EAL_MdMethod *md, bool isGm, const CRYPT_RandSeedMethod *seedMeth, void *seedCtx);
#endif
#ifdef HITLS_CRYPTO_DRBG_CTR
/**
* @ingroup drbg
* @brief Apply for a context for the CTR_DRBG.
* @brief This API does not support multiple threads.
*
* @param ciphMeth AES method
* @param keyLen Key length
* @param isGm is sm4
* @param isUsedDf Indicates whether to use derivation function.
* @param seedMeth DRBG seed hook
* @param seedCtx DRBG seed context
*
* @retval DRBG_Ctx* Success
* @retval NULL failure
*/
DRBG_Ctx *DRBG_NewCtrCtx(const EAL_SymMethod *ciphMeth, const uint32_t keyLen, bool isGm, const bool isUsedDf,
const CRYPT_RandSeedMethod *seedMeth, void *seedCtx);
#endif
#ifdef __cplusplus
}
#endif
#endif // HITLS_CRYPTO_DRBG
#endif // DRBG_LOCAL_H
|
2301_79861745/bench_create
|
crypto/drbg/src/drbg_local.h
|
C
|
unknown
| 4,287
|
/*
* 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_DSA_H
#define CRYPT_DSA_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_DSA
#include <stdint.h>
#include "crypt_bn.h"
#include "crypt_types.h"
#include "bsl_params.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
#ifndef CRYPT_DSA_TRY_MAX_CNT
#define CRYPT_DSA_TRY_MAX_CNT 100 // Maximum number of attempts to generate keys and signatures
#endif
#define CRYPT_DSA_FFC_PARAM 1
#define CRYPT_DH_FFC_PARAM 2
#define CRYPT_DISABLE_SP800_KEYGEN_FLAG 0
#define CRYPT_ENABLE_SP800_KEYGEN_FLAG 1
/* DSA key parameters */
typedef struct DSA_Para CRYPT_DSA_Para;
/* DSA key context */
typedef struct DSA_Ctx CRYPT_DSA_Ctx;
/**
* @ingroup dsa
* @brief dsa Allocates context memory space.
*
* @retval (CRYPT_DSA_Ctx *) Pointer to the memory space of the allocated context
* @retval NULL Invalid null pointer
*/
CRYPT_DSA_Ctx *CRYPT_DSA_NewCtx(void);
/**
* @ingroup dsa
* @brief dsa Allocates context memory space.
*
* @param libCtx [IN] Library context
*
* @retval (CRYPT_DSA_Ctx *) Pointer to the memory space of the allocated context
* @retval NULL Invalid null pointer
*/
CRYPT_DSA_Ctx *CRYPT_DSA_NewCtxEx(void *libCtx);
/**
* @ingroup dsa
* @brief Copy the DSA context. After the duplication is complete, invoke the CRYPT_DSA_FreeCtx to release the memory.
*
* @param ctx [IN] Source DSA context
*
* @return CRYPT_DSA_Ctx Dsa context pointer
* If the operation fails, null is returned.
*/
CRYPT_DSA_Ctx *CRYPT_DSA_DupCtx(CRYPT_DSA_Ctx *dsaCtx);
/**
* @ingroup dsa
* @brief dsa Release the key context structure
*
* @param ctx [IN] Indicates the pointer to the context structure to be released. The ctx is set NULL by the invoker.
*/
void CRYPT_DSA_FreeCtx(CRYPT_DSA_Ctx *ctx);
/**
* @ingroup dsa
* @brief dsa generate key parameter structure
*
* @param para [IN] dsa external parameter
*
* @retval (CRYPT_DSA_Para *) Pointer to the memory space of the allocated context
* @retval NULL Invalid null pointer
*/
CRYPT_DSA_Para *CRYPT_DSA_NewPara(const CRYPT_DsaPara *para);
/**
* @ingroup dsa
* @brief Release the key parameter structure of DSA.
*
* @param para [IN] Pointer to the key parameter structure to be released. para is set NULL by the invoker.
*/
void CRYPT_DSA_FreePara(CRYPT_DSA_Para *para);
/**
* @ingroup dsa
* @brief Set the data of the key parameter structure to the key structure.
*
* @param ctx [IN] Key structure for setting related parameters. The key specification is 1024-3072 bits.
* @param para [IN] Key parameters
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input.
* @retval CRYPT_DSA_ERR_KEY_PARA The key parameter data is incorrect.
* @retval CRYPT_MEM_ALLOC_FAIL internal memory allocation error
* @retval BN error code. An error occurred in the internal BigNum calculation.
* @retval CRYPT_SUCCESS Set successfully.
*/
int32_t CRYPT_DSA_SetPara(CRYPT_DSA_Ctx *ctx, const CRYPT_DsaPara *para);
/**
* @ingroup dsa
* @brief Set the parameter data in the key structure to the key parameter structure.
*
* @param ctx [IN] Key structure for setting related parameters. The key specification is 1024-3072 bits.
* @param para [OUT] Key parameters
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input.
* @retval CRYPT_DSA_PARA_ERROR The key parameter data is incorrect.
* @retval BN error code. An error occurred in the internal BigNum calculation.
* @retval CRYPT_SUCCESS Get successfully.
*/
int32_t CRYPT_DSA_GetPara(const CRYPT_DSA_Ctx *ctx, CRYPT_DsaPara *para);
/**
* @ingroup dsa
* @brief dsa Obtain the key length.
*
* @param ctx [IN] DSA 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_DSA_GetBits(const CRYPT_DSA_Ctx *ctx);
/**
* @ingroup dsa
* @brief dsa Obtain the required length of the signature.
*
* @param ctx [IN] DSA 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_DSA_GetSignLen(const CRYPT_DSA_Ctx *ctx);
/**
* @ingroup dsa
* @brief Generate a DSA key pair.
*
* @param ctx [IN/OUT] DSA context structure
*
* @retval CRYPT_NULL_INPUT Error null pointer input.
* @retval CRYPT_DSA_ERR_KEY_PARA The key parameter data is incorrect.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure.
* @retval CRYPT_DSA_ERR_TRY_CNT Unable to generate results within the specified number of attempts.
* @retval BN error code. An error occurred in the internal BigNum calculation.
* @retval CRYPT_SUCCESS The key pair is successfully generated.
*/
int32_t CRYPT_DSA_Gen(CRYPT_DSA_Ctx *ctx);
/**
* @ingroup dsa
* @brief DSA Signature
*
* @param ctx [IN] DSA 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_DSA_GetSignLen.
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input.
* @retval CRYPT_DSA_BUFF_LEN_NOT_ENOUGH The buffer length is insufficient.
* @retval CRYPT_DSA_ERR_KEY_INFO The key information is incorrect.
* @retval CRYPT_DSA_ERR_TRY_CNT Unable to generate results within the specified number of attempts.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure.
* @retval BN error An error occurred in the internal BigNum operation.
* @retval CRYPT_SUCCESS Signed successfully.
*/
int32_t CRYPT_DSA_Sign(const CRYPT_DSA_Ctx *ctx, int32_t algId, const uint8_t *data, uint32_t dataLen,
uint8_t *sign, uint32_t *signLen);
/**
* @ingroup dsa
* @brief DSA Signature
*
* @param ctx [IN] DSA 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_DSA_GetSignLen.
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input.
* @retval CRYPT_DSA_BUFF_LEN_NOT_ENOUGH The buffer length is insufficient.
* @retval CRYPT_DSA_ERR_KEY_INFO The key information is incorrect.
* @retval CRYPT_DSA_ERR_TRY_CNT Unable to generate results within the specified number of attempts.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure.
* @retval BN error An error occurred in the internal BigNum operation.
* @retval CRYPT_SUCCESS Signed successfully.
*/
int32_t CRYPT_DSA_SignData(const CRYPT_DSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen,
uint8_t *sign, uint32_t *signLen);
/**
* @ingroup dsa
* @brief DSA verification
*
* @param ctx [IN] DSA 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_DSA_ERR_KEY_INFO The key information is incorrect.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure.
* @retval CRYPT_DSA_DECODE_FAIL Signature Data Decoding Failure.
* @retval CRYPT_DSA_VERIFY_FAIL Failed to verify the signature.
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS The signature is verified successfully.
*/
int32_t CRYPT_DSA_VerifyData(const CRYPT_DSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen,
const uint8_t *sign, uint32_t signLen);
/**
* @ingroup dsa
* @brief DSA verification
*
* @param ctx [IN] DSA 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_DSA_ERR_KEY_INFO The key information is incorrect.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure.
* @retval CRYPT_DSA_DECODE_FAIL Signature Data Decoding Failure.
* @retval CRYPT_DSA_VERIFY_FAIL Failed to verify the signature.
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS The signature is verified successfully.
*/
int32_t CRYPT_DSA_Verify(const CRYPT_DSA_Ctx *ctx, int32_t algId, const uint8_t *data, uint32_t dataLen,
const uint8_t *sign, uint32_t signLen);
/**
* @ingroup dsa
* @brief Set the private key data for the DSA.
*
* @param ctx [IN] DSA context structure
* @param prv [IN] External private key data
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input.
* @retval CRYPT_DSA_ERR_KEY_PARA The key parameter data is incorrect.
* @retval CRYPT_DSA_ERR_KEY_INFO The key information is incorrect.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure.
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS Set successfully.
*/
int32_t CRYPT_DSA_SetPrvKey(CRYPT_DSA_Ctx *ctx, const CRYPT_DsaPrv *prv);
/**
* @ingroup dsa
* @brief Set the public key data for the DSA.
*
* @param ctx [IN] DSA context structure
* @param pub [IN] External public key data
*
* @retval CRYPT_NULL_INPUT Error null pointer input.
* @retval CRYPT_DSA_ERR_KEY_PARA The key parameter data is incorrect.
* @retval CRYPT_DSA_ERR_KEY_INFO The key information is incorrect.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure.
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS Set successfully.
*/
int32_t CRYPT_DSA_SetPubKey(CRYPT_DSA_Ctx *ctx, const CRYPT_DsaPub *pub);
/**
* @ingroup dsa
* @brief Obtain the private key data of the DSA.
*
* @param ctx [IN] DSA context structure
* @param prv [OUT] External private key data
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input.
* @retval CRYPT_DSA_BUFF_LEN_NOT_ENOUGH The buffer length is insufficient.
* @retval CRYPT_DSA_ERR_KEY_INFO The key information is incorrect.
* @retval BN error. An error occurs in the internal BigNum calculation.
* @retval CRYPT_SUCCESS Obtained successfully.
*/
int32_t CRYPT_DSA_GetPrvKey(const CRYPT_DSA_Ctx *ctx, CRYPT_DsaPrv *prv);
/**
* @ingroup dsa
* @brief Obtain the public key data of the DSA.
*
* @param ctx [IN] DSA context structure
* @param pub [OUT] External public key data
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input.
* @retval CRYPT_DSA_BUFF_LEN_NOT_ENOUGH The buffer length is insufficient.
* @retval CRYPT_DSA_ERR_KEY_INFO The key information is incorrect.
* @retval BN error. An error occurred in the internal BigNum calculation.
* @retval CRYPT_SUCCESS Obtained successfully.
*/
int32_t CRYPT_DSA_GetPubKey(const CRYPT_DSA_Ctx *ctx, CRYPT_DsaPub *pub);
#ifdef HITLS_BSL_PARAMS
/**
* @ingroup dsa
* @brief Set the data of the key parameter structure to the key structure.
*
* @param ctx [IN] Key structure for setting related parameters. The key specification is 1024-3072 bits.
* @param para [IN] Key parameters
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input.
* @retval CRYPT_DSA_ERR_KEY_PARA The key parameter data is incorrect.
* @retval CRYPT_MEM_ALLOC_FAIL internal memory allocation error
* @retval BN error code. An error occurred in the internal BigNum calculation.
* @retval CRYPT_SUCCESS Set successfully.
*/
int32_t CRYPT_DSA_SetParaEx(CRYPT_DSA_Ctx *ctx, const BSL_Param *para);
/**
* @ingroup dsa
* @brief Set the parameter data in the key structure to the key parameter structure.
*
* @param ctx [IN] Key structure for setting related parameters. The key specification is 1024-3072 bits.
* @param para [OUT] Key parameters
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input.
* @retval CRYPT_DSA_PARA_ERROR The key parameter data is incorrect.
* @retval BN error code. An error occurred in the internal BigNum calculation.
* @retval CRYPT_SUCCESS Get successfully.
*/
int32_t CRYPT_DSA_GetParaEx(const CRYPT_DSA_Ctx *ctx, BSL_Param *para);
/**
* @ingroup dsa
* @brief Set the private key data for the DSA.
*
* @param ctx [IN] DSA context structure
* @param para [IN] External private key data
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input.
* @retval CRYPT_DSA_ERR_KEY_PARA The key parameter data is incorrect.
* @retval CRYPT_DSA_ERR_KEY_INFO The key information is incorrect.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure.
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS Set successfully.
*/
int32_t CRYPT_DSA_SetPrvKeyEx(CRYPT_DSA_Ctx *ctx, const BSL_Param *para);
/**
* @ingroup dsa
* @brief Set the public key data for the DSA.
*
* @param ctx [IN] DSA context structure
* @param para [IN] External public key data
*
* @retval CRYPT_NULL_INPUT Error null pointer input.
* @retval CRYPT_DSA_ERR_KEY_PARA The key parameter data is incorrect.
* @retval CRYPT_DSA_ERR_KEY_INFO The key information is incorrect.
* @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure.
* @retval BN error. An error occurs in the internal BigNum operation.
* @retval CRYPT_SUCCESS Set successfully.
*/
int32_t CRYPT_DSA_SetPubKeyEx(CRYPT_DSA_Ctx *ctx, const BSL_Param *para);
/**
* @ingroup dsa
* @brief Obtain the private key data of the DSA.
*
* @param ctx [IN] DSA context structure
* @param para [OUT] External private key data
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input.
* @retval CRYPT_DSA_BUFF_LEN_NOT_ENOUGH The buffer length is insufficient.
* @retval CRYPT_DSA_ERR_KEY_INFO The key information is incorrect.
* @retval BN error. An error occurs in the internal BigNum calculation.
* @retval CRYPT_SUCCESS Obtained successfully.
*/
int32_t CRYPT_DSA_GetPrvKeyEx(const CRYPT_DSA_Ctx *ctx, BSL_Param *para);
/**
* @ingroup dsa
* @brief Obtain the public key data of the DSA.
*
* @param ctx [IN] DSA context structure
* @param para [OUT] External public key data
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input.
* @retval CRYPT_DSA_BUFF_LEN_NOT_ENOUGH The buffer length is insufficient.
* @retval CRYPT_DSA_ERR_KEY_INFO The key information is incorrect.
* @retval BN error. An error occurred in the internal BigNum calculation.
* @retval CRYPT_SUCCESS Obtained successfully.
*/
int32_t CRYPT_DSA_GetPubKeyEx(const CRYPT_DSA_Ctx *ctx, BSL_Param *para);
#endif
/**
* @ingroup dsa
* @brief dsa Compare public keys and parameters
*
* @param a [IN] DSA context structure
* @param b [IN] DSA context structure
*
* @retval CRYPT_SUCCESS is the same
* @retval CRYPT_NULL_INPUT Invalid null pointer input.
* @retval CRYPT_DSA_ERR_KEY_INFO The key information is incorrect.
* @retval CRYPT_DSA_PUBKEY_NOT_EQUAL Public keys are not equal.
* @retval CRYPT_DSA_PARA_ERROR The parameter information is incorrect.
* @retval CRYPT_DSA_PARA_NOT_EQUAL The parameters are not equal.
*/
int32_t CRYPT_DSA_Cmp(const CRYPT_DSA_Ctx *a, const CRYPT_DSA_Ctx *b);
/**
* @ingroup dsa
* @brief DSA control interface
*
* @param ctx [IN] DSA context structure
* @param opt [IN] Operation mode
* @param val [IN] Parameter
* @param len [IN] val length
*
* @retval CRYPT_NULL_INPUT Invalid null pointer input
* @retval CRYPT_SUCCESS obtained successfully.
*/
int32_t CRYPT_DSA_Ctrl(CRYPT_DSA_Ctx *ctx, int32_t opt, void *val, uint32_t len);
/**
* @ingroup DSA
* @brief DSA get security bits
*
* @param ctx [IN] DSA Context structure
*
* @retval security bits
*/
int32_t CRYPT_DSA_GetSecBits(const CRYPT_DSA_Ctx *ctx);
#ifdef HITLS_CRYPTO_DSA_CHECK
/**
* @ingroup dsa
* @brief check the key pair consistency
*
* @param checkType [IN] check type
* @param pkey1 [IN] dsa key context structure
* @param pkey2 [IN] dsa key context structure
*
* @retval CRYPT_SUCCESS succeeded
* @retval other error.
*/
int32_t CRYPT_DSA_Check(uint32_t checkType, const CRYPT_DSA_Ctx *pkey1, const CRYPT_DSA_Ctx *pkey2);
#endif // HITLS_CRYPTO_DSA_CHECK
#ifdef __cplusplus
}
#endif
#endif // HITLS_CRYPTO_DSA
#endif // CRYPT_DSA_H
|
2301_79861745/bench_create
|
crypto/dsa/include/crypt_dsa.h
|
C
|
unknown
| 17,937
|
/*
* 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_DSA
#include "crypt_errno.h"
#include "securec.h"
#include "bsl_sal.h"
#include "bsl_err_internal.h"
#include "crypt_utils.h"
#include "crypt_encode_internal.h"
#include "dsa_local.h"
#include "crypt_dsa.h"
#include "eal_md_local.h"
#include "crypt_util_rand.h"
#include "crypt_params_key.h"
#ifdef HITLS_BSL_PARAMS
#include "bsl_params.h"
#include "crypt_params_key.h"
#endif
CRYPT_DSA_Ctx *CRYPT_DSA_NewCtx(void)
{
CRYPT_DSA_Ctx *ctx = BSL_SAL_Malloc(sizeof(CRYPT_DSA_Ctx));
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
(void)memset_s(ctx, sizeof(CRYPT_DSA_Ctx), 0, sizeof(CRYPT_DSA_Ctx));
BSL_SAL_ReferencesInit(&(ctx->references));
return ctx;
}
CRYPT_DSA_Ctx *CRYPT_DSA_NewCtxEx(void *libCtx)
{
CRYPT_DSA_Ctx *ctx = CRYPT_DSA_NewCtx();
if (ctx == NULL) {
return NULL;
}
ctx->libCtx = libCtx;
return ctx;
}
static bool InputBufferCheck(const uint8_t *buffer, uint32_t bufferLen)
{
if (buffer == NULL || bufferLen == 0) {
return true;
}
return false;
}
static int32_t NewParaCheck(const CRYPT_DsaPara *para)
{
bool invalidInput = (para == NULL) ||
InputBufferCheck(para->p, para->pLen) ||
InputBufferCheck(para->q, para->qLen) ||
InputBufferCheck(para->g, para->gLen);
if (invalidInput) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (para->pLen > BN_BITS_TO_BYTES(DSA_MAX_PBITS)) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_KEY_PARA);
return CRYPT_DSA_ERR_KEY_PARA;
}
if (para->qLen > para->pLen) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_KEY_PARA);
return CRYPT_DSA_ERR_KEY_PARA;
}
if (para->gLen > para->pLen) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_KEY_PARA);
return CRYPT_DSA_ERR_KEY_PARA;
}
return CRYPT_SUCCESS;
}
static CRYPT_DSA_Para *ParaMemGet(uint32_t bits)
{
CRYPT_DSA_Para *para = BSL_SAL_Malloc(sizeof(CRYPT_DSA_Para));
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
para->p = BN_Create(bits);
para->q = BN_Create(bits);
para->g = BN_Create(bits);
if (para->p == NULL || para->q == NULL || para->g == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
CRYPT_DSA_FreePara(para);
return NULL;
}
return para;
}
CRYPT_DSA_Para *CRYPT_DSA_NewPara(const CRYPT_DsaPara *para)
{
if (NewParaCheck(para) != CRYPT_SUCCESS) {
return NULL;
}
CRYPT_DSA_Para *retPara = ParaMemGet(para->pLen * 8); // bits = bytes * 8
if (retPara == NULL) {
return NULL;
}
int32_t ret = BN_Bin2Bn(retPara->p, para->p, para->pLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
ret = BN_Bin2Bn(retPara->q, para->q, para->qLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
ret = BN_Bin2Bn(retPara->g, para->g, para->gLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
return retPara;
ERR:
CRYPT_DSA_FreePara(retPara);
return NULL;
}
void CRYPT_DSA_FreePara(CRYPT_DSA_Para *para)
{
if (para == NULL) {
return;
}
BN_Destroy(para->p);
BN_Destroy(para->q);
BN_Destroy(para->g);
BSL_SAL_FREE(para);
}
void CRYPT_DSA_FreeCtx(CRYPT_DSA_Ctx *ctx)
{
if (ctx == NULL) {
return;
}
int ref = 0;
BSL_SAL_AtomicDownReferences(&(ctx->references), &ref);
if (ref > 0) {
return;
}
BSL_SAL_ReferencesFree(&(ctx->references));
CRYPT_DSA_FreePara(ctx->para);
BN_Destroy(ctx->x);
BN_Destroy(ctx->y);
BSL_SAL_FREE(ctx->mdAttr);
BSL_SAL_FREE(ctx);
}
static int32_t ParaPQGCheck(const BN_BigNum *p, const BN_BigNum *q, const BN_BigNum *g)
{
uint32_t pBits = BN_Bits(p);
BN_BigNum *r = BN_Create(pBits + 1);
BN_Optimizer *opt = BN_OptimizerCreate();
int32_t ret;
if (r == NULL || opt == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
// judgment of numeric values
// r = p - 1
ret = BN_SubLimb(r, p, 1);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
// q < p - 1
if (BN_Cmp(q, r) >= 0) {
ret = CRYPT_DSA_ERR_KEY_PARA;
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
// g < p - 1
if (BN_Cmp(g, r) >= 0) {
ret = CRYPT_DSA_ERR_KEY_PARA;
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
// judgment of multiple relationship about p & q
ret = BN_Div(NULL, r, r, q, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
// (p - 1) % q == 0
if (!BN_IsZero(r)) {
ret = CRYPT_DSA_ERR_KEY_PARA;
BSL_ERR_PUSH_ERROR(ret);
}
EXIT:
BN_Destroy(r);
BN_OptimizerDestroy(opt);
return ret;
}
static int32_t ParaDataCheck(const CRYPT_DSA_Para *para)
{
const BN_BigNum *p = para->p;
const BN_BigNum *q = para->q;
const BN_BigNum *g = para->g;
// 1. judge validity of length
uint32_t pBits = BN_Bits(p);
if (pBits < DSA_MIN_PBITS || pBits > DSA_MAX_PBITS) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_KEY_PARA);
return CRYPT_DSA_ERR_KEY_PARA;
}
if (BN_Bits(q) < DSA_MIN_QBITS) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_KEY_PARA);
return CRYPT_DSA_ERR_KEY_PARA;
}
// 2. parity judgment of p & q and value judgment of g
// p is an odd number && q is an odd number
if (BN_GetBit(p, 0) == 0 || BN_GetBit(q, 0) == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_KEY_PARA);
return CRYPT_DSA_ERR_KEY_PARA;
}
// g != 1 && g != 0
if (BN_IsOne(g) || BN_IsZero(g)) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_KEY_PARA);
return CRYPT_DSA_ERR_KEY_PARA;
}
// This interface is invoked only here, and pushErr is performed internally.
// If this interface fails, pushErr does not need to be invoked.
return ParaPQGCheck(p, q, g);
}
static CRYPT_DSA_Para *ParaDup(const CRYPT_DSA_Para *para)
{
CRYPT_DSA_Para *ret = BSL_SAL_Malloc(sizeof(CRYPT_DSA_Para));
if (ret == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
ret->p = BN_Dup(para->p);
ret->q = BN_Dup(para->q);
ret->g = BN_Dup(para->g);
if (ret->p == NULL || ret->q == NULL || ret->g == NULL) {
CRYPT_DSA_FreePara(ret);
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_KEY_PARA);
return NULL;
}
return ret;
}
int32_t CRYPT_DSA_SetPara(CRYPT_DSA_Ctx *ctx, const CRYPT_DsaPara *para)
{
if (ctx == NULL || para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_DSA_Para *dsaPara = CRYPT_DSA_NewPara(para);
if (dsaPara == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_NEW_PARA_FAIL);
return CRYPT_EAL_ERR_NEW_PARA_FAIL;
}
int32_t ret = ParaDataCheck(dsaPara);
if (ret != CRYPT_SUCCESS) {
CRYPT_DSA_FreePara(dsaPara);
return ret;
}
BN_Destroy(ctx->x);
BN_Destroy(ctx->y);
CRYPT_DSA_FreePara(ctx->para);
ctx->x = NULL;
ctx->y = NULL;
ctx->para = dsaPara;
return CRYPT_SUCCESS;
}
int32_t CRYPT_DSA_GetPara(const CRYPT_DSA_Ctx *ctx, CRYPT_DsaPara *para)
{
if (ctx == NULL || para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_PARA_ERROR);
return CRYPT_DSA_PARA_ERROR;
}
int32_t ret = BN_Bn2Bin(ctx->para->p, para->p, &(para->pLen));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = BN_Bn2Bin(ctx->para->q, para->q, &(para->qLen));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = BN_Bn2Bin(ctx->para->g, para->g, &(para->gLen));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
CRYPT_DSA_Ctx *CRYPT_DSA_DupCtx(CRYPT_DSA_Ctx *dsaCtx)
{
if (dsaCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return NULL;
}
CRYPT_DSA_Ctx *dsaNewCtx = BSL_SAL_Malloc(sizeof(CRYPT_DSA_Ctx));
if (dsaNewCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
(void)memset_s(dsaNewCtx, sizeof(CRYPT_DSA_Ctx), 0, sizeof(CRYPT_DSA_Ctx));
GOTO_ERR_IF_SRC_NOT_NULL(dsaNewCtx->x, dsaCtx->x, BN_Dup(dsaCtx->x), CRYPT_MEM_ALLOC_FAIL);
GOTO_ERR_IF_SRC_NOT_NULL(dsaNewCtx->y, dsaCtx->y, BN_Dup(dsaCtx->y), CRYPT_MEM_ALLOC_FAIL);
GOTO_ERR_IF_SRC_NOT_NULL(dsaNewCtx->para, dsaCtx->para, ParaDup(dsaCtx->para), CRYPT_MEM_ALLOC_FAIL);
GOTO_ERR_IF_SRC_NOT_NULL(dsaNewCtx->mdAttr, dsaCtx->mdAttr, BSL_SAL_Dump(dsaCtx->mdAttr,
strlen(dsaCtx->mdAttr) + 1), CRYPT_MEM_ALLOC_FAIL);
dsaNewCtx->libCtx = dsaCtx->libCtx;
BSL_SAL_ReferencesInit(&(dsaNewCtx->references));
return dsaNewCtx;
ERR:
CRYPT_DSA_FreeCtx(dsaNewCtx);
return NULL;
}
uint32_t CRYPT_DSA_GetBits(const CRYPT_DSA_Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return 0;
}
if (ctx->para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_KEY_PARA);
return 0;
}
return BN_Bits(ctx->para->p);
}
uint32_t CRYPT_DSA_GetSignLen(const CRYPT_DSA_Ctx *ctx)
{
if (ctx == NULL || ctx->para == NULL) {
return 0;
}
uint32_t qLen = BN_Bytes(ctx->para->q);
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;
}
/* x != 0 && x < q */
int32_t CRYPT_DSA_SetPrvKey(CRYPT_DSA_Ctx *ctx, const CRYPT_DsaPrv *prv)
{
if (ctx == NULL || prv == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (InputBufferCheck(prv->data, prv->len)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_KEY_PARA);
return CRYPT_DSA_ERR_KEY_PARA;
}
if (BN_Bytes(ctx->para->q) < prv->len) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_KEY_INFO);
return CRYPT_DSA_ERR_KEY_INFO;
}
BN_BigNum *bnX = BN_Create(prv->len * 8);
if (bnX == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
int32_t ret = BN_Bin2Bn(bnX, prv->data, prv->len);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
// x < q
if (BN_Cmp(bnX, ctx->para->q) >= 0) {
ret = CRYPT_DSA_ERR_KEY_INFO;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
// x != 0
if (BN_IsZero(bnX)) {
ret = CRYPT_DSA_ERR_KEY_INFO;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
BN_Destroy(ctx->x);
ctx->x = bnX;
return ret;
ERR:
BN_Destroy(bnX);
return ret;
}
/* y != 0 && y != 1 && y < p */
int32_t CRYPT_DSA_SetPubKey(CRYPT_DSA_Ctx *ctx, const CRYPT_DsaPub *pub)
{
if (ctx == NULL || pub == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (InputBufferCheck(pub->data, pub->len)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_KEY_PARA);
return CRYPT_DSA_ERR_KEY_PARA;
}
if (BN_Bytes(ctx->para->p) < pub->len) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_KEY_INFO);
return CRYPT_DSA_ERR_KEY_INFO;
}
BN_BigNum *bnY = BN_Create(pub->len * 8); // bits = bytes * 8
if (bnY == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
int32_t ret = BN_Bin2Bn(bnY, pub->data, pub->len);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
// y < p
if (BN_Cmp(bnY, ctx->para->p) >= 0) {
ret = CRYPT_DSA_ERR_KEY_INFO;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
// y != 0 && y != 1
if (BN_IsZero(bnY) || BN_IsOne(bnY)) {
ret = CRYPT_DSA_ERR_KEY_INFO;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
BN_Destroy(ctx->y);
ctx->y = bnY;
return CRYPT_SUCCESS;
ERR:
BN_Destroy(bnY);
return ret;
}
int32_t CRYPT_DSA_GetPrvKey(const CRYPT_DSA_Ctx *ctx, CRYPT_DsaPrv *prv)
{
if (ctx == NULL || prv == NULL || prv->data == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_KEY_PARA);
return CRYPT_DSA_ERR_KEY_PARA;
}
if (ctx->x == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_KEY_INFO);
return CRYPT_DSA_ERR_KEY_INFO;
}
if (BN_Bytes(ctx->para->q) > prv->len) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_BUFF_LEN_NOT_ENOUGH);
return CRYPT_DSA_BUFF_LEN_NOT_ENOUGH;
}
int32_t ret = BN_Bn2Bin(ctx->x, prv->data, &(prv->len));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
int32_t CRYPT_DSA_GetPubKey(const CRYPT_DSA_Ctx *ctx, CRYPT_DsaPub *pub)
{
if (ctx == NULL || pub == NULL || pub->data == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->y == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_KEY_INFO);
return CRYPT_DSA_ERR_KEY_INFO;
}
if (ctx->para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_KEY_PARA);
return CRYPT_DSA_ERR_KEY_PARA;
}
if (BN_Bytes(ctx->para->p) > pub->len) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_BUFF_LEN_NOT_ENOUGH);
return CRYPT_DSA_BUFF_LEN_NOT_ENOUGH;
}
int32_t ret = BN_Bn2Bin(ctx->y, pub->data, &(pub->len));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
#ifdef HITLS_BSL_PARAMS
int32_t CRYPT_DSA_SetParaEx(CRYPT_DSA_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_DSA_P) == NULL) {
return CRYPT_SUCCESS;
}
CRYPT_DsaPara dsaPara = {0};
(void)GetConstParamValue(para, CRYPT_PARAM_DSA_P, &dsaPara.p, &dsaPara.pLen);
(void)GetConstParamValue(para, CRYPT_PARAM_DSA_Q, &dsaPara.q, &dsaPara.qLen);
(void)GetConstParamValue(para, CRYPT_PARAM_DSA_G, &dsaPara.g, &dsaPara.gLen);
return CRYPT_DSA_SetPara(ctx, &dsaPara);
}
int32_t CRYPT_DSA_GetParaEx(const CRYPT_DSA_Ctx *ctx, BSL_Param *para)
{
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_DsaPara eccPara = {0};
BSL_Param *paramP = GetParamValue(para, CRYPT_PARAM_DSA_P, &eccPara.p, &eccPara.pLen);
BSL_Param *paramQ = GetParamValue(para, CRYPT_PARAM_DSA_Q, &eccPara.q, &eccPara.qLen);
BSL_Param *paramG = GetParamValue(para, CRYPT_PARAM_DSA_G, &eccPara.g, &eccPara.gLen);
int32_t ret = CRYPT_DSA_GetPara(ctx, &eccPara);
if (ret != CRYPT_SUCCESS) {
return ret;
}
paramP->useLen = eccPara.pLen;
paramQ->useLen = eccPara.qLen;
paramG->useLen = eccPara.gLen;
return ret;
}
int32_t CRYPT_DSA_SetPrvKeyEx(CRYPT_DSA_Ctx *ctx, const BSL_Param *para)
{
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_DsaPrv dsaPrv = {0};
(void)GetConstParamValue(para, CRYPT_PARAM_DSA_PRVKEY, &dsaPrv.data, &dsaPrv.len);
return CRYPT_DSA_SetPrvKey(ctx, &dsaPrv);
}
int32_t CRYPT_DSA_SetPubKeyEx(CRYPT_DSA_Ctx *ctx, const BSL_Param *para)
{
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_DsaPub dsaPub = {0};
(void)GetConstParamValue(para, CRYPT_PARAM_DSA_PUBKEY, &dsaPub.data, &dsaPub.len);
return CRYPT_DSA_SetPubKey(ctx, &dsaPub);
}
int32_t CRYPT_DSA_GetPrvKeyEx(const CRYPT_DSA_Ctx *ctx, BSL_Param *para)
{
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_DsaPrv dsaPrv = {0};
BSL_Param *paramPrv = GetParamValue(para, CRYPT_PARAM_DSA_PRVKEY, &dsaPrv.data, &dsaPrv.len);
int32_t ret = CRYPT_DSA_GetPrvKey(ctx, &dsaPrv);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if (paramPrv != NULL) {
paramPrv->useLen = dsaPrv.len;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_DSA_GetPubKeyEx(const CRYPT_DSA_Ctx *ctx, BSL_Param *para)
{
if (para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
CRYPT_DsaPub dsaPub = {0};
BSL_Param *paramPub = GetParamValue(para, CRYPT_PARAM_DSA_PUBKEY, &dsaPub.data, &dsaPub.len);
int32_t ret = CRYPT_DSA_GetPubKey(ctx, &dsaPub);
if (ret != CRYPT_SUCCESS) {
return ret;
}
if (paramPub != NULL) {
paramPub->useLen = dsaPub.len;
}
return CRYPT_SUCCESS;
}
#endif
static int32_t RandRangeQ(void *libCtx, BN_BigNum *r, const BN_BigNum *q)
{
int32_t cnt = 0;
for (cnt = 0; cnt < CRYPT_DSA_TRY_MAX_CNT; cnt++) {
int32_t ret = BN_RandRangeEx(libCtx, r, q);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (BN_IsZero(r)) {
continue;
}
return CRYPT_SUCCESS; // if succeed then exit
}
/* If the key fails to be generated after try CRYPT_DSA_TRI_MAX_CNT times, then failed and exit. */
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_TRY_CNT);
return CRYPT_DSA_ERR_TRY_CNT;
}
static void RefreshCtx(CRYPT_DSA_Ctx *ctx, BN_BigNum *x, BN_BigNum *y, int32_t ret)
{
if (ret == CRYPT_SUCCESS) {
BN_Destroy(ctx->x);
BN_Destroy(ctx->y);
ctx->x = x;
ctx->y = y;
} else {
BN_Destroy(x);
BN_Destroy(y);
}
}
/* Security length from NIST.FIPS.186-4 4.2 */
static uint32_t DSAFips1864ValidateSecurityLength(uint32_t pBits, uint32_t qBits, int isGen, int type)
{
if (type == CRYPT_DSA_FFC_PARAM) {
if (pBits == 3072 && qBits == 256) { // If Pbits = 3072 and Qbits = 256.
return 128; // Secure length is 128.
}
if (pBits == 2048 && (qBits == 224 || qBits == 256)) { // If Pbits = 2048 and Qbits = 224 or 256.
return 112; // Secure length is 112.
}
/* Security strength of 80 bits is no longer considered adequate, and is retained only for compatibility. */
if (isGen == 1) {
return 0;
}
if (pBits == 1024 && qBits == 160) { // If Pbits = 1024 and Qbits = 160.
return 80; // Secure length is 80.
}
} else if (type == CRYPT_DH_FFC_PARAM) {
if (pBits == 2048 && (qBits == 224 || qBits == 256)) { // If Pbits = 2048 and Qbits = 224 or 256.
return 112; // Secure length is 112.
}
}
return 0;
}
// fips186-4 A.2.2
int32_t CryptDsaFips1864PartialValidateG(const CRYPT_DSA_Para *dsaPara)
{
if (BN_IsNegative(dsaPara->g) == true || BN_IsZero(dsaPara->g) == true || BN_IsOne(dsaPara->g) == true) { // g < 2
BSL_ERR_PUSH_ERROR(CRYPT_DSA_VERIFY_FAIL);
return CRYPT_DSA_VERIFY_FAIL;
}
int32_t ret;
BN_Optimizer *opt = BN_OptimizerCreate();
RETURN_RET_IF(opt == NULL, CRYPT_MEM_ALLOC_FAIL);
(void)OptimizerStart(opt);
uint32_t pBits = BN_Bits(dsaPara->p);
BN_BigNum *p_1 = OptimizerGetBn(opt, BITS_TO_BN_UNIT(pBits));
if (p_1 == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
ret = CRYPT_MEM_ALLOC_FAIL;
goto ERR;
}
ret = BN_SubLimb(p_1, dsaPara->p, 1);
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
if (BN_Cmp(dsaPara->g, p_1) > 0) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_VERIFY_FAIL);
ret = CRYPT_DSA_VERIFY_FAIL;
goto ERR;
}
ret = BN_ModExp(p_1, dsaPara->g, dsaPara->q, dsaPara->p, opt);
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
if (BN_IsOne(p_1) != true) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_VERIFY_FAIL);
ret = CRYPT_DSA_VERIFY_FAIL;
}
ERR:
OptimizerEnd(opt);
BN_OptimizerDestroy(opt);
return ret;
}
// Generate private key, from SP800-56Ar3 5_6_1_1_4
static int32_t DSA_GenPrivateKey(void *libCtx, const CRYPT_DSA_Para *para, BN_BigNum *privKey)
{
uint32_t pBits = BN_Bits(para->p);
uint32_t qBits = BN_Bits(para->q);
RETURN_RET_IF(DSAFips1864ValidateSecurityLength(pBits, qBits, 1, CRYPT_DSA_FFC_PARAM) == 0, CRYPT_DSA_PARA_ERROR);
int32_t ret = CryptDsaFips1864PartialValidateG(para);
RETURN_RET_IF(ret != CRYPT_SUCCESS, ret);
ret = CRYPT_MEM_ALLOC_FAIL;
BN_BigNum *pow = BN_Create(qBits + 1);
GOTO_ERR_IF_TRUE(pow == NULL, ret);
GOTO_ERR_IF(BN_SetLimb(pow, 1), ret);
GOTO_ERR_IF(BN_Lshift(pow, pow, qBits), ret);
BN_BigNum *min = pow;
if (BN_Cmp(min, para->q) > 0) {
min = para->q;
}
while (true) {
GOTO_ERR_IF(RandRangeQ(libCtx, privKey, pow), ret); // c
GOTO_ERR_IF(BN_AddLimb(privKey, privKey, 1), ret); // c + 1
if (BN_Cmp(privKey, min) < 0) { // c <= min - 2 equal to c + 1 < min.
break;
}
}
ERR:
if (ret != CRYPT_SUCCESS) {
(void)BN_Zeroize(privKey);
}
BN_Destroy(pow);
return ret;
}
int32_t CRYPT_DSA_Gen(CRYPT_DSA_Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_KEY_PARA);
return CRYPT_DSA_ERR_KEY_PARA;
}
int32_t ret = CRYPT_SUCCESS;
int32_t cnt;
BN_BigNum *x = BN_Create(BN_Bits(ctx->para->q));
BN_BigNum *y = BN_Create(BN_Bits(ctx->para->p));
BN_Mont *mont = BN_MontCreate(ctx->para->p);
BN_Optimizer *opt = BN_OptimizerCreate();
if (x == NULL || y == NULL || opt == NULL || mont == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
for (cnt = 0; cnt < CRYPT_DSA_TRY_MAX_CNT; cnt++) {
/* Generate the private key x of [1, q-1], see RFC6979-2.2. */
if ((ctx->flag & CRYPT_ENABLE_SP800_KEYGEN_FLAG) != 0) {
ret = DSA_GenPrivateKey(ctx->libCtx, ctx->para, x);
} else {
ret = RandRangeQ(ctx->libCtx, x, ctx->para->q);
}
if (ret != CRYPT_SUCCESS) {
// Internal API, the BSL_ERR_PUSH_ERROR info is already exists when failed.
goto ERR;
}
/* Calculate the public key y. */
ret = BN_MontExpConsttime(y, ctx->para->g, x, mont, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
/* y != 0 && y != 1 */
if (BN_IsZero(y) || BN_IsOne(y)) {
continue;
}
goto ERR; // If succeed then exit.
}
/* If the key fails to be generated after try CRYPT_DSA_TRY_MAX_CNT times, then failed and exit. */
ret = CRYPT_DSA_ERR_TRY_CNT;
BSL_ERR_PUSH_ERROR(ret);
ERR:
RefreshCtx(ctx, x, y, ret);
BN_MontDestroy(mont);
BN_OptimizerDestroy(opt);
return ret;
}
// Get the input hash data, see RFC6979-2.4.1 and RFC6979-2.3.2
static BN_BigNum *DSA_Bits2Int(BN_BigNum *q, const uint8_t *data, uint32_t dataLen)
{
BN_BigNum *d = BN_Create(BN_Bits(q)); // 1 byte = 8 bits
if (d == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
if (data != NULL) {
uint32_t qLen = BN_Bytes(q);
uint32_t dLen = (dataLen < qLen) ? dataLen : qLen;
// The input parameters of the function have been verified, and no failure exists.
(void)BN_Bin2Bn(d, data, dLen);
}
return d;
}
// s = (h + x*r)*k^-1 mod q
// s' = (h*blind + x*r*blind)*k^-1*blind^-1 mod q
// s == s'
static int32_t CalcSValue(const CRYPT_DSA_Ctx *ctx, BN_BigNum *r, BN_BigNum *s, BN_BigNum *k,
BN_BigNum *d, BN_Optimizer *opt)
{
BN_BigNum *blind = BN_Create(BN_Bits(ctx->para->q));
if (blind == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
BN_BigNum *blindm = BN_Create(BN_Bits(ctx->para->q));
if (blindm == NULL) {
BN_Destroy(blind);
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
int32_t ret;
GOTO_ERR_IF(RandRangeQ(ctx->libCtx, blind, ctx->para->q), ret);
GOTO_ERR_IF(BN_ModMul(s, blind, ctx->x, ctx->para->q, opt), ret);
GOTO_ERR_IF(BN_ModMul(s, s, r, ctx->para->q, opt), ret);
GOTO_ERR_IF(BN_ModMul(blindm, blind, d, ctx->para->q, opt), ret);
GOTO_ERR_IF(BN_ModAdd(s, s, blindm, ctx->para->q, opt), ret);
GOTO_ERR_IF(BN_ModInv(k, k, ctx->para->q, opt), ret);
GOTO_ERR_IF(BN_ModMul(s, s, k, ctx->para->q, opt), ret);
GOTO_ERR_IF(BN_ModInv(blind, blind, ctx->para->q, opt), ret);
GOTO_ERR_IF(BN_ModMul(s, s, blind, ctx->para->q, opt), ret);
ERR:
BN_Destroy(blind);
BN_Destroy(blindm);
return ret;
}
static int32_t SignCore(const CRYPT_DSA_Ctx *ctx, BN_BigNum *d, BN_BigNum *r,
BN_BigNum *s)
{
int32_t cnt = 0;
int32_t ret = CRYPT_SUCCESS;
BN_BigNum *k = BN_Create(BN_Bits(ctx->para->q));
BN_Mont *montP = BN_MontCreate(ctx->para->p);
BN_Optimizer *opt = BN_OptimizerCreate();
if (k == NULL || montP == NULL || opt == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
for (cnt = 0; cnt < CRYPT_DSA_TRY_MAX_CNT; cnt++) {
// Generate random number k of [1, q-1], see RFC6979-2.4.2 */
ret = RandRangeQ(ctx->libCtx, k, ctx->para->q);
if (ret != CRYPT_SUCCESS) {
// Internal function. The BSL_ERR_PUSH_ERROR information exists when the failure occurs.
goto EXIT;
}
// Compute r = g^k mod p mod q, see RFC6979-2.4.3 */
ret = BN_MontExpConsttime(r, ctx->para->g, k, montP, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BN_Mod(r, r, ctx->para->q, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
if (BN_IsZero(r)) {
continue;
}
// Compute s = (h+x*sign->r)/k mod q, see RFC6979-2.4.4 */
ret = CalcSValue(ctx, r, s, k, d, opt);
if (ret != CRYPT_SUCCESS) {
goto EXIT;
}
if (BN_IsZero(s)) {
continue;
}
goto EXIT; // The signature generation meets the requirements and exits successfully.
}
ret = CRYPT_DSA_ERR_TRY_CNT;
BSL_ERR_PUSH_ERROR(ret);
EXIT:
BN_Destroy(k);
BN_MontDestroy(montP);
BN_OptimizerDestroy(opt);
return ret;
}
static int32_t CryptDsaSign(const CRYPT_DSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen, BN_BigNum **r,
BN_BigNum **s)
{
int32_t ret;
BN_BigNum *signR = NULL;
BN_BigNum *signS = NULL;
BN_BigNum *d = DSA_Bits2Int(ctx->para->q, data, dataLen);
if (d == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
signR = BN_Create(BN_Bits(ctx->para->p));
signS = BN_Create(BN_Bits(ctx->para->q));
if ((signR == NULL) || (signS == NULL)) {
BN_Destroy(d);
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
ret = CRYPT_MEM_ALLOC_FAIL;
goto ERR;
}
ret = SignCore(ctx, d, signR, signS);
BN_Destroy(d);
if (ret != CRYPT_SUCCESS) {
goto ERR;
}
*r = signR;
*s = signS;
return ret;
ERR:
BN_Destroy(signR);
BN_Destroy(signS);
return ret;
}
// Data with a value of 0 can also be signed.
int32_t CRYPT_DSA_SignData(const CRYPT_DSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen,
uint8_t *sign, uint32_t *signLen)
{
if (ctx == NULL || sign == NULL || signLen == NULL || (data == NULL && dataLen != 0)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_KEY_PARA);
return CRYPT_DSA_ERR_KEY_PARA;
}
if (ctx->x == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_KEY_INFO);
return CRYPT_DSA_ERR_KEY_INFO;
}
if (*signLen < CRYPT_DSA_GetSignLen(ctx)) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_BUFF_LEN_NOT_ENOUGH);
return CRYPT_DSA_BUFF_LEN_NOT_ENOUGH;
}
int32_t ret;
BN_BigNum *r = NULL;
BN_BigNum *s = NULL;
ret = CryptDsaSign(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_DSA_Sign(const CRYPT_DSA_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_DSA_SignData(ctx, hash, hashLen, sign, signLen);
}
static int32_t VerifyCore(const CRYPT_DSA_Ctx *ctx, BN_BigNum *d, BN_BigNum *r, BN_BigNum *s)
{
int32_t ret = CRYPT_MEM_ALLOC_FAIL;
BN_BigNum *u1 = BN_Create(BN_Bits(ctx->para->p));
BN_BigNum *u2 = BN_Create(BN_Bits(ctx->para->p));
BN_BigNum *w = BN_Create(BN_Bits(ctx->para->q));
BN_Mont *montP = BN_MontCreate(ctx->para->p);
BN_Optimizer *opt = BN_OptimizerCreate();
if (u1 == NULL || u2 == NULL || w == NULL || montP == NULL || opt == NULL) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
/* Calculate w = 1/s mod q
* u1 = (d * w) mod q
* u2 = (r * w) mod q
* u1 = (g ^ u1) mod p
* u2 = (y ^ u2) mod p
* v = (u1 * u2) mod p
* v = v mod q
* If v == r, sign verification is succeeded.
*/
ret = BN_ModInv(w, s, ctx->para->q, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BN_ModMul(u1, d, w, ctx->para->q, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BN_ModMul(u2, r, w, ctx->para->q, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BN_MontExpMul(u1, ctx->para->g, u1, ctx->y, u2, montP, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BN_Mod(u1, u1, ctx->para->q, opt);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
ret = BN_Cmp(u1, r);
if (ret != 0) {
BSL_ERR_PUSH_ERROR(ret);
ret = CRYPT_DSA_VERIFY_FAIL;
}
EXIT:
BN_Destroy(u1);
BN_Destroy(u2);
BN_Destroy(w);
BN_MontDestroy(montP);
BN_OptimizerDestroy(opt);
return ret;
}
int32_t CRYPT_DSA_VerifyData(const CRYPT_DSA_Ctx *ctx, const uint8_t *data, uint32_t dataLen,
const uint8_t *sign, uint32_t signLen)
{
if (ctx == NULL || sign == NULL || signLen == 0 || (data == NULL && dataLen != 0)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->para == NULL || ctx->y == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_KEY_INFO);
return CRYPT_DSA_ERR_KEY_INFO;
}
int32_t ret;
BN_BigNum *r = BN_Create(BN_Bits(ctx->para->p));
BN_BigNum *s = BN_Create(BN_Bits(ctx->para->q));
BN_BigNum *d = DSA_Bits2Int(ctx->para->q, data, dataLen);
if (r == NULL || s == NULL || d == NULL) {
ret = CRYPT_MEM_ALLOC_FAIL;
goto EXIT;
}
ret = CRYPT_EAL_DecodeSign(sign, signLen, r, s);
if (ret != CRYPT_SUCCESS) {
goto EXIT;
}
ret = VerifyCore(ctx, d, r, s);
EXIT:
BN_Destroy(r);
BN_Destroy(s);
BN_Destroy(d);
return ret;
}
int32_t CRYPT_DSA_Verify(const CRYPT_DSA_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_DSA_VerifyData(ctx, hash, hashLen, sign, signLen);
}
int32_t CRYPT_DSA_Cmp(const CRYPT_DSA_Ctx *a, const CRYPT_DSA_Ctx *b)
{
RETURN_RET_IF(a == NULL || b == NULL, CRYPT_NULL_INPUT);
RETURN_RET_IF(a->y == NULL || b->y == NULL, CRYPT_DSA_ERR_KEY_INFO);
RETURN_RET_IF(BN_Cmp(a->y, b->y) != 0, CRYPT_DSA_PUBKEY_NOT_EQUAL);
// para must be both NULL and non-NULL.
RETURN_RET_IF((a->para == NULL) != (b->para == NULL), CRYPT_DSA_PARA_ERROR);
if (a->para != NULL) {
RETURN_RET_IF(BN_Cmp(a->para->p, b->para->p) != 0 ||
BN_Cmp(a->para->q, b->para->q) != 0 ||
BN_Cmp(a->para->g, b->para->g) != 0,
CRYPT_DSA_PARA_NOT_EQUAL);
}
return CRYPT_SUCCESS;
}
static uint32_t CRYPT_DSA_GetPrvKeyLen(const CRYPT_DSA_Ctx *ctx)
{
return BN_Bytes(ctx->x);
}
static uint32_t CRYPT_DSA_GetPubKeyLen(const CRYPT_DSA_Ctx *ctx)
{
if (ctx->para != NULL) {
return BN_Bytes(ctx->para->p);
}
if (ctx->y != NULL) {
return BN_Bytes(ctx->y);
}
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return 0;
}
int32_t CRYPT_DSA_GetSecBits(const CRYPT_DSA_Ctx *ctx)
{
if (ctx == NULL || ctx->para == NULL || ctx->para->p == NULL || ctx->para->q == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return 0;
}
return BN_SecBits((int32_t)BN_Bits(ctx->para->p), (int32_t)BN_Bits(ctx->para->q));
}
#ifdef HITLS_CRYPTO_DSA_GEN_PARA
static int32_t GetDsaParamValue(const BSL_Param *params, int32_t paramId, uint32_t maxLen,
const uint8_t **value, uint32_t *valueLen)
{
const BSL_Param *param = BSL_PARAM_FindConstParam(params, paramId);
if (param == NULL || param->value == NULL || param->valueLen > maxLen || param->valueLen == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_KEY_PARA);
return CRYPT_DSA_ERR_KEY_PARA;
}
*value = param->value;
*valueLen = param->valueLen;
return CRYPT_SUCCESS;
}
static int32_t DSAFips1864GenQ(int32_t algId, void *libCtx, const char *mdAttr, uint32_t qBits,
const uint8_t *seed, uint32_t seedLen, BN_BigNum *q)
{
uint8_t hash[64] = {0}; // 64 is max hash len
uint32_t hashLen = sizeof(hash) / sizeof(hash[0]);
int32_t ret = EAL_Md(algId, libCtx, mdAttr, seed, seedLen, hash, &hashLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
uint8_t *md = hash;
uint32_t qLen = qBits >> 3;
if (hashLen > qLen) {
md = hash + (hashLen - qLen);
}
md[0] |= 0x80;
md[qLen - 1] |= 0x01;
ret = BN_Bin2Bn(q, md, qLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
static int32_t DSAFips1864GenP(DSA_FIPS186_4_Para *fipsPara, const BN_BigNum *pow,
BN_Optimizer *opt, BSL_Buffer *seed, CRYPT_DSA_Para *dsaPara, void *libCtx, const char *mdAttr)
{
uint8_t hash[64]; // 64 is max hash len
uint32_t hashLen;
uint32_t outLen = CRYPT_GetMdSizeById(fipsPara->algId) * 8; // bytes * 8 = bits
RETURN_RET_IF(outLen == 0, CRYPT_EAL_ERR_ALGID);
uint32_t n = (fipsPara->l - 1) / outLen; // ((pBits + outLen - 1) / outLen) - 1
int32_t ret = OptimizerStart(opt);
RETURN_RET_IF(ret != CRYPT_SUCCESS, ret);
BN_BigNum *V = OptimizerGetBn(opt, BITS_TO_BN_UNIT(outLen));
if (V == NULL) {
OptimizerEnd(opt);
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
for (uint32_t j = 0; j <= n; j++) {
for (uint32_t k = 0; k < seed->dataLen; k++) {
seed->data[seed->dataLen - k - 1]++;
if (seed->data[seed->dataLen - k - 1] != 0) { // no carry
break;
}
}
hashLen = sizeof(hash) / sizeof(hash[0]);
(void)memset_s(hash, hashLen, 0, hashLen);
ret = EAL_Md(fipsPara->algId, libCtx, mdAttr, seed->data, seed->dataLen, hash, &hashLen);
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
ret = BN_Bin2Bn(V, hash, hashLen);
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
ret = BN_Lshift(V, V, outLen * j);
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
ret = BN_Add(dsaPara->p, dsaPara->p, V);
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
}
ret = BN_MaskBit(dsaPara->p, fipsPara->l - 1);
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
ret = BN_Add(V, pow, dsaPara->p);
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
ret = BN_Lshift(dsaPara->p, dsaPara->q, 1);
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
ret = BN_Mod(dsaPara->p, V, dsaPara->p, opt);
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
ret = BN_SubLimb(dsaPara->p, dsaPara->p, 1);
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
ret = BN_Sub(dsaPara->p, V, dsaPara->p);
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
OptimizerEnd(opt);
return CRYPT_SUCCESS;
ERR:
(void)BN_Zeroize(dsaPara->p);
OptimizerEnd(opt);
return ret;
}
static int32_t SetPQ2Para(CRYPT_DSA_Para *destPara, const CRYPT_DSA_Para *srcPara)
{
uint32_t pBits = BN_Bits(srcPara->p);
uint32_t qBits = BN_Bits(srcPara->q);
BN_BigNum *pOut = BN_Create(pBits);
if (pOut == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
BN_BigNum *qOut = BN_Create(qBits);
if (qOut == NULL) {
BN_Destroy(pOut);
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
int32_t ret = BN_Copy(pOut, srcPara->p);
if (ret != CRYPT_SUCCESS) {
BN_Destroy(pOut);
BN_Destroy(qOut);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = BN_Copy(qOut, srcPara->q);
if (ret != CRYPT_SUCCESS) {
BN_Destroy(pOut);
BN_Destroy(qOut);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
BN_Destroy(destPara->p);
BN_Destroy(destPara->q);
destPara->p = pOut;
destPara->q = qOut;
return CRYPT_SUCCESS;
}
// fips186-4 A.1.1.2
int32_t CryptDsaFips1864GenPq(CRYPT_DSA_Ctx *ctx, DSA_FIPS186_4_Para *fipsPara, uint32_t type,
BSL_Buffer *seed, uint32_t *counter)
{
BSL_Buffer msg = {NULL, 0};
RETURN_RET_IF(DSAFips1864ValidateSecurityLength(fipsPara->l, fipsPara->n, 1, type) == 0, CRYPT_DSA_PARA_ERROR);
uint32_t outLen = CRYPT_GetMdSizeById(fipsPara->algId);
RETURN_RET_IF(seed->dataLen * 8 < fipsPara->n || outLen * 8 < fipsPara->n, CRYPT_DSA_PARA_ERROR); // from FIPS.186-4
BN_Optimizer *opt = BN_OptimizerCreate();
RETURN_RET_IF(opt == NULL, CRYPT_MEM_ALLOC_FAIL);
(void)OptimizerStart(opt);
BN_BigNum *pow = OptimizerGetBn(opt, BITS_TO_BN_UNIT(fipsPara->l));
BN_BigNum *pTmp = OptimizerGetBn(opt, BITS_TO_BN_UNIT(fipsPara->l));
BN_BigNum *qTmp = OptimizerGetBn(opt, BITS_TO_BN_UNIT(fipsPara->n));
msg.dataLen = seed->dataLen;
msg.data = (uint8_t *)BSL_SAL_Calloc(seed->dataLen, 1);
int32_t ret = CRYPT_MEM_ALLOC_FAIL;
GOTO_ERR_IF_TRUE(pow == NULL || pTmp == NULL || qTmp == NULL || msg.data == NULL, ret);
CRYPT_DSA_Para dsaParaTmp = {pTmp, qTmp, NULL};
GOTO_ERR_IF(BN_SetLimb(pow, 1), ret);
GOTO_ERR_IF(BN_Lshift(pow, pow, fipsPara->l - 1), ret);
while (true) { // until valid p,q or error occurs.
/* Generate Q */
GOTO_ERR_IF(CRYPT_RandEx(ctx->libCtx, seed->data, seed->dataLen), ret);
(void)memcpy_s(msg.data, seed->dataLen, seed->data, seed->dataLen);
GOTO_ERR_IF(DSAFips1864GenQ(fipsPara->algId, ctx->libCtx, ctx->mdAttr, fipsPara->n, seed->data, seed->dataLen,
qTmp), ret);
ret = BN_PrimeCheck(qTmp, 0, opt, NULL);
if (ret == CRYPT_BN_NOR_CHECK_PRIME) {
continue;
}
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
/* Generate P */
uint32_t cntMax = 4 * fipsPara->l - 1; // 4 * fipsPara->l - 1 from FIPS.186-4.
for (uint32_t cnt = 0; cnt <= cntMax; cnt++) {
GOTO_ERR_IF(BN_Zeroize(pTmp), ret);
GOTO_ERR_IF(DSAFips1864GenP(fipsPara, pow, opt, &msg, &dsaParaTmp, ctx->libCtx, ctx->mdAttr), ret);
if (BN_Cmp(pTmp, pow) < 0) {
continue;
}
ret = BN_PrimeCheck(pTmp, 0, opt, NULL);
if (ret == CRYPT_BN_NOR_CHECK_PRIME) {
continue;
}
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
GOTO_ERR_IF(SetPQ2Para(ctx->para, &dsaParaTmp), ret);
*counter = cnt;
goto ERR; // success
}
}
ERR:
BSL_SAL_ClearFree(msg.data, msg.dataLen);
OptimizerEnd(opt);
BN_OptimizerDestroy(opt);
return ret;
}
// fips186-4 A.1.1.3
int32_t CryptDsaFips1864ValidatePq(int32_t algId, void *libCtx, const char *mdAttr, uint32_t type,
BSL_Buffer *seed, CRYPT_DSA_Para *dsaPara, uint32_t counter)
{
BSL_Buffer msg = {NULL, 0};
uint32_t pBits = BN_Bits(dsaPara->p);
uint32_t qBits = BN_Bits(dsaPara->q);
RETURN_RET_IF(DSAFips1864ValidateSecurityLength(pBits, qBits, 0, type) == 0, CRYPT_DSA_PARA_ERROR);
RETURN_RET_IF(seed->dataLen * 8 < qBits || counter > 4 * pBits - 1, CRYPT_DSA_PARA_ERROR); // from FIPS.186-4
BN_Optimizer *opt = BN_OptimizerCreate();
RETURN_RET_IF(opt == NULL, CRYPT_MEM_ALLOC_FAIL);
(void)OptimizerStart(opt);
BN_BigNum *pow = OptimizerGetBn(opt, BITS_TO_BN_UNIT(pBits));
BN_BigNum *pTmp = OptimizerGetBn(opt, BITS_TO_BN_UNIT(pBits));
BN_BigNum *qTmp = OptimizerGetBn(opt, BITS_TO_BN_UNIT(qBits));
msg.dataLen = seed->dataLen;
msg.data = (uint8_t *)BSL_SAL_Dump(seed->data, seed->dataLen);
int32_t ret = CRYPT_MEM_ALLOC_FAIL;
GOTO_ERR_IF_TRUE(pow == NULL || pTmp == NULL || qTmp == NULL || msg.data == NULL, ret);
CRYPT_DSA_Para dsaParaTmp = {pTmp, qTmp, NULL};
GOTO_ERR_IF(BN_SetLimb(pow, 1), ret);
GOTO_ERR_IF(BN_Lshift(pow, pow, pBits - 1), ret);
/* Validate Q */
GOTO_ERR_IF(DSAFips1864GenQ(algId, libCtx, mdAttr, qBits, seed->data, seed->dataLen, qTmp), ret);
GOTO_ERR_IF(BN_PrimeCheck(qTmp, 0, opt, NULL), ret);
ret = CRYPT_DSA_PARA_NOT_EQUAL;
GOTO_ERR_IF_TRUE(BN_Cmp(qTmp, dsaPara->q), ret);
/* Validate P */
DSA_FIPS186_4_Para fipsPara = {algId, 0, pBits, qBits};
for (uint32_t i = 0; i <= counter; i++) {
GOTO_ERR_IF(BN_Zeroize(pTmp), ret);
GOTO_ERR_IF(DSAFips1864GenP(&fipsPara, pow, opt, &msg, &dsaParaTmp, libCtx, mdAttr), ret);
if (BN_Cmp(pTmp, pow) < 0) {
continue;
}
ret = BN_PrimeCheck(pTmp, 0, opt, NULL);
if (ret == CRYPT_BN_NOR_CHECK_PRIME) {
continue;
}
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
if (BN_Cmp(pTmp, dsaPara->p) != 0) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_PARA_NOT_EQUAL);
ret = CRYPT_DSA_PARA_NOT_EQUAL;
}
goto ERR;
}
ERR:
OptimizerEnd(opt);
BN_OptimizerDestroy(opt);
BSL_SAL_ClearFree(msg.data, msg.dataLen);
return ret;
}
// fips186-4 A.2.3
int32_t CryptDsaFips1864GenVerifiableG(DSA_FIPS186_4_Para *fipsPara, BSL_Buffer *seed, CRYPT_DSA_Para *dsaPara)
{
RETURN_RET_IF(fipsPara->index < 0, CRYPT_INVALID_ARG);
int32_t ret;
uint8_t hash[64]; // 64 is max hash len
uint32_t hashLen;
uint32_t pBits = BN_Bits(dsaPara->p);
BN_Optimizer *opt = BN_OptimizerCreate();
RETURN_RET_IF(opt == NULL, CRYPT_MEM_ALLOC_FAIL);
(void)OptimizerStart(opt);
BN_BigNum *e = OptimizerGetBn(opt, BITS_TO_BN_UNIT(pBits));
BN_BigNum *gTmp = OptimizerGetBn(opt, BITS_TO_BN_UNIT(pBits));
BN_BigNum *gOut = BN_Create(pBits);
uint32_t msgLen = seed->dataLen + 7; // "ggen" + index + counter = 7
uint8_t *msg = (uint8_t *)BSL_SAL_Calloc(msgLen, 1);
if (e == NULL || gTmp == NULL || gOut == NULL || msg == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
ret = CRYPT_MEM_ALLOC_FAIL;
goto ERR;
}
GOTO_ERR_IF(BN_SubLimb(e, dsaPara->p, 1), ret);
GOTO_ERR_IF(BN_Div(e, NULL, e, dsaPara->q, opt), ret);
(void)memcpy_s(msg, msgLen, seed->data, seed->dataLen);
(void)memcpy_s(msg + seed->dataLen, msgLen - seed->dataLen, "ggen", 4); // 4 is the length of "ggen".
msg[seed->dataLen + 4] = (uint8_t)(fipsPara->index & 0xff); // skip 4 bytes.
for (int32_t cnt = 1; cnt <= 0xFFFF; cnt++) {
msg[seed->dataLen + 5] = (uint8_t)((cnt >> 8) & 0xff); // skip 5 bytes, get high 8 bits in cnt.
msg[seed->dataLen + 6] = (uint8_t)(cnt & 0xff); // skip 6 bytes.
hashLen = sizeof(hash) / sizeof(hash[0]);
(void)memset_s(hash, hashLen, 0, hashLen);
GOTO_ERR_IF(EAL_Md(fipsPara->algId, NULL, NULL, msg, msgLen, hash, &hashLen), ret);
GOTO_ERR_IF(BN_Bin2Bn(gTmp, hash, hashLen), ret);
GOTO_ERR_IF(BN_ModExp(gTmp, gTmp, e, dsaPara->p, opt), ret);
if (BN_IsNegative(gTmp) == true || BN_IsZero(gTmp) == true || BN_IsOne(gTmp) == true) { // gTmp < 2
continue;
}
GOTO_ERR_IF(BN_Copy(gOut, gTmp), ret);
BN_Destroy(dsaPara->g);
dsaPara->g = gOut;
goto ERR; // success
}
BSL_ERR_PUSH_ERROR(CRYPT_DSA_ERR_TRY_CNT);
ret = CRYPT_DSA_ERR_TRY_CNT;
ERR:
if (ret != CRYPT_SUCCESS) {
BN_Destroy(gOut);
}
OptimizerEnd(opt);
BN_OptimizerDestroy(opt);
BSL_SAL_ClearFree(msg, msgLen);
return ret;
}
// fips186-4 A.2.1
int32_t CryptDsaFips1864GenUnverifiableG(CRYPT_DSA_Para *dsaPara)
{
int32_t ret;
uint32_t pBits = BN_Bits(dsaPara->p);
BN_Optimizer *opt = BN_OptimizerCreate();
RETURN_RET_IF(opt == NULL, CRYPT_MEM_ALLOC_FAIL);
(void)OptimizerStart(opt);
BN_BigNum *e = OptimizerGetBn(opt, BITS_TO_BN_UNIT(pBits));
BN_BigNum *p_1 = OptimizerGetBn(opt, BITS_TO_BN_UNIT(pBits));
BN_BigNum *h = OptimizerGetBn(opt, BITS_TO_BN_UNIT(pBits));
BN_BigNum *gTmp = OptimizerGetBn(opt, BITS_TO_BN_UNIT(pBits));
BN_BigNum *gOut = BN_Create(pBits);
if (e == NULL || p_1 == NULL || h == NULL || gTmp == NULL || gOut == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
ret = CRYPT_MEM_ALLOC_FAIL;
goto ERR;
}
ret = BN_SubLimb(p_1, dsaPara->p, 1);
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
ret = BN_Div(e, NULL, p_1, dsaPara->q, opt);
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
ret = BN_SetLimb(h, 1);
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
while (true) {
ret = BN_AddLimb(h, h, 1);
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
if (BN_Cmp(h, p_1) >= 0) {
BSL_ERR_PUSH_ERROR(CRYPT_BN_BITS_INVALID);
ret = CRYPT_BN_BITS_INVALID;
goto ERR;
}
ret = BN_ModExp(gTmp, h, e, dsaPara->p, opt);
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
if (BN_IsOne(gTmp) == true) { // 4. If (gTmp = 1), then go to step 2.
continue;
}
ret = BN_Copy(gOut, gTmp);
GOTO_ERR_IF_TRUE(ret != CRYPT_SUCCESS, ret);
BN_Destroy(dsaPara->g);
dsaPara->g = gOut;
goto ERR; // success
}
ERR:
if (ret != CRYPT_SUCCESS) {
BN_Destroy(gOut);
}
OptimizerEnd(opt);
BN_OptimizerDestroy(opt);
return ret;
}
// fips186-4 A.2.4
int32_t CryptDsaFips1864ValidateG(DSA_FIPS186_4_Para *fipsPara, BSL_Buffer *seed, CRYPT_DSA_Para *dsaPara)
{
int32_t ret = CryptDsaFips1864PartialValidateG(dsaPara);
if (ret != CRYPT_SUCCESS) {
return ret;
}
CRYPT_DSA_Para dsaVerify = {dsaPara->p, dsaPara->q, NULL};
ret = CryptDsaFips1864GenVerifiableG(fipsPara, seed, &dsaVerify);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (BN_Cmp(dsaVerify.g, dsaPara->g) == 0) {
ret = CRYPT_SUCCESS;
} else {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_VERIFY_FAIL);
ret = CRYPT_DSA_VERIFY_FAIL;
}
BN_Destroy(dsaVerify.g);
return ret;
}
static int32_t DSA_GetFipsPara(BSL_Param *params, DSA_FIPS186_4_Para *fipsPara, BSL_Buffer *seed)
{
const uint8_t *algId = NULL;
const uint8_t *pBits = NULL;
const uint8_t *qBits = NULL;
const uint8_t *index = NULL;
const uint8_t *seedLen = NULL;
uint32_t len = 0;
int32_t ret = GetDsaParamValue(params, CRYPT_PARAM_DSA_ALGID, sizeof(int32_t), &algId, &len);
if (ret != CRYPT_SUCCESS || len != sizeof(int32_t)) {
return CRYPT_DSA_ERR_KEY_PARA;
}
ret = GetDsaParamValue(params, CRYPT_PARAM_DSA_PBITS, sizeof(uint32_t), &pBits, &len);
if (ret != CRYPT_SUCCESS || len != sizeof(uint32_t)) {
return CRYPT_DSA_ERR_KEY_PARA;
}
ret = GetDsaParamValue(params, CRYPT_PARAM_DSA_QBITS, sizeof(uint32_t), &qBits, &len);
if (ret != CRYPT_SUCCESS || len != sizeof(uint32_t)) {
return CRYPT_DSA_ERR_KEY_PARA;
}
ret = GetDsaParamValue(params, CRYPT_PARAM_DSA_GINDEX, sizeof(int32_t), &index, &len);
if (ret != CRYPT_SUCCESS || len != sizeof(int32_t)) {
return CRYPT_DSA_ERR_KEY_PARA;
}
ret = GetDsaParamValue(params, CRYPT_PARAM_DSA_SEEDLEN, sizeof(uint32_t), &seedLen, &len);
if (ret != CRYPT_SUCCESS || len != sizeof(uint32_t)) {
return CRYPT_DSA_ERR_KEY_PARA;
}
fipsPara->algId = *(const int32_t *)algId;
fipsPara->l = *(const uint32_t *)pBits;
fipsPara->n = *(const uint32_t *)qBits;
fipsPara->index = *(const int32_t *)index;
seed->dataLen = *(const uint32_t *)seedLen;
seed->data = (uint8_t *)BSL_SAL_Calloc(seed->dataLen, 1);
if (seed->data == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
return CRYPT_SUCCESS;
}
/* generate PQ NIST.FIPS.186-4 A.1.1.2 */
/* generate G NIST.FIPS.186-4 A.2.3 */
int32_t CryptDsaFips1864GenParams(CRYPT_DSA_Ctx *ctx, void *val)
{
int32_t ret;
uint32_t counter;
DSA_FIPS186_4_Para fipsPara = {0};
BSL_Buffer seed = {0};
CRYPT_DSA_Para *dsaPara = NULL;
CRYPT_DSA_Para *oldPara = NULL;
BSL_Param *params = (BSL_Param *)val;
if (params == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
ret = DSA_GetFipsPara(params, &fipsPara, &seed);
if (ret != CRYPT_SUCCESS) {
return ret;
}
dsaPara = (CRYPT_DSA_Para *)BSL_SAL_Calloc(1, sizeof(CRYPT_DSA_Para));
if (dsaPara == NULL) {
BSL_SAL_Free(seed.data);
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
oldPara = ctx->para;
ctx->para = dsaPara;
ret = CryptDsaFips1864GenPq(ctx, &fipsPara, CRYPT_DSA_FFC_PARAM, &seed, &counter);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_ClearFree(seed.data, seed.dataLen);
BSL_SAL_Free(ctx->para);
ctx->para = oldPara;
return ret;
}
ret = CryptDsaFips1864GenVerifiableG(&fipsPara, &seed, ctx->para);
BSL_SAL_ClearFree(seed.data, seed.dataLen);
if (ret != CRYPT_SUCCESS) {
CRYPT_DSA_FreePara(ctx->para);
ctx->para = oldPara;
return ret;
}
CRYPT_DSA_FreePara(oldPara);
return CRYPT_SUCCESS;
}
#endif /* HITLS_CRYPTO_DSA_GEN_PARA */
// Set flag == 1, enable generate private key SP800-56Ar3 5_6_1_1_4.
static int32_t CRYPT_SetFipsFlag(CRYPT_DSA_Ctx *ctx, void *val, uint32_t len)
{
if (len != sizeof(uint32_t)) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_PARA_ERROR);
return CRYPT_DSA_PARA_ERROR;
}
uint32_t flag = *(uint32_t *)val;
ctx->flag = (uint8_t)flag;
return CRYPT_SUCCESS;
}
int32_t CRYPT_DSA_Ctrl(CRYPT_DSA_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 GetUintCtrl(ctx, val, len, (GetUintCallBack)CRYPT_DSA_GetBits);
case CRYPT_CTRL_GET_SIGNLEN:
return GetUintCtrl(ctx, val, len, (GetUintCallBack)CRYPT_DSA_GetSignLen);
case CRYPT_CTRL_GET_SECBITS:
return GetUintCtrl(ctx, val, len, (GetUintCallBack)CRYPT_DSA_GetSecBits);
case CRYPT_CTRL_GET_PUBKEY_LEN:
return GetUintCtrl(ctx, val, len, (GetUintCallBack)CRYPT_DSA_GetPubKeyLen);
case CRYPT_CTRL_GET_PRVKEY_LEN:
return GetUintCtrl(ctx, val, len, (GetUintCallBack)CRYPT_DSA_GetPrvKeyLen);
case CRYPT_CTRL_UP_REFERENCES:
if (val == NULL || len != (uint32_t)sizeof(int)) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
return BSL_SAL_AtomicUpReferences(&(ctx->references), (int *)val);
case CRYPT_CTRL_SET_GEN_FLAG:
return CRYPT_SetFipsFlag(ctx, val, len);
#ifdef HITLS_CRYPTO_DSA_GEN_PARA
case CRYPT_CTRL_GEN_PARA:
return CryptDsaFips1864GenParams(ctx, val);
#endif /* HITLS_CRYPTO_DSA_GEN_PARA */
default:
break;
}
BSL_ERR_PUSH_ERROR(CRYPT_DSA_UNSUPPORTED_CTRL_OPTION);
return CRYPT_DSA_UNSUPPORTED_CTRL_OPTION;
}
#ifdef HITLS_CRYPTO_DSA_CHECK
static int32_t DsaKeyPairCheck(const CRYPT_DSA_Ctx *pub, const CRYPT_DSA_Ctx *prv)
{
int32_t ret;
if (prv == NULL || pub == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (prv->para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR);
return CRYPT_DH_PARA_ERROR;
}
ret = CRYPT_FFC_KeyPairCheck(prv->x, pub->y, prv->para->p, prv->para->g);
if (ret == CRYPT_PAIRWISE_CHECK_FAIL) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_PAIRWISE_CHECK_FAIL);
ret = CRYPT_DSA_PAIRWISE_CHECK_FAIL;
}
return ret;
}
/*
* SP800-56a 5.6.2.1.2
* for check an FFC key pair.
*/
static int32_t DsaPrvKeyCheck(const CRYPT_DSA_Ctx *pkey)
{
if (pkey == NULL || pkey->para == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret = CRYPT_FFC_PrvCheck(pkey->x, pkey->para->p, pkey->para->q);
if (ret == CRYPT_INVALID_KEY) {
BSL_ERR_PUSH_ERROR(CRYPT_DSA_INVALID_PRVKEY);
ret = CRYPT_DSA_INVALID_PRVKEY;
}
return ret;
}
int32_t CRYPT_DSA_Check(uint32_t checkType, const CRYPT_DSA_Ctx *pkey1, const CRYPT_DSA_Ctx *pkey2)
{
switch (checkType) {
case CRYPT_PKEY_CHECK_KEYPAIR:
return DsaKeyPairCheck(pkey1, pkey2);
case CRYPT_PKEY_CHECK_PRVKEY:
return DsaPrvKeyCheck(pkey1);
default:
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
}
#endif // HITLS_CRYPTO_DSA_CHECK
#endif /* HITLS_CRYPTO_DSA */
|
2301_79861745/bench_create
|
crypto/dsa/src/dsa_core.c
|
C
|
unknown
| 56,232
|
/*
* 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 DSA_LOCAL_H
#define DSA_LOCAL_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_DSA
#include "crypt_bn.h"
#include "crypt_dsa.h"
#include "sal_atomic.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cpluscplus */
#define DSA_MIN_PBITS 1024 // The minimum specification of DSA: 1024 bits
#define DSA_MAX_PBITS 3072 // The maximum specification of DSA: 3072 bits
#define DSA_MIN_QBITS 160 // The minimum specification of parameter q of DSA
/* DSA key parameters */
struct DSA_Para {
BN_BigNum *p;
BN_BigNum *q;
BN_BigNum *g;
};
/* DSA key ctx */
struct DSA_Ctx {
BN_BigNum *x; // private key
BN_BigNum *y; // public key
CRYPT_DSA_Para *para; // key parameter
BSL_SAL_RefCount references;
void *libCtx;
char *mdAttr;
uint8_t flag;
};
typedef struct {
int32_t algId; // hash algid
int32_t index; // gen g need index
uint32_t l; // pbits
uint32_t n; // qbits
} DSA_FIPS186_4_Para;
#ifdef __cplusplus
}
#endif
#endif // HITLS_CRYPTO_DSA
#endif // DSA_LOCAL_H
|
2301_79861745/bench_create
|
crypto/dsa/src/dsa_local.h
|
C
|
unknown
| 1,567
|
/*
* 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_PKEY_H
#define EAL_PKEY_H
#include "crypt_eal_pkey.h"
#include "crypt_eal_provider.h"
#include "crypt_local_types.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
typedef struct {
int32_t algId;
CRYPT_EAL_ProvMgrCtx *mgrCtx;
EAL_PkeyUnitaryMethod *keyMgmtMethod;
} CRYPT_EAL_PkeyMgmtInfo;
typedef struct {
CRYPT_EAL_ProvMgrCtx *mgrCtx;
const CRYPT_EAL_Func *funcsAsyCipher;
const CRYPT_EAL_Func *funcsExch;
const CRYPT_EAL_Func *funcSign;
const CRYPT_EAL_Func *funcKem;
const CRYPT_EAL_Func *funcsKeyMgmt;
} CRYPT_EAL_AsyAlgFuncsInfo;
/**
* @ingroup crypt_eal_pkey
* @brief Create a new asymmetric key context by key management information.
*
* @param pkey [IN/OUT] The asymmetric key context to be created.
* @param pkeyAlgInfo [IN] The key management information.
* @param keyRef [IN] The reference to the key.
* @param keyRefLen [IN] The length of the key reference.
*
* @return CRYPT_SUCCESS on success, CRYPT_ERROR on failure.
*/
CRYPT_EAL_PkeyCtx *CRYPT_EAL_MakeKeyByPkeyAlgInfo(CRYPT_EAL_PkeyMgmtInfo *pkeyAlgInfo, void *keyRef,
uint32_t keyRefLen);
/**
* @ingroup crypt_eal_pkey
* @brief Get the key management information by algorithm ID and attribute name.
*
* @param libCtx [IN] The library context.
* @param algId [IN] The algorithm ID.
* @param attrName [IN] The attribute name.
* @param pkeyAlgInfo [OUT] The key management information.
*/
int32_t CRYPT_EAL_GetPkeyAlgInfo(CRYPT_EAL_LibCtx *libCtx, int32_t algId, const char *attrName,
CRYPT_EAL_PkeyMgmtInfo *pkeyAlgInfo);
int32_t CRYPT_EAL_SetPkeyMethod(EAL_PkeyUnitaryMethod **pkeyMethod, const CRYPT_EAL_Func *funcsKeyMgmt,
const CRYPT_EAL_Func *funcsAsyCipher, const CRYPT_EAL_Func *funcsExch, const CRYPT_EAL_Func *funcSign,
const CRYPT_EAL_Func *funcKem);
int32_t CRYPT_EAL_ProviderGetAsyAlgFuncs(CRYPT_EAL_LibCtx *libCtx, int32_t algId, uint32_t pkeyOperType,
const char *attrName, CRYPT_EAL_AsyAlgFuncsInfo *funcs);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // EAL_PKEY_H
|
2301_79861745/bench_create
|
crypto/eal/include/eal_pkey.h
|
C
|
unknown
| 2,600
|
/*
* 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_CIPHER)
#include "securec.h"
#include "crypt_algid.h"
#include "crypt_eal_cipher.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "eal_cipher_local.h"
#include "eal_common.h"
#include "crypt_utils.h"
#include "crypt_ealinit.h"
#include "crypt_types.h"
#ifdef HITLS_CRYPTO_PROVIDER
#include "crypt_provider.h"
#endif
static void CipherCopyMethod(const EAL_CipherMethod *modeMethod, EAL_CipherUnitaryMethod *method)
{
method->newCtx = modeMethod->newCtx;
method->initCtx = modeMethod->initCtx;
method->deinitCtx = modeMethod->deinitCtx;
method->update = modeMethod->update;
method->final = modeMethod->final;
method->ctrl = modeMethod->ctrl;
method->freeCtx = modeMethod->freeCtx;
}
static CRYPT_EAL_CipherCtx *CipherNewDefaultCtx(CRYPT_CIPHER_AlgId id)
{
int32_t ret;
const EAL_CipherMethod *modeMethod = NULL;
ret = EAL_FindCipher(id, &modeMethod);
if (ret != CRYPT_SUCCESS) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, id, ret);
return NULL;
}
CRYPT_EAL_CipherCtx *ctx = (CRYPT_EAL_CipherCtx *)BSL_SAL_Calloc(1u, sizeof(struct CryptEalCipherCtx));
if (ctx == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, id, CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
EAL_CipherUnitaryMethod *method = (EAL_CipherUnitaryMethod *)BSL_SAL_Calloc(1u, sizeof(EAL_CipherUnitaryMethod));
if (method == NULL) {
BSL_SAL_Free(ctx);
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, id, CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
void *modeCtx = modeMethod->newCtx(id);
if (modeCtx == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, id, CRYPT_EAL_CIPHER_ERR_NEWCTX);
BSL_SAL_Free(ctx);
BSL_SAL_Free(method);
return NULL;
}
CipherCopyMethod(modeMethod, method);
ctx->id = id;
ctx->method = method;
ctx->ctx = modeCtx;
ctx->states = EAL_CIPHER_STATE_NEW;
return ctx;
}
#ifdef HITLS_CRYPTO_PROVIDER
static int32_t CRYPT_EAL_SetCipherMethod(CRYPT_EAL_CipherCtx *ctx, const CRYPT_EAL_Func *funcs)
{
int32_t index = 0;
EAL_CipherUnitaryMethod *method = BSL_SAL_Calloc(1, sizeof(EAL_CipherUnitaryMethod));
if (method == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
while (funcs[index].id != 0) {
switch (funcs[index].id) {
case CRYPT_EAL_IMPLCIPHER_NEWCTX:
method->provNewCtx = funcs[index].func;
break;
case CRYPT_EAL_IMPLCIPHER_INITCTX:
method->initCtx = funcs[index].func;
break;
case CRYPT_EAL_IMPLCIPHER_UPDATE:
method->update = funcs[index].func;
break;
case CRYPT_EAL_IMPLCIPHER_FINAL:
method->final = funcs[index].func;
break;
case CRYPT_EAL_IMPLCIPHER_DEINITCTX:
method->deinitCtx = funcs[index].func;
break;
case CRYPT_EAL_IMPLCIPHER_FREECTX:
method->freeCtx = funcs[index].func;
break;
case CRYPT_EAL_IMPLCIPHER_CTRL:
method->ctrl = funcs[index].func;
break;
default:
BSL_SAL_FREE(method);
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_ERR_UNEXPECTED_IMPL);
return CRYPT_PROVIDER_ERR_UNEXPECTED_IMPL;
}
index++;
}
ctx->method = method;
return CRYPT_SUCCESS;
}
CRYPT_EAL_CipherCtx *CRYPT_EAL_ProviderCipherNewCtxInner(CRYPT_EAL_LibCtx *libCtx, int32_t algId, const char *attrName)
{
const CRYPT_EAL_Func *funcs = NULL;
void *provCtx = NULL;
int32_t ret = CRYPT_EAL_ProviderGetFuncs(libCtx, CRYPT_EAL_OPERAID_SYMMCIPHER, algId, attrName,
(const CRYPT_EAL_Func **)&funcs, &provCtx);
if (ret != CRYPT_SUCCESS) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, algId, ret);
return NULL;
}
CRYPT_EAL_CipherCtx *ctx = BSL_SAL_Calloc(1u, sizeof(CRYPT_EAL_CipherCtx));
if (ctx == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, algId, CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
ret = CRYPT_EAL_SetCipherMethod(ctx, funcs);
if (ret != BSL_SUCCESS) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, algId, ret);
BSL_SAL_FREE(ctx);
return NULL;
}
if (ctx->method->provNewCtx == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, algId, CRYPT_PROVIDER_ERR_IMPL_NULL);
BSL_SAL_FREE(ctx->method);
BSL_SAL_FREE(ctx);
return NULL;
}
ctx->ctx = ctx->method->provNewCtx(provCtx, algId);
if (ctx->ctx == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, algId, CRYPT_MEM_ALLOC_FAIL);
BSL_SAL_FREE(ctx->method);
BSL_SAL_FREE(ctx);
return NULL;
}
ctx->id = algId;
ctx->states = EAL_CIPHER_STATE_NEW;
ctx->isProvider = true;
return ctx;
}
#endif
CRYPT_EAL_CipherCtx *CRYPT_EAL_ProviderCipherNewCtx(CRYPT_EAL_LibCtx *libCtx, int32_t algId, const char *attrName)
{
#ifdef HITLS_CRYPTO_PROVIDER
return CRYPT_EAL_ProviderCipherNewCtxInner(libCtx, algId, attrName);
#else
(void)libCtx;
(void)attrName;
return CRYPT_EAL_CipherNewCtx(algId);
#endif
}
CRYPT_EAL_CipherCtx *CRYPT_EAL_CipherNewCtx(CRYPT_CIPHER_AlgId id)
{
#ifdef HITLS_CRYPTO_ASM_CHECK
if (CRYPT_ASMCAP_Cipher(id) != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_ASM_NOT_SUPPORT);
return NULL;
}
#endif
return CipherNewDefaultCtx(id);
}
void CRYPT_EAL_CipherFreeCtx(CRYPT_EAL_CipherCtx *ctx)
{
if (ctx == NULL) {
// If the input parameter is NULL, it is not considered as an error.
return;
}
if (ctx->method == NULL || ctx->method->freeCtx == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, ctx->id, CRYPT_EAL_ALG_NOT_SUPPORT);
BSL_SAL_FREE(ctx->method);
BSL_SAL_FREE(ctx);
return;
}
(void)ctx->method->freeCtx(ctx->ctx);
BSL_SAL_FREE(ctx->method);
// Free the memory eal ctx and mode ctx at the EAL layer.
BSL_SAL_FREE(ctx);
}
int32_t CRYPT_EAL_CipherInit(CRYPT_EAL_CipherCtx *ctx, const uint8_t *key, uint32_t keyLen, const uint8_t *iv,
uint32_t ivLen, bool enc)
{
int32_t ret;
if (ctx == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, CRYPT_CIPHER_MAX, CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->method == NULL || ctx->method->initCtx == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, ctx->id, CRYPT_EAL_ALG_NOT_SUPPORT);
return CRYPT_EAL_ALG_NOT_SUPPORT;
}
CRYPT_EAL_CipherDeinit(ctx);
if (ctx->states != EAL_CIPHER_STATE_NEW) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, ctx->id, CRYPT_EAL_ERR_STATE);
return CRYPT_EAL_ERR_STATE;
}
ret = ctx->method->initCtx(ctx->ctx, key, keyLen, iv, ivLen, NULL, enc);
if (ret != CRYPT_SUCCESS) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, ctx->id, ret);
return ret;
}
ctx->states = EAL_CIPHER_STATE_INIT;
return CRYPT_SUCCESS;
}
void CRYPT_EAL_CipherDeinit(CRYPT_EAL_CipherCtx *ctx)
{
if (ctx == NULL) {
// If the ctx is NULL during deinit, it is not considered as an error.
return;
}
if (ctx->method == NULL || ctx->method->deinitCtx == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, ctx->id, CRYPT_EAL_ALG_NOT_SUPPORT);
return;
}
int32_t ret = ctx->method->deinitCtx(ctx->ctx);
if (ret != CRYPT_SUCCESS) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, ctx->id, ret);
}
// Restore the state to the state after the new is successful.
ctx->states = EAL_CIPHER_STATE_NEW;
}
// no need for IV, the value can be set to NULL
int32_t CRYPT_EAL_CipherReinit(CRYPT_EAL_CipherCtx *ctx, uint8_t *iv, uint32_t ivLen)
{
int32_t ret;
if (ctx == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, CRYPT_CIPHER_MAX, CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
// Without init, reinit cannot be invoked directly.
if (ctx->states == EAL_CIPHER_STATE_NEW) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, ctx->id, CRYPT_EAL_ERR_STATE);
return CRYPT_EAL_ERR_STATE;
}
// Reset the IV. In this case, reset the IV is not restricted by the states.
if (ctx->method == NULL || ctx->method->ctrl == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, ctx->id, CRYPT_EAL_ALG_NOT_SUPPORT);
return CRYPT_EAL_ALG_NOT_SUPPORT;
}
ret = ctx->method->ctrl(ctx->ctx, CRYPT_CTRL_REINIT_STATUS, iv, ivLen);
if (ret != CRYPT_SUCCESS) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, ctx->id, ret);
return ret;
}
// Reset the states.
ctx->states = EAL_CIPHER_STATE_INIT;
return CRYPT_SUCCESS;
}
static bool IsPartialOverLap(const void *out, const void *in, uint32_t len)
{
uintptr_t diff;
if ((uintptr_t)out > (uintptr_t)in) {
diff = (uintptr_t)out - (uintptr_t)in;
return diff < (uintptr_t)len;
}
// If in >= out, this case is valid.
return false;
}
static int32_t CheckUpdateParam(const CRYPT_EAL_CipherCtx *ctx, const uint8_t *in, uint32_t inLen, const uint8_t *out,
const uint32_t *outLen)
{
if (ctx == NULL || out == NULL || outLen == NULL || (in == NULL && inLen != 0)) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if ((in != NULL && inLen != 0) && IsPartialOverLap(out, in, inLen)) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_PART_OVERLAP);
return CRYPT_EAL_ERR_PART_OVERLAP;
}
// If the state is not init or update, the state is regarded as an error.
// If the state is final or new, update cannot be directly invoked.
if (!(ctx->states == EAL_CIPHER_STATE_INIT || ctx->states == EAL_CIPHER_STATE_UPDATE)) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_STATE);
return CRYPT_EAL_ERR_STATE;
}
if (ctx->method == NULL || ctx->method->update == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, ctx->id, CRYPT_EAL_ALG_NOT_SUPPORT);
return CRYPT_EAL_ALG_NOT_SUPPORT;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_EAL_CipherUpdate(CRYPT_EAL_CipherCtx *ctx, const uint8_t *in, uint32_t inLen, uint8_t *out,
uint32_t *outLen)
{
int32_t ret = CheckUpdateParam(ctx, in, inLen, out, outLen);
if (ret != CRYPT_SUCCESS) {
// The push error in CheckUpdateParam can be locate the only error location. No need to add the push error here.
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, (ctx == NULL) ? CRYPT_CIPHER_MAX : ctx->id, ret);
return ret;
}
ret = ctx->method->update(ctx->ctx, in, inLen, out, outLen);
if (ret != CRYPT_SUCCESS) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, ctx->id, ret);
return ret;
}
ctx->states = EAL_CIPHER_STATE_UPDATE;
return CRYPT_SUCCESS;
}
int32_t CheckFinalParam(const CRYPT_EAL_CipherCtx *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 the state is not init or update, the state is regarded as an error.
// If the state is final or new, update cannot be directly invoked.
if (!(ctx->states == EAL_CIPHER_STATE_UPDATE || ctx->states == EAL_CIPHER_STATE_INIT)) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_STATE);
return CRYPT_EAL_ERR_STATE;
}
if (ctx->method == NULL || ctx->method->final == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_NOT_SUPPORT);
return CRYPT_EAL_ALG_NOT_SUPPORT;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_EAL_CipherFinal(CRYPT_EAL_CipherCtx *ctx, uint8_t *out, uint32_t *outLen)
{
int32_t ret;
ret = CheckFinalParam(ctx, out, outLen);
if (ret != CRYPT_SUCCESS) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, (ctx == NULL) ? CRYPT_CIPHER_MAX : ctx->id, ret);
return ret;
}
ret = ctx->method->final(ctx->ctx, out, outLen);
if (ret != CRYPT_SUCCESS) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, ctx->id, ret);
return ret;
}
ctx->states = EAL_CIPHER_STATE_FINAL;
return CRYPT_SUCCESS;
}
static bool CipherCtrlIsCanSet(const CRYPT_EAL_CipherCtx *ctx, int32_t type)
{
if (ctx->states == EAL_CIPHER_STATE_NEW) {
return false;
}
if (ctx->states == EAL_CIPHER_STATE_FINAL) {
return false;
}
if ((ctx->states == EAL_CIPHER_STATE_UPDATE) &&
(type == CRYPT_CTRL_SET_COUNT || type == CRYPT_CTRL_SET_TAGLEN ||
type == CRYPT_CTRL_SET_MSGLEN || type == CRYPT_CTRL_SET_AAD)) {
return false;
}
return true;
}
int32_t CRYPT_EAL_CipherCtrl(CRYPT_EAL_CipherCtx *ctx, int32_t type, void *data, uint32_t len)
{
if (ctx == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, CRYPT_CIPHER_MAX, CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
// The IV cannot be set through the Ctrl. You need to set the IV through the init and reinit.
if (type == CRYPT_CTRL_SET_IV || type == CRYPT_CTRL_REINIT_STATUS) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, ctx->id, CRYPT_EAL_CIPHER_CTRL_ERROR);
return CRYPT_EAL_CIPHER_CTRL_ERROR;
}
// If the algorithm is running in the intermediate state, write operations are not allowed.
if (!CipherCtrlIsCanSet(ctx, type)) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, ctx->id, CRYPT_EAL_ERR_STATE);
return CRYPT_EAL_ERR_STATE;
}
// Setting AAD indicates that the encryption operation has started and no more write operations are allowed.
if (type == CRYPT_CTRL_SET_AAD) {
ctx->states = EAL_CIPHER_STATE_UPDATE;
} else if (type == CRYPT_CTRL_GET_TAG) {
// After getTag the system enters the final state.
ctx->states = EAL_CIPHER_STATE_FINAL;
}
if (ctx->method == NULL || ctx->method->ctrl == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, ctx->id, CRYPT_EAL_ALG_NOT_SUPPORT);
return CRYPT_EAL_ALG_NOT_SUPPORT;
}
int32_t ret = ctx->method->ctrl(ctx->ctx, type, data, len);
if (ret != CRYPT_SUCCESS) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, ctx->id, ret);
return ret;
}
return ret;
}
int32_t CRYPT_EAL_CipherSetPadding(CRYPT_EAL_CipherCtx *ctx, CRYPT_PaddingType type)
{
if (ctx == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, CRYPT_CIPHER_MAX, CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->method == NULL || ctx->method->ctrl == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, ctx->id, CRYPT_EAL_ALG_NOT_SUPPORT);
return CRYPT_EAL_ALG_NOT_SUPPORT;
}
int32_t ret = ctx->method->ctrl(ctx->ctx, CRYPT_CTRL_SET_PADDING, (void *)&type, sizeof(type));
if (ret != CRYPT_SUCCESS) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, ctx->id, ret);
}
return ret;
}
int32_t CRYPT_EAL_CipherGetPadding(CRYPT_EAL_CipherCtx *ctx)
{
if (ctx == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, CRYPT_CIPHER_MAX, CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->method == NULL || ctx->method->ctrl == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, ctx->id, CRYPT_EAL_ALG_NOT_SUPPORT);
return CRYPT_EAL_ALG_NOT_SUPPORT;
}
int32_t type;
int32_t ret = ctx->method->ctrl(ctx->ctx, CRYPT_CTRL_GET_PADDING, (void *)&type, sizeof(type));
if (ret != CRYPT_SUCCESS) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, ctx->id, ret);
return CRYPT_PADDING_MAX_COUNT;
}
return type;
}
bool CRYPT_EAL_CipherIsValidAlgId(CRYPT_CIPHER_AlgId id)
{
const EAL_CipherMethod *m = NULL;
return EAL_FindCipher(id, &m) == CRYPT_SUCCESS;
}
static const uint32_t CIPHER_IS_AEAD[] = {
CRYPT_CIPHER_AES128_CCM,
CRYPT_CIPHER_AES192_CCM,
CRYPT_CIPHER_AES256_CCM,
CRYPT_CIPHER_AES128_GCM,
CRYPT_CIPHER_AES192_GCM,
CRYPT_CIPHER_AES256_GCM,
CRYPT_CIPHER_CHACHA20_POLY1305,
CRYPT_CIPHER_SM4_GCM,
};
// Check whether the algorithm is the AEAD algorithm. If yes, true is returned. Otherwise, false is returned.
static bool IsAeadAlg(CRYPT_CIPHER_AlgId id)
{
if (ParamIdIsValid(id, CIPHER_IS_AEAD, sizeof(CIPHER_IS_AEAD) / sizeof(CIPHER_IS_AEAD[0]))) {
return true;
}
return false;
}
int32_t CRYPT_EAL_CipherGetInfo(CRYPT_CIPHER_AlgId id, int32_t type, uint32_t *infoValue)
{
if (infoValue == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, id, CRYPT_INVALID_ARG);
return CRYPT_INVALID_ARG;
}
CRYPT_CipherInfo info = {0};
if (EAL_GetCipherInfo(id, &info) != CRYPT_SUCCESS) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, id, CRYPT_ERR_ALGID);
return CRYPT_ERR_ALGID;
}
switch (type) {
case CRYPT_INFO_IS_AEAD:
(*infoValue) = IsAeadAlg(id) ? 1 : 0;
break;
case CRYPT_INFO_IS_STREAM:
(*infoValue) = (uint32_t)!((info.blockSize) != 1);
break;
case CRYPT_INFO_IV_LEN:
(*infoValue) = info.ivLen;
break;
case CRYPT_INFO_KEY_LEN:
(*infoValue) = info.keyLen;
break;
case CRYPT_INFO_BLOCK_LEN:
(*infoValue) = (uint32_t)info.blockSize;
break;
default:
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_CIPHER, id, CRYPT_EAL_INTO_TYPE_NOT_SUPPORT);
return CRYPT_EAL_INTO_TYPE_NOT_SUPPORT;
}
return CRYPT_SUCCESS;
}
#endif
|
2301_79861745/bench_create
|
crypto/eal/src/eal_cipher.c
|
C
|
unknown
| 18,569
|
/*
* 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_CIPHER_LOCAL_H
#define EAL_CIPHER_LOCAL_H
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_EAL) && defined(HITLS_CRYPTO_CIPHER)
#include "crypt_algid.h"
#include "crypt_eal_cipher.h"
#include "crypt_local_types.h"
#ifdef HITLS_CRYPTO_GCM
#include "crypt_modes_gcm.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/**
* @ingroup crypt_cipherstates
* Symmetry encryption/decryption status */
typedef enum {
EAL_CIPHER_STATE_NEW,
EAL_CIPHER_STATE_INIT,
EAL_CIPHER_STATE_UPDATE,
EAL_CIPHER_STATE_FINAL
} EAL_CipherStates;
/**
* @ingroup alg map
* Symmetric encryption/decryption mode and ID of the encryption algorithm.
*/
typedef struct {
uint32_t id;
CRYPT_MODE_AlgId modeId;
} EAL_SymAlgMap;
/**
* @ingroup EAL
*
* CRYPT_CipherInfo: User search algorithm information. Currently, only blockSize is available.
*/
typedef struct {
CRYPT_CIPHER_AlgId id;
uint8_t blockSize;
uint32_t keyLen;
uint32_t ivLen;
} CRYPT_CipherInfo;
/**
* @ingroup crypt_eal_cipherctx
* Asymmetric algorithm data type */
struct CryptEalCipherCtx {
#ifdef HITLS_CRYPTO_PROVIDER
bool isProvider;
#endif
CRYPT_CIPHER_AlgId id;
EAL_CipherStates states; /**< record status */
void *ctx; /**< handle of the mode */
EAL_CipherUnitaryMethod *method; /**< method corresponding to the encryption/decryption mode */
};
const EAL_SymMethod *EAL_GetSymMethod(int32_t algId);
/**
* @brief Obtain the EAL_CipherMethod based on the algorithm ID.
*
* @param id [IN] Symmetric encryption/decryption algorithm ID.
* @param modeMethod [IN/OUT] EAL_CipherMethod Pointer
* @return If it's successful, the system returns CRYPT_SUCCESS and assigns the value to the method in m.
* If it's failed, returns CRYPT_EAL_ERR_ALGID: ID of the unsupported algorithm.
*/
int32_t EAL_FindCipher(CRYPT_CIPHER_AlgId id, const EAL_CipherMethod **modeMethod);
/**
* @brief Obtain keyLen/ivLen/blockSize based on the algorithm ID.
*
* @param id [IN] Symmetric algorithm ID.
* @param id [OUT] Assign the obtained keyLen/ivLen/blockSize to the variable corresponding to info.
*
* @return Success: CRYPT_SUCCESS
* Failure: CRYPT_ERR_ALGID
*/
int32_t EAL_GetCipherInfo(CRYPT_CIPHER_AlgId id, CRYPT_CipherInfo *info);
/**
* @brief Obtain mode method based on the algorithm ID
*
* @param id [IN] Symmetric encryption/decryption algorithm ID.
* @return If the operation is successful, the combination of ciphers is returned.
* If the operation fails, NULL is returned.
*/
const EAL_CipherMethod *EAL_FindModeMethod(CRYPT_MODE_AlgId id);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // HITLS_CRYPTO_CIPHER
#endif // EAL_CIPHER_LOCAL_H
|
2301_79861745/bench_create
|
crypto/eal/src/eal_cipher_local.h
|
C
|
unknown
| 3,325
|
/*
* 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_CIPHER)
#include "bsl_err_internal.h"
#include "crypt_errno.h"
#include "eal_cipher_local.h"
#include "crypt_modes.h"
#include "crypt_local_types.h"
#ifdef HITLS_CRYPTO_CTR
#include "crypt_modes_ctr.h"
#endif
#ifdef HITLS_CRYPTO_CBC
#include "crypt_modes_cbc.h"
#endif
#ifdef HITLS_CRYPTO_ECB
#include "crypt_modes_ecb.h"
#endif
#ifdef HITLS_CRYPTO_GCM
#include "crypt_modes_gcm.h"
#endif
#ifdef HITLS_CRYPTO_CCM
#include "crypt_modes_ccm.h"
#endif
#ifdef HITLS_CRYPTO_XTS
#include "crypt_modes_xts.h"
#endif
#ifdef HITLS_CRYPTO_AES
#include "crypt_aes.h"
#endif
#if defined(HITLS_CRYPTO_CHACHA20) && defined(HITLS_CRYPTO_CHACHA20POLY1305)
#include "crypt_modes_chacha20poly1305.h"
#endif
#ifdef HITLS_CRYPTO_CHACHA20
#include "crypt_chacha20.h"
#endif
#ifdef HITLS_CRYPTO_SM4
#include "crypt_sm4.h"
#endif
#ifdef HITLS_CRYPTO_CFB
#include "crypt_modes_cfb.h"
#endif
#ifdef HITLS_CRYPTO_OFB
#include "crypt_modes_ofb.h"
#endif
#include "eal_common.h"
#include "bsl_sal.h"
#if defined(HITLS_CRYPTO_CHACHA20) && defined(HITLS_CRYPTO_CHACHA20POLY1305)
static const EAL_CipherMethod CHACHA20_POLY1305_METHOD = {
(CipherNewCtx)MODES_CHACHA20POLY1305_NewCtx,
(CipherInitCtx)MODES_CHACHA20POLY1305_InitCtx,
(CipherDeInitCtx)MODES_CHACHA20POLY1305_DeInitCtx,
(CipherUpdate)MODES_CHACHA20POLY1305_Update,
(CipherFinal)MODES_CHACHA20POLY1305_Final,
(CipherCtrl)MODES_CHACHA20POLY1305_Ctrl,
(CipherFreeCtx)MODES_CHACHA20POLY1305_FreeCtx
};
#endif
#ifdef HITLS_CRYPTO_CTR
static const EAL_CipherMethod CTR_METHOD = {
(CipherNewCtx)MODES_CTR_NewCtx,
(CipherInitCtx)MODES_CTR_InitCtxEx,
(CipherDeInitCtx)MODES_CTR_DeInitCtx,
(CipherUpdate)MODES_CTR_UpdateEx,
(CipherFinal)MODES_CTR_Final,
(CipherCtrl)MODES_CTR_Ctrl,
(CipherFreeCtx)MODES_CTR_FreeCtx
};
#endif
#ifdef HITLS_CRYPTO_CBC
static const EAL_CipherMethod CBC_METHOD = {
(CipherNewCtx)MODES_CBC_NewCtx,
(CipherInitCtx)MODES_CBC_InitCtxEx,
(CipherDeInitCtx)MODES_CBC_DeInitCtx,
(CipherUpdate)MODES_CBC_UpdateEx,
(CipherFinal)MODES_CBC_FinalEx,
(CipherCtrl)MODES_CBC_Ctrl,
(CipherFreeCtx)MODES_CBC_FreeCtx
};
#endif
#ifdef HITLS_CRYPTO_ECB
static const EAL_CipherMethod ECB_METHOD = {
(CipherNewCtx)MODES_ECB_NewCtx,
(CipherInitCtx)MODES_ECB_InitCtxEx,
(CipherDeInitCtx)MODES_ECB_DeinitCtx,
(CipherUpdate)MODES_ECB_UpdateEx,
(CipherFinal)MODES_ECB_FinalEx,
(CipherCtrl)MODES_ECB_Ctrl,
(CipherFreeCtx)MODES_ECB_FreeCtx
};
#endif
#ifdef HITLS_CRYPTO_CCM
static const EAL_CipherMethod CCM_METHOD = {
(CipherNewCtx)MODES_CCM_NewCtx,
(CipherInitCtx)MODES_CCM_InitCtx,
(CipherDeInitCtx)MODES_CCM_DeInitCtx,
(CipherUpdate)MODES_CCM_UpdateEx,
(CipherFinal)MODES_CCM_Final,
(CipherCtrl)MODES_CCM_Ctrl,
(CipherFreeCtx)MODES_CCM_FreeCtx
};
#endif
#ifdef HITLS_CRYPTO_GCM
static const EAL_CipherMethod GCM_METHOD = {
(CipherNewCtx)MODES_GCM_NewCtx,
(CipherInitCtx)MODES_GCM_InitCtxEx,
(CipherDeInitCtx)MODES_GCM_DeInitCtx,
(CipherUpdate)MODES_GCM_UpdateEx,
(CipherFinal)MODES_GCM_Final,
(CipherCtrl)MODES_GCM_Ctrl,
(CipherFreeCtx)MODES_GCM_FreeCtx
};
#endif
#ifdef HITLS_CRYPTO_CFB
static const EAL_CipherMethod CFB_METHOD = {
(CipherNewCtx)MODES_CFB_NewCtx,
(CipherInitCtx)MODES_CFB_InitCtxEx,
(CipherDeInitCtx)MODES_CFB_DeInitCtx,
(CipherUpdate)MODES_CFB_UpdateEx,
(CipherFinal)MODES_CFB_Final,
(CipherCtrl)MODES_CFB_Ctrl,
(CipherFreeCtx)MODES_CFB_FreeCtx
};
#endif
#ifdef HITLS_CRYPTO_OFB
static const EAL_CipherMethod OFB_METHOD = {
(CipherNewCtx)MODES_OFB_NewCtx,
(CipherInitCtx)MODES_OFB_InitCtxEx,
(CipherDeInitCtx)MODES_OFB_DeInitCtx,
(CipherUpdate)MODES_OFB_UpdateEx,
(CipherFinal)MODES_OFB_Final,
(CipherCtrl)MODES_OFB_Ctrl,
(CipherFreeCtx)MODES_OFB_FreeCtx
};
#endif
#ifdef HITLS_CRYPTO_XTS
static const EAL_CipherMethod XTS_METHOD = {
(CipherNewCtx)MODES_XTS_NewCtx,
(CipherInitCtx)MODES_XTS_InitCtxEx,
(CipherDeInitCtx)MODES_XTS_DeInitCtx,
(CipherUpdate)MODES_XTS_UpdateEx,
(CipherFinal)MODES_XTS_Final,
(CipherCtrl)MODES_XTS_Ctrl,
(CipherFreeCtx)MODES_XTS_FreeCtx
};
#endif
/**
* g_modeMethod[id]
* The content of g_modeMethod has a hash mapping relationship with CRYPT_MODE_AlgId. Change the value accordingly.
*/
static const EAL_CipherMethod *g_modeMethod[CRYPT_MODE_MAX] = {
#ifdef HITLS_CRYPTO_CBC
&CBC_METHOD,
#else
NULL,
#endif // cbc
#ifdef HITLS_CRYPTO_ECB
&ECB_METHOD,
#else
NULL,
#endif // ecb
#ifdef HITLS_CRYPTO_CTR
&CTR_METHOD,
#else
NULL,
#endif // ctr
#ifdef HITLS_CRYPTO_XTS
&XTS_METHOD,
#else
NULL,
#endif // xts
#ifdef HITLS_CRYPTO_CCM
&CCM_METHOD,
#else
NULL,
#endif // ccm
#ifdef HITLS_CRYPTO_GCM
&GCM_METHOD,
#else
NULL,
#endif // gcm
#if defined(HITLS_CRYPTO_CHACHA20) && defined(HITLS_CRYPTO_CHACHA20POLY1305)
&CHACHA20_POLY1305_METHOD,
#else
NULL,
#endif // chacha20
#ifdef HITLS_CRYPTO_CFB
&CFB_METHOD,
#else
NULL,
#endif // cfb
#ifdef HITLS_CRYPTO_OFB
&OFB_METHOD
#else
NULL
#endif // ofb
};
const EAL_CipherMethod *EAL_FindModeMethod(CRYPT_MODE_AlgId id)
{
if (id < 0 || id >= CRYPT_MODE_MAX) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_ALGID);
return NULL;
}
return g_modeMethod[id];
}
static const EAL_SymAlgMap SYM_ID_MAP[] = {
#ifdef HITLS_CRYPTO_AES
{.id = CRYPT_CIPHER_AES128_CBC, .modeId = CRYPT_MODE_CBC },
{.id = CRYPT_CIPHER_AES192_CBC, .modeId = CRYPT_MODE_CBC },
{.id = CRYPT_CIPHER_AES256_CBC, .modeId = CRYPT_MODE_CBC },
{.id = CRYPT_CIPHER_AES128_ECB, .modeId = CRYPT_MODE_ECB },
{.id = CRYPT_CIPHER_AES192_ECB, .modeId = CRYPT_MODE_ECB },
{.id = CRYPT_CIPHER_AES256_ECB, .modeId = CRYPT_MODE_ECB },
{.id = CRYPT_CIPHER_AES128_CTR, .modeId = CRYPT_MODE_CTR },
{.id = CRYPT_CIPHER_AES192_CTR, .modeId = CRYPT_MODE_CTR },
{.id = CRYPT_CIPHER_AES256_CTR, .modeId = CRYPT_MODE_CTR },
{.id = CRYPT_CIPHER_AES128_CCM, .modeId = CRYPT_MODE_CCM },
{.id = CRYPT_CIPHER_AES192_CCM, .modeId = CRYPT_MODE_CCM },
{.id = CRYPT_CIPHER_AES256_CCM, .modeId = CRYPT_MODE_CCM },
{.id = CRYPT_CIPHER_AES128_GCM, .modeId = CRYPT_MODE_GCM },
{.id = CRYPT_CIPHER_AES192_GCM, .modeId = CRYPT_MODE_GCM },
{.id = CRYPT_CIPHER_AES256_GCM, .modeId = CRYPT_MODE_GCM },
{.id = CRYPT_CIPHER_AES128_CFB, .modeId = CRYPT_MODE_CFB },
{.id = CRYPT_CIPHER_AES192_CFB, .modeId = CRYPT_MODE_CFB },
{.id = CRYPT_CIPHER_AES256_CFB, .modeId = CRYPT_MODE_CFB },
{.id = CRYPT_CIPHER_AES128_OFB, .modeId = CRYPT_MODE_OFB },
{.id = CRYPT_CIPHER_AES192_OFB, .modeId = CRYPT_MODE_OFB },
{.id = CRYPT_CIPHER_AES256_OFB, .modeId = CRYPT_MODE_OFB },
{.id = CRYPT_CIPHER_AES128_XTS, .modeId = CRYPT_MODE_XTS },
{.id = CRYPT_CIPHER_AES256_XTS, .modeId = CRYPT_MODE_XTS },
#endif
#ifdef HITLS_CRYPTO_CHACHA20
{.id = CRYPT_CIPHER_CHACHA20_POLY1305, .modeId = CRYPT_MODE_CHACHA20_POLY1305},
#endif
#ifdef HITLS_CRYPTO_SM4
{.id = CRYPT_CIPHER_SM4_XTS, .modeId = CRYPT_MODE_XTS },
{.id = CRYPT_CIPHER_SM4_ECB, .modeId = CRYPT_MODE_ECB },
{.id = CRYPT_CIPHER_SM4_CBC, .modeId = CRYPT_MODE_CBC },
{.id = CRYPT_CIPHER_SM4_CTR, .modeId = CRYPT_MODE_CTR },
{.id = CRYPT_CIPHER_SM4_GCM, .modeId = CRYPT_MODE_GCM },
{.id = CRYPT_CIPHER_SM4_CFB, .modeId = CRYPT_MODE_CFB },
{.id = CRYPT_CIPHER_SM4_OFB, .modeId = CRYPT_MODE_OFB },
#endif
};
int32_t EAL_FindCipher(CRYPT_CIPHER_AlgId id, const EAL_CipherMethod **modeMethod)
{
uint32_t num = sizeof(SYM_ID_MAP) / sizeof(SYM_ID_MAP[0]);
const EAL_SymAlgMap *symAlgMap = NULL;
for (uint32_t i = 0; i < num; i++) {
if (SYM_ID_MAP[i].id == id) {
symAlgMap = &SYM_ID_MAP[i];
break;
}
}
if (symAlgMap == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_ALGID);
return CRYPT_EAL_ERR_ALGID;
}
*modeMethod = EAL_FindModeMethod(symAlgMap->modeId);
if (*modeMethod == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_ALGID);
return CRYPT_EAL_ERR_ALGID;
}
return CRYPT_SUCCESS;
}
#ifdef HITLS_CRYPTO_AES
static const EAL_SymMethod AES128_METHOD = {
(SetEncryptKey)CRYPT_AES_SetEncryptKey128,
(SetDecryptKey)CRYPT_AES_SetDecryptKey128,
(EncryptBlock)CRYPT_AES_Encrypt,
(DecryptBlock)CRYPT_AES_Decrypt,
(DeInitBlockCtx)CRYPT_AES_Clean,
NULL,
16,
sizeof(CRYPT_AES_Key),
CRYPT_SYM_AES128
};
static const EAL_SymMethod AES192_METHOD = {
(SetEncryptKey)CRYPT_AES_SetEncryptKey192,
(SetDecryptKey)CRYPT_AES_SetDecryptKey192,
(EncryptBlock)CRYPT_AES_Encrypt,
(DecryptBlock)CRYPT_AES_Decrypt,
(DeInitBlockCtx)CRYPT_AES_Clean,
NULL,
16,
sizeof(CRYPT_AES_Key),
CRYPT_SYM_AES192
};
static const EAL_SymMethod AES256_METHOD = {
(SetEncryptKey)CRYPT_AES_SetEncryptKey256,
(SetDecryptKey)CRYPT_AES_SetDecryptKey256,
(EncryptBlock)CRYPT_AES_Encrypt,
(DecryptBlock)CRYPT_AES_Decrypt,
(DeInitBlockCtx)CRYPT_AES_Clean,
NULL,
16,
sizeof(CRYPT_AES_Key),
CRYPT_SYM_AES256
};
#endif
#ifdef HITLS_CRYPTO_CHACHA20
static const EAL_SymMethod CHACHA20_METHOD = {
(SetEncryptKey)CRYPT_CHACHA20_SetKey,
(SetDecryptKey)CRYPT_CHACHA20_SetKey,
(EncryptBlock)CRYPT_CHACHA20_Update,
(DecryptBlock)CRYPT_CHACHA20_Update,
(DeInitBlockCtx)CRYPT_CHACHA20_Clean,
(CipherCtrl)CRYPT_CHACHA20_Ctrl,
1,
sizeof(CRYPT_CHACHA20_Ctx),
CRYPT_SYM_CHACHA20
};
#endif
#ifdef HITLS_CRYPTO_SM4
static const EAL_SymMethod SM4_METHOD = {
(SetEncryptKey)CRYPT_SM4_SetKey,
(SetDecryptKey)CRYPT_SM4_SetKey,
(EncryptBlock)CRYPT_SM4_Encrypt,
(DecryptBlock)CRYPT_SM4_Decrypt,
(DeInitBlockCtx)CRYPT_SM4_Clean,
NULL,
16,
sizeof(CRYPT_SM4_Ctx),
CRYPT_SYM_SM4
};
#endif
const EAL_SymMethod *EAL_GetSymMethod(int32_t algId)
{
switch (algId) {
#ifdef HITLS_CRYPTO_AES
case CRYPT_CIPHER_AES128_CBC:
case CRYPT_CIPHER_AES128_ECB:
case CRYPT_CIPHER_AES128_XTS:
case CRYPT_CIPHER_AES128_CTR:
case CRYPT_CIPHER_AES128_CCM:
case CRYPT_CIPHER_AES128_GCM:
case CRYPT_CIPHER_AES128_CFB:
case CRYPT_CIPHER_AES128_OFB:
return &AES128_METHOD;
case CRYPT_CIPHER_AES192_CBC:
case CRYPT_CIPHER_AES192_ECB:
case CRYPT_CIPHER_AES192_CTR:
case CRYPT_CIPHER_AES192_CCM:
case CRYPT_CIPHER_AES192_GCM:
case CRYPT_CIPHER_AES192_CFB:
case CRYPT_CIPHER_AES192_OFB:
return &AES192_METHOD;
case CRYPT_CIPHER_AES256_CBC:
case CRYPT_CIPHER_AES256_ECB:
case CRYPT_CIPHER_AES256_CTR:
case CRYPT_CIPHER_AES256_XTS:
case CRYPT_CIPHER_AES256_CCM:
case CRYPT_CIPHER_AES256_GCM:
case CRYPT_CIPHER_AES256_CFB:
case CRYPT_CIPHER_AES256_OFB:
return &AES256_METHOD;
#endif
#ifdef HITLS_CRYPTO_SM4
case CRYPT_CIPHER_SM4_XTS:
case CRYPT_CIPHER_SM4_CBC:
case CRYPT_CIPHER_SM4_ECB:
case CRYPT_CIPHER_SM4_CTR:
case CRYPT_CIPHER_SM4_GCM:
case CRYPT_CIPHER_SM4_CFB:
case CRYPT_CIPHER_SM4_OFB:
return &SM4_METHOD;
#endif
#ifdef HITLS_CRYPTO_CHACHA20
case CRYPT_CIPHER_CHACHA20_POLY1305:
return &CHACHA20_METHOD;
#endif
default:
return NULL;
}
}
static CRYPT_CipherInfo g_cipherInfo[] = {
#ifdef HITLS_CRYPTO_AES
{.id = CRYPT_CIPHER_AES128_CBC, .blockSize = 16, .keyLen = 16, .ivLen = 16},
{.id = CRYPT_CIPHER_AES192_CBC, .blockSize = 16, .keyLen = 24, .ivLen = 16},
{.id = CRYPT_CIPHER_AES256_CBC, .blockSize = 16, .keyLen = 32, .ivLen = 16},
{.id = CRYPT_CIPHER_AES128_ECB, .blockSize = 16, .keyLen = 16, .ivLen = 0},
{.id = CRYPT_CIPHER_AES192_ECB, .blockSize = 16, .keyLen = 24, .ivLen = 0},
{.id = CRYPT_CIPHER_AES256_ECB, .blockSize = 16, .keyLen = 32, .ivLen = 0},
{.id = CRYPT_CIPHER_AES128_CTR, .blockSize = 1, .keyLen = 16, .ivLen = 16},
{.id = CRYPT_CIPHER_AES192_CTR, .blockSize = 1, .keyLen = 24, .ivLen = 16},
{.id = CRYPT_CIPHER_AES256_CTR, .blockSize = 1, .keyLen = 32, .ivLen = 16},
{.id = CRYPT_CIPHER_AES128_CCM, .blockSize = 1, .keyLen = 16, .ivLen = 12},
{.id = CRYPT_CIPHER_AES192_CCM, .blockSize = 1, .keyLen = 24, .ivLen = 12},
{.id = CRYPT_CIPHER_AES256_CCM, .blockSize = 1, .keyLen = 32, .ivLen = 12},
{.id = CRYPT_CIPHER_AES128_GCM, .blockSize = 1, .keyLen = 16, .ivLen = 12},
{.id = CRYPT_CIPHER_AES192_GCM, .blockSize = 1, .keyLen = 24, .ivLen = 12},
{.id = CRYPT_CIPHER_AES256_GCM, .blockSize = 1, .keyLen = 32, .ivLen = 12},
{.id = CRYPT_CIPHER_AES128_CFB, .blockSize = 1, .keyLen = 16, .ivLen = 16},
{.id = CRYPT_CIPHER_AES192_CFB, .blockSize = 1, .keyLen = 24, .ivLen = 16},
{.id = CRYPT_CIPHER_AES256_CFB, .blockSize = 1, .keyLen = 32, .ivLen = 16},
{.id = CRYPT_CIPHER_AES128_OFB, .blockSize = 1, .keyLen = 16, .ivLen = 16},
{.id = CRYPT_CIPHER_AES192_OFB, .blockSize = 1, .keyLen = 24, .ivLen = 16},
{.id = CRYPT_CIPHER_AES256_OFB, .blockSize = 1, .keyLen = 32, .ivLen = 16},
{.id = CRYPT_CIPHER_AES128_XTS, .blockSize = 1, .keyLen = 32, .ivLen = 16},
{.id = CRYPT_CIPHER_AES256_XTS, .blockSize = 1, .keyLen = 64, .ivLen = 16},
#endif
#ifdef HITLS_CRYPTO_CHACHA20
{.id = CRYPT_CIPHER_CHACHA20_POLY1305, .blockSize = 1, .keyLen = 32, .ivLen = 12},
#endif
#ifdef HITLS_CRYPTO_SM4
{.id = CRYPT_CIPHER_SM4_XTS, .blockSize = 1, .keyLen = 32, .ivLen = 16},
{.id = CRYPT_CIPHER_SM4_CBC, .blockSize = 16, .keyLen = 16, .ivLen = 16},
{.id = CRYPT_CIPHER_SM4_ECB, .blockSize = 16, .keyLen = 16, .ivLen = 0},
{.id = CRYPT_CIPHER_SM4_CTR, .blockSize = 1, .keyLen = 16, .ivLen = 16},
{.id = CRYPT_CIPHER_SM4_GCM, .blockSize = 1, .keyLen = 16, .ivLen = 12},
{.id = CRYPT_CIPHER_SM4_CFB, .blockSize = 1, .keyLen = 16, .ivLen = 16},
{.id = CRYPT_CIPHER_SM4_OFB, .blockSize = 1, .keyLen = 16, .ivLen = 16},
#endif
};
/**
* Search for the lengths of the block, key, and IV of algorithm. If ID in g_cipherInfo is changed,
* synchronize the value of the SDV_CRYPTO_CIPHER_FUN_TC008 test case.
* The input ID has a mapping relationship with g_ealCipherMethod and CRYPT_CIPHER_AlgId.
* The corresponding information must be synchronized to symMap.
* The symMap and CRYPT_SYM_AlgId, CRYPT_MODE_AlgId depend on each other. Synchronize the corresponding information.
*/
int32_t EAL_GetCipherInfo(CRYPT_CIPHER_AlgId id, CRYPT_CipherInfo *info)
{
uint32_t num = sizeof(g_cipherInfo) / sizeof(g_cipherInfo[0]);
const CRYPT_CipherInfo *cipherInfoGet = NULL;
for (uint32_t i = 0; i < num; i++) {
if (g_cipherInfo[i].id == id) {
cipherInfoGet = &g_cipherInfo[i];
break;
}
}
if (cipherInfoGet == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID);
return CRYPT_ERR_ALGID;
}
info->blockSize = cipherInfoGet->blockSize;
info->ivLen = cipherInfoGet->ivLen;
info->keyLen = cipherInfoGet->keyLen;
return CRYPT_SUCCESS;
}
#endif
|
2301_79861745/bench_create
|
crypto/eal/src/eal_cipher_method.c
|
C
|
unknown
| 15,720
|
/*
* 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)
#include <stddef.h>
#include "crypt_types.h"
#include "crypt_eal_md.h"
#include "crypt_eal_mac.h"
#include "eal_cipher_local.h"
#include "eal_pkey_local.h"
#include "eal_md_local.h"
#include "eal_mac_local.h"
#include "bsl_err_internal.h"
#include "eal_common.h"
EventReport g_eventReportFunc = NULL;
void CRYPT_EAL_RegEventReport(EventReport func)
{
g_eventReportFunc = func;
}
void EAL_EventReport(CRYPT_EVENT_TYPE oper, CRYPT_ALGO_TYPE type, int32_t id, int32_t err)
{
if (g_eventReportFunc == NULL) {
return;
}
g_eventReportFunc(oper, type, id, err);
}
#endif
|
2301_79861745/bench_create
|
crypto/eal/src/eal_common.c
|
C
|
unknown
| 1,190
|
/*
* 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_COMMON_H
#define EAL_COMMON_H
#include "hitls_build.h"
#ifdef HITLS_CRYPTO_EAL
#include <stdint.h>
#include "crypt_types.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
#define EAL_ERR_REPORT(oper, type, id, err) \
do { \
EAL_EventReport((oper), (type), (id), (err)); \
BSL_ERR_PUSH_ERROR((err)); \
} while (0)
void EAL_EventReport(CRYPT_EVENT_TYPE oper, CRYPT_ALGO_TYPE type, int32_t id, int32_t err);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // HITLS_CRYPTO_EAL
#endif // EAL_COMMON_H
|
2301_79861745/bench_create
|
crypto/eal/src/eal_common.h
|
C
|
unknown
| 1,094
|
/*
* 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_ENTROPY)
#include "securec.h"
#include "bsl_err_internal.h"
#include "crypt_errno.h"
#include "eal_entropy.h"
#define EAL_MAX_ENTROPY_EVERY_BYTE 8
#define EAL_ECF_OUT_LEN 16
static uint32_t GetMinLen(void *pool, uint32_t entropy, uint32_t minLen)
{
uint32_t minEntropy = ENTROPY_SeedPoolGetMinEntropy(pool);
if (minEntropy == 0) {
return 0;
}
uint32_t len = (uint32_t)(((uint64_t)entropy + (uint64_t)minEntropy - 1) / (uint64_t)minEntropy);
/* '<' indicates that the data with a length of len can provide sufficient bit entropy. */
if (len < minLen) {
len = minLen;
}
return len;
}
EAL_EntropyCtx *EAL_EntropyNewCtx(CRYPT_EAL_SeedPoolCtx *seedPool, uint8_t isNpesUsed, uint32_t minLen,
uint32_t maxLen, uint32_t entropy)
{
if (minLen > maxLen || maxLen == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
return NULL;
}
if (!ENTROPY_SeedPoolCheckState(seedPool->pool, isNpesUsed)) {
BSL_ERR_PUSH_ERROR(CRYPT_SEED_POOL_STATE_ERROR);
return NULL;
}
if (entropy > maxLen * EAL_MAX_ENTROPY_EVERY_BYTE) {
BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_RANGE_ERROR);
return NULL;
}
EAL_EntropyCtx *ctx = BSL_SAL_Malloc(sizeof(EAL_EntropyCtx));
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
(void)memset_s(ctx, sizeof(EAL_EntropyCtx), 0, sizeof(EAL_EntropyCtx));
ctx->minLen = minLen;
ctx->maxLen = maxLen;
ctx->isNpesUsed = isNpesUsed;
ctx->requestEntropy = entropy;
ctx->isNeedFe = (minLen == maxLen) ? true : false;
uint32_t needLen;
if (ctx->isNeedFe) {
ctx->ecfuncId = CRYPT_MAC_CMAC_AES128;
ctx->ecfOutLen = EAL_ECF_OUT_LEN;
ctx->ecfunc = EAL_EntropyGetECF(CRYPT_MAC_CMAC_AES128);
needLen = minLen;
} else {
needLen = GetMinLen(seedPool->pool, entropy, minLen);
}
ctx->buf = BSL_SAL_Malloc(needLen);
if (ctx->buf == NULL) {
BSL_SAL_Free(ctx);
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
ctx->bufLen = needLen;
return ctx;
}
void EAL_EntropyFreeCtx(EAL_EntropyCtx *ctx)
{
if (ctx->buf != NULL) {
(void)memset_s(ctx->buf, ctx->bufLen, 0, ctx->bufLen);
BSL_SAL_FREE(ctx->buf);
}
BSL_SAL_Free(ctx);
}
static int32_t EAL_EntropyObtain(void *seedPool, EAL_EntropyCtx *ctx)
{
while (ctx->curEntropy < ctx->requestEntropy) {
uint32_t needEntropy = ctx->requestEntropy - ctx->curEntropy;
uint8_t *buff = ctx->buf + ctx->curLen;
uint32_t len = ctx->bufLen - ctx->curLen;
uint32_t entropy = ENTROPY_SeedPoolCollect(seedPool, ctx->isNpesUsed, needEntropy, buff, &len);
if (entropy == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_SEED_POOL_NO_ENTROPY_OBTAINED);
return CRYPT_SEED_POOL_NO_ENTROPY_OBTAINED;
}
ctx->curEntropy += entropy;
ctx->curLen += len;
}
/*
* If the entropy data length is greater than the upper limit, the entropy source quality cannot meet the
* requirements and an error is reported.
*/
if (ctx->curLen > ctx->maxLen) {
BSL_ERR_PUSH_ERROR(CRYPT_SEED_POOL_NOT_MEET_REQUIREMENT);
return CRYPT_SEED_POOL_NOT_MEET_REQUIREMENT;
}
if (ctx->curLen < ctx->minLen) {
/*
* If the length of the entropy data is less than the lower limit of the required length,
* the entropy data that meets the length requirement is read without considering the entropy.
*/
uint32_t len = ctx->minLen - ctx->curLen;
uint32_t ent = ENTROPY_SeedPoolCollect(seedPool, true, 0, ctx->buf + ctx->curLen, &len);
if (ent == 0 || len != ctx->minLen - ctx->curLen) {
BSL_ERR_PUSH_ERROR(CRYPT_SEED_POOL_NO_SUFFICIENT_ENTROPY);
return CRYPT_SEED_POOL_NO_SUFFICIENT_ENTROPY;
}
ctx->curLen = ctx->minLen;
}
return CRYPT_SUCCESS;
}
static int32_t EAL_EntropyFesObtain(void *seedPool, EAL_EntropyCtx *ctx)
{
ENTROPY_ECFCtx seedCtx = {ctx->ecfuncId, ctx->ecfOutLen, ctx->ecfunc};
int32_t ret = ENTROPY_GetFullEntropyInput(&seedCtx, seedPool, ctx->isNpesUsed, ctx->requestEntropy, ctx->buf,
ctx->bufLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ctx->curEntropy = ctx->requestEntropy;
ctx->curLen = ctx->bufLen;
return ret;
}
int32_t EAL_EntropyCollection(CRYPT_EAL_SeedPoolCtx *seedPool, EAL_EntropyCtx *ctx)
{
if (!ENTROPY_SeedPoolCheckState(seedPool->pool, true)) {
BSL_ERR_PUSH_ERROR(CRYPT_SEED_POOL_STATE_ERROR);
return CRYPT_SEED_POOL_STATE_ERROR;
}
if (!ctx->isNeedFe || ENTROPY_SeedPoolGetMinEntropy(seedPool->pool) == EAL_MAX_ENTROPY_EVERY_BYTE) {
return EAL_EntropyObtain(seedPool->pool, ctx);
} else {
return EAL_EntropyFesObtain(seedPool->pool, ctx);
}
}
uint8_t *EAL_EntropyDetachBuf(EAL_EntropyCtx *ctx, uint32_t *len)
{
if (ctx->curEntropy < ctx->requestEntropy) {
BSL_ERR_PUSH_ERROR(CRYPT_DRBG_FAIL_GET_ENTROPY);
return NULL;
}
uint8_t *data = ctx->buf;
*len = ctx->curLen;
ctx->buf = NULL;
ctx->bufLen = 0;
ctx->curLen = 0;
ctx->curEntropy = 0;
return data;
}
static int32_t GetEntropy(void *seedCtx, CRYPT_Data *entropy, uint32_t strength, CRYPT_Range *lenRange)
{
return CRYPT_EAL_SeedPoolGetEntropy(seedCtx, entropy, strength, lenRange);
}
static void CleanEntropy(void *ctx, CRYPT_Data *entropy)
{
(void)ctx;
BSL_SAL_CleanseData(entropy->data, entropy->len);
BSL_SAL_FREE(entropy->data);
}
static int32_t GetNonce(void *ctx, CRYPT_Data *nonce, uint32_t strength, CRYPT_Range *lenRange)
{
return GetEntropy(ctx, nonce, strength, lenRange);
}
static void CleanNonce(void *ctx, CRYPT_Data *nonce)
{
CleanEntropy(ctx, nonce);
}
int32_t EAL_SetDefaultEntropyMeth(CRYPT_RandSeedMethod *meth)
{
if (meth == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
meth->getEntropy = GetEntropy;
meth->cleanEntropy = CleanEntropy;
meth->cleanNonce = CleanNonce;
meth->getNonce = GetNonce;
return CRYPT_SUCCESS;
}
#endif
|
2301_79861745/bench_create
|
crypto/eal/src/eal_entropy.c
|
C
|
unknown
| 6,865
|
/*
* 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_ENTROPY_H
#define EAL_ENTROPY_H
#include "hitls_build.h"
#if defined(HITLS_CRYPTO_EAL) && defined(HITLS_CRYPTO_ENTROPY)
#include "crypt_eal_entropy.h"
#include "bsl_sal.h"
#include "crypt_entropy.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
#ifdef HITLS_CRYPTO_ENTROPY_SYS
struct CryptEalEntropySource {
ENTROPY_EntropySource *es;
BSL_SAL_ThreadLockHandle lock; // thread lock
};
#endif
typedef struct {
/* whether non-physical entropy sources are allowed. */
bool isNpesUsed;
/* whether a full-entropy bit string is required. */
bool isNeedFe;
/* the minimum length of entropy data. */
uint32_t minLen;
/* the maximum length of entropy data. */
uint32_t maxLen;
/* the amount of entropy required. */
uint32_t requestEntropy;
/* the current amount of entropy. */
uint32_t curEntropy;
/* external conditioning function algorithm */
int32_t ecfuncId;
int32_t ecfOutLen;
/* external conditioning function */
ExternalConditioningFunction ecfunc;
/* the length of the existing entropy data */
uint32_t curLen;
/* the length of entropy buffer. */
uint32_t bufLen;
/* the buffer of entropy buffer. */
uint8_t *buf;
} EAL_EntropyCtx;
struct EAL_SeedPool {
CRYPT_EAL_Es *es;
void *pool;
BSL_SAL_ThreadLockHandle lock; // thread lock
};
/*
* @brief Creating an Entropy Source Application Handle.
*
* @param seedPool[IN] seed pool handle
* @param isNpesUsed[IN] whether non-physical entropy sources are allowed
* @param minLen[IN] the minimum length of entropy data
* @param maxLen[IN] the maximum length of entropy data
* @param entropy[IN] the amount of entropy required
* @return entropy context
*/
EAL_EntropyCtx *EAL_EntropyNewCtx(CRYPT_EAL_SeedPoolCtx *seedPool, uint8_t isNpesUsed, uint32_t minLen,
uint32_t maxLen, uint32_t entropy);
/*
* @brief Release an Entropy Source Application Handle.
*
* @param ctx[IN] seed pool handle
* @return void
*/
void EAL_EntropyFreeCtx(EAL_EntropyCtx *ctx);
/*
* @brief collect entropy data.
*
* @param seedPool[IN] seed pool handle
* @param ctx[IN] entropy source application Handle
* @return success: CRYPT_SUCCESS
* failed: other error codes
*/
int32_t EAL_EntropyCollection(CRYPT_EAL_SeedPoolCtx *seedPool, EAL_EntropyCtx *ctx);
/*
* @brief pop entropy data.
*
* @param seedPool[IN] seed pool handle
* @param ctx[IN] entropy source application Handle
* @param len[OUT] entropy buf length
* @return success: buffer
* failed: NULL
*/
uint8_t *EAL_EntropyDetachBuf(EAL_EntropyCtx *ctx, uint32_t *len);
/**
* @brief Set the random number method that uses the default system entropy source.
*
* @param meth meth method
* @return Success: CRYPT_SUCCESS
*/
int32_t EAL_SetDefaultEntropyMeth(CRYPT_RandSeedMethod *meth);
/**
* @brief Obtain the conditioning function of the corresponding algorithm.
*
* @param algId algId
* @return ExternalConditioningFunction
*/
ExternalConditioningFunction EAL_EntropyGetECF(uint32_t algId);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif
#endif
|
2301_79861745/bench_create
|
crypto/eal/src/eal_entropy.h
|
C
|
unknown
| 3,681
|
/*
* 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_ENTROPY)
#include "securec.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "eal_entropy.h"
#include "eal_common.h"
#ifdef HITLS_CRYPTO_ENTROPY_SYS
#include "eal_md_local.h"
#endif
#include "crypt_eal_entropy.h"
#define CRYPT_ENTROPY_SOURCE_FULL_ENTROPY 8
#ifdef HITLS_CRYPTO_ENTROPY_GM_CF
#define HITLS_ENTROPY_DEFAULT_CF "sm3_df"
#else
#define HITLS_ENTROPY_DEFAULT_CF "sha256_df"
#endif
#ifdef HITLS_CRYPTO_ENTROPY_SYS
CRYPT_EAL_Es *CRYPT_EAL_EsNew(void)
{
CRYPT_EAL_Es *esCtx = BSL_SAL_Malloc(sizeof(CRYPT_EAL_Es));
if (esCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
(void)memset_s(esCtx, sizeof(CRYPT_EAL_Es), 0, sizeof(CRYPT_EAL_Es));
esCtx->es = ENTROPY_EsNew();
if (esCtx->es == NULL) {
BSL_SAL_Free(esCtx);
BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ES_CREATE_ERROR);
return NULL;
}
int32_t ret = BSL_SAL_ThreadLockNew(&esCtx->lock);
if (ret != CRYPT_SUCCESS) {
ENTROPY_EsFree(esCtx->es);
BSL_SAL_FREE(esCtx);
BSL_ERR_PUSH_ERROR(ret);
return NULL;
}
return esCtx;
}
void CRYPT_EAL_EsFree(CRYPT_EAL_Es *esCtx)
{
if (esCtx == NULL) {
return;
}
BSL_SAL_ThreadLockHandle lock = esCtx->lock;
esCtx->lock = NULL;
if (BSL_SAL_ThreadWriteLock(lock) != BSL_SUCCESS) {
ENTROPY_EsFree(esCtx->es);
BSL_SAL_ThreadLockFree(lock);
BSL_SAL_Free(esCtx);
return;
}
ENTROPY_EsFree(esCtx->es);
(void)BSL_SAL_ThreadUnlock(lock);
BSL_SAL_ThreadLockFree(lock);
BSL_SAL_Free(esCtx);
return;
}
int32_t CRYPT_EAL_EsInit(CRYPT_EAL_Es *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret = BSL_SAL_ThreadWriteLock(ctx->lock);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = ENTROPY_EsInit(ctx->es);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
(void)BSL_SAL_ThreadUnlock(ctx->lock);
return ret;
}
uint32_t CRYPT_EAL_EsEntropyGet(CRYPT_EAL_Es *esCtx, uint8_t *data, uint32_t len)
{
if (esCtx == NULL || data == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return 0;
}
int32_t ret = BSL_SAL_ThreadWriteLock((esCtx->lock));
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR((ret));
return 0;
}
uint32_t resLen = ENTROPY_EsEntropyGet(esCtx->es, data, len);
(void)BSL_SAL_ThreadUnlock(esCtx->lock);
return resLen;
}
static uint32_t EAL_CfGetAlgId(const char *name)
{
if (strcmp(name, "sm3_df") == 0) {
return CRYPT_MD_SM3;
}
if (strcmp(name, "sha224_df") == 0) {
return CRYPT_MD_SHA224;
}
if (strcmp(name, "sha256_df") == 0) {
return CRYPT_MD_SHA256;
}
if (strcmp(name, "sha384_df") == 0) {
return CRYPT_MD_SHA384;
}
if (strcmp(name, "sha512_df") == 0) {
return CRYPT_MD_SHA512;
}
return CRYPT_MD_MAX;
}
static int32_t EAL_CFSetDfMethod(CRYPT_EAL_Es *esCtx, const char *name)
{
CRYPT_MD_AlgId alg = EAL_CfGetAlgId(name);
if (alg == CRYPT_MD_MAX) {
BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ECF_ALG_ERROR);
return CRYPT_ENTROPY_ECF_ALG_ERROR;
}
const EAL_MdMethod *md = EAL_MdFindDefaultMethod(alg);
if (md == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_MD, alg, CRYPT_EAL_ERR_ALGID);
return CRYPT_ENTROPY_ECF_ALG_ERROR;
}
ENTROPY_CFPara para = {alg, (void *)(uintptr_t)md};
return ENTROPY_EsCtrl(esCtx->es, CRYPT_ENTROPY_SET_CF, (void *)¶, sizeof(ENTROPY_CFPara));
}
static int32_t EAL_EsPoolCfSet(CRYPT_EAL_Es *esCtx, void *data, uint32_t len)
{
if (data == NULL || len == 0) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (strstr(data, "df") != NULL) {
return EAL_CFSetDfMethod(esCtx, data);
}
BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ECF_ALG_ERROR);
return CRYPT_ENTROPY_ECF_ALG_ERROR;
}
static int32_t EAL_EsCtrl(CRYPT_EAL_Es *esCtx, int32_t cmd, void *data, uint32_t len)
{
switch (cmd) {
case CRYPT_ENTROPY_SET_CF:
return EAL_EsPoolCfSet(esCtx, data, len);
case CRYPT_ENTROPY_GATHER_ENTROPY:
return ENTROPY_EsEntropyGather(esCtx->es);
default:
return ENTROPY_EsCtrl(esCtx->es, cmd, data, len);
}
}
int32_t CRYPT_EAL_EsCtrl(CRYPT_EAL_Es *esCtx, int32_t type, void *data, uint32_t len)
{
if (esCtx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (type < CRYPT_ENTROPY_SET_POOL_SIZE || type >= CRYPT_ENTROPY_MAX) {
BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_ES_CTRL_ERROR);
return CRYPT_ENTROPY_ES_CTRL_ERROR;
}
int32_t ret = BSL_SAL_ThreadWriteLock(esCtx->lock);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = EAL_EsCtrl(esCtx, type, data, len);
(void)BSL_SAL_ThreadUnlock(esCtx->lock);
return ret;
}
static CRYPT_EAL_Es *EsDefaultCreate(void)
{
CRYPT_EAL_Es *es = CRYPT_EAL_EsNew();
if (es == NULL) {
return NULL;
}
char *data = HITLS_ENTROPY_DEFAULT_CF;
int32_t ret = CRYPT_EAL_EsCtrl(es, CRYPT_ENTROPY_SET_CF, data, strlen(data));
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_EsFree(es);
return NULL;
}
ret = ENTROPY_EsInit(es->es);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_EsFree(es);
return NULL;
}
return es;
}
#endif
CRYPT_EAL_SeedPoolCtx *CRYPT_EAL_SeedPoolNew(bool isCreateNullPool)
{
CRYPT_EAL_SeedPoolCtx *ctx = BSL_SAL_Malloc(sizeof(CRYPT_EAL_SeedPoolCtx));
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
(void)memset_s(ctx, sizeof(CRYPT_EAL_SeedPoolCtx), 0, sizeof(CRYPT_EAL_SeedPoolCtx));
int32_t ret = BSL_SAL_ThreadLockNew(&ctx->lock);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_FREE(ctx);
BSL_ERR_PUSH_ERROR(ret);
return NULL;
}
ctx->pool = ENTROPY_SeedPoolNew(isCreateNullPool);
if (ctx->pool == NULL) {
CRYPT_EAL_SeedPoolFree(ctx);
BSL_ERR_PUSH_ERROR(CRYPT_SEED_POOL_NEW_ERROR);
return NULL;
}
#ifdef HITLS_CRYPTO_ENTROPY_SYS
if (isCreateNullPool) {
ctx->es = NULL;
return ctx;
}
ctx->es = EsDefaultCreate();
if (ctx->es == NULL) {
CRYPT_EAL_SeedPoolFree(ctx);
return NULL;
}
CRYPT_EAL_EsPara para = {false, CRYPT_ENTROPY_SOURCE_FULL_ENTROPY, ctx->es,
(CRYPT_EAL_EntropyGet)CRYPT_EAL_EsEntropyGet};
ret = ENTROPY_SeedPoolAddEs(ctx->pool, ¶);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_SeedPoolFree(ctx);
BSL_ERR_PUSH_ERROR(ret);
return NULL;
}
#endif
return ctx;
}
int32_t CRYPT_EAL_SeedPoolAddEs(CRYPT_EAL_SeedPoolCtx *ctx, const CRYPT_EAL_EsPara *para)
{
if (ctx == NULL || para == NULL || para->minEntropy == 0 || para->minEntropy > CRYPT_ENTROPY_SOURCE_FULL_ENTROPY ||
para->entropyGet == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret = BSL_SAL_ThreadWriteLock(ctx->lock);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = ENTROPY_SeedPoolAddEs(ctx->pool, para);
(void)BSL_SAL_ThreadUnlock(ctx->lock);
return ret;
}
void CRYPT_EAL_SeedPoolFree(CRYPT_EAL_SeedPoolCtx *ctx)
{
if (ctx == NULL) {
return;
}
(void)BSL_SAL_ThreadWriteLock(ctx->lock);
if (ctx->pool != NULL) {
ENTROPY_SeedPoolFree(ctx->pool);
ctx->pool = NULL;
}
#ifdef HITLS_CRYPTO_ENTROPY_SYS
if (ctx->es != NULL) {
CRYPT_EAL_EsFree(ctx->es);
ctx->es = NULL;
}
#endif
(void)BSL_SAL_ThreadUnlock(ctx->lock);
BSL_SAL_ThreadLockFree(ctx->lock);
BSL_SAL_FREE(ctx);
return;
}
static int32_t SeedPoolGetEntropy(CRYPT_EAL_SeedPoolCtx *poolCtx, CRYPT_Data *entropy, uint32_t strength,
const CRYPT_Range *lenRange)
{
EAL_EntropyCtx *ctx = EAL_EntropyNewCtx(poolCtx, true, lenRange->min, lenRange->max, strength);
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_ENTROPY_CTX_CREATE_FAILED);
return CRYPT_ENTROPY_CTX_CREATE_FAILED;
}
int32_t ret = EAL_EntropyCollection(poolCtx, ctx);
if (ret != CRYPT_SUCCESS) {
EAL_EntropyFreeCtx(ctx);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
entropy->data = EAL_EntropyDetachBuf(ctx, &entropy->len);
EAL_EntropyFreeCtx(ctx);
if (entropy->data == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_DRBG_FAIL_GET_ENTROPY);
return CRYPT_DRBG_FAIL_GET_ENTROPY;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_EAL_SeedPoolGetEntropy(CRYPT_EAL_SeedPoolCtx *ctx, CRYPT_Data *entropy, uint32_t strength,
const CRYPT_Range *lenRange)
{
if (ctx == NULL || entropy == NULL || lenRange == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
int32_t ret = BSL_SAL_ThreadWriteLock(ctx->lock);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = SeedPoolGetEntropy(ctx, entropy, strength, lenRange);
(void)BSL_SAL_ThreadUnlock(ctx->lock);
return ret;
}
#endif
|
2301_79861745/bench_create
|
crypto/eal/src/eal_entropyPool.c
|
C
|
unknown
| 10,317
|
/*
* 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_ENTROPY)
#include "securec.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "eal_entropy.h"
#include "eal_common.h"
#include "crypt_eal_mac.h"
#include "crypt_eal_md.h"
#ifdef HITLS_CRYPTO_MAC
#define ECF_ALG_KEY_LEN 16
static int32_t ECFMac(uint32_t algId, uint8_t *in, uint32_t inLen, uint8_t *out, uint32_t *outLen)
{
CRYPT_EAL_MacCtx *ctx = CRYPT_EAL_MacNewCtx(algId);
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_ENTROPY_CONDITION_FAILURE;
}
uint32_t keyLen = ECF_ALG_KEY_LEN;
uint8_t *ecfKey = (uint8_t *)BSL_SAL_Malloc(keyLen);
if (ecfKey == NULL) {
CRYPT_EAL_MacFreeCtx(ctx);
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return CRYPT_MEM_ALLOC_FAIL;
}
/* reference nist-800 90c-3pd section 3.3.1.1
* Unlike other cryptographic applications, keys used in these external conditioning functions do not require
* secrecy to accomplish their purpose so may be hard-coded, fixed, or all zeros.
*/
(void)memset_s(ecfKey, keyLen, 0, keyLen);
int32_t ret = CRYPT_EAL_MacInit(ctx, ecfKey, keyLen);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_MacFreeCtx(ctx);
BSL_SAL_FREE(ecfKey);
return ret;
}
ret = CRYPT_EAL_MacUpdate(ctx, in, inLen);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_MacFreeCtx(ctx);
BSL_SAL_FREE(ecfKey);
return ret;
}
ret = CRYPT_EAL_MacFinal(ctx, out, outLen);
CRYPT_EAL_MacFreeCtx(ctx);
BSL_SAL_FREE(ecfKey);
return ret;
}
#endif
ExternalConditioningFunction EAL_EntropyGetECF(uint32_t algId)
{
(void)algId;
#ifdef HITLS_CRYPTO_MAC
return ECFMac;
#else
return NULL;
#endif
}
#endif
|
2301_79861745/bench_create
|
crypto/eal/src/eal_entropy_ecf.c
|
C
|
unknown
| 2,370
|
/*
* 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_KDF)
#include <stdint.h>
#include "crypt_eal_kdf.h"
#include "securec.h"
#include "bsl_err_internal.h"
#include "crypt_local_types.h"
#include "crypt_eal_mac.h"
#ifdef HITLS_CRYPTO_PROVIDER
#include "crypt_eal_implprovider.h"
#include "crypt_provider.h"
#endif
#include "crypt_algid.h"
#include "crypt_errno.h"
#include "eal_mac_local.h"
#include "eal_kdf_local.h"
#ifdef HITLS_CRYPTO_HMAC
#include "crypt_hmac.h"
#endif
#ifdef HITLS_CRYPTO_PBKDF2
#include "crypt_pbkdf2.h"
#endif
#ifdef HITLS_CRYPTO_HKDF
#include "crypt_hkdf.h"
#endif
#ifdef HITLS_CRYPTO_KDFTLS12
#include "crypt_kdf_tls12.h"
#endif
#ifdef HITLS_CRYPTO_SCRYPT
#include "crypt_scrypt.h"
#endif
#include "eal_common.h"
#include "crypt_utils.h"
#include "bsl_sal.h"
static CRYPT_EAL_KdfCTX *KdfAllocCtx(CRYPT_KDF_AlgId id, EAL_KdfUnitaryMethod *method)
{
CRYPT_EAL_KdfCTX *ctx = BSL_SAL_Calloc(1u, sizeof(CRYPT_EAL_KdfCTX));
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
void *data = method->newCtx();
if (data == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_KDF, id, CRYPT_MEM_ALLOC_FAIL);
BSL_SAL_FREE(ctx);
return NULL;
}
ctx->data = data;
return ctx;
}
static void EalKdfCopyMethod(const EAL_KdfMethod *method, EAL_KdfUnitaryMethod *dest)
{
dest->newCtx = method->newCtx;
dest->setParam = method->setParam;
dest->derive = method->derive;
dest->deinit = method->deinit;
dest->freeCtx = method->freeCtx;
}
#ifdef HITLS_CRYPTO_PROVIDER
static int32_t CRYPT_EAL_SetKdfMethod(CRYPT_EAL_KdfCTX *ctx, const CRYPT_EAL_Func *funcs)
{
int32_t index = 0;
EAL_KdfUnitaryMethod *method = BSL_SAL_Calloc(1, sizeof(EAL_KdfUnitaryMethod));
if (method == NULL) {
BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
while (funcs[index].id != 0) {
switch (funcs[index].id) {
case CRYPT_EAL_IMPLKDF_NEWCTX:
method->provNewCtx = funcs[index].func;
break;
case CRYPT_EAL_IMPLKDF_SETPARAM:
method->setParam = funcs[index].func;
break;
case CRYPT_EAL_IMPLKDF_DERIVE:
method->derive = funcs[index].func;
break;
case CRYPT_EAL_IMPLKDF_DEINITCTX:
method->deinit = funcs[index].func;
break;
case CRYPT_EAL_IMPLKDF_CTRL:
method->ctrl = funcs[index].func;
break;
case CRYPT_EAL_IMPLKDF_FREECTX:
method->freeCtx = funcs[index].func;
break;
default:
BSL_SAL_FREE(method);
BSL_ERR_PUSH_ERROR(CRYPT_PROVIDER_ERR_UNEXPECTED_IMPL);
return CRYPT_PROVIDER_ERR_UNEXPECTED_IMPL;
}
index++;
}
ctx->method = method;
return CRYPT_SUCCESS;
}
CRYPT_EAL_KdfCTX *CRYPT_EAL_ProviderKdfNewCtxInner(CRYPT_EAL_LibCtx *libCtx, int32_t algId, const char *attrName)
{
const CRYPT_EAL_Func *funcs = NULL;
void *provCtx = NULL;
int32_t ret = CRYPT_EAL_ProviderGetFuncs(libCtx, CRYPT_EAL_OPERAID_KDF, algId, attrName,
&funcs, &provCtx);
if (ret != CRYPT_SUCCESS) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_KDF, algId, ret);
return NULL;
}
CRYPT_EAL_KdfCTX *ctx = BSL_SAL_Calloc(1u, sizeof(CRYPT_EAL_KdfCTX));
if (ctx == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_KDF, algId, CRYPT_MEM_ALLOC_FAIL);
return NULL;
}
ret = CRYPT_EAL_SetKdfMethod(ctx, funcs);
if (ret != BSL_SUCCESS) {
BSL_SAL_FREE(ctx);
return NULL;
}
if (ctx->method->provNewCtx == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_KDF, algId, CRYPT_PROVIDER_ERR_IMPL_NULL);
BSL_SAL_FREE(ctx->method);
BSL_SAL_FREE(ctx);
return NULL;
}
ctx->data = ctx->method->provNewCtx(provCtx, algId);
if (ctx->data == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_KDF, algId, CRYPT_MEM_ALLOC_FAIL);
BSL_SAL_FREE(ctx->method);
BSL_SAL_FREE(ctx);
return NULL;
}
ctx->id = algId;
ctx->isProvider = true;
return ctx;
}
#endif // HITLS_CRYPTO_PROVIDER
bool CRYPT_EAL_KdfIsValidAlgId(CRYPT_KDF_AlgId id)
{
const EAL_KdfMethod *method = EAL_KdfFindMethod(id);
if (method == NULL) {
return false;
} else {
return true;
}
}
CRYPT_EAL_KdfCTX *CRYPT_EAL_ProviderKdfNewCtx(CRYPT_EAL_LibCtx *libCtx, int32_t algId, const char *attrName)
{
#ifdef HITLS_CRYPTO_PROVIDER
return CRYPT_EAL_ProviderKdfNewCtxInner(libCtx, algId, attrName);
#else
(void)libCtx;
(void)attrName;
return CRYPT_EAL_KdfNewCtx(algId);
return NULL;
#endif
}
CRYPT_EAL_KdfCTX *CRYPT_EAL_KdfNewCtx(CRYPT_KDF_AlgId algId)
{
const EAL_KdfMethod *method = EAL_KdfFindMethod(algId);
if (method == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_KDF, algId, CRYPT_EAL_ERR_ALGID);
return NULL;
}
EAL_KdfUnitaryMethod *temp = BSL_SAL_Calloc(1, sizeof(EAL_KdfUnitaryMethod));
if (temp == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_KDF, algId, BSL_MALLOC_FAIL);
return NULL;
}
EalKdfCopyMethod(method, temp);
CRYPT_EAL_KdfCTX *ctx = KdfAllocCtx(algId, temp);
if (ctx == NULL) {
BSL_SAL_FREE(temp);
return NULL;
}
ctx->id = algId;
ctx->method = temp;
return ctx;
}
int32_t CRYPT_EAL_KdfSetParam(CRYPT_EAL_KdfCTX *ctx, const BSL_Param *param)
{
int32_t ret;
if (ctx == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_KDF, CRYPT_KDF_MAX, CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->method == NULL || ctx->method->setParam == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_KDF, ctx->id, CRYPT_EAL_ALG_NOT_SUPPORT);
return CRYPT_EAL_ALG_NOT_SUPPORT;
}
ret = ctx->method->setParam(ctx->data, param);
if (ret != CRYPT_SUCCESS) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_KDF, ctx->id, ret);
}
return ret;
}
int32_t CRYPT_EAL_KdfDerive(CRYPT_EAL_KdfCTX *ctx, uint8_t *key, uint32_t keyLen)
{
if (ctx == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_KDF, CRYPT_KDF_MAX, CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
if (ctx->method == NULL || ctx->method->derive == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_KDF, ctx->id, CRYPT_EAL_ALG_NOT_SUPPORT);
return CRYPT_EAL_ALG_NOT_SUPPORT;
}
int32_t ret = ctx->method->derive(ctx->data, key, keyLen);
if (ret != CRYPT_SUCCESS) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_KDF, ctx->id, ret);
return ret;
}
return CRYPT_SUCCESS;
}
int32_t CRYPT_EAL_KdfDeInitCtx(CRYPT_EAL_KdfCTX *ctx)
{
if (ctx == NULL || ctx->method == NULL || ctx->method->deinit == NULL) {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_KDF, CRYPT_KDF_MAX, CRYPT_NULL_INPUT);
return CRYPT_NULL_INPUT;
}
ctx->method->deinit(ctx->data);
return CRYPT_SUCCESS;
}
void CRYPT_EAL_KdfFreeCtx(CRYPT_EAL_KdfCTX *ctx)
{
if (ctx == NULL) {
return;
}
if (ctx->method != NULL && ctx->method->freeCtx != NULL) {
ctx->method->freeCtx(ctx->data);
EAL_EventReport(CRYPT_EVENT_ZERO, CRYPT_ALGO_KDF, ctx->id, CRYPT_SUCCESS);
} else {
EAL_ERR_REPORT(CRYPT_EVENT_ERR, CRYPT_ALGO_KDF, ctx->id, CRYPT_EAL_ALG_NOT_SUPPORT);
}
BSL_SAL_FREE(ctx->method);
BSL_SAL_FREE(ctx);
return;
}
#endif
|
2301_79861745/bench_create
|
crypto/eal/src/eal_kdf.c
|
C
|
unknown
| 8,217
|