summaryrefslogtreecommitdiffstats
path: root/old/botan/src/pubkey/elgamal/elg_core.cpp
blob: 8b8c8f50bc5cca62d2126d2b6d3eb1a837fa0cd1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
* ElGamal Core
* (C) 1999-2007 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/

#include <botan/elg_core.h>
#include <botan/numthry.h>
#include <botan/pk_engine.h>
#include <botan/parsing.h>
#include <algorithm>

namespace Botan {

namespace {

const u32bit BLINDING_BITS = BOTAN_PRIVATE_KEY_OP_BLINDING_BITS;

}

/*
* ELG_Core Constructor
*/
ELG_Core::ELG_Core(const DL_Group& group, const BigInt& y)
   {
   op = Engine_Core::elg_op(group, y, 0);
   p_bytes = 0;
   }

/*
* ELG_Core Constructor
*/
ELG_Core::ELG_Core(RandomNumberGenerator& rng,
                   const DL_Group& group, const BigInt& y, const BigInt& x)
   {
   op = Engine_Core::elg_op(group, y, x);

   const BigInt& p = group.get_p();
   p_bytes = p.bytes();

   if(BLINDING_BITS)
      {
      BigInt k(rng, std::min(p.bits()-1, BLINDING_BITS));
      blinder = Blinder(k, power_mod(k, x, p), p);
      }
   }

/*
* ELG_Core Copy Constructor
*/
ELG_Core::ELG_Core(const ELG_Core& core)
   {
   op = 0;
   if(core.op)
      op = core.op->clone();
   blinder = core.blinder;
   p_bytes = core.p_bytes;
   }

/*
* ELG_Core Assignment Operator
*/
ELG_Core& ELG_Core::operator=(const ELG_Core& core)
   {
   delete op;
   if(core.op)
      op = core.op->clone();
   blinder = core.blinder;
   p_bytes = core.p_bytes;
   return (*this);
   }

/*
* ElGamal Encrypt Operation
*/
SecureVector<byte> ELG_Core::encrypt(const byte in[], u32bit length,
                                     const BigInt& k) const
   {
   return op->encrypt(in, length, k);
   }

/*
* ElGamal Decrypt Operation
*/
SecureVector<byte> ELG_Core::decrypt(const byte in[], u32bit length) const
   {
   if(length != 2*p_bytes)
      throw Invalid_Argument("ELG_Core::decrypt: Invalid message");

   BigInt a(in, p_bytes);
   BigInt b(in + p_bytes, p_bytes);

   return BigInt::encode(blinder.unblind(op->decrypt(blinder.blind(a), b)));
   }

}