rp2350 0.1.0

Hardware Abstraction Layer for RP2350 microcontrollers
Documentation
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! SHA-256 hardware accelerator driver for RP2350
//!
//! The RP2350 includes a hardware SHA-256 accelerator that can compute
//! SHA-256 hashes much faster than a software implementation.
//!
//! ## Example
//!
//! ```ignore
//! use rp2350::sha256::Sha256;
//!
//! let dp = rp2350_pac::Peripherals::take().unwrap();
//! let mut sha = Sha256::init(dp.SHA256);
//!
//! // `hash()` handles block splitting and padding automatically.
//! let data = b"Hello, World!";
//! let digest = sha.hash(data);
//!
//! for byte in digest {
//!     // ...
//! }
//! ```

use crate::Steal;
use crate::reset::Resettable;
use rp2350_pac::SHA256;

/// SHA-256 block size in bytes
pub const BLOCK_SIZE: usize = 64;

/// SHA-256 digest size in bytes
pub const DIGEST_SIZE: usize = 32;

/// DMA transfer size configuration
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum DmaSize {
    /// 8-bit DMA transfers
    Bit8 = 0,
    /// 16-bit DMA transfers
    Bit16 = 1,
    /// 32-bit DMA transfers
    Bit32 = 2,
}

/// SHA-256 hardware accelerator driver
pub struct Sha256 {
    sha256: SHA256,
}

impl Sha256 {
    /// Initialize the SHA-256 hardware accelerator.
    ///
    /// Takes ownership of the [`rp2350_pac::SHA256`] register block, resets
    /// the peripheral, and brings it out of reset.
    ///
    /// # Arguments
    ///
    /// * `sha256` — The PAC-level [`rp2350_pac::SHA256`] peripheral instance.
    #[inline]
    pub fn init(sha256: rp2350_pac::SHA256) -> Self {
        // Reset then unreset to guarantee clean register state
        <rp2350_pac::SHA256 as Resettable>::init();

        Self { sha256 }
    }

    /// Obtain a handle to the SHA-256 hardware accelerator without
    /// re-initializing.
    ///
    /// # Safety
    ///
    /// The caller must ensure the SHA-256 peripheral has already been reset
    /// and initialized (e.g. via [`Sha256::init`]) before use. Prefer
    /// [`Sha256::init`] which handles initialization automatically.
    #[inline]
    pub unsafe fn steal() -> Steal<Self> {
        Steal(Self {
            sha256: unsafe { SHA256::steal() },
        })
    }

    /// Get a reference to the SHA256 registers
    #[inline]
    fn regs(&self) -> &rp2350_pac::sha256::RegisterBlock {
        &self.sha256
    }

    // ========================================================================
    // Control and Status
    // ========================================================================

    /// Start a new SHA-256 hash computation
    ///
    /// This prepares the core for a new checksum. The SUMx registers are
    /// initialised to the proper values for the start of a SHA-256 hash.
    #[inline]
    pub fn start(&mut self) {
        self.regs().csr.trigger_start();
    }

    /// Check if the core is ready to accept more data
    #[inline]
    pub fn is_wdata_ready(&self) -> bool {
        self.regs().csr.wdata_rdy()
    }

    /// Check if the checksum in SUMx registers is valid
    #[inline]
    pub fn is_sum_valid(&self) -> bool {
        self.regs().csr.sum_vld()
    }

    /// Check if a write error occurred (write when not ready)
    #[inline]
    pub fn has_write_error(&self) -> bool {
        self.regs().csr.err_wdata_not_rdy()
    }

    /// Clear the write error flag
    #[inline]
    pub fn clear_write_error(&mut self) {
        self.regs().csr.clr_err_wdata_not_rdy();
    }

    /// Enable byte swapping of 32-bit values
    ///
    /// When enabled, bytes are swapped at the point they are committed
    /// to the SHA-256 message schedule.
    #[inline]
    pub fn enable_byte_swap(&mut self) {
        self.regs().csr.set_bswap();
    }

    /// Disable byte swapping of 32-bit values
    #[inline]
    pub fn disable_byte_swap(&mut self) {
        self.regs().csr.clr_bswap();
    }

    /// Check if byte swapping is enabled
    #[inline]
    pub fn is_byte_swap_enabled(&self) -> bool {
        self.regs().csr.bswap()
    }

    /// Configure DMA transfer size
    #[inline]
    pub fn set_dma_size(&mut self, size: DmaSize) {
        self.regs().csr.write_dma_size(size as u32);
    }

    /// Get the current DMA transfer size configuration
    #[inline]
    pub fn dma_size(&self) -> DmaSize {
        match self.regs().csr.dma_size() {
            0 => DmaSize::Bit8,
            1 => DmaSize::Bit16,
            _ => DmaSize::Bit32,
        }
    }

