desox 0.3.1

(incomplete) MIFARE DESFire EV3 APDU bindings.
Documentation
// {{{ Copyright (c) Paul R. Tagliamonte <paultag@gmail.com>, 2026
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. }}}

/// This implements the MIFARE DESFire KDF scheme used as part of the
/// authentication flow.
///
/// During the handshake, both the card and host prove control of the same
/// shared private key by encrypting data back and forth and manipulating the
/// plain text. The random data that was encrypted back and forth (half
/// generated by the card, half generated by the host) is used to generate
/// a session key.
///
/// Currently the block size and key size are assumed to be the same (BLOCK_SIZE),
/// which is *NOT* a good assumption. However, I didn't/don't plan on adding
/// 3DES right now, but when/if I do, BLOCK_SIZE will likely need to change,
/// and change throughout the codebase.
///
/// This implements the KDF scheme to join two random blocks of data from
/// the card and host to derive the shared session key.
pub trait Kdf<const BLOCK_SIZE: usize> {
    /// Join the two blocks of random data, and create a single block of
    /// random data to be used as a key.
    fn derive(&self) -> [u8; BLOCK_SIZE];
}

impl Kdf<8> for ([u8; 8], [u8; 8]) {
    fn derive(&self) -> [u8; 8] {
        let (rnd_a, rnd_b) = self;
        let mut out = [0; 8];
        out[..4].copy_from_slice(&rnd_a[..4]);
        out[4..].copy_from_slice(&rnd_b[..4]);
        out.iter_mut().for_each(|v| *v &= 0b11111110);
        out
    }
}

impl Kdf<16> for ([u8; 16], [u8; 16]) {
    fn derive(&self) -> [u8; 16] {
        let (rnd_a, rnd_b) = self;
        let mut out = [0; 16];
        out[0..4].copy_from_slice(&rnd_a[0..4]);
        out[4..8].copy_from_slice(&rnd_b[0..4]);
        out[8..12].copy_from_slice(&rnd_a[12..16]);
        out[12..16].copy_from_slice(&rnd_b[12..16]);
        out
    }
}

// vim: foldmethod=marker