8 #include <botan/emsa4.h>
9 #include <botan/mgf1.h>
10 #include <botan/internal/bit_ops.h>
17 void EMSA4::update(
const byte input[],
size_t length)
19 hash->
update(input, length);
25 SecureVector<byte> EMSA4::raw_data()
33 SecureVector<byte> EMSA4::encoding_of(
const MemoryRegion<byte>& msg,
35 RandomNumberGenerator&
rng)
39 if(msg.size() != HASH_SIZE)
40 throw Encoding_Error(
"EMSA4::encoding_of: Bad input length");
41 if(output_bits < 8*HASH_SIZE + 8*SALT_SIZE + 9)
42 throw Encoding_Error(
"EMSA4::encoding_of: Output length is too small");
44 const size_t output_length = (output_bits + 7) / 8;
46 SecureVector<byte> salt = rng.random_vec(SALT_SIZE);
48 for(
size_t j = 0; j != 8; ++j)
51 hash->
update(salt, SALT_SIZE);
52 SecureVector<byte> H = hash->
final();
54 SecureVector<byte> EM(output_length);
56 EM[output_length - HASH_SIZE - SALT_SIZE - 2] = 0x01;
57 EM.copy(output_length - 1 - HASH_SIZE - SALT_SIZE, salt, SALT_SIZE);
58 mgf->
mask(H, HASH_SIZE, EM, output_length - HASH_SIZE - 1);
59 EM[0] &= 0xFF >> (8 * ((output_bits + 7) / 8) - output_bits);
60 EM.copy(output_length - 1 - HASH_SIZE, H, HASH_SIZE);
61 EM[output_length-1] = 0xBC;
69 bool EMSA4::verify(
const MemoryRegion<byte>& const_coded,
70 const MemoryRegion<byte>& raw,
size_t key_bits)
73 const size_t KEY_BYTES = (key_bits + 7) / 8;
75 if(key_bits < 8*HASH_SIZE + 9)
78 if(raw.size() != HASH_SIZE)
81 if(const_coded.size() > KEY_BYTES || const_coded.size() <= 1)
84 if(const_coded[const_coded.size()-1] != 0xBC)
87 SecureVector<byte> coded = const_coded;
88 if(coded.size() < KEY_BYTES)
90 SecureVector<byte> temp(KEY_BYTES);
91 temp.copy(KEY_BYTES - coded.size(), coded, coded.size());
95 const size_t TOP_BITS = 8 * ((key_bits + 7) / 8) - key_bits;
96 if(TOP_BITS > 8 -
high_bit(coded[0]))
99 SecureVector<byte> DB(&coded[0], coded.size() - HASH_SIZE - 1);
100 SecureVector<byte> H(&coded[coded.size() - HASH_SIZE - 1], HASH_SIZE);
102 mgf->
mask(H, H.size(), DB, coded.size() - H.size() - 1);
103 DB[0] &= 0xFF >> TOP_BITS;
105 size_t salt_offset = 0;
106 for(
size_t j = 0; j != DB.size(); ++j)
109 { salt_offset = j + 1;
break; }
116 SecureVector<byte> salt(&DB[salt_offset], DB.size() - salt_offset);
118 for(
size_t j = 0; j != 8; ++j)
122 SecureVector<byte> H2 = hash->
final();
131 SALT_SIZE(h->output_length()), hash(h)
140 SALT_SIZE(salt_size), hash(h)
EMSA4(HashFunction *hash)
virtual HashFunction * clone() const =0
virtual void mask(const byte in[], size_t in_len, byte out[], size_t out_len) const =0
RandomNumberGenerator * rng
void update(const byte in[], size_t length)
virtual size_t output_length() const =0