forked from cryptape/libecc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fp_pow.c
84 lines (72 loc) · 1.96 KB
/
fp_pow.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
/*
* 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 "../nn/nn_logical.h"
#include "fp_mul_redc1.h"
#include "fp_pow.h"
#include "fp.h"
/*
* NOT constant time with regard to the bitlength of exp.
* Aliasing not supported.
*/
#define TAB_ENTRIES 2
static void _fp_pow(fp_t out, fp_src_t base, nn_src_t exp)
{
fp base_monty, mul_monty, sqr_monty, out_monty, r;
fp_src_t tab_monty[TAB_ENTRIES];
bitcnt_t explen;
u8 expbit;
fp_check_initialized(base);
nn_check_initialized(exp);
fp_init(out, base->ctx);
MUST_HAVE(!nn_iszero(exp));
fp_init(&base_monty, out->ctx);
fp_init(&mul_monty, out->ctx);
fp_init(&sqr_monty, out->ctx);
fp_init(&out_monty, out->ctx);
fp_init(&r, out->ctx);
fp_set_nn(&r, &(out->ctx->r));
explen = nn_bitlen(exp) - 1;
fp_redcify(&base_monty, base);
nn_copy(&(out_monty.fp_val), &(base_monty.fp_val));
tab_monty[0] = &r;
tab_monty[1] = &base_monty;
while (explen-- > 0) {
expbit = nn_getbit(exp, explen);
fp_sqr_redc1(&sqr_monty, &out_monty);
fp_tabselect(&mul_monty, expbit, tab_monty, TAB_ENTRIES);
fp_mul_redc1(&out_monty, &sqr_monty, &mul_monty);
}
fp_unredcify(out, &out_monty);
fp_uninit(&base_monty);
fp_uninit(&mul_monty);
fp_uninit(&sqr_monty);
fp_uninit(&out_monty);
fp_uninit(&r);
}
/* Aliased version */
void fp_pow(fp_t out, fp_src_t base, nn_src_t exp)
{
/* Handle output aliasing */
if (out == base) {
fp out_cpy;
_fp_pow(&out_cpy, base, exp);
fp_init(out, out_cpy.ctx);
fp_copy(out, &out_cpy);
fp_uninit(&out_cpy);
} else {
_fp_pow(out, base, exp);
}
}