Apply %restore_fcommon macro for Address Sanitizer
[platform/upstream/nettle.git] / curve25519-eh-to-x.c
1 /* curve25519-x.c
2
3    Copyright (C) 2014 Niels Möller
4
5    This file is part of GNU Nettle.
6
7    GNU Nettle is free software: you can redistribute it and/or
8    modify it under the terms of either:
9
10      * the GNU Lesser General Public License as published by the Free
11        Software Foundation; either version 3 of the License, or (at your
12        option) any later version.
13
14    or
15
16      * the GNU General Public License as published by the Free
17        Software Foundation; either version 2 of the License, or (at your
18        option) any later version.
19
20    or both in parallel, as here.
21
22    GNU Nettle is distributed in the hope that it will be useful,
23    but WITHOUT ANY WARRANTY; without even the implied warranty of
24    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
25    General Public License for more details.
26
27    You should have received copies of the GNU General Public License and
28    the GNU Lesser General Public License along with this program.  If
29    not, see http://www.gnu.org/licenses/.
30 */
31
32 #if HAVE_CONFIG_H
33 # include "config.h"
34 #endif
35
36 #include <string.h>
37
38 #include "curve25519.h"
39
40 #include "ecc.h"
41 #include "ecc-internal.h"
42
43 /* Transform a point on the twisted Edwards curve to the curve25519
44    Montgomery curve, and return the x coordinate. */
45 void
46 curve25519_eh_to_x (mp_limb_t *xp, const mp_limb_t *p,
47                     mp_limb_t *scratch)
48 {
49 #define vp (p + ecc->p.size)
50 #define wp (p + 2*ecc->p.size)
51 #define t0 scratch
52 #define t1 (scratch + ecc->p.size)
53 #define t2 (scratch + 2*ecc->p.size)
54
55   const struct ecc_curve *ecc = &_nettle_curve25519;
56   mp_limb_t cy;
57
58   /* If u = U/W and v = V/W are the coordiantes of the point on the
59      Edwards curve we get the curve25519 x coordinate as
60
61      x = (1+v) / (1-v) = (W + V) / (W - V)
62   */
63   /* NOTE: For the infinity point, this subtraction gives zero (mod
64      p), which isn't invertible. For curve25519, the desired output is
65      x = 0, and we should be fine, since ecc_modp_inv returns 0
66      in this case. */
67   ecc_modp_sub (ecc, t0, wp, vp);
68   /* Needs a total of 5*size storage. */
69   ecc->p.invert (&ecc->p, t1, t0, t2 + ecc->p.size);
70   
71   ecc_modp_add (ecc, t0, wp, vp);
72   ecc_modp_mul (ecc, t2, t0, t1);
73
74   cy = mpn_sub_n (xp, t2, ecc->p.m, ecc->p.size);
75   cnd_copy (cy, xp, t2, ecc->p.size);
76 #undef vp
77 #undef wp
78 #undef t0
79 #undef t1
80 #undef t2
81 }