desfire/crypto/
util.rs

1use crate::error::{Error, Result};
2use simple_error::simple_error;
3
4/// Extracts the the last `n` bytes of a slice. n being the blocksize.
5pub fn extract_last_block(data: &[u8], blocksize: usize) -> Result<&[u8]> {
6    if data.len() % blocksize != 0 {
7        return Err(simple_error!(
8            "Data is not compatible with blocksize: data(length): {}, blocksize: {}.",
9            data.len(),
10            blocksize
11        )
12        .into());
13    }
14
15    Ok(&data[(data.len() - blocksize)..])
16}
17
18/// Takes a given input and zero pads it to a multiple of blocksize
19pub fn expand_to_blocksize(data: &mut [u8], blocksize: usize) -> Result<Vec<u8>> {
20    let diff = data.len() % blocksize;
21
22    if diff == 0 {
23        return Ok(data.to_vec());
24    } else {
25        let mut buf = vec![0 as u8; data.len() + blocksize - diff];
26        buf[..data.len()].copy_from_slice(data);
27        Ok(buf)
28    }
29}