This repository has been archived by the owner on Jan 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 86
/
fp_mul.c
98 lines (78 loc) · 2.43 KB
/
fp_mul.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
* Copyright (C) 2017 - This file is part of libecc project
*
* Authors:
* Ryad BENADJILA <[email protected]>
* Arnaud EBALARD <[email protected]>
* Jean-Pierre FLORI <[email protected]>
*
* Contributors:
* Nicolas VIVET <[email protected]>
* Karim KHALFALLAH <[email protected]>
*
* This software is licensed under a dual BSD and GPL v2 license.
* See LICENSE file at the root folder of the project.
*/
#include "fp_mul.h"
#include "fp_pow.h"
#include "../nn/nn_add.h"
#include "../nn/nn_mul.h"
#include "../nn/nn_div.h"
#include "../nn/nn_modinv.h"
int fp_mul(fp_t out, fp_src_t in1, fp_src_t in2)
{
int ret;
ret = fp_check_initialized(in1); EG(ret, err);
ret = fp_check_initialized(in2); EG(ret, err);
ret = fp_check_initialized(out); EG(ret, err);
MUST_HAVE(out->ctx == in1->ctx, ret, err);
MUST_HAVE(out->ctx == in2->ctx, ret, err);
ret = nn_mul(&(out->fp_val), &(in1->fp_val), &(in2->fp_val)); EG(ret, err);
ret = nn_mod_unshifted(&(out->fp_val), &(out->fp_val), &(in1->ctx->p_normalized),
in1->ctx->p_reciprocal, in1->ctx->p_shift);
err:
return ret;
}
int fp_sqr(fp_t out, fp_src_t in)
{
return fp_mul(out, in, in);
}
/* We use Fermat's little theorem for our inversion in Fp:
* x^(p-1) = 1 mod (p) means that x^(p-2) mod(p) is the modular
* inverse of x mod (p)
*/
int fp_inv(fp_t out, fp_src_t in)
{
/* Use our lower layer Fermat modular inversion with precomputed
* Montgomery coefficients.
*/
int ret;
ret = fp_check_initialized(in); EG(ret, err);
ret = fp_check_initialized(out); EG(ret, err);
MUST_HAVE(out->ctx == in->ctx, ret, err);
/* We can use the Fermat inversion as p is surely prime here */
ret = nn_modinv_fermat_redc(&(out->fp_val), &(in->fp_val), &(in->ctx->p), &(in->ctx->r), &(in->ctx->r_square), in->ctx->mpinv);
err:
return ret;
}
int fp_inv_word(fp_t out, word_t w)
{
int ret;
ret = fp_check_initialized(out); EG(ret, err);
ret = nn_modinv_word(&(out->fp_val), w, &(out->ctx->p));
err:
return ret;
}
int fp_div(fp_t out, fp_src_t num, fp_src_t den)
{
int ret;
ret = fp_check_initialized(num); EG(ret, err);
ret = fp_check_initialized(den); EG(ret, err);
ret = fp_check_initialized(out); EG(ret, err);
MUST_HAVE(out->ctx == num->ctx, ret, err);
MUST_HAVE(out->ctx == den->ctx, ret, err);
ret = fp_inv(out, den); EG(ret, err);
ret = fp_mul(out, num, out);
err:
return ret;
}