Path: blob/main/crypto/libecc/src/curves/ec_montgomery.c
34869 views
/*1* Copyright (C) 2021 - This file is part of libecc project2*3* Authors:4* Ryad BENADJILA <[email protected]>5* Arnaud EBALARD <[email protected]>6*7* This software is licensed under a dual BSD and GPL v2 license.8* See LICENSE file at the root folder of the project.9*/10#include <libecc/curves/ec_montgomery.h>1112#define EC_MONTGOMERY_CRV_MAGIC ((word_t)(0x83734673a0443720ULL))1314/* Check if a Montgomery curve is initialized.15* Returns 0 on success, -1 on error.16*/17int ec_montgomery_crv_check_initialized(ec_montgomery_crv_src_t crv)18{19int ret;2021MUST_HAVE((crv != NULL) && (crv->magic == EC_MONTGOMERY_CRV_MAGIC), ret, err);22ret = 0;2324err:25return ret;26}2728/*29* Initialize pointed Montgomery curve structure using given A and B30* Fp elements representing curve equation (B v^2 = u^3 + A u^2 + u) parameters.31*32* The function returns 0 on success, -1 on error.33*/34int ec_montgomery_crv_init(ec_montgomery_crv_t crv, fp_src_t A, fp_src_t B, nn_src_t order)35{36int ret, iszero;37fp tmp;38tmp.magic = WORD(0);3940MUST_HAVE((crv != NULL), ret, err);4142ret = nn_check_initialized(order); EG(ret, err);43ret = fp_check_initialized(A); EG(ret, err);44ret = fp_check_initialized(B); EG(ret, err);45MUST_HAVE(A->ctx == B->ctx, ret, err);4647ret = fp_init(&tmp, A->ctx); EG(ret, err);4849/* A and B elements of Fp, A unequal to (+/-)2 and B non zero */50ret = fp_set_word_value(&tmp, 2); EG(ret, err);51ret = fp_add(&tmp, A, &tmp); EG(ret, err);52MUST_HAVE((!fp_iszero(&tmp, &iszero)) && (!iszero), ret, err);5354ret = fp_set_word_value(&tmp, 2); EG(ret, err);55ret = fp_sub(&tmp, A, &tmp); EG(ret, err);56MUST_HAVE((!fp_iszero(&tmp, &iszero)) && (!iszero), ret, err);57MUST_HAVE((!fp_iszero(B, &iszero)) && (!iszero), ret, err);5859ret = fp_init(&(crv->A), A->ctx); EG(ret, err);60ret = fp_init(&(crv->B), B->ctx); EG(ret, err);6162ret = fp_copy(&(crv->A), A); EG(ret, err);63ret = fp_copy(&(crv->B), B); EG(ret, err);6465ret = nn_copy(&(crv->order), order); EG(ret, err);6667crv->magic = EC_MONTGOMERY_CRV_MAGIC;6869err:70fp_uninit(&tmp);7172return ret;73}7475/* Uninitialize curve76*/77void ec_montgomery_crv_uninit(ec_montgomery_crv_t crv)78{79if ((crv != NULL) && (crv->magic == EC_MONTGOMERY_CRV_MAGIC)) {80crv->magic = WORD(0);81}8283return;84}858687