imix/test/
sha256_test.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
5//! This tests a software SHA256 implementation. To run this test,
6//! add this line to the imix boot sequence:
7//! ```
8//!     test::sha256_test::run_sha256();
9//! ```
10//! This test uses a deferred call (for callbacks). It tries to
11//! hash 'hello world' and uses Digest::validate to check that the hash
12//! is correct.
13//!
14//! The expected output is
15//! Sha256Test: Verification result: Ok(true)
16//!
17//! This tests whether the SHA-256 hash of the string "hello hello
18//! hello hello hello hello hello hello hello hello hello hello "
19//! hashes correctly. This string is 12 repetitions of "hello ", so is
20//! 72 bytes long. As SHA uses 64-byte/512 bit blocks, this verifies
21//! that multi-block hashes work correctly.
22
23use core::ptr::addr_of_mut;
24
25use capsules_extra::sha256::Sha256Software;
26use capsules_extra::test::sha256::TestSha256;
27use kernel::static_init;
28
29pub unsafe fn run_sha256() {
30    let t = static_init_test_sha256();
31    t.run();
32}
33
34// HSTRING is "hello world" and HHASH is the SHA-256 hash of this string.
35pub static mut HSTRING: [u8; 11] = *b"hello world";
36
37pub static mut HHASH: [u8; 32] = [
38    0xB9, 0x4D, 0x27, 0xB9, 0x93, 0x4D, 0x3E, 0x08, 0xA5, 0x2E, 0x52, 0xD7, 0xDA, 0x7D, 0xAB, 0xFA,
39    0xC4, 0x84, 0xEF, 0xE3, 0x7A, 0x53, 0x80, 0xEE, 0x90, 0x88, 0xF7, 0xAC, 0xE2, 0xEF, 0xCD, 0xE9,
40];
41
42// LSTRING is 12 repetitions of "hello " (72 bytes long) and LHASH is
43// the SHA-256 hash of this string.
44pub static mut LSTRING: [u8; 72] = [0; 72];
45pub static mut LHASH: [u8; 32] = [
46    0x59, 0x42, 0xc3, 0x71, 0x6f, 0x02, 0x82, 0x89, 0x3f, 0xbe, 0x04, 0x9b, 0xa2, 0x0e, 0x56, 0x0e,
47    0x45, 0x94, 0xd5, 0xee, 0x15, 0xcb, 0x8a, 0x1e, 0x28, 0x7c, 0x20, 0x12, 0xc2, 0xce, 0xb5, 0xa9,
48];
49
50unsafe fn static_init_test_sha256() -> &'static TestSha256 {
51    let sha = static_init!(Sha256Software<'static>, Sha256Software::new());
52    kernel::deferred_call::DeferredCallClient::register(sha);
53    let bytes = b"hello ";
54    for i in 0..12 {
55        for j in 0..6 {
56            LSTRING[i * 6 + j] = bytes[j];
57        }
58    }
59    // We expect LSTRING to hash to LHASH, so final argument is true
60    let test = static_init!(
61        TestSha256,
62        TestSha256::new(
63            sha,
64            &mut *addr_of_mut!(LSTRING),
65            &mut *addr_of_mut!(LHASH),
66            true
67        )
68    );
69
70    test
71}