km003c-lib 0.4.0

Protocol parser and async USB library for the ChargerLAB POWER-Z KM003C
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
//! Authentication module for KM003C device
//!
//! This module provides data structures and encryption helpers for the
//! StreamingAuth (0x4C) and MemoryRead (0x44) commands required for AdcQueue streaming.
//!
//! # Authentication Flow
//!
//! 1. Read HardwareID from device memory at 0x40010450 using MemoryRead (0x44)
//! 2. Send StreamingAuth (0x4C) with HardwareID embedded in encrypted payload
//! 3. Device validates and grants auth level 1 (AdcQueue access)
//!
//! Firmware V1.9.9 also grants level 2 when the same 12-byte credential field
//! matches the beginning of its selected calibration record. Response
//! attribute bits 1-2 contain the resulting authentication level.
//!
//! # AES Keys
//!
//! - StreamingAuth encrypt (host→device): `Fa0b4tA25f4R038a`
//! - StreamingAuth decrypt (device→host): `FX0b4tA25f4R038a`
//! - MemoryRead: `Lh2yfB7n6X7d9a5Z`
//!
//! # Usage
//!
//! Use the `Packet::MemoryRead` and `Packet::StreamingAuth` variants from the
//! message module to send authentication commands. This module provides the
//! underlying encryption and data structures.

use aes::Aes128;
use aes::cipher::{BlockCipherDecrypt, BlockCipherEncrypt, KeyInit};

use crate::packet::{PacketType, StreamingAuthHeader};

const STREAMING_AUTH_HEADER_SIZE: usize = 4;
const STREAMING_AUTH_PAYLOAD_SIZE: usize = 32;
const STREAMING_AUTH_RESULT_FLAG: u16 = 1;
const STREAMING_AUTH_LEVEL_SHIFT: u32 = 1;
const STREAMING_AUTH_LEVEL_MASK: u16 = 0b11 << STREAMING_AUTH_LEVEL_SHIFT;
const AES_BLOCK_SIZE: usize = 16;
pub(crate) const STREAMING_AUTH_RESPONSE_ID: u8 = 0;

/// AES-128 key for StreamingAuth encryption (host → device)
pub const STREAMING_AUTH_KEY_ENC: &[u8; 16] = b"Fa0b4tA25f4R038a";

/// AES-128 key for StreamingAuth decryption (device → host)
pub const STREAMING_AUTH_KEY_DEC: &[u8; 16] = b"FX0b4tA25f4R038a";

/// AES-128 key for MemoryRead command
pub const MEMORY_READ_KEY: &[u8; 16] = b"Lh2yfB7n6X7d9a5Z";

/// Memory address where HardwareID is stored
pub const HARDWARE_ID_ADDRESS: u32 = 0x40010450;

/// Size of HardwareID in bytes
pub const HARDWARE_ID_SIZE: usize = 12;

/// Memory address for DeviceInfo1 (model, HW version, mfg date)
pub const DEVICE_INFO_ADDRESS: u32 = 0x00000420;

/// Memory address for FirmwareInfo (FW version, build date)
pub const FIRMWARE_INFO_ADDRESS: u32 = 0x00004420;

/// Memory address for CalibrationData (serial, UUID, timestamp)
pub const CALIBRATION_ADDRESS: u32 = 0x03000C00;

/// Preferred calibration record used for level-2 authentication when present.
pub const PREFERRED_CALIBRATION_ADDRESS: u32 = 0x03000D80;

/// Size of info blocks (DeviceInfo, FirmwareInfo, Calibration)
pub const INFO_BLOCK_SIZE: usize = 64;

/// Size of the credential embedded in a StreamingAuth request.
pub const STREAMING_AUTH_CREDENTIAL_SIZE: usize = 12;

/// 12-byte Hardware ID read from device memory at 0x40010450
///
/// Structure:
/// - Bytes 0-5: Serial prefix (e.g., "071KBP" ASCII)
/// - Bytes 6-7: Separator (typically 0x0D 0xFF)
/// - Bytes 8-9: Device ID (little-endian u16)
/// - Bytes 10-11: Padding (typically 0xFF 0xFF)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HardwareId {
    bytes: [u8; HARDWARE_ID_SIZE],
}

impl HardwareId {
    /// Create HardwareId from raw bytes
    pub fn from_bytes(bytes: [u8; HARDWARE_ID_SIZE]) -> Self {
        Self { bytes }
    }

