summaryrefslogtreecommitdiffstats
path: root/comm/third_party/botan/src/lib/pk_pad/emsa_x931/emsa_x931.cpp
blob: b1f698f86dc2961c5b83c8de052a820717739498 (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
/*
* EMSA_X931
* (C) 1999-2007 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/emsa_x931.h>
#include <botan/exceptn.h>
#include <botan/hash_id.h>

namespace Botan {

namespace {

secure_vector<uint8_t> emsa2_encoding(const secure_vector<uint8_t>& msg,
                                   size_t output_bits,
                                   const secure_vector<uint8_t>& empty_hash,
                                   uint8_t 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("EMSA_X931::encoding_of: Bad input length");
   if(output_length < HASH_SIZE + 4)
      throw Encoding_Error("EMSA_X931::encoding_of: Output length is too small");

   const bool empty_input = (msg == empty_hash);

   secure_vector<uint8_t> output(output_length);

   output[0] = (empty_input ? 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.data(), msg.size());
   output[output_length-2] = hash_id;
   output[output_length-1] = 0xCC;

   return output;
   }

}

std::string EMSA_X931::name() const
   {
   return "EMSA2(" + m_hash->name() + ")";
   }

void EMSA_X931::update(const uint8_t input[], size_t length)
   {
   m_hash->update(input, length);
   }

secure_vector<uint8_t> EMSA_X931::raw_data()
   {
   return m_hash->final();
   }

/*
* EMSA_X931 Encode Operation
*/
secure_vector<uint8_t> EMSA_X931::encoding_of(const secure_vector<uint8_t>& msg,
                                      size_t output_bits,
                                      RandomNumberGenerator&)
   {
   return emsa2_encoding(msg, output_bits, m_empty_hash, m_hash_id);
   }

/*
* EMSA_X931 Verify Operation
*/
bool EMSA_X931::verify(const secure_vector<uint8_t>& coded,
                   const secure_vector<uint8_t>& raw,
                   size_t key_bits)
   {
   try
      {
      return (coded == emsa2_encoding(raw, key_bits,
                                      m_empty_hash, m_hash_id));
      }
   catch(...)
      {
      return false;
      }
   }

/*
* EMSA_X931 Constructor
*/
EMSA_X931::EMSA_X931(HashFunction* hash) : m_hash(hash)
   {
   m_empty_hash = m_hash->final();

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

   if(!m_hash_id)
      throw Encoding_Error("EMSA_X931 no hash identifier for " + hash->name());
   }

}