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 /**
14   @file ltc_ecc_map.c
15   ECC Crypto, Tom St Denis
16 */
17 
18 #ifdef LTC_MECC
19 
20 /**
21   Map a projective jacbobian point back to affine space
22   @param P        [in/out] The point to map
23   @param modulus  The modulus of the field the ECC curve is in
24   @param mp       The "b" value from montgomery_setup()
25   @return CRYPT_OK on success
26 */
ltc_ecc_map(ecc_point * P,void * modulus,void * mp)27 int ltc_ecc_map(ecc_point *P, void *modulus, void *mp)
28 {
29    void *t1, *t2;
30    int   err;
31 
32    LTC_ARGCHK(P       != NULL);
33    LTC_ARGCHK(modulus != NULL);
34    LTC_ARGCHK(mp      != NULL);
35 
36    if (mp_iszero(P->z)) {
37       return ltc_ecc_set_point_xyz(0, 0, 1, P);
38    }
39 
40    if ((err = mp_init_multi(&t1, &t2, NULL)) != CRYPT_OK) {
41       return err;
42    }
43 
44    /* first map z back to normal */
45    if ((err = mp_montgomery_reduce(P->z, modulus, mp)) != CRYPT_OK)           { goto done; }
46 
47    /* get 1/z */
48    if ((err = mp_invmod(P->z, modulus, t1)) != CRYPT_OK)                      { goto done; }
49 
50    /* get 1/z^2 and 1/z^3 */
51    if ((err = mp_sqr(t1, t2)) != CRYPT_OK)                                    { goto done; }
52    if ((err = mp_mod(t2, modulus, t2)) != CRYPT_OK)                           { goto done; }
53    if ((err = mp_mul(t1, t2, t1)) != CRYPT_OK)                                { goto done; }
54    if ((err = mp_mod(t1, modulus, t1)) != CRYPT_OK)                           { goto done; }
55 
56    /* multiply against x/y */
57    if ((err = mp_mul(P->x, t2, P->x)) != CRYPT_OK)                            { goto done; }
58    if ((err = mp_montgomery_reduce(P->x, modulus, mp)) != CRYPT_OK)           { goto done; }
59    if ((err = mp_mul(P->y, t1, P->y)) != CRYPT_OK)                            { goto done; }
60    if ((err = mp_montgomery_reduce(P->y, modulus, mp)) != CRYPT_OK)           { goto done; }
61    if ((err = mp_set(P->z, 1)) != CRYPT_OK)                                   { goto done; }
62 
63    err = CRYPT_OK;
64 done:
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 
75