    /// Get the serial prefix (first 6 bytes as ASCII string)
    pub fn serial_prefix(&self) -> Option<String> {
        let prefix = &self.bytes[0..6];
        if prefix.iter().all(|&b| b.is_ascii_alphanumeric()) {
            Some(String::from_utf8_lossy(prefix).to_string())
        } else {
            None
        }
    }

    /// Get the device ID (bytes 8-9 as little-endian u16)
    pub fn device_id(&self) -> u16 {
        u16::from_le_bytes([self.bytes[8], self.bytes[9]])
    }

    /// Get raw bytes
    pub fn as_bytes(&self) -> &[u8; HARDWARE_ID_SIZE] {
        &self.bytes
    }
}

impl std::fmt::Display for HardwareId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", hex::encode(self.bytes))
    }
}

/// Opaque 12-byte credential embedded in a StreamingAuth request.
///
/// Firmware V1.9.9 accepts the device HardwareID for auth level 1 and the
/// beginning of its selected calibration record for auth level 2.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthCredential {
    bytes: [u8; STREAMING_AUTH_CREDENTIAL_SIZE],
}

impl AuthCredential {
    /// Create a credential from its exact wire bytes.
    pub fn from_bytes(bytes: [u8; STREAMING_AUTH_CREDENTIAL_SIZE]) -> Self {
        Self { bytes }
    }

    /// Return the exact credential bytes.
    pub fn as_bytes(&self) -> &[u8; STREAMING_AUTH_CREDENTIAL_SIZE] {
        &self.bytes
    }
}

impl From<&HardwareId> for AuthCredential {
    fn from(hardware_id: &HardwareId) -> Self {
        Self::from_bytes(*hardware_id.as_bytes())
    }
}

impl From<HardwareId> for AuthCredential {
    fn from(hardware_id: HardwareId) -> Self {
        Self::from(&hardware_id)
    }
}

/// Device information parsed from memory blocks
#[derive(Debug, Clone, Default)]
pub struct DeviceInfo {
    /// Model name (e.g., "KM003C")
    pub model: String,
    /// Hardware version (e.g., "2.1")
    pub hw_version: String,
    /// Manufacturing date (e.g., "2022.11.7")
    pub mfg_date: String,
    /// Firmware version (e.g., "1.9.9")
    pub fw_version: String,
    /// Firmware build date (e.g., "2025.9.22")
    pub fw_date: String,
    /// Serial ID from calibration (e.g., "007965")
    pub serial_id: String,
    /// UUID/hash from calibration
    pub uuid: String,
}

impl DeviceInfo {
    /// Parse DeviceInfo1 block (64 bytes from 0x420)
    ///
    /// Layout:
    /// - 0x00-0x0F: reserved
    /// - 0x10-0x1B: model (12 bytes, null-terminated)
    /// - 0x1C-0x27: hw_version (12 bytes, null-terminated)
    /// - 0x28-0x3F: mfg_date (24 bytes, null-terminated)
    pub fn parse_device_info(&mut self, data: &[u8]) {
        if data.len() >= 64 {
            self.model = extract_string(data, 0x10, 0x1C);
            self.hw_version = extract_string(data, 0x1C, 0x28);
            self.mfg_date = extract_string(data, 0x28, 0x40);
        }
    }

    /// Parse FirmwareInfo block (64 bytes from 0x4420)
    ///
    /// Layout:
    /// - 0x00-0x03: magic (0x00004000 or 0xFFFFFFFF if invalid)
    /// - 0x10-0x1B: model (12 bytes)
    /// - 0x1C-0x27: fw_version (12 bytes, null-terminated)
    /// - 0x28-0x33: fw_date (12 bytes, null-terminated)
    pub fn parse_firmware_info(&mut self, data: &[u8]) {
        if data.len() >= 64 {
            // Check magic - if 0xFFFFFFFF, firmware info is invalid
            let magic = u32::from_le_bytes(data[0..4].try_into().unwrap_or([0xFF; 4]));
            if magic != 0xFFFFFFFF {
                self.fw_version = extract_string(data, 0x1C, 0x28);
                self.fw_date = extract_string(data, 0x28, 0x34);
            }
        }
    }

    /// Parse CalibrationData block (64 bytes from 0x3000C00)
    ///
    /// Layout:
    /// - 0x00-0x06: serial_id (7 bytes, space-padded)
    /// - 0x07-0x26: UUID (32 bytes hex string)
    pub fn parse_calibration(&mut self, data: &[u8]) {
        if data.len() >= 64 {
            self.serial_id = extract_string(data, 0x00, 0x07).trim().to_string();
            self.uuid = extract_string(data, 0x07, 0x27);
        }
    }
}

