aboutsummaryrefslogtreecommitdiffstats
path: root/src/pk_pad/emsa2/emsa2.cpp
blob: d299ddacd23fb39fbb7a4548c78dd752460d373e (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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
* EMSA2
* (C) 1999-2007 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/

#include <botan/emsa2.h>
#include <botan/hash_id.h>

namespace Botan {

namespace {

/*
* EMSA2 Encode Operation
*/
secure_vector<byte> emsa2_encoding(const secure_vector<byte>& msg,
                                  size_t output_bits,
                                  const secure_vector<byte>& empty_hash,
                                  byte hash_id)
   {
   const size_t HASH_SIZE = empty_hash.size();

   size_t output_length = (output_bits + 1) / 8;

   if(msg.size() != HASH_SIZE)
      throw Encoding_Error("EMSA2::encoding_of: Bad input length");
   if(output_length < HASH_SIZE + 4)
      throw Encoding_Error("EMSA2::encoding_of: Output length is too small");

   bool empty = true;
   for(size_t j = 0; j != HASH_SIZE; ++j)
      if(empty_hash[j] != msg[j])
         empty = false;

   secure_vector<byte> output(output_length);

   output[0] = (empty ? 0x4B : 0x6B);
   output[output_length - 3 - HASH_SIZE] = 0xBA;
   set_mem(&output[1], output_length - 4 - HASH_SIZE, 0xBB);
   buffer_insert(output, output_length - (HASH_SIZE + 2), &msg[0], msg.size());
   output[output_length-2] = hash_id;
   output[output_length-1] = 0xCC;

   return output;
   }

}

/*
* EMSA2 Update Operation
*/
void EMSA2::update(const byte input[], size_t length)
   {
   hash->update(input, length);
   }

/*
* Return the raw (unencoded) data
*/
secure_vector<byte> EMSA2::raw_data()
   {
   return hash->final();
   }

/*
* EMSA2 Encode Operation
*/
secure_vector<byte> EMSA2::encoding_of(const secure_vector<byte>& msg,
                                      size_t output_bits,
                                      RandomNumberGenerator&)
   {
   return emsa2_encoding(msg, output_bits, empty_hash, hash_id);
   }

/*
* EMSA2 Verify Operation
*/
bool EMSA2::verify(const secure_vector<byte>& coded,
                   const secure_vector<byte>& raw,
                   size_t key_bits)
   {
   try
      {
      return (coded == emsa2_encoding(raw, key_bits,
                                      empty_hash, hash_id));
      }
   catch(...)
      {
      return false;
      }
   }

/*
* EMSA2 Constructor
*/
EMSA2::EMSA2(HashFunction* hash_in) : hash(hash_in)
   {
   empty_hash = hash->final();

   hash_id = ieee1363_hash_id(hash->name());

   if(hash_id == 0)
      {
      delete hash;
      throw Encoding_Error("EMSA2 cannot be used with " + hash->name());
      }
   }

}