comparison libtomcrypt/src/pk/dh/dh_generate_key.c @ 1471:6dba84798cd5

Update to libtomcrypt 1.18.1, merged with Dropbear changes
author Matt Johnston <matt@ucc.asn.au>
date Fri, 09 Feb 2018 21:44:05 +0800
parents
children
comparison
equal deleted inserted replaced
1470:8bba51a55704 1471:6dba84798cd5
1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
2 *
3 * LibTomCrypt is a library that provides various cryptographic
4 * algorithms in a highly modular and flexible manner.
5 *
6 * The library is free for all purposes without any express
7 * guarantee it works.
8 */
9
10 #include "tomcrypt.h"
11
12 #ifdef LTC_MDH
13
14 static int _dh_groupsize_to_keysize(int groupsize)
15 {
16 /* The strength estimates from https://tools.ietf.org/html/rfc3526#section-8
17 * We use "Estimate 2" to get an appropriate private key (exponent) size.
18 */
19 if (groupsize <= 0) {
20 return 0;
21 }
22 else if (groupsize <= 192) {
23 return 30; /* 1536-bit => key size 240-bit */
24 }
25 else if (groupsize <= 256) {
26 return 40; /* 2048-bit => key size 320-bit */
27 }
28 else if (groupsize <= 384) {
29 return 52; /* 3072-bit => key size 416-bit */
30 }
31 else if (groupsize <= 512) {
32 return 60; /* 4096-bit => key size 480-bit */
33 }
34 else if (groupsize <= 768) {
35 return 67; /* 6144-bit => key size 536-bit */
36 }
37 else if (groupsize <= 1024) {
38 return 77; /* 8192-bit => key size 616-bit */
39 }
40 else {
41 return 0;
42 }
43 }
44
45 int dh_generate_key(prng_state *prng, int wprng, dh_key *key)
46 {
47 unsigned char *buf;
48 unsigned long keysize;
49 int err, max_iterations = LTC_PK_MAX_RETRIES;
50
51 LTC_ARGCHK(key != NULL);
52 LTC_ARGCHK(ltc_mp.name != NULL);
53
54 /* good prng? */
55 if ((err = prng_is_valid(wprng)) != CRYPT_OK) {
56 return err;
57 }
58
59 keysize = _dh_groupsize_to_keysize(mp_unsigned_bin_size(key->prime));
60 if (keysize == 0) {
61 err = CRYPT_INVALID_KEYSIZE;
62 goto freemp;
63 }
64
65 /* allocate buffer */
66 buf = XMALLOC(keysize);
67 if (buf == NULL) {
68 err = CRYPT_MEM;
69 goto freemp;
70 }
71
72 key->type = PK_PRIVATE;
73 do {
74 /* make up random buf */
75 if (prng_descriptor[wprng].read(buf, keysize, prng) != keysize) {
76 err = CRYPT_ERROR_READPRNG;
77 goto freebuf;
78 }
79 /* load the x value - private key */
80 if ((err = mp_read_unsigned_bin(key->x, buf, keysize)) != CRYPT_OK) {
81 goto freebuf;
82 }
83 /* compute the y value - public key */
84 if ((err = mp_exptmod(key->base, key->x, key->prime, key->y)) != CRYPT_OK) {
85 goto freebuf;
86 }
87 err = dh_check_pubkey(key);
88 } while (err != CRYPT_OK && max_iterations-- > 0);
89
90 freebuf:
91 zeromem(buf, keysize);
92 XFREE(buf);
93 freemp:
94 if (err != CRYPT_OK) dh_free(key);
95 return err;
96 }
97
98 #endif /* LTC_MDH */
99
100 /* ref: $Format:%D$ */
101 /* git commit: $Format:%H$ */
102 /* commit time: $Format:%ai$ */