/// Extract null-terminated string from byte slice
fn extract_string(data: &[u8], start: usize, end: usize) -> String {
    if start >= data.len() || end > data.len() || start >= end {
        return String::new();
    }
    let slice = &data[start..end];
    // Find null terminator or end of slice
    let len = slice.iter().position(|&b| b == 0).unwrap_or(slice.len());
    String::from_utf8_lossy(&slice[..len]).to_string()
}

/// Result of StreamingAuth command
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StreamingAuthResult {
    /// Whether authentication was successful (AdcQueue access granted)
    pub success: bool,
    /// Raw attribute value from response
    pub attribute: u16,
    /// Auth level: 0 = failed, 1 = device auth, 2 = calibration auth
    pub auth_level: u8,
    /// Decrypted response payload (32 bytes)
    pub decrypted_payload: [u8; 32],
}

impl StreamingAuthResult {
    /// Check if AdcQueue streaming is enabled
    pub fn adcqueue_enabled(&self) -> bool {
        self.auth_level != 0
    }
}

/// Result of device initialization
///
/// Convenience struct for protocol research scripts that manage
/// the init sequence manually rather than using `KM003C::new()`.
#[derive(Debug, Clone)]
pub struct InitResult {
    /// Device information (model, versions, serial, etc.)
    pub device_info: DeviceInfo,
    /// Hardware ID used for authentication
    pub hardware_id: HardwareId,
    /// Authentication result
    pub auth: StreamingAuthResult,
}

impl InitResult {
    /// Check if device is ready for AdcQueue streaming
    pub fn is_authenticated(&self) -> bool {
        self.auth.success && self.auth.adcqueue_enabled()
    }
}

/// Build MemoryRead encrypted payload (32 bytes)
///
/// # Arguments
/// * `address` - Memory address to read from
/// * `size` - Number of bytes to read
///
/// # Returns
/// 32-byte AES-encrypted payload
pub fn build_memory_read_payload(address: u32, size: u32) -> [u8; 32] {
    // Build 32-byte plaintext
    let mut plaintext = [0xFFu8; 32];

    // Bytes 0-3: Address (little-endian)
    plaintext[0..4].copy_from_slice(&address.to_le_bytes());

    // Bytes 4-7: Size (little-endian)
    plaintext[4..8].copy_from_slice(&size.to_le_bytes());

    // Bytes 8-11: Magic (0xFFFFFFFF)
    plaintext[8..12].copy_from_slice(&0xFFFFFFFFu32.to_le_bytes());

    // Bytes 12-15: CRC32 of bytes 0-11
    let crc = crc32fast::hash(&plaintext[0..12]);
    plaintext[12..16].copy_from_slice(&crc.to_le_bytes());

    // Bytes 16-31: Already 0xFF from initialization

    // Encrypt with AES-128-ECB
    aes_ecb_encrypt(&plaintext, MEMORY_READ_KEY)
}

/// Decrypt and validate a 32-byte MemoryRead request payload.
pub fn parse_memory_read_payload(ciphertext: &[u8]) -> Option<(u32, u32)> {
    let plaintext = decrypt_memory_read_response(ciphertext)?;
    if plaintext.len() != 32 {
        return None;
    }

    let address = u32::from_le_bytes(plaintext[0..4].try_into().ok()?);
    let size = u32::from_le_bytes(plaintext[4..8].try_into().ok()?);
    let magic = u32::from_le_bytes(plaintext[8..12].try_into().ok()?);
    let checksum = u32::from_le_bytes(plaintext[12..16].try_into().ok()?);
    if magic != u32::MAX || checksum != crc32fast::hash(&plaintext[..12]) || plaintext[16..] != [0xFF; 16] {
        return None;
    }

    Some((address, size))
}

/// Size of the confirmation body the device echoes for a MemoryRead request.
pub const MEMORY_READ_CONFIRMATION_SIZE: usize = 16;

/// Fields echoed by the device in a MemoryRead confirmation body.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MemoryReadConfirmation {
    pub address: u32,
    pub size: u32,
    pub magic: u32,
    pub checksum: u32,
    /// CRC-32 recomputed over the first 12 bytes of the body.
    pub expected_checksum: u32,
}

