Skip to main content

capsules_extra/test/
sha256.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4// Copyright Oxidos Automotive 2026.
5
6//! Test the implementation of SHA256 driver by performing a hash
7//! and checking it against the expected hash value. It uses
8//! DigestData::add_date and DigestVerify::verify through the
9//! Digest trait.
10
11use core::cell::Cell;
12use core::cmp;
13
14use capsules_core::test::capsule_test::{CapsuleTest, CapsuleTestClient};
15use kernel::ErrorCode;
16use kernel::debug;
17use kernel::hil::digest;
18use kernel::utilities::cells::{OptionalCell, TakeCell};
19use kernel::utilities::leasable_buffer::SubSlice;
20use kernel::utilities::leasable_buffer::SubSliceMut;
21
22const SHA256_DIGEST_LEN: usize = 32;
23
24pub struct TestSha256<'a, H: digest::Digest<'a, SHA256_DIGEST_LEN>> {
25    sha: &'a H,
26    data: TakeCell<'static, [u8]>, // The data to hash
27    hash: TakeCell<'static, [u8; SHA256_DIGEST_LEN]>, // The supplied hash
28    position: Cell<usize>,         // Keep track of position in data
29    correct: Cell<bool>,           // Whether supplied hash is correct
30    client: OptionalCell<&'static dyn CapsuleTestClient>,
31}
32
33// We add data in chunks of 12 bytes to ensure that the underlying
34// buffering mechanism works correctly (it can handle filling blocks
35// as well as zeroing out incomplete blocks).
36const CHUNK_SIZE: usize = 12;
37
38impl<'a, H: digest::Digest<'a, SHA256_DIGEST_LEN> + digest::Sha256> TestSha256<'a, H> {
39    pub fn new(
40        sha: &'a H,
41        data: &'static mut [u8],
42        hash: &'static mut [u8; SHA256_DIGEST_LEN],
43        correct: bool,
44    ) -> Self {
45        TestSha256 {
46            sha,
47            data: TakeCell::new(data),
48            hash: TakeCell::new(hash),
49            position: Cell::new(0),
50            correct: Cell::new(correct),
51            client: OptionalCell::empty(),
52        }
53    }
54
55    pub fn run(&'a self) {
56        let r = self.sha.set_mode_sha256();
57        if r.is_err() {
58            panic!("Sha256Test: failed to set mode: {:?}", r)
59        }
60        self.sha.set_client(self);
61        let data = self.data.take().unwrap();
62        let chunk_size = cmp::min(CHUNK_SIZE, data.len());
63        self.position.set(chunk_size);
64        let mut buffer = SubSliceMut::new(data);
65        buffer.slice(0..chunk_size);
66        let r = self.sha.add_mut_data(buffer);
67        if r.is_err() {
68            panic!("Sha256Test: failed to add data: {:?}", r);
69        }
70    }
71}
72
73impl<'a, H: digest::Digest<'a, SHA256_DIGEST_LEN>> digest::ClientData<SHA256_DIGEST_LEN>
74    for TestSha256<'a, H>
75{
76    fn add_data_done(&self, _result: Result<(), ErrorCode>, _data: SubSlice<'static, u8>) {
77        unimplemented!()
78    }
79
80    fn add_mut_data_done(&self, result: Result<(), ErrorCode>, mut data: SubSliceMut<'static, u8>) {
81        if data.len() != 0 {
82            let r = self.sha.add_mut_data(data);
83            if r.is_err() {
84                panic!("Sha256Test: failed to add data: {:?}", r);
85            }
86        } else {
87            data.reset();
88            if self.position.get() < data.len() {
89                let new_position = cmp::min(data.len(), self.position.get() + CHUNK_SIZE);
90                data.slice(self.position.get()..new_position);
91                debug!(
92                    "Sha256Test: Setting slice to {}..{}",
93                    self.position.get(),
94                    new_position
95                );
96                let r = self.sha.add_mut_data(data);
97                if r.is_err() {
98                    panic!("Sha256Test: failed to add data: {:?}", r);
99                }
100                self.position.set(new_position);
101            } else {
102                data.reset();
103                self.data.put(Some(data.take()));
104                match result {
105                    Ok(()) => {
106                        let v = self.sha.verify(self.hash.take().unwrap());
107                        if v.is_err() {
108                            panic!("Sha256Test: failed to verify: {:?}", v);
109                        }
110                    }
111                    Err(e) => {
112                        panic!("Sha256Test: adding data failed: {:?}", e);
113                    }
114                }
115            }
116        }
117    }
118}
119
120impl<'a, H: digest::Digest<'a, SHA256_DIGEST_LEN>> digest::ClientVerify<SHA256_DIGEST_LEN>
121    for TestSha256<'a, H>
122{
123    fn verification_done(
124        &self,
125        result: Result<bool, ErrorCode>,
126        compare: &'static mut [u8; SHA256_DIGEST_LEN],
127    ) {
128        self.hash.put(Some(compare));
129        debug!("Sha256Test: Verification result: {:?}", result);
130        match result {
131            Ok(success) => {
132                if success != self.correct.get() {
133                    panic!(
134                        "Sha256Test: Verification should have been {}, was {}",
135                        self.correct.get(),
136                        success
137                    );
138                } else {
139                    self.client.map(|client| {
140                        client.done(Ok(()));
141                    });
142                }
143            }
144            Err(e) => {
145                panic!("Sha256Test: Error in verification: {:?}", e);
146            }
147        }
148    }
149}
150
151impl<'a, H: digest::Digest<'a, SHA256_DIGEST_LEN>> digest::ClientHash<SHA256_DIGEST_LEN>
152    for TestSha256<'a, H>
153{
154    fn hash_done(
155        &self,
156        _result: Result<(), ErrorCode>,
157        _digest: &'static mut [u8; SHA256_DIGEST_LEN],
158    ) {
159    }
160}
161
162impl<'a, H: digest::Digest<'a, SHA256_DIGEST_LEN>> CapsuleTest for TestSha256<'a, H> {
163    fn set_client(&self, client: &'static dyn CapsuleTestClient) {
164        self.client.set(client);
165    }
166}