mySQL 5.0.11 sources for tomato
[tomato.git] / release / src / router / mysql / extra / yassl / taocrypt / src / dh.cpp
blobd6a61cfb1f39fc9b0dd653e67c1853038a9d6be3
1 /*
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,
16 MA 02110-1301 USA.
20 /* dh.cpp implements Diffie-Hellman support
23 #include "runtime.hpp"
24 #include "dh.hpp"
25 #include "asn.hpp"
26 #include <math.h>
28 namespace TaoCrypt {
31 namespace { // locals
33 unsigned int DiscreteLogWorkFactor(unsigned int n)
35 // assuming discrete log takes about the same time as factoring
36 if (n<5)
37 return 0;
38 else
39 return (unsigned int)(2.4 * pow((double)n, 1.0/3.0) *
40 pow(log(double(n)), 2.0/3.0) - 5);
43 } // namespace locals
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());
67 Integer x(priv, bc);
68 Integer y(a_exp_b_mod_c(g_, x, p_));
69 y.Encode(pub, bc);
73 // Generate Agreement
74 void DH::Agree(byte* agree, const byte* priv, const byte* otherPub, word32
75 otherSz)
77 const word32 bc(p_.ByteCount());
78 Integer x(priv, bc);
79 Integer y;
80 if (otherSz)
81 y.Decode(otherPub, otherSz);
82 else
83 y.Decode(otherPub, bc);
85 Integer z(a_exp_b_mod_c(y, x, p_));
86 z.Encode(agree, bc);
90 DH::DH(Source& source)
92 Initialize(source);
96 void DH::Initialize(Source& source)
98 DH_Decoder decoder(source);
99 decoder.Decode(*this);
103 } // namespace