impl MemoryReadConfirmation {
    /// Decode the 16-byte confirmation body that follows the packet header.
    pub fn from_bytes(body: &[u8]) -> Option<Self> {
        let body: &[u8; MEMORY_READ_CONFIRMATION_SIZE] = body.first_chunk()?;
        let word = |range: std::ops::Range<usize>| {
            u32::from_le_bytes(body[range].try_into().expect("fixed-size confirmation field"))
        };

        Some(Self {
            address: word(0..4),
            size: word(4..8),
            magic: word(8..12),
            checksum: word(12..16),
            expected_checksum: crc32fast::hash(&body[..12]),
        })
    }

    /// Whether the magic word and the CRC-32 both match.
    pub fn is_intact(&self) -> bool {
        self.magic == u32::MAX && self.checksum == self.expected_checksum
    }
}

/// Decode a MemoryRead confirmation body into its echoed address and size.
///
/// Returns `None` when the body is truncated, the magic word is wrong, or the
/// CRC-32 does not match.
pub fn parse_memory_read_confirmation(body: &[u8]) -> Option<(u32, u32)> {
    let confirmation = MemoryReadConfirmation::from_bytes(body)?;
    confirmation
        .is_intact()
        .then_some((confirmation.address, confirmation.size))
}

/// Build a MemoryRead (0x44) request packet
///
/// The wire layout lives in [`crate::message::Packet::to_raw_packet`]; this is
/// a convenience wrapper for callers that want the finished bytes.
///
/// # Arguments
/// * `address` - Memory address to read from
/// * `size` - Number of bytes to read
/// * `tid` - Transaction ID
///
/// # Returns
/// 36-byte packet: 4-byte header + 32-byte AES-encrypted payload
pub fn build_memory_read_packet(address: u32, size: u32, tid: u8) -> Vec<u8> {
    serialize_infallible(crate::message::Packet::MemoryRead { address, size }, tid)
}

/// Build StreamingAuth encrypted payload (32 bytes)
///
/// # Arguments
/// * `credential` - 12-byte device or calibration credential
///
/// # Returns
/// 32-byte AES-encrypted payload
pub fn build_streaming_auth_payload(credential: &AuthCredential) -> [u8; 32] {
    // Build 32-byte plaintext
    let mut plaintext = [0u8; 32];

    // Bytes 0-7: Timestamp (milliseconds since epoch)
    let timestamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0);
    plaintext[0..8].copy_from_slice(&timestamp.to_le_bytes());

    // Bytes 8-19: device or calibration authentication credential
    plaintext[8..20].copy_from_slice(credential.as_bytes());

    // Bytes 20-31: Random padding
    let random_bytes: [u8; 12] = rand::random();
    plaintext[20..32].copy_from_slice(&random_bytes);

    // Encrypt with AES-128-ECB
    aes_ecb_encrypt(&plaintext, STREAMING_AUTH_KEY_ENC)
}

/// Decrypt a host-to-device StreamingAuth request and extract its credential.
pub fn parse_streaming_auth_request_payload(ciphertext: &[u8]) -> Option<AuthCredential> {
    let encrypted: [u8; STREAMING_AUTH_PAYLOAD_SIZE] = ciphertext.try_into().ok()?;
    let plaintext = aes_ecb_decrypt(&encrypted, STREAMING_AUTH_KEY_ENC);
    Some(AuthCredential::from_bytes(plaintext[8..20].try_into().ok()?))
}

/// Encrypt a StreamingAuth payload (for serializing responses)
///
/// # Arguments
/// * `plaintext` - 32-byte plaintext payload
///
/// # Returns
/// 32-byte AES-encrypted payload
pub fn encrypt_streaming_auth_response_payload(plaintext: &[u8; 32]) -> [u8; 32] {
    aes_ecb_encrypt(plaintext, STREAMING_AUTH_KEY_DEC)
}

/// Build a StreamingAuth (0x4C) request packet
///
/// The wire layout lives in [`crate::message::Packet::to_raw_packet`]; this is
/// a convenience wrapper for callers that want the finished bytes.
///
/// # Arguments
/// * `credential` - 12-byte device or calibration credential
/// * `tid` - Transaction ID
///
/// # Returns
/// 36-byte packet: 4-byte header + 32-byte AES-encrypted payload
pub fn build_streaming_auth_packet(credential: &AuthCredential, tid: u8) -> Vec<u8> {
    serialize_infallible(
        crate::message::Packet::StreamingAuth {
            credential: credential.clone(),
        },
        tid,
    )
}

