3 * Copyright (C) 2006-2014 wolfSSL Inc.
5 * This file is part of CyaSSL.
7 * CyaSSL is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * CyaSSL is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
26 #include <cyassl/ctaocrypt/settings.h>
30 #include <cyassl/ctaocrypt/dh.h>
31 #include <cyassl/ctaocrypt/error-crypt.h>
35 #define XPOW(x,y) pow((x),(y))
36 #define XLOG(x) log((x))
38 /* user's own math lib */
44 static INLINE word32 min(word32 a, word32 b)
52 void InitDhKey(DhKey* key)
55 /* TomsFastMath doesn't use memory allocation */
63 void FreeDhKey(DhKey* key)
66 /* TomsFastMath doesn't use memory allocation */
74 static word32 DiscreteLogWorkFactor(word32 n)
76 /* assuming discrete log takes about the same time as factoring */
80 return (word32)(2.4 * XPOW((double)n, 1.0/3.0) *
81 XPOW(XLOG((double)n), 2.0/3.0) - 5);
85 static int GeneratePrivate(DhKey* key, RNG* rng, byte* priv, word32* privSz)
88 word32 sz = mp_unsigned_bin_size(&key->p);
89 sz = min(sz, 2 * DiscreteLogWorkFactor(sz * CYASSL_BIT_SIZE) /
92 ret = RNG_GenerateBlock(rng, priv, sz);
104 static int GeneratePublic(DhKey* key, const byte* priv, word32 privSz,
105 byte* pub, word32* pubSz)
112 if (mp_init_multi(&x, &y, 0, 0, 0, 0) != MP_OKAY)
115 if (mp_read_unsigned_bin(&x, priv, privSz) != MP_OKAY)
118 if (ret == 0 && mp_exptmod(&key->g, &x, &key->p, &y) != MP_OKAY)
121 if (ret == 0 && mp_to_unsigned_bin(&y, pub) != MP_OKAY)
125 *pubSz = mp_unsigned_bin_size(&y);
134 int DhGenerateKeyPair(DhKey* key, RNG* rng, byte* priv, word32* privSz,
135 byte* pub, word32* pubSz)
137 int ret = GeneratePrivate(key, rng, priv, privSz);
139 return (ret != 0) ? ret : GeneratePublic(key, priv, *privSz, pub, pubSz);
142 int DhAgree(DhKey* key, byte* agree, word32* agreeSz, const byte* priv,
143 word32 privSz, const byte* otherPub, word32 pubSz)
151 if (mp_init_multi(&x, &y, &z, 0, 0, 0) != MP_OKAY)
154 if (mp_read_unsigned_bin(&x, priv, privSz) != MP_OKAY)
157 if (ret == 0 && mp_read_unsigned_bin(&y, otherPub, pubSz) != MP_OKAY)
160 if (ret == 0 && mp_exptmod(&y, &x, &key->p, &z) != MP_OKAY)
163 if (ret == 0 && mp_to_unsigned_bin(&z, agree) != MP_OKAY)
167 *agreeSz = mp_unsigned_bin_size(&z);