    /// DREQ selection for SHA-256 DMA transfers.
    ///
    /// Use this with a DMA channel's `treq_sel` to pace writes
    /// to the SHA-256 engine's data register.
    pub const DREQ: crate::dma::TreqSel = crate::dma::TreqSel::Sha256;

    /// Get the write data register address for DMA.
    ///
    /// DMA should write data to this address (WDATA register).
    /// Configure the DMA data size to match [`set_dma_size()`](Self::set_dma_size).
    #[inline]
    pub fn wdata_address(&self) -> u32 {
        rp2350_pac::SHA256::PTR as u32 + 0x04
    }

    // ========================================================================
    // Data Writing
    // ========================================================================

    /// Wait until the core is ready to accept data.
    ///
    /// # Panics
    ///
    /// Panics if the hardware does not become ready within
    /// [`crate::spin::SPIN_TIMEOUT`] iterations.
    #[inline]
    pub fn wait_ready(&self) {
        crate::spin::spin_wait("SHA-256 data ready", || self.is_wdata_ready());
    }

    /// Wait until the checksum is valid.
    ///
    /// # Panics
    ///
    /// Panics if the checksum is not computed within
    /// [`crate::spin::SPIN_TIMEOUT`] iterations.
    #[inline]
    pub fn wait_sum_valid(&self) {
        crate::spin::spin_wait("SHA-256 sum valid", || self.is_sum_valid());
    }

    /// Write a single 32-bit word of data
    ///
    /// You must write exactly 16 words (64 bytes) per block.
    /// After each block, wait for `is_wdata_ready()` to become true.
    #[inline]
    pub fn write_word(&mut self, word: u32) {
        self.regs().wdata.write_wdata(word);
    }

    /// Write a single 32-bit word of data, waiting if necessary
    #[inline]
    pub fn write_word_blocking(&mut self, word: u32) {
        self.wait_ready();
        self.write_word(word);
    }

    /// Write a block of 64 bytes (16 words)
    ///
    /// # Panics
    /// Panics if `block.len()` is not exactly 64.
    pub fn write_block(&mut self, block: &[u8]) {
        assert_eq!(
            block.len(),
            BLOCK_SIZE,
            "SHA-256 block must be exactly 64 bytes"
        );

        for chunk in block.as_chunks::<4>().0 {
            let word = u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
            self.write_word_blocking(word);
        }
    }

    /// Write a block of 16 32-bit words
    ///
    /// # Panics
    /// Panics if `words.len()` is not exactly 16.
    pub fn write_block_words(&mut self, words: &[u32]) {
        assert_eq!(words.len(), 16, "SHA-256 block must be exactly 16 words");

        for &word in words {
            self.write_word_blocking(word);
        }
    }

    // ========================================================================
    // Reading the Hash
    // ========================================================================

    /// Read the hash result as an array of 8 32-bit words
    ///
    /// Note: The checksum is only valid when `is_sum_valid()` returns true.
    #[inline]
    pub fn read_hash_words(&self) -> [u32; 8] {
        let regs = self.regs();
        [
            regs.sum0.read_bits(),
            regs.sum1.read_bits(),
            regs.sum2.read_bits(),
            regs.sum3.read_bits(),
            regs.sum4.read_bits(),
            regs.sum5.read_bits(),
            regs.sum6.read_bits(),
            regs.sum7.read_bits(),
        ]
    }

    /// Read the hash result as a 32-byte array
    ///
    /// Note: The checksum is only valid when `is_sum_valid()` returns true.
    #[inline]
    pub fn read_hash(&self) -> [u8; DIGEST_SIZE] {
        let words = self.read_hash_words();
        let mut hash = [0u8; DIGEST_SIZE];

        for (i, word) in words.iter().enumerate() {
            let bytes = word.to_be_bytes();
            hash[i * 4..(i + 1) * 4].copy_from_slice(&bytes);
        }

        hash
    }

    /// Read the hash result, waiting for it to be valid first
    #[inline]
    pub fn read_hash_blocking(&self) -> [u8; DIGEST_SIZE] {
        self.wait_sum_valid();
        self.read_hash()
    }

    // ========================================================================
    // High-Level API
    // ========================================================================