/// Serialize a packet whose `to_raw_packet` conversion cannot fail.
fn serialize_infallible(packet: crate::message::Packet, tid: u8) -> Vec<u8> {
    let raw = packet
        .to_raw_packet(tid)
        .expect("auth command packets are always serializable");
    bytes::Bytes::from(raw).to_vec()
}

/// Parse StreamingAuth (0x4C) response from full packet
///
/// # Arguments
/// * `response` - Raw response bytes (at least 36 bytes: 4-byte header + 32-byte payload)
///
/// # Returns
/// Parsed authentication result
pub fn parse_streaming_auth_response(response: &[u8]) -> Option<StreamingAuthResult> {
    if response.len() < STREAMING_AUTH_HEADER_SIZE + STREAMING_AUTH_PAYLOAD_SIZE {
        return None;
    }

    let (header_bytes, payload) = response.split_at(STREAMING_AUTH_HEADER_SIZE);
    let header = StreamingAuthHeader::from_bytes(header_bytes.try_into().ok()?);
    parse_streaming_auth_response_parts(header, payload)
}

pub(crate) fn parse_streaming_auth_response_parts(
    header: StreamingAuthHeader,
    payload: &[u8],
) -> Option<StreamingAuthResult> {
    if header.packet_type() != u8::from(PacketType::StreamingAuth)
        || header.reserved_flag()
        || header.id() != STREAMING_AUTH_RESPONSE_ID
        || header.attribute() & STREAMING_AUTH_RESULT_FLAG == 0
    {
        return None;
    }

    parse_streaming_auth_response_payload(payload, header.attribute())
}

/// Parse and decrypt a StreamingAuth response payload with its raw response attribute.
pub fn parse_streaming_auth_response_payload(payload: &[u8], attribute: u16) -> Option<StreamingAuthResult> {
    let encrypted: [u8; STREAMING_AUTH_PAYLOAD_SIZE] = payload.get(..STREAMING_AUTH_PAYLOAD_SIZE)?.try_into().ok()?;
    let decrypted = aes_ecb_decrypt(&encrypted, STREAMING_AUTH_KEY_DEC);
    let auth_level = ((attribute & STREAMING_AUTH_LEVEL_MASK) >> STREAMING_AUTH_LEVEL_SHIFT) as u8;

    Some(StreamingAuthResult {
        success: auth_level != 0,
        attribute,
        auth_level,
        decrypted_payload: decrypted,
    })
}

/// AES-128-ECB encrypt 32 bytes
fn aes_ecb_encrypt(plaintext: &[u8; 32], key: &[u8; 16]) -> [u8; 32] {
    let cipher = Aes128::new(key.into());
    let mut output = *plaintext;

    for block in output.as_chunks_mut::<AES_BLOCK_SIZE>().0 {
        encrypt_aes_block(&cipher, block);
    }

    output
}

/// Decrypt an unframed MemoryRead response payload
///
/// The response payload is AES-encrypted with MEMORY_READ_KEY.
/// Useful for protocol research and manual memory reads.
pub fn decrypt_memory_read_response(ciphertext: &[u8]) -> Option<Vec<u8>> {
    if ciphertext.is_empty() || !ciphertext.len().is_multiple_of(AES_BLOCK_SIZE) {
        return None;
    }

    // Decrypt in 16-byte blocks
    let cipher = Aes128::new(MEMORY_READ_KEY.into());
    let mut output = ciphertext.to_vec();

    for block in output.chunks_mut(AES_BLOCK_SIZE) {
        if block.len() == AES_BLOCK_SIZE {
            decrypt_aes_block(&cipher, block);
        }
    }

    Some(output)
}

/// AES-128-ECB decrypt 32 bytes
fn aes_ecb_decrypt(ciphertext: &[u8; 32], key: &[u8; 16]) -> [u8; 32] {
    let cipher = Aes128::new(key.into());
    let mut output = *ciphertext;

    for block in output.as_chunks_mut::<AES_BLOCK_SIZE>().0 {
        decrypt_aes_block(&cipher, block);
    }

    output
}

fn encrypt_aes_block(cipher: &Aes128, bytes: &mut [u8]) {
    let block: &mut [u8; AES_BLOCK_SIZE] = bytes.try_into().expect("AES chunk has the block size");
    cipher.encrypt_block(block.into());
}

fn decrypt_aes_block(cipher: &Aes128, bytes: &mut [u8]) {
    let block: &mut [u8; AES_BLOCK_SIZE] = bytes.try_into().expect("AES chunk has the block size");
    cipher.decrypt_block(block.into());
}

