embedded_cal_rustcrypto/
hash.rs1use super::*;
5use embedded_cal::{Cal, HashProvider};
6
7#[derive(PartialEq, Eq, Debug, Clone)]
8pub enum HashAlgorithm<BA> {
9 Sha256,
10 Direct(BA),
11}
12
13impl<BA: embedded_cal::HashAlgorithm> embedded_cal::HashAlgorithm for HashAlgorithm<BA> {
14 fn len(&self) -> usize {
15 match self {
16 HashAlgorithm::Sha256 => 32,
17 HashAlgorithm::Direct(a) => a.len(),
18 }
19 }
20
21 #[inline]
22 fn from_cose_number(number: impl Into<i128>) -> Option<Self> {
23 let number: i128 = number.into();
24 if let Some(a) = BA::from_cose_number(number) {
25 return Some(HashAlgorithm::Direct(a));
26 }
27 match number {
28 -16 => Some(HashAlgorithm::Sha256),
29 _ => None,
30 }
31 }
32
33 fn from_ni_id(number: u8) -> Option<Self> {
34 if let Some(a) = BA::from_ni_id(number) {
35 return Some(HashAlgorithm::Direct(a));
36 }
37 match number {
38 1 => Some(HashAlgorithm::Sha256),
39 _ => None,
40 }
41 }
42
43 fn from_ni_name(name: &str) -> Option<Self> {
44 if let Some(a) = BA::from_ni_name(name) {
45 return Some(HashAlgorithm::Direct(a));
46 }
47 match name {
48 "sha-256" => Some(HashAlgorithm::Sha256),
49 _ => None,
50 }
51 }
52}
53
54#[derive(Clone)]
55pub enum HashState<BHS> {
56 Sha256(sha2::Sha256),
57 Direct(BHS),
58}
59
60pub enum HashResult<BHR> {
61 Sha256([u8; 32]),
62 Direct(BHR),
63}
64
65impl<BHR: AsRef<[u8]>> AsRef<[u8]> for HashResult<BHR> {
66 fn as_ref(&self) -> &[u8] {
67 match self {
68 HashResult::Sha256(r) => &r[..],
69 HashResult::Direct(r) => r.as_ref(),
70 }
71 }
72}
73
74impl<Base: Cal> HashProvider for RustcryptoCalExtender<Base> {
75 type Algorithm = HashAlgorithm<HashAlgorithmOf<Base>>;
76 type State = HashState<HashStateOf<Base>>;
77 type Output = HashResult<HashOutputOf<Base>>;
78
79 fn init(&mut self, algorithm: Self::Algorithm) -> Self::State {
80 match algorithm {
81 HashAlgorithm::Sha256 => HashState::Sha256(Default::default()),
83 HashAlgorithm::Direct(a) => HashState::Direct(self.base.hash().init(a)),
84 }
85 }
86
87 fn update(&mut self, instance: &mut Self::State, data: &[u8]) {
88 match instance {
89 HashState::Sha256(s) => s.update(data),
91 HashState::Direct(i) => self.base.hash().update(i, data),
92 }
93 }
94
95 fn finalize(&mut self, instance: Self::State) -> Self::Output {
96 match instance {
97 HashState::Sha256(s) => HashResult::Sha256(s.finalize().into()),
99 HashState::Direct(i) => HashResult::Direct(self.base.hash().finalize(i)),
100 }
101 }
102
103 fn hash(&mut self, algorithm: Self::Algorithm, data: &[u8]) -> Self::Output {
104 if let HashAlgorithm::Direct(a) = algorithm {
105 return HashResult::Direct(self.base.hash().hash(a, data));
106 };
107
108 let mut state = self.init(algorithm);
110 self.update(&mut state, data);
111 self.finalize(state)
112 }
113}