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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#![no_std]
extern crate block_buffer;
extern crate byte_tools;
#[cfg(feature = "generic")]
extern crate digest;
#[cfg(feature = "generic")]
extern crate generic_array;
#[cfg(not(feature = "asm"))]
extern crate fake_simd as simd;
#[cfg(feature = "asm")]
extern crate sha1_asm as utils;
#[cfg(not(feature = "asm"))]
mod utils;
use utils::compress;
use byte_tools::write_u32v_be;
use block_buffer::BlockBuffer512;
#[cfg(feature = "generic")]
pub use digest::Digest;
#[cfg(feature = "generic")]
use generic_array::GenericArray;
#[cfg(feature = "generic")]
use generic_array::typenum::{U20, U64};
mod consts;
use consts::{STATE_LEN, H};
#[derive(Copy, Clone)]
pub struct Sha1 {
h: [u32; STATE_LEN],
len: u64,
buffer: BlockBuffer512,
}
impl Default for Sha1 {
fn default() -> Self {
Sha1{ h: H, len: 0u64, buffer: Default::default() }
}
}
impl Sha1 {
#[inline]
fn finalize(mut self) -> [u32; STATE_LEN] {
{
let state = &mut self.h;
let len_bits = self.len << 3;
self.buffer.len_padding(len_bits.to_be(), |d| compress(state, d));
}
self.h
}
#[inline]
pub fn hash(self) -> [u8; 20] {
let mut out = [0u8; 20];
write_u32v_be(&mut out, &self.finalize());
out
}
#[inline]
pub fn consume(&mut self, input: &[u8]) {
self.len += input.len() as u64;
let state = &mut self.h;
self.buffer.input(input, |d| compress(state, d));
}
}
#[cfg(feature = "generic")]
impl digest::BlockInput for Sha1 {
type BlockSize = U64;
}
#[cfg(feature = "generic")]
impl digest::Input for Sha1 {
fn process(&mut self, input: &[u8]) {
self.consume(input);
}
}
#[cfg(feature = "generic")]
impl digest::FixedOutput for Sha1 {
type OutputSize = U20;
fn fixed_result(self) -> GenericArray<u8, Self::OutputSize> {
let mut out = GenericArray::default();
write_u32v_be(&mut out, &self.finalize());
out
}
}