/// AES-128-ECB decrypt a single 16-byte block
///
/// Useful for protocol research and manual decryption of individual blocks.
pub fn aes_ecb_decrypt_block(ciphertext: &[u8; 16], key: &[u8; 16]) -> [u8; 16] {
    let cipher = Aes128::new(key.into());
    let mut output = *ciphertext;
    decrypt_aes_block(&cipher, &mut output);
    output
}

/// AES-128-ECB decrypt multiple 16-byte blocks
///
/// # Arguments
/// * `ciphertext` - Encrypted data (must be multiple of 16 bytes)
/// * `key` - 16-byte AES key
///
/// # Returns
/// Decrypted data, or error if ciphertext length is not a multiple of 16
pub fn aes_ecb_decrypt_blocks(ciphertext: &[u8], key: &[u8; 16]) -> Result<Vec<u8>, crate::error::KMError> {
    if !ciphertext.len().is_multiple_of(AES_BLOCK_SIZE) {
        return Err(crate::error::KMError::InvalidPacket(format!(
            "AES ciphertext must be a multiple of {AES_BLOCK_SIZE} bytes, got {}",
            ciphertext.len()
        )));
    }

    let cipher = Aes128::new(key.into());
    let mut output = ciphertext.to_vec();

    for block in output.as_chunks_mut::<AES_BLOCK_SIZE>().0 {
        decrypt_aes_block(&cipher, block);
    }

    Ok(output)
}

#[cfg(test)]
mod tests {
    use super::*;

    // Known working hardcoded packets from CLI (captured from working session)
    // MemoryRead packet (tid=2): reads HardwareID from 0x40010450
    const HARDCODED_MEMORY_READ: &str = "4402010133f8860c0054288cdc7e52729826872dd18b539a39c407d5c063d91102e36a9e";
    // StreamingAuth packet (tid=6): authenticates with embedded HardwareID
    const HARDCODED_STREAMING_AUTH: &str = "4c0600025538815b69a452c83e54ef1d70f3bc9ae6aac1b12a6ac07c20fde58c7bf517ca";

    #[test]
    fn test_hardware_id_parsing() {
        // Example HardwareID: "071KBP" + separator + device ID 2577
        let bytes: [u8; 12] = [
            0x30, 0x37, 0x31, 0x4b, 0x42, 0x50, // "071KBP"
            0x0d, 0xff, // separator
            0x11, 0x0a, // device ID 2577 (LE)
            0xff, 0xff, // padding
        ];

        let hw_id = HardwareId::from_bytes(bytes);
        assert_eq!(hw_id.serial_prefix(), Some("071KBP".to_string()));
        assert_eq!(hw_id.device_id(), 2577);
    }

    #[test]
    fn test_aes_roundtrip() {
        let plaintext = [0x42u8; 32];
        let encrypted = aes_ecb_encrypt(&plaintext, STREAMING_AUTH_KEY_ENC);
        // Note: Can't decrypt with same key in real protocol, but can test structure
        assert_ne!(encrypted, plaintext);
        assert_eq!(encrypted.len(), 32);
    }

    #[test]
    fn test_memory_read_packet_structure() {
        let packet = build_memory_read_packet(HARDWARE_ID_ADDRESS, HARDWARE_ID_SIZE as u32, 0x02);
        assert_eq!(packet.len(), 36);
        assert_eq!(packet[0], 0x44); // MemoryRead
        assert_eq!(packet[1], 0x02); // TID
        assert_eq!(packet[2], 0x01); // Attribute low
        assert_eq!(packet[3], 0x01); // Attribute high
    }

    #[test]
    fn test_streaming_auth_packet_structure() {
        let hw_id = HardwareId::from_bytes([0x30, 0x37, 0x31, 0x4b, 0x42, 0x50, 0x0d, 0xff, 0x11, 0x0a, 0xff, 0xff]);
        let packet = build_streaming_auth_packet(&AuthCredential::from(&hw_id), 0x06);
        assert_eq!(packet.len(), 36);
        assert_eq!(packet[0], 0x4C); // StreamingAuth
        assert_eq!(packet[1], 0x06); // TID
        assert_eq!(packet[2], 0x00); // Attribute low
        assert_eq!(packet[3], 0x02); // Attribute high (0x0002)
    }

    #[test]
    fn test_streaming_auth_calibration_credential_roundtrip() {
        let credential = AuthCredential::from_bytes(*b"007965 CDFDD");
        let encrypted = build_streaming_auth_payload(&credential);

        assert_eq!(parse_streaming_auth_request_payload(&encrypted), Some(credential));
    }

