apple_cryptokit/hashing/
mod.rs1pub mod sha1;
3pub mod sha256;
4pub mod sha384;
5pub mod sha512;
6
7pub use sha1::{sha1_hash, sha1_hash_to, SHA1};
9pub use sha256::{sha256_hash, sha256_hash_to, Sha256, SHA256};
10pub use sha384::{sha384_hash, sha384_hash_to, Sha384, SHA384};
11pub use sha512::{sha512_hash, sha512_hash_to, Sha512, SHA512};
12
13pub trait HashFunction {
15 const OUTPUT_SIZE: usize;
17
18 fn hash(data: &[u8]) -> Vec<u8> {
20 let mut output = vec![0u8; Self::OUTPUT_SIZE];
21 Self::hash_to(data, &mut output);
22 output
23 }
24
25 fn hash_to(data: &[u8], output: &mut [u8]);
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum HashAlgorithm {
38 Sha1,
39 Sha256,
40 Sha384,
41 Sha512,
42}
43
44impl HashAlgorithm {
45 pub fn output_size(&self) -> usize {
47 match self {
48 HashAlgorithm::Sha1 => 20,
49 HashAlgorithm::Sha256 => 32,
50 HashAlgorithm::Sha384 => 48,
51 HashAlgorithm::Sha512 => 64,
52 }
53 }
54
55 pub fn compute(&self, data: &[u8]) -> Vec<u8> {
57 match self {
58 HashAlgorithm::Sha1 => sha1_hash(data).to_vec(),
59 HashAlgorithm::Sha256 => sha256_hash(data).to_vec(),
60 HashAlgorithm::Sha384 => sha384_hash(data).to_vec(),
61 HashAlgorithm::Sha512 => sha512_hash(data).to_vec(),
62 }
63 }
64
65 pub fn compute_to(&self, data: &[u8], output: &mut [u8]) {
73 assert!(
74 output.len() >= self.output_size(),
75 "Output buffer too small: {} < {}",
76 output.len(),
77 self.output_size()
78 );
79 match self {
80 HashAlgorithm::Sha1 => sha1_hash_to(data, output),
81 HashAlgorithm::Sha256 => sha256_hash_to(data, output),
82 HashAlgorithm::Sha384 => sha384_hash_to(data, output),
83 HashAlgorithm::Sha512 => sha512_hash_to(data, output),
84 }
85 }
86}
87
88pub struct HashBuilder {
90 algorithm: HashAlgorithm,
91}
92
93impl HashBuilder {
94 pub fn new(algorithm: HashAlgorithm) -> Self {
96 Self { algorithm }
97 }
98
99 pub fn compute(&self, data: &[u8]) -> Vec<u8> {
101 self.algorithm.compute(data)
102 }
103
104 pub fn compute_to(&self, data: &[u8], output: &mut [u8]) {
106 self.algorithm.compute_to(data, output)
107 }
108
109 pub fn output_size(&self) -> usize {
111 self.algorithm.output_size()
112 }
113}