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