MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
dh.cpp
1 /*
2  Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
3 
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.
7 
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.
12 
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.
17 */
18 
19 
20 /* dh.cpp implements Diffie-Hellman support
21 */
22 
23 #include "runtime.hpp"
24 #include "dh.hpp"
25 #include "asn.hpp"
26 #include <math.h>
27 
28 namespace TaoCrypt {
29 
30 
31 namespace { // locals
32 
33 unsigned int DiscreteLogWorkFactor(unsigned int n)
34 {
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);
41 }
42 
43 } // namespace locals
44 
45 
46 // Generate a DH Key Pair
47 void DH::GenerateKeyPair(RandomNumberGenerator& rng, byte* priv, byte* pub)
48 {
49  GeneratePrivate(rng, priv);
50  GeneratePublic(priv, pub);
51 }
52 
53 
54 // Generate private value
55 void DH::GeneratePrivate(RandomNumberGenerator& rng, byte* priv)
56 {
57  Integer x(rng, Integer::One(), min(p_ - 1,
58  Integer::Power2(2*DiscreteLogWorkFactor(p_.BitCount())) ) );
59  x.Encode(priv, p_.ByteCount());
60 }
61 
62 
63 // Generate public value
64 void DH::GeneratePublic(const byte* priv, byte* pub)
65 {
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);
70 }
71 
72 
73 // Generate Agreement
74 void DH::Agree(byte* agree, const byte* priv, const byte* otherPub, word32
75  otherSz)
76 {
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);
84 
85  Integer z(a_exp_b_mod_c(y, x, p_));
86  z.Encode(agree, bc);
87 }
88 
89 
90 DH::DH(Source& source)
91 {
92  Initialize(source);
93 }
94 
95 
96 void DH::Initialize(Source& source)
97 {
98  DH_Decoder decoder(source);
99  decoder.Decode(*this);
100 }
101 
102 
103 } // namespace