1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 
4 #include "tomcrypt_private.h"
5 
6 #ifdef LTC_MECC
7 
8 /** Returns whether [x,y] is a point on curve defined by dp
9   @param dp     curve parameters
10   @param x      x point coordinate
11   @param y      y point coordinate
12   @return CRYPT_OK if valid
13 */
14 
ltc_ecc_is_point(const ltc_ecc_dp * dp,void * x,void * y)15 int ltc_ecc_is_point(const ltc_ecc_dp *dp, void *x, void *y)
16 {
17   void *prime, *a, *b, *t1, *t2;
18   int err;
19 
20   prime = dp->prime;
21   b     = dp->B;
22   a     = dp->A;
23 
24   if ((err = mp_init_multi(&t1, &t2, LTC_NULL)) != CRYPT_OK)  return err;
25 
26   /* compute y^2 */
27   if ((err = mp_sqr(y, t1)) != CRYPT_OK)                  goto cleanup;
28 
29   /* compute x^3 */
30   if ((err = mp_sqr(x, t2)) != CRYPT_OK)                  goto cleanup;
31   if ((err = mp_mod(t2, prime, t2)) != CRYPT_OK)          goto cleanup;
32   if ((err = mp_mul(x, t2, t2)) != CRYPT_OK)              goto cleanup;
33 
34   /* compute y^2 - x^3 */
35   if ((err = mp_sub(t1, t2, t1)) != CRYPT_OK)             goto cleanup;
36 
37   /* compute y^2 - x^3 - a*x */
38   if ((err = mp_submod(prime, a, prime, t2)) != CRYPT_OK) goto cleanup;
39   if ((err = mp_mulmod(t2, x, prime, t2)) != CRYPT_OK)    goto cleanup;
40   if ((err = mp_addmod(t1, t2, prime, t1)) != CRYPT_OK)   goto cleanup;
41 
42   /* adjust range (0, prime) */
43   while (mp_cmp_d(t1, 0) == LTC_MP_LT) {
44      if ((err = mp_add(t1, prime, t1)) != CRYPT_OK)       goto cleanup;
45   }
46   while (mp_cmp(t1, prime) != LTC_MP_LT) {
47      if ((err = mp_sub(t1, prime, t1)) != CRYPT_OK)       goto cleanup;
48   }
49 
50   /* compare to b */
51   if (mp_cmp(t1, b) != LTC_MP_EQ) {
52      err = CRYPT_INVALID_PACKET;
53   } else {
54      err = CRYPT_OK;
55   }
56 
57 cleanup:
58   mp_clear_multi(t1, t2, LTC_NULL);
59   return err;
60 }
61 
62 #endif
63