a99ac1a95ccb27beec89a22124e7364c2403d2b9
2 * Copyright (c) 2017 Thomas Pornin <pornin@bolet.org>
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
19 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
20 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 * This file contains some additional functions for "i15" big integers.
29 * These functions are needed to support ECDSA.
34 br_i15_rshift(uint16_t *x
, int count
)
39 len
= (x
[0] + 15) >> 4;
44 for (u
= 2; u
<= len
; u
++) {
48 x
[u
- 1] = ((w
<< (15 - count
)) | r
) & 0x7FFF;
56 br_i15_bit_length(uint16_t *x
, size_t xlen
)
68 twk
= MUX(c
, (uint32_t)xlen
, twk
);
70 return (twk
<< 4) + BIT_LENGTH(tw
);
75 br_i15_decode(uint16_t *x
, const void *src
, size_t len
)
77 const unsigned char *buf
;
90 acc
|= (b
<< acc_len
);
93 x
[v
++] = acc
& 0x7FFF;
101 x
[0] = br_i15_bit_length(x
+ 1, v
- 1);
106 br_i15_from_monty(uint16_t *x
, const uint16_t *m
, uint16_t m0i
)
110 len
= (m
[0] + 15) >> 4;
111 for (u
= 0; u
< len
; u
++) {
114 f
= MUL15(x
[1], m0i
) & 0x7FFF;
116 for (v
= 0; v
< len
; v
++) {
119 z
= (uint32_t)x
[v
+ 1] + MUL15(f
, m
[v
+ 1]) + cc
;
129 * We may have to do an extra subtraction, but only if the
130 * value in x[] is indeed greater than or equal to that of m[],
131 * which is why we must do two calls (first call computes the
132 * carry, second call performs the subtraction only if the carry
135 br_i15_sub(x
, m
, NOT(br_i15_sub(x
, m
, 0)));