1 // SPDX-License-Identifier: BSD-2-Clause
2 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
3  *
4  * LibTomCrypt is a library that provides various cryptographic
5  * algorithms in a highly modular and flexible manner.
6  *
7  * The library is free for all purposes without any express
8  * guarantee it works.
9  */
10 
11 #include "tomcrypt_private.h"
12 
13 #ifdef LTC_MECC
14 
15 /** Returns whether [x,y] is a point on curve defined by dp
16   @param dp     curve parameters
17   @param x      x point coordinate
18   @param y      y point coordinate
19   @return CRYPT_OK if valid
20 */
21 
ltc_ecc_is_point(const ltc_ecc_dp * dp,void * x,void * y)22 int ltc_ecc_is_point(const ltc_ecc_dp *dp, void *x, void *y)
23 {
24   void *prime, *a, *b, *t1, *t2;
25   int err;
26 
27   prime = dp->prime;
28   b     = dp->B;
29   a     = dp->A;
30 
31   if ((err = mp_init_multi(&t1, &t2, NULL)) != CRYPT_OK)  return err;
32 
33   /* compute y^2 */
34   if ((err = mp_sqr(y, t1)) != CRYPT_OK)                  goto cleanup;
35 
36   /* compute x^3 */
37   if ((err = mp_sqr(x, t2)) != CRYPT_OK)                  goto cleanup;
38   if ((err = mp_mod(t2, prime, t2)) != CRYPT_OK)          goto cleanup;
39   if ((err = mp_mul(x, t2, t2)) != CRYPT_OK)              goto cleanup;
40 
41   /* compute y^2 - x^3 */
42   if ((err = mp_sub(t1, t2, t1)) != CRYPT_OK)             goto cleanup;
43 
44   /* compute y^2 - x^3 - a*x */
45   if ((err = mp_submod(prime, a, prime, t2)) != CRYPT_OK) goto cleanup;
46   if ((err = mp_mulmod(t2, x, prime, t2)) != CRYPT_OK)    goto cleanup;
47   if ((err = mp_addmod(t1, t2, prime, t1)) != CRYPT_OK)   goto cleanup;
48 
49   /* adjust range (0, prime) */
50   while (mp_cmp_d(t1, 0) == LTC_MP_LT) {
51      if ((err = mp_add(t1, prime, t1)) != CRYPT_OK)       goto cleanup;
52   }
53   while (mp_cmp(t1, prime) != LTC_MP_LT) {
54      if ((err = mp_sub(t1, prime, t1)) != CRYPT_OK)       goto cleanup;
55   }
56 
57   /* compare to b */
58   if (mp_cmp(t1, b) != LTC_MP_EQ) {
59      err = CRYPT_INVALID_PACKET;
60   } else {
61      err = CRYPT_OK;
62   }
63 
64 cleanup:
65   mp_clear_multi(t1, t2, NULL);
66   return err;
67 }
68 
69 #endif
70 
71 /* ref:         $Format:%D$ */
72 /* git commit:  $Format:%H$ */
73 /* commit time: $Format:%ai$ */
74