    #[test]
    fn test_streaming_auth_response_uses_header_result() {
        use crate::{Packet, RawPacket};
        use bytes::Bytes;

        let plaintext = [0x5a; STREAMING_AUTH_PAYLOAD_SIZE];
        let encrypted = aes_ecb_encrypt(&plaintext, STREAMING_AUTH_KEY_DEC);

        let response = |attribute| {
            let header = StreamingAuthHeader::new()
                .with_packet_type(PacketType::StreamingAuth.into())
                .with_reserved_flag(false)
                .with_id(0)
                .with_attribute(attribute);
            let mut bytes = Vec::from(header.into_bytes());
            bytes.extend_from_slice(&encrypted);
            bytes
        };

        let device_auth = parse_streaming_auth_response(&response(0x0203)).unwrap();
        assert!(device_auth.success);
        assert!(device_auth.adcqueue_enabled());
        assert_eq!(device_auth.auth_level, 1);
        assert_eq!(device_auth.attribute, 0x0203);
        assert_eq!(device_auth.decrypted_payload, plaintext);

        let calibration_auth = parse_streaming_auth_response(&response(0x0205)).unwrap();
        assert!(calibration_auth.success);
        assert!(calibration_auth.adcqueue_enabled());
        assert_eq!(calibration_auth.auth_level, 2);
        assert_eq!(calibration_auth.attribute, 0x0205);
        assert_eq!(calibration_auth.decrypted_payload, plaintext);

        let serialized = Bytes::from(
            Packet::StreamingAuthResponse(calibration_auth.clone())
                .to_raw_packet(99)
                .unwrap(),
        );
        let reparsed = RawPacket::try_from(serialized).unwrap();
        assert_eq!(
            Packet::try_from(reparsed).unwrap(),
            Packet::StreamingAuthResponse(calibration_auth)
        );

        let raw_failure = RawPacket::try_from(Bytes::from(response(0x0201))).unwrap();
        let Packet::StreamingAuthResponse(failure) = Packet::try_from(raw_failure).unwrap() else {
            panic!("expected StreamingAuthResponse");
        };
        assert!(!failure.success);
        assert!(!failure.adcqueue_enabled());
        assert_eq!(failure.auth_level, 0);
        assert_eq!(failure.attribute, 0x0201);
        assert_eq!(failure.decrypted_payload, plaintext);
    }

    #[test]
    fn test_decrypt_hardcoded_memory_read() {
        // Decrypt the hardcoded MemoryRead packet to see what it reads
        // NOTE: The hardcoded packet reads from 0x420 (size 64), NOT 0x40010450 (HardwareID)
        let packet = hex::decode(HARDCODED_MEMORY_READ).unwrap();

        // Check header
        assert_eq!(packet[0], 0x44, "MemoryRead type");
        assert_eq!(packet[1], 0x02, "TID=2");
        assert_eq!(packet[2], 0x01, "Attribute low");
        assert_eq!(packet[3], 0x01, "Attribute high");

        // Decrypt payload (bytes 4-35)
        let ciphertext: [u8; 32] = packet[4..36].try_into().unwrap();
        let plaintext = aes_ecb_decrypt(&ciphertext, MEMORY_READ_KEY);

        // Extract address (bytes 0-3, little-endian)
        let address = u32::from_le_bytes([plaintext[0], plaintext[1], plaintext[2], plaintext[3]]);
        // Extract size (bytes 4-7, little-endian)
        let size = u32::from_le_bytes([plaintext[4], plaintext[5], plaintext[6], plaintext[7]]);

        println!("Decrypted MemoryRead: address=0x{:08X}, size={}", address, size);
        println!("Plaintext: {:02x?}", plaintext);

        // The hardcoded packet actually reads from 0x420 with size 64 (different memory region)
        assert_eq!(address, 0x420, "Hardcoded reads from 0x420");
        assert_eq!(size, 64, "Hardcoded reads 64 bytes");
    }

