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_MDH
14 
15 /**
16   Check DH public key (INTERNAL ONLY, not part of public API)
17   @param key    The key you wish to test
18   @return CRYPT_OK if successful
19 */
dh_check_pubkey(const dh_key * key)20 int dh_check_pubkey(const dh_key *key)
21 {
22    void *p_minus1;
23    ltc_mp_digit digit;
24    int i, digit_count, bits_set = 0, err;
25 
26    LTC_ARGCHK(key != NULL);
27 
28    if ((err = mp_init(&p_minus1)) != CRYPT_OK) {
29       return err;
30    }
31 
32    /* avoid: y <= 1 OR y >= p-1 */
33    if ((err = mp_sub_d(key->prime, 1, p_minus1)) != CRYPT_OK) {
34       goto error;
35    }
36    if (mp_cmp(key->y, p_minus1) != LTC_MP_LT || mp_cmp_d(key->y, 1) != LTC_MP_GT) {
37       err = CRYPT_INVALID_ARG;
38       goto error;
39    }
40 
41    /* public key must have more than one bit set */
42    digit_count = mp_get_digit_count(key->y);
43    for (i = 0; i < digit_count && bits_set < 2; i++) {
44       digit = mp_get_digit(key->y, i);
45       while (digit > 0) {
46          if (digit & 1) bits_set++;
47          digit >>= 1;
48       }
49    }
50    if (bits_set > 1) {
51       err = CRYPT_OK;
52    }
53    else {
54       err = CRYPT_INVALID_ARG;
55    }
56 
57 error:
58    mp_clear(p_minus1);
59    return err;
60 }
61 
62 #endif /* LTC_MDH */
63 
64 /* ref:         $Format:%D$ */
65 /* git commit:  $Format:%H$ */
66 /* commit time: $Format:%ai$ */
67