Botan 1.10.17
emsa2.cpp
Go to the documentation of this file.
1/*
2* EMSA2
3* (C) 1999-2007 Jack Lloyd
4*
5* Distributed under the terms of the Botan license
6*/
7
8#include <botan/emsa2.h>
9#include <botan/hash_id.h>
10
11namespace Botan {
12
13namespace {
14
15/*
16* EMSA2 Encode Operation
17*/
18SecureVector<byte> emsa2_encoding(const MemoryRegion<byte>& msg,
19 size_t output_bits,
20 const MemoryRegion<byte>& empty_hash,
21 byte hash_id)
22 {
23 const size_t HASH_SIZE = empty_hash.size();
24
25 size_t output_length = (output_bits + 1) / 8;
26
27 if(msg.size() != HASH_SIZE)
28 throw Encoding_Error("EMSA2::encoding_of: Bad input length");
29 if(output_length < HASH_SIZE + 4)
30 throw Encoding_Error("EMSA2::encoding_of: Output length is too small");
31
32 bool empty = true;
33 for(size_t j = 0; j != HASH_SIZE; ++j)
34 if(empty_hash[j] != msg[j])
35 empty = false;
36
37 SecureVector<byte> output(output_length);
38
39 output[0] = (empty ? 0x4B : 0x6B);
40 output[output_length - 3 - HASH_SIZE] = 0xBA;
41 set_mem(&output[1], output_length - 4 - HASH_SIZE, 0xBB);
42 output.copy(output_length - (HASH_SIZE + 2), &msg[0], msg.size());
43 output[output_length-2] = hash_id;
44 output[output_length-1] = 0xCC;
45
46 return output;
47 }
48
49}
50
51/*
52* EMSA2 Update Operation
53*/
54void EMSA2::update(const byte input[], size_t length)
55 {
56 hash->update(input, length);
57 }
58
59/*
60* Return the raw (unencoded) data
61*/
63 {
64 return hash->final();
65 }
66
67/*
68* EMSA2 Encode Operation
69*/
70SecureVector<byte> EMSA2::encoding_of(const MemoryRegion<byte>& msg,
71 size_t output_bits,
73 {
74 return emsa2_encoding(msg, output_bits, empty_hash, hash_id);
75 }
76
77/*
78* EMSA2 Verify Operation
79*/
80bool EMSA2::verify(const MemoryRegion<byte>& coded,
81 const MemoryRegion<byte>& raw,
82 size_t key_bits)
83 {
84 try
85 {
86 return (coded == emsa2_encoding(raw, key_bits,
87 empty_hash, hash_id));
88 }
89 catch(...)
90 {
91 return false;
92 }
93 }
94
95/*
96* EMSA2 Constructor
97*/
98EMSA2::EMSA2(HashFunction* hash_in) : hash(hash_in)
99 {
100 empty_hash = hash->final();
101
102 const std::string hash_name = hash->name();
103 hash_id = ieee1363_hash_id(hash_name);
104
105 if(hash_id == 0)
106 {
107 delete hash;
108 throw Encoding_Error("EMSA2 cannot be used with " + hash_name);
109 }
110 }
111
112}
EMSA2(HashFunction *hash)
Definition emsa2.cpp:98
virtual SecureVector< byte > raw_data()=0
size_t size() const
Definition secmem.h:29
void set_mem(T *ptr, size_t n, byte val)
Definition mem_ops.h:45
byte ieee1363_hash_id(const std::string &name)
Definition hash_id.cpp:93
Encoding_Error(const std::string &name)
Definition exceptn.h:131