tizen 2.4 release
[external/nettle.git] / ecc-point.c
1 /* ecc-point.c */
2
3 /* nettle, low-level cryptographics library
4  *
5  * Copyright (C) 2013 Niels Möller
6  *  
7  * The nettle library is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU Lesser General Public License as published by
9  * the Free Software Foundation; either version 2.1 of the License, or (at your
10  * option) any later version.
11  * 
12  * The nettle library is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
15  * License for more details.
16  * 
17  * You should have received a copy of the GNU Lesser General Public License
18  * along with the nettle library; see the file COPYING.LIB.  If not, write to
19  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
20  * MA 02111-1301, USA.
21  */
22
23 /* Development of Nettle's ECC support was funded by the .SE Internet Fund. */
24
25 #if HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #include "ecc.h"
30 #include "ecc-internal.h"
31
32 void
33 ecc_point_init (struct ecc_point *p, const struct ecc_curve *ecc)
34 {
35   p->ecc = ecc;
36   p->p = gmp_alloc_limbs (2*ecc->size);
37 }
38
39 void
40 ecc_point_clear (struct ecc_point *p)
41 {
42   gmp_free_limbs (p->p, 2*p->ecc->size);
43 }
44
45 int
46 ecc_point_set (struct ecc_point *p, const mpz_t x, const mpz_t y)
47 {
48   mp_size_t size;  
49   mpz_t lhs, rhs;
50   mpz_t t;
51   int res;
52
53   size = p->ecc->size;
54   
55   if (mpz_sgn (x) < 0 || mpz_limbs_cmp (x, p->ecc->p, size) >= 0
56       || mpz_sgn (y) < 0 || mpz_limbs_cmp (y, p->ecc->p, size) >= 0)
57     return 0;
58
59   mpz_init (lhs);
60   mpz_init (rhs);
61
62   /* Check that y^2 = x^3 - 3*x + b (mod p) */
63   mpz_mul (lhs, y, y);
64   mpz_mul (rhs, x, x);
65   mpz_sub_ui (rhs, rhs, 3);
66   mpz_mul (rhs, rhs, x);
67   mpz_add (rhs, rhs, mpz_roinit_n (t, p->ecc->b, size));
68
69   res = mpz_congruent_p (lhs, rhs, mpz_roinit_n (t, p->ecc->p, size));
70
71   mpz_clear (lhs);
72   mpz_clear (rhs);
73
74   if (!res)
75     return 0;
76
77   mpz_limbs_copy (p->p, x, size);
78   mpz_limbs_copy (p->p + size, y, size);
79
80   return 1;
81 }
82
83 void
84 ecc_point_get (const struct ecc_point *p, mpz_t x, mpz_t y)
85 {
86   mp_size_t size = p->ecc->size;
87   if (x)
88     mpz_set_n (x, p->p, size);
89   if (y)
90     mpz_set_n (y, p->p + size, size);
91 }