monotone

monotone Mtn Source Tree

Root/botan/mdx_hash.cpp

1/*************************************************
2* MDx Hash Function Source File *
3* (C) 1999-2007 The Botan Project *
4*************************************************/
5
6#include <botan/mdx_hash.h>
7#include <botan/loadstor.h>
8
9namespace Botan {
10
11/*************************************************
12* MDx_HashFunction Constructor *
13*************************************************/
14MDx_HashFunction::MDx_HashFunction(u32bit hash_len, u32bit block_len,
15 bool byte_end, bool bit_end,
16 u32bit cnt_size) :
17 HashFunction(hash_len, block_len), buffer(block_len),
18 BIG_BYTE_ENDIAN(byte_end), BIG_BIT_ENDIAN(bit_end), COUNT_SIZE(cnt_size)
19 {
20 if(COUNT_SIZE >= OUTPUT_LENGTH || COUNT_SIZE >= HASH_BLOCK_SIZE)
21 throw Invalid_Argument("MDx_HashFunction: COUNT_SIZE is too big");
22 count = position = 0;
23 }
24
25/*************************************************
26* Clear memory of sensitive data *
27*************************************************/
28void MDx_HashFunction::clear() throw()
29 {
30 buffer.clear();
31 count = position = 0;
32 }
33
34/*************************************************
35* Update the hash *
36*************************************************/
37void MDx_HashFunction::add_data(const byte input[], u32bit length)
38 {
39 count += length;
40
41 if(position)
42 {
43 buffer.copy(position, input, length);
44
45 if(position + length >= HASH_BLOCK_SIZE)
46 {
47 hash(buffer.begin());
48 input += (HASH_BLOCK_SIZE - position);
49 length -= (HASH_BLOCK_SIZE - position);
50 position = 0;
51 }
52 }
53
54 while(length >= HASH_BLOCK_SIZE)
55 {
56 hash(input);
57 input += HASH_BLOCK_SIZE;
58 length -= HASH_BLOCK_SIZE;
59 }
60
61 buffer.copy(position, input, length);
62
63 position += length;
64 }
65
66/*************************************************
67* Finalize a Hash *
68*************************************************/
69void MDx_HashFunction::final_result(byte output[])
70 {
71 buffer[position] = (BIG_BIT_ENDIAN ? 0x80 : 0x01);
72 for(u32bit j = position+1; j != HASH_BLOCK_SIZE; ++j)
73 buffer[j] = 0;
74 if(position >= HASH_BLOCK_SIZE - COUNT_SIZE)
75 {
76 hash(buffer);
77 buffer.clear();
78 }
79 write_count(buffer + HASH_BLOCK_SIZE - COUNT_SIZE);
80
81 hash(buffer);
82 copy_out(output);
83 clear();
84 }
85
86/*************************************************
87* Write the count bits to the buffer *
88*************************************************/
89void MDx_HashFunction::write_count(byte out[])
90 {
91 if(COUNT_SIZE < 8)
92 throw Invalid_State("MDx_HashFunction::write_count: COUNT_SIZE < 8");
93
94 const u64bit bit_count = count * 8;
95
96 if(BIG_BYTE_ENDIAN)
97 store_be(bit_count, out + COUNT_SIZE - 8);
98 else
99 store_le(bit_count, out + COUNT_SIZE - 8);
100 }
101
102}

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status