    /// Compute SHA-256 hash of the given data
    ///
    /// This handles all padding automatically according to the SHA-256 spec:
    /// - Append a '1' bit
    /// - Append '0' bits until length ≡ 448 (mod 512)
    /// - Append original message length as 64-bit big-endian
    pub fn hash(&mut self, data: &[u8]) -> [u8; DIGEST_SIZE] {
        self.start();

        let bit_len = (data.len() as u64) * 8;

        // Process complete 64-byte blocks
        let mut offset = 0;
        while offset + BLOCK_SIZE <= data.len() {
            self.write_block(&data[offset..offset + BLOCK_SIZE]);
            offset += BLOCK_SIZE;
        }

        // Handle final block(s) with padding
        let remaining = data.len() - offset;
        let mut final_block = [0u8; BLOCK_SIZE * 2]; // May need two blocks

        // Copy remaining data
        final_block[..remaining].copy_from_slice(&data[offset..]);

        // Append '1' bit (0x80)
        final_block[remaining] = 0x80;

        // Calculate how many final blocks we need
        let final_blocks = if remaining + 9 > BLOCK_SIZE { 2 } else { 1 };

        // Append length at the end of the last block
        let len_offset = final_blocks * BLOCK_SIZE - 8;
        final_block[len_offset..len_offset + 8].copy_from_slice(&bit_len.to_be_bytes());

        // Write final block(s)
        for i in 0..final_blocks {
            self.write_block(&final_block[i * BLOCK_SIZE..(i + 1) * BLOCK_SIZE]);
        }

        self.read_hash_blocking()
    }

    /// Compute the SHA-256 hash, consuming and returning `self`.
    ///
    /// Unlike [`hash`](Self::hash), this takes ownership of the peripheral and
    /// returns it alongside the digest — useful when the caller cannot hold a
    /// mutable borrow across the call.
    #[inline]
    pub fn hash_owned(mut self, data: &[u8]) -> ([u8; DIGEST_SIZE], Self) {
        let hash = self.hash(data);
        (hash, self)
    }
}

/// Incremental SHA-256 hasher
///
/// This allows computing a hash incrementally by calling `update()` multiple times.
pub struct Sha256Hasher {
    sha: Sha256,
    buffer: [u8; BLOCK_SIZE],
    buffer_len: usize,
    total_len: u64,
}

impl Sha256Hasher {
    /// Create a new incremental hasher from an already-initialized [`Sha256`]
    /// instance.
    ///
    /// Unlike [`new`](Self::new), this constructor is safe because the
    /// `Sha256` object has already been properly initialized (e.g. via
    /// [`Sha256::init`]).
    pub fn from_sha256(mut sha: Sha256) -> Self {
        sha.start();

        Self {
            sha,
            buffer: [0u8; BLOCK_SIZE],
            buffer_len: 0,
            total_len: 0,
        }
    }

    /// Create a new incremental hasher.
    ///
    /// # Safety
    ///
    /// The caller must ensure the SHA-256 peripheral has already been
    /// initialized via [`Sha256::init`] before using this hasher.
    pub unsafe fn new() -> Self {
        // SAFETY: caller guarantees Sha256::init() was called before.
        // Unwrap Steal to gain &mut self access for start().
        let mut sha = unsafe { Sha256::steal().0 };
        sha.start();

        Self {
            sha,
            buffer: [0u8; BLOCK_SIZE],
            buffer_len: 0,
            total_len: 0,
        }
    }

    /// Update the hash with more data
    pub fn update(&mut self, data: &[u8]) {
        self.total_len += data.len() as u64;
        let mut offset = 0;

        // If we have buffered data, try to complete a block
        if self.buffer_len > 0 {
            let needed = BLOCK_SIZE - self.buffer_len;
            if data.len() >= needed {
                self.buffer[self.buffer_len..].copy_from_slice(&data[..needed]);
                self.sha.write_block(&self.buffer);
                self.buffer_len = 0;
                offset = needed;
            } else {
                self.buffer[self.buffer_len..self.buffer_len + data.len()].copy_from_slice(data);
                self.buffer_len += data.len();
                return;
            }
        }

        // Process complete blocks
        while offset + BLOCK_SIZE <= data.len() {
            self.sha.write_block(&data[offset..offset + BLOCK_SIZE]);
            offset += BLOCK_SIZE;
        }

        // Buffer remaining data
        if offset < data.len() {
            let remaining = data.len() - offset;
            self.buffer[..remaining].copy_from_slice(&data[offset..]);
            self.buffer_len = remaining;
        }
    }

    /// Finalize the hash and return the result
    pub fn finalize(mut self) -> [u8; DIGEST_SIZE] {
        let bit_len = self.total_len * 8;

        // Create final padding
        let mut final_block = [0u8; BLOCK_SIZE * 2];
        final_block[..self.buffer_len].copy_from_slice(&self.buffer[..self.buffer_len]);
        final_block[self.buffer_len] = 0x80;

        let final_blocks = if self.buffer_len + 9 > BLOCK_SIZE {
            2
        } else {
            1
        };
        let len_offset = final_blocks * BLOCK_SIZE - 8;
        final_block[len_offset..len_offset + 8].copy_from_slice(&bit_len.to_be_bytes());

        for i in 0..final_blocks {
            self.sha
                .write_block(&final_block[i * BLOCK_SIZE..(i + 1) * BLOCK_SIZE]);
        }

        self.sha.read_hash_blocking()
    }
}