3 * Copyright (C) 2006-2012 Sawtooth Consulting Ltd.
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
28 #include <cyassl/ctaocrypt/dh.h>
29 #include <cyassl/ctaocrypt/error.h>
33 #define XPOW(x,y) pow((x),(y))
34 #define XLOG(x) log((x))
36 /* user's own math lib */
42 static INLINE word32 min(word32 a, word32 b)
50 void InitDhKey(DhKey* key)
53 /* TomsFastMath doesn't use memory allocation */
61 void FreeDhKey(DhKey* key)
64 /* TomsFastMath doesn't use memory allocation */
72 static word32 DiscreteLogWorkFactor(word32 n)
74 /* assuming discrete log takes about the same time as factoring */
78 return (word32)(2.4 * XPOW((double)n, 1.0/3.0) *
79 XPOW(XLOG((double)n), 2.0/3.0) - 5);
83 static void GeneratePrivate(DhKey* key, RNG* rng, byte* priv, word32* privSz)
85 word32 sz = mp_unsigned_bin_size(&key->p);
86 sz = min(sz, 2 * DiscreteLogWorkFactor(sz * BIT_SIZE) / BIT_SIZE + 1);
88 RNG_GenerateBlock(rng, priv, sz);
95 static int GeneratePublic(DhKey* key, const byte* priv, word32 privSz,
96 byte* pub, word32* pubSz)
103 if (mp_init_multi(&x, &y, 0, 0, 0, 0) != MP_OKAY)
106 if (mp_read_unsigned_bin(&x, priv, privSz) != MP_OKAY)
109 if (ret == 0 && mp_exptmod(&key->g, &x, &key->p, &y) != MP_OKAY)
112 if (ret == 0 && mp_to_unsigned_bin(&y, pub) != MP_OKAY)
116 *pubSz = mp_unsigned_bin_size(&y);
125 int DhGenerateKeyPair(DhKey* key, RNG* rng, byte* priv, word32* privSz,
126 byte* pub, word32* pubSz)
128 GeneratePrivate(key, rng, priv, privSz);
129 return GeneratePublic(key, priv, *privSz, pub, pubSz);
133 int DhAgree(DhKey* key, byte* agree, word32* agreeSz, const byte* priv,
134 word32 privSz, const byte* otherPub, word32 pubSz)
142 if (mp_init_multi(&x, &y, &z, 0, 0, 0) != MP_OKAY)
145 if (mp_read_unsigned_bin(&x, priv, privSz) != MP_OKAY)
148 if (ret == 0 && mp_read_unsigned_bin(&y, otherPub, pubSz) != MP_OKAY)
151 if (ret == 0 && mp_exptmod(&y, &x, &key->p, &z) != MP_OKAY)
154 if (ret == 0 && mp_to_unsigned_bin(&z, agree) != MP_OKAY)
158 *agreeSz = mp_unsigned_bin_size(&z);