    #[test]
    fn test_memory_read_for_hardware_id() {
        // Verify our library generates correct MemoryRead for HardwareID
        let generated = build_memory_read_packet(HARDWARE_ID_ADDRESS, HARDWARE_ID_SIZE as u32, 0x02);

        // Check header
        assert_eq!(generated[0], 0x44, "MemoryRead type");
        assert_eq!(generated[1], 0x02, "TID=2");
        assert_eq!(generated[2], 0x01, "Attribute low");
        assert_eq!(generated[3], 0x01, "Attribute high");

        // Decrypt and verify address/size
        let ciphertext: [u8; 32] = generated[4..36].try_into().unwrap();
        let plaintext = aes_ecb_decrypt(&ciphertext, MEMORY_READ_KEY);

        let address = u32::from_le_bytes([plaintext[0], plaintext[1], plaintext[2], plaintext[3]]);
        let size = u32::from_le_bytes([plaintext[4], plaintext[5], plaintext[6], plaintext[7]]);

        assert_eq!(address, HARDWARE_ID_ADDRESS, "Should read from 0x40010450");
        assert_eq!(size, HARDWARE_ID_SIZE as u32, "Should read 12 bytes");

        // Verify CRC32 is correct (bytes 12-15)
        let expected_crc = crc32fast::hash(&plaintext[0..12]);
        let actual_crc = u32::from_le_bytes([plaintext[12], plaintext[13], plaintext[14], plaintext[15]]);
        assert_eq!(actual_crc, expected_crc, "CRC32 should be valid");
    }

    #[test]
    fn test_decrypt_hardcoded_streaming_auth() {
        // Decrypt the hardcoded StreamingAuth packet to extract HardwareID
        let packet = hex::decode(HARDCODED_STREAMING_AUTH).unwrap();

        // Check header
        assert_eq!(packet[0], 0x4C, "StreamingAuth type");
        assert_eq!(packet[1], 0x06, "TID=6");
        assert_eq!(packet[2], 0x00, "Attribute low");
        assert_eq!(packet[3], 0x02, "Attribute high");

        // Decrypt payload (bytes 4-35) using ENCRYPT key (since host->device uses encrypt key)
        let ciphertext: [u8; 32] = packet[4..36].try_into().unwrap();
        let plaintext = aes_ecb_decrypt(&ciphertext, STREAMING_AUTH_KEY_ENC);

        // Structure: timestamp(8) + HardwareID(12) + padding(12)
        let timestamp = u64::from_le_bytes(plaintext[0..8].try_into().unwrap());
        let hardware_id_bytes: [u8; 12] = plaintext[8..20].try_into().unwrap();
        let hardware_id = HardwareId::from_bytes(hardware_id_bytes);

        println!("Decrypted StreamingAuth:");
        println!("  Timestamp: {} ms", timestamp);
        println!("  HardwareID: {}", hardware_id);
        println!("  Serial prefix: {:?}", hardware_id.serial_prefix());
        println!("  Device ID: {}", hardware_id.device_id());
        println!("  Plaintext: {:02x?}", plaintext);

        // Verify the extracted HardwareID
        assert_eq!(hardware_id.serial_prefix(), Some("071KBP".to_string()));
        assert_eq!(hardware_id.device_id(), 2577);
        assert!(timestamp > 0, "Timestamp should be non-zero");
    }

    #[test]
    fn test_streaming_auth_with_known_hardware_id() {
        // Use the HardwareID extracted from the working hardcoded packet
        // HardwareID: 071KBP, device ID 2577
        let hw_id = HardwareId::from_bytes([
            0x30, 0x37, 0x31, 0x4b, 0x42, 0x50, // "071KBP"
            0x0d, 0xff, // separator
            0x11, 0x0a, // device ID 2577 (LE)
            0xff, 0xff, // padding
        ]);

        // Generate StreamingAuth packet
        let packet = build_streaming_auth_packet(&AuthCredential::from(&hw_id), 0x06);

        // Verify header matches hardcoded
        let hardcoded = hex::decode(HARDCODED_STREAMING_AUTH).unwrap();
        assert_eq!(&packet[0..4], &hardcoded[0..4], "Headers must match");

        // Decrypt our generated packet to verify HardwareID is embedded correctly
        let ciphertext: [u8; 32] = packet[4..36].try_into().unwrap();
        let plaintext = aes_ecb_decrypt(&ciphertext, STREAMING_AUTH_KEY_ENC);

        // Extract and verify HardwareID
        let extracted_hw: [u8; 12] = plaintext[8..20].try_into().unwrap();
        assert_eq!(extracted_hw, hw_id.bytes, "HardwareID must be embedded correctly");

        // Timestamp should be recent (within last hour - 3600000 ms)
        let timestamp = u64::from_le_bytes(plaintext[0..8].try_into().unwrap());
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_millis() as u64;
        assert!(timestamp > now - 3600000, "Timestamp should be recent");
        assert!(timestamp <= now + 1000, "Timestamp should not be in future");
    }
}