2 Copyright (C) 2000-2007 MySQL AB
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; version 2 of the License.
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
13 You should have received a copy of the GNU General Public License
14 along with this program; see the file COPYING. If not, write to the
15 Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
20 /* dh.cpp implements Diffie-Hellman support
23 #include "runtime.hpp"
33 unsigned int DiscreteLogWorkFactor(unsigned int n
)
35 // assuming discrete log takes about the same time as factoring
39 return (unsigned int)(2.4 * pow((double)n
, 1.0/3.0) *
40 pow(log(double(n
)), 2.0/3.0) - 5);
46 // Generate a DH Key Pair
47 void DH::GenerateKeyPair(RandomNumberGenerator
& rng
, byte
* priv
, byte
* pub
)
49 GeneratePrivate(rng
, priv
);
50 GeneratePublic(priv
, pub
);
54 // Generate private value
55 void DH::GeneratePrivate(RandomNumberGenerator
& rng
, byte
* priv
)
57 Integer
x(rng
, Integer::One(), min(p_
- 1,
58 Integer::Power2(2*DiscreteLogWorkFactor(p_
.BitCount())) ) );
59 x
.Encode(priv
, p_
.ByteCount());
63 // Generate public value
64 void DH::GeneratePublic(const byte
* priv
, byte
* pub
)
66 const word32
bc(p_
.ByteCount());
68 Integer
y(a_exp_b_mod_c(g_
, x
, p_
));
74 void DH::Agree(byte
* agree
, const byte
* priv
, const byte
* otherPub
, word32
77 const word32
bc(p_
.ByteCount());
81 y
.Decode(otherPub
, otherSz
);
83 y
.Decode(otherPub
, bc
);
85 Integer
z(a_exp_b_mod_c(y
, x
, p_
));
90 DH::DH(Source
& source
)
96 void DH::Initialize(Source
& source
)
98 DH_Decoder
decoder(source
);
99 decoder
.Decode(*this);