xref: /freebsd/crypto/libecc/src/curves/ec_montgomery.c (revision f0865ec9906d5a18fa2a3b61381f22ce16e606ad)
1 /*
2  *  Copyright (C) 2021 - This file is part of libecc project
3  *
4  *  Authors:
5  *      Ryad BENADJILA <ryadbenadjila@gmail.com>
6  *      Arnaud EBALARD <arnaud.ebalard@ssi.gouv.fr>
7  *
8  *  This software is licensed under a dual BSD and GPL v2 license.
9  *  See LICENSE file at the root folder of the project.
10  */
11 #include <libecc/curves/ec_montgomery.h>
12 
13 #define EC_MONTGOMERY_CRV_MAGIC ((word_t)(0x83734673a0443720ULL))
14 
15 /* Check if a Montgomery curve is initialized.
16  * Returns 0 on success, -1 on error.
17  */
ec_montgomery_crv_check_initialized(ec_montgomery_crv_src_t crv)18 int ec_montgomery_crv_check_initialized(ec_montgomery_crv_src_t crv)
19 {
20 	int ret;
21 
22 	MUST_HAVE((crv != NULL) && (crv->magic == EC_MONTGOMERY_CRV_MAGIC), ret, err);
23 	ret = 0;
24 
25 err:
26 	return ret;
27 }
28 
29 /*
30  * Initialize pointed Montgomery curve structure using given A and B
31  * Fp elements representing curve equation (B v^2 = u^3 + A u^2 + u) parameters.
32  *
33  * The function returns 0 on success, -1 on error.
34  */
ec_montgomery_crv_init(ec_montgomery_crv_t crv,fp_src_t A,fp_src_t B,nn_src_t order)35 int ec_montgomery_crv_init(ec_montgomery_crv_t crv, fp_src_t A, fp_src_t B, nn_src_t order)
36 {
37 	int ret, iszero;
38 	fp tmp;
39 	tmp.magic = WORD(0);
40 
41 	MUST_HAVE((crv != NULL), ret, err);
42 
43 	ret = nn_check_initialized(order); EG(ret, err);
44 	ret = fp_check_initialized(A); EG(ret, err);
45 	ret = fp_check_initialized(B); EG(ret, err);
46 	MUST_HAVE(A->ctx == B->ctx, ret, err);
47 
48 	ret = fp_init(&tmp, A->ctx); EG(ret, err);
49 
50 	/* A and B elements of Fp, A unequal to (+/-)2 and B non zero */
51 	ret = fp_set_word_value(&tmp, 2); EG(ret, err);
52 	ret = fp_add(&tmp, A, &tmp); EG(ret, err);
53 	MUST_HAVE((!fp_iszero(&tmp, &iszero)) && (!iszero), ret, err);
54 
55 	ret = fp_set_word_value(&tmp, 2); EG(ret, err);
56 	ret = fp_sub(&tmp, A, &tmp); EG(ret, err);
57 	MUST_HAVE((!fp_iszero(&tmp, &iszero)) && (!iszero), ret, err);
58 	MUST_HAVE((!fp_iszero(B, &iszero)) && (!iszero), ret, err);
59 
60 	ret = fp_init(&(crv->A), A->ctx); EG(ret, err);
61 	ret = fp_init(&(crv->B), B->ctx); EG(ret, err);
62 
63 	ret = fp_copy(&(crv->A), A); EG(ret, err);
64 	ret = fp_copy(&(crv->B), B); EG(ret, err);
65 
66 	ret = nn_copy(&(crv->order), order); EG(ret, err);
67 
68 	crv->magic = EC_MONTGOMERY_CRV_MAGIC;
69 
70 err:
71 	fp_uninit(&tmp);
72 
73 	return ret;
74 }
75 
76 /* Uninitialize curve
77  */
ec_montgomery_crv_uninit(ec_montgomery_crv_t crv)78 void ec_montgomery_crv_uninit(ec_montgomery_crv_t crv)
79 {
80 	if ((crv != NULL) && (crv->magic == EC_MONTGOMERY_CRV_MAGIC)) {
81 		crv->magic = WORD(0);
82 	}
83 
84 	return;
85 }
86