Skip to main content

spodes_rs/service/
ciphering.rs

1//! Service-specific glo-/ded-ciphering of xDLMS APDUs (IEC 62056-5-3, 5.7).
2//!
3//! A ciphered APDU has the form
4//!
5//! ```text
6//! tag | length | SC | IC | [ciphertext] | [tag]
7//! ```
8//!
9//! where the security header `SC ‖ IC` is the 1-octet security control byte and
10//! the 4-octet invocation counter. The initialization vector is
11//! `system-title ‖ IC`, the block cipher key is the (global or dedicated)
12//! encryption key `EK`, and — when authentication is applied — the additional
13//! authenticated data is `SC ‖ AK` (authenticated encryption) or
14//! `SC ‖ AK ‖ plaintext` (authentication only). The GCM tag is truncated to 12
15//! octets (security suite 0, AES-GCM-128).
16//!
17//! For GOST ciphering (Р 1323565.1), Kuznyechik CTR+CMAC is used with a
18//! 16-byte CMAC tag.
19//!
20//! Validated against the authenticated-encryption test vector of IEC 62056-5-3
21//! Annex E.5.
22
23use aead::AeadInOut;
24use aes_gcm::aead::consts::U12;
25use aes_gcm::aes::{Aes128, Aes256};
26use aes_gcm::KeyInit as AesKeyInit;
27use aes_gcm::{AesGcm, Nonce, Tag};
28use cipher::block::BlockCipherEncrypt;
29use cmac::Cmac;
30use kuznyechik::Kuznyechik;
31
32/// AES-128-GCM with a 96-bit (12-octet) authentication tag.
33type Aes128Gcm12 = AesGcm<Aes128, U12, U12>;
34/// AES-256-GCM with a 96-bit (12-octet) authentication tag.
35type Aes256Gcm12 = AesGcm<Aes256, U12, U12>;
36/// Kuznyechik CMAC type (used internally).
37#[allow(dead_code)]
38type KuznyechikCmac = Cmac<Kuznyechik>;
39
40/// Bit masks of the security control byte (SC), IEC 62056-5-3 Table 27.
41pub mod security_control {
42    /// Authentication is applied (bit 4).
43    pub const AUTHENTICATION: u8 = 0x10;
44    /// Encryption is applied (bit 5).
45    pub const ENCRYPTION: u8 = 0x20;
46    /// The broadcast key set is used instead of the unicast one (bit 6).
47    pub const KEY_SET_BROADCAST: u8 = 0x40;
48    /// Compression is applied (bit 7).
49    pub const COMPRESSION: u8 = 0x80;
50    /// Convenience value: authenticated encryption with security suite 0.
51    pub const AUTHENTICATED_ENCRYPTION: u8 = AUTHENTICATION | ENCRYPTION;
52}
53
54/// GOST security suite identifier (Р 1323565.1, suite id = 0x0D).
55pub const GOST_SUITE_ID: u8 = 0x0D;
56
57/// Checks if the security control byte indicates a GOST suite.
58pub fn is_gost_suite(sc: u8) -> bool {
59    (sc & 0x0F) == GOST_SUITE_ID
60}
61
62/// Ciphered-APDU tags for service-specific global ciphering.
63pub mod glo {
64    /// `glo-initiate-request`.
65    pub const INITIATE_REQUEST: u8 = 0x21;
66    /// `glo-initiate-response`.
67    pub const INITIATE_RESPONSE: u8 = 0x28;
68    /// `glo-get-request`.
69    pub const GET_REQUEST: u8 = 0xC8;
70    /// `glo-set-request`.
71    pub const SET_REQUEST: u8 = 0xC9;
72    /// `glo-action-request`.
73    pub const ACTION_REQUEST: u8 = 0xCB;
74    /// `glo-get-response`.
75    pub const GET_RESPONSE: u8 = 0xCC;
76    /// `glo-set-response`.
77    pub const SET_RESPONSE: u8 = 0xCD;
78    /// `glo-action-response`.
79    pub const ACTION_RESPONSE: u8 = 0xCF;
80}
81
82/// Ciphered-APDU tags for service-specific dedicated ciphering.
83pub mod ded {
84    /// `ded-get-request`.
85    pub const GET_REQUEST: u8 = 0xD0;
86    /// `ded-set-request`.
87    pub const SET_REQUEST: u8 = 0xD1;
88    /// `ded-action-request`.
89    pub const ACTION_REQUEST: u8 = 0xD3;
90    /// `ded-get-response`.
91    pub const GET_RESPONSE: u8 = 0xD4;
92    /// `ded-set-response`.
93    pub const SET_RESPONSE: u8 = 0xD5;
94    /// `ded-action-response`.
95    pub const ACTION_RESPONSE: u8 = 0xD7;
96}
97
98/// Errors from ciphering / deciphering.
99#[derive(Debug, PartialEq, Eq)]
100pub enum CipherError {
101    /// The system title was not 8 octets.
102    InvalidSystemTitle,
103    /// The encryption key was not 16 or 32 octets.
104    InvalidKey,
105    /// The ciphered APDU was too short for its security header.
106    Truncated,
107    /// The authentication tag did not verify.
108    AuthenticationFailed,
109    /// The AES-GCM engine reported an error.
110    CryptoError,
111    /// The received invocation counter did not increase past the last one
112    /// accepted from this peer (a replayed or reordered-backward APDU).
113    ReplayDetected,
114    /// The invocation counter has reached its maximum value and cannot be
115    /// used to protect another APDU without re-keying.
116    InvocationCounterExhausted,
117}
118
119impl std::fmt::Display for CipherError {
120    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121        write!(f, "{self:?}")
122    }
123}
124
125impl std::error::Error for CipherError {}
126
127/// The security material and parameters for one ciphering operation.
128#[derive(Debug, Clone)]
129pub struct SecurityContext {
130    /// Security control byte (SC).
131    pub security_control: u8,
132    /// Block cipher (encryption) key, 16 or 32 octets.
133    pub encryption_key: Vec<u8>,
134    /// Authentication key (AK), used in the additional authenticated data.
135    pub authentication_key: Vec<u8>,
136    /// System title, 8 octets (forms the IV together with the IC).
137    pub system_title: Vec<u8>,
138    /// Invocation counter (IC).
139    pub invocation_counter: u32,
140    /// The last invocation counter accepted from the peer, for replay
141    /// rejection. Set by `for_suite`; updated by the `*_unprotect` functions.
142    last_peer_ic: u32,
143    /// Whether `last_peer_ic` holds a value yet (false until the first
144    /// successful unprotect).
145    ic_valid: bool,
146}
147
148impl Drop for SecurityContext {
149    /// Zeroizes the key material when the context is dropped, so secrets do
150    /// not linger in freed memory.
151    fn drop(&mut self) {
152        use zeroize::Zeroize;
153        self.encryption_key.zeroize();
154        self.authentication_key.zeroize();
155    }
156}
157
158impl SecurityContext {
159    /// Builds a context for a given protection level and security suite,
160    /// validating that the encryption key length matches the suite
161    /// (16 octets for suites 0/1, 32 for suite 2) and deriving the security
162    /// control byte from the policy and the suite id.
163    pub fn for_suite(
164        policy: crate::security::SecurityPolicy,
165        suite: crate::security::SecuritySuite,
166        encryption_key: Vec<u8>,
167        authentication_key: Vec<u8>,
168        system_title: Vec<u8>,
169        invocation_counter: u32,
170    ) -> Result<SecurityContext, CipherError> {
171        if encryption_key.len() != suite.aes_key_len() {
172            return Err(CipherError::InvalidKey);
173        }
174        Ok(SecurityContext {
175            security_control: policy.security_control_byte(suite),
176            encryption_key,
177            authentication_key,
178            system_title,
179            invocation_counter,
180            last_peer_ic: 0,
181            ic_valid: false,
182        })
183    }
184
185    /// Checks the received invocation counter against the last one accepted
186    /// from this peer, rejecting a replayed or reordered-backward APDU
187    /// *before* any decryption is attempted (IEC 62056-5-3: the IC must
188    /// increase monotonically per peer).
189    fn check_replay(&self, ic: u32) -> Result<(), CipherError> {
190        if self.ic_valid && ic <= self.last_peer_ic {
191            return Err(CipherError::ReplayDetected);
192        }
193        Ok(())
194    }
195
196    /// Records `ic` as the last invocation counter accepted from the peer,
197    /// after a successful unprotect.
198    fn accept_peer_ic(&mut self, ic: u32) {
199        self.last_peer_ic = ic;
200        self.ic_valid = true;
201    }
202
203    /// Rejects protecting an APDU once the invocation counter has reached
204    /// its maximum value: it must never wrap back to a smaller value, per
205    /// IEC 62056-5-3. Re-keying (a fresh IC) is required past this point.
206    fn check_send_ic(&self) -> Result<(), CipherError> {
207        if self.invocation_counter == u32::MAX {
208            return Err(CipherError::InvocationCounterExhausted);
209        }
210        Ok(())
211    }
212
213    /// Advisory check for the host: true once the invocation counter is
214    /// within 1000 of overflow, signalling that the keys should be rotated
215    /// (a fresh system-title/key pair resets the counter) before
216    /// [`CipherError::InvocationCounterExhausted`] starts rejecting sends.
217    pub fn key_rotation_needed(&self) -> bool {
218        self.invocation_counter >= u32::MAX - 1000
219    }
220
221    fn authentication(&self) -> bool {
222        self.security_control & security_control::AUTHENTICATION != 0
223    }
224
225    fn encryption(&self) -> bool {
226        self.security_control & security_control::ENCRYPTION != 0
227    }
228
229    fn iv(&self) -> Result<[u8; 12], CipherError> {
230        if self.system_title.len() != 8 {
231            return Err(CipherError::InvalidSystemTitle);
232        }
233        let mut iv = [0u8; 12];
234        iv[..8].copy_from_slice(&self.system_title);
235        iv[8..].copy_from_slice(&self.invocation_counter.to_be_bytes());
236        Ok(iv)
237    }
238}
239
240/// Protects `plaintext` (a plain xDLMS APDU) and returns the ciphered APDU with
241/// the given `ciphered_tag` (see [`glo`] / [`ded`]).
242pub fn protect(ctx: &SecurityContext, ciphered_tag: u8, plaintext: &[u8]) -> Result<Vec<u8>, CipherError> {
243    ctx.check_send_ic()?;
244    let iv = ctx.iv()?;
245    let sc = ctx.security_control;
246
247    let mut protected = Vec::new();
248    match (ctx.authentication(), ctx.encryption()) {
249        (true, true) => {
250            // Authenticated encryption: AAD = SC ‖ AK, output = ciphertext ‖ tag.
251            let aad = [&[sc][..], &ctx.authentication_key].concat();
252            let mut buf = plaintext.to_vec();
253            let tag = gcm_encrypt_in_place(&ctx.encryption_key, &iv, &aad, &mut buf)?;
254            protected.extend_from_slice(&buf);
255            protected.extend_from_slice(&tag);
256        }
257        (true, false) => {
258            // Authentication only: AAD = SC ‖ AK ‖ plaintext, output = plaintext ‖ tag.
259            let aad = [&[sc][..], &ctx.authentication_key, plaintext].concat();
260            let mut empty = Vec::new();
261            let tag = gcm_encrypt_in_place(&ctx.encryption_key, &iv, &aad, &mut empty)?;
262            protected.extend_from_slice(plaintext);
263            protected.extend_from_slice(&tag);
264        }
265        (false, true) => {
266            // Encryption only: no AAD, no tag, output = ciphertext.
267            let mut buf = plaintext.to_vec();
268            gcm_encrypt_in_place(&ctx.encryption_key, &iv, &[], &mut buf)?;
269            protected.extend_from_slice(&buf);
270        }
271        (false, false) => protected.extend_from_slice(plaintext),
272    }
273
274    // tag | length | SC | IC | protected.
275    let mut body = Vec::with_capacity(5 + protected.len());
276    body.push(sc);
277    body.extend_from_slice(&ctx.invocation_counter.to_be_bytes());
278    body.extend_from_slice(&protected);
279
280    let mut apdu = vec![ciphered_tag];
281    push_length(body.len(), &mut apdu);
282    apdu.extend_from_slice(&body);
283    Ok(apdu)
284}
285
286/// Removes protection from a ciphered APDU, returning `(ciphered_tag, plaintext)`.
287///
288/// The invocation counter carried in the header is written into `ctx` so the
289/// same context can decipher a following APDU with the peer's counter. Per
290/// IEC 62056-5-3 the IC must increase monotonically per peer; a received IC
291/// that does not exceed the last one accepted from this peer is rejected as
292/// a replay *before* any decryption is attempted, and `ctx` is left
293/// unchanged.
294pub fn unprotect(ctx: &mut SecurityContext, apdu: &[u8]) -> Result<(u8, Vec<u8>), CipherError> {
295    let ciphered_tag = *apdu.first().ok_or(CipherError::Truncated)?;
296    let (len, header) = read_length(&apdu[1..]).ok_or(CipherError::Truncated)?;
297    let body = apdu.get(1 + header..1 + header + len).ok_or(CipherError::Truncated)?;
298    if body.len() < 5 {
299        return Err(CipherError::Truncated);
300    }
301    let sc = body[0];
302    let ic = u32::from_be_bytes([body[1], body[2], body[3], body[4]]);
303    ctx.check_replay(ic)?;
304    ctx.security_control = sc;
305    ctx.invocation_counter = ic;
306    let protected = &body[5..];
307    let iv = ctx.iv()?;
308
309    let plaintext = match (ctx.authentication(), ctx.encryption()) {
310        (true, true) => {
311            if protected.len() < 12 {
312                return Err(CipherError::Truncated);
313            }
314            let (ct, tag) = protected.split_at(protected.len() - 12);
315            let aad = [&[sc][..], &ctx.authentication_key].concat();
316            gcm_decrypt(&ctx.encryption_key, &iv, &aad, ct, tag)?
317        }
318        (true, false) => {
319            if protected.len() < 12 {
320                return Err(CipherError::Truncated);
321            }
322            let (plain, tag) = protected.split_at(protected.len() - 12);
323            let aad = [&[sc][..], &ctx.authentication_key, plain].concat();
324            // Verify by recomputing the tag over an empty message.
325            let mut empty = Vec::new();
326            let expected = gcm_encrypt_in_place(&ctx.encryption_key, &iv, &aad, &mut empty)?;
327            if expected.as_slice() != tag {
328                return Err(CipherError::AuthenticationFailed);
329            }
330            plain.to_vec()
331        }
332        (false, true) => {
333            let mut buf = protected.to_vec();
334            gcm_decrypt_no_tag(&ctx.encryption_key, &iv, &mut buf)?;
335            buf
336        }
337        (false, false) => protected.to_vec(),
338    };
339    ctx.accept_peer_ic(ic);
340    Ok((ciphered_tag, plaintext))
341}
342
343// ============================================================================
344// GOST ciphering (Р 1323565.1): Kuznyechik CTR + CMAC
345// ============================================================================
346
347/// GOST-authenticated encryption using Kuznyechik CTR+CMAC (Р 1323565.1).
348///
349/// - Encryption: Kuznyechik in CTR mode (IV = system_title ‖ IC).
350/// - Authentication: Kuznyechik CMAC over `SC ‖ AK ‖ ciphertext`.
351/// - Tag: 16-byte full CMAC output.
352///
353/// Returns the encrypted APDU with the GOST tag appended.
354pub fn gost_protect(ctx: &SecurityContext, ciphered_tag: u8, plaintext: &[u8]) -> Result<Vec<u8>, CipherError> {
355    ctx.check_send_ic()?;
356    if ctx.encryption_key.len() != 32 {
357        return Err(CipherError::InvalidKey);
358    }
359    let sc = ctx.security_control;
360    let iv = ctx.iv()?;
361    let nonce = build_gost_nonce(&iv);
362
363    match (ctx.authentication(), ctx.encryption()) {
364        (true, true) => {
365            // Encrypt with CTR, then compute CMAC over SC ‖ AK ‖ ciphertext.
366            let ciphertext = gost_ctr_encrypt(&ctx.encryption_key, &nonce, plaintext)?;
367            let aad = [[sc].as_ref(), &ctx.authentication_key, &ciphertext].concat();
368            let tag = gost_cmac_tag(&ctx.encryption_key, &aad)?;
369            let mut body = Vec::with_capacity(5 + ciphertext.len() + 16);
370            body.push(sc);
371            body.extend_from_slice(&ctx.invocation_counter.to_be_bytes());
372            body.extend_from_slice(&ciphertext);
373            body.extend_from_slice(&tag);
374            let mut apdu = vec![ciphered_tag];
375            push_length(body.len(), &mut apdu);
376            apdu.extend_from_slice(&body);
377            Ok(apdu)
378        }
379        (true, false) => {
380            // Authentication only: CMAC over SC ‖ AK ‖ plaintext.
381            let aad = [[sc].as_ref(), &ctx.authentication_key, plaintext].concat();
382            let tag = gost_cmac_tag(&ctx.encryption_key, &aad)?;
383            let mut body = Vec::with_capacity(5 + plaintext.len() + 16);
384            body.push(sc);
385            body.extend_from_slice(&ctx.invocation_counter.to_be_bytes());
386            body.extend_from_slice(plaintext);
387            body.extend_from_slice(&tag);
388            let mut apdu = vec![ciphered_tag];
389            push_length(body.len(), &mut apdu);
390            apdu.extend_from_slice(&body);
391            Ok(apdu)
392        }
393        (false, true) => {
394            // Encryption only: no tag.
395            let ciphertext = gost_ctr_encrypt(&ctx.encryption_key, &nonce, plaintext)?;
396            let mut body = Vec::with_capacity(5 + ciphertext.len());
397            body.push(sc);
398            body.extend_from_slice(&ctx.invocation_counter.to_be_bytes());
399            body.extend_from_slice(&ciphertext);
400            let mut apdu = vec![ciphered_tag];
401            push_length(body.len(), &mut apdu);
402            apdu.extend_from_slice(&body);
403            Ok(apdu)
404        }
405        (false, false) => {
406            let mut body = Vec::with_capacity(5 + plaintext.len());
407            body.push(sc);
408            body.extend_from_slice(&ctx.invocation_counter.to_be_bytes());
409            body.extend_from_slice(plaintext);
410            let mut apdu = vec![ciphered_tag];
411            push_length(body.len(), &mut apdu);
412            apdu.extend_from_slice(&body);
413            Ok(apdu)
414        }
415    }
416}
417
418/// Removes GOST ciphering from an APDU, returning `(ciphered_tag, plaintext)`.
419/// Rejects a replayed or reordered-backward invocation counter before any
420/// decryption is attempted; see [`unprotect`].
421pub fn gost_unprotect(ctx: &mut SecurityContext, apdu: &[u8]) -> Result<(u8, Vec<u8>), CipherError> {
422    let ciphered_tag = *apdu.first().ok_or(CipherError::Truncated)?;
423    let (len, header) = read_length(&apdu[1..]).ok_or(CipherError::Truncated)?;
424    let body = apdu.get(1 + header..1 + header + len).ok_or(CipherError::Truncated)?;
425    if body.len() < 5 {
426        return Err(CipherError::Truncated);
427    }
428    let sc = body[0];
429    let ic = u32::from_be_bytes([body[1], body[2], body[3], body[4]]);
430    ctx.check_replay(ic)?;
431    ctx.security_control = sc;
432    ctx.invocation_counter = ic;
433    let protected = &body[5..];
434    let iv = ctx.iv()?;
435    let nonce = build_gost_nonce(&iv);
436
437    let plaintext = match (ctx.authentication(), ctx.encryption()) {
438        (true, true) => {
439            if protected.len() < 16 {
440                return Err(CipherError::Truncated);
441            }
442            let (ct, tag) = protected.split_at(protected.len() - 16);
443            let aad = [[sc].as_ref(), &ctx.authentication_key, ct].concat();
444            let expected_tag = gost_cmac_tag(&ctx.encryption_key, &aad)?;
445            if tag != expected_tag.as_slice() {
446                return Err(CipherError::AuthenticationFailed);
447            }
448            gost_ctr_decrypt(&ctx.encryption_key, &nonce, ct)?
449        }
450        (true, false) => {
451            if protected.len() < 16 {
452                return Err(CipherError::Truncated);
453            }
454            let (plain, tag) = protected.split_at(protected.len() - 16);
455            let aad = [[sc].as_ref(), &ctx.authentication_key, plain].concat();
456            let expected_tag = gost_cmac_tag(&ctx.encryption_key, &aad)?;
457            if tag != expected_tag.as_slice() {
458                return Err(CipherError::AuthenticationFailed);
459            }
460            plain.to_vec()
461        }
462        (false, true) => gost_ctr_decrypt(&ctx.encryption_key, &nonce, protected)?,
463        (false, false) => protected.to_vec(),
464    };
465    ctx.accept_peer_ic(ic);
466    Ok((ciphered_tag, plaintext))
467}
468
469/// Kuznyechik CTR-mode encryption.
470fn gost_ctr_encrypt(key: &[u8], nonce: &[u8; 16], plaintext: &[u8]) -> Result<Vec<u8>, CipherError> {
471    use cipher::BlockCipherEncrypt;
472    let cipher = Kuznyechik::new_from_slice(key).map_err(|_| CipherError::InvalidKey)?;
473    let mut ciphertext = plaintext.to_vec();
474    let mut counter = *nonce;
475
476    for chunk in ciphertext.chunks_mut(16) {
477        // Encrypt counter block to get keystream
478        let mut keystream = cipher::Array::from(counter);
479        cipher.encrypt_block(&mut keystream);
480        let ks: [u8; 16] = keystream.into();
481        // XOR plaintext with keystream
482        for (i, byte) in chunk.iter_mut().enumerate() {
483            *byte ^= ks[i];
484        }
485        // Increment counter (big-endian)
486        increment_counter(&mut counter);
487    }
488    Ok(ciphertext)
489}
490
491/// Kuznyechik CTR-mode decryption (same as encryption for CTR).
492fn gost_ctr_decrypt(key: &[u8], nonce: &[u8; 16], ciphertext: &[u8]) -> Result<Vec<u8>, CipherError> {
493    // CTR mode decryption is identical to encryption
494    gost_ctr_encrypt(key, nonce, ciphertext)
495}
496
497/// Kuznyechik CMAC tag computation (16 bytes).
498/// Implements CMAC manually using Kuznyechik block cipher (GOST R 34.13-2015).
499fn gost_cmac_tag(key: &[u8], data: &[u8]) -> Result<Vec<u8>, CipherError> {
500    if key.len() != 32 {
501        return Err(CipherError::InvalidKey);
502    }
503
504    let cipher = Kuznyechik::new_from_slice(key).map_err(|_| CipherError::InvalidKey)?;
505
506    // Generate subkeys K1 and K2
507    let mut l = cipher::Array::from([0u8; 16]);
508    cipher.encrypt_block(&mut l);
509    let l_bytes: [u8; 16] = l.into();
510
511    let k1 = ghash_subkey(&l_bytes);
512    let k2 = ghash_subkey(&k1);
513
514    // Process data in 16-byte blocks
515    let mut state = [0u8; 16];
516    let chunks: Vec<&[u8]> = data.chunks(16).collect();
517    let last_block = data.chunks(16).last();
518
519    if data.is_empty() || last_block.is_some_and(|b| b.len() == 16) {
520        // Data is empty or last block is full
521        for chunk in &chunks {
522            xor_blocks(&mut state, chunk);
523            let mut block = cipher::Array::from(state);
524            cipher.encrypt_block(&mut block);
525            state = block.into();
526        }
527        if !data.is_empty() && last_block.is_some_and(|b| b.len() == 16) {
528            // XOR K1 into state before final block
529            xor_blocks(&mut state, &k1);
530            let mut block = cipher::Array::from(state);
531            cipher.encrypt_block(&mut block);
532            state = block.into();
533        }
534    } else {
535        // Last block is partial - pad and XOR K2
536        let mut padded = [0u8; 16];
537        padded[..chunks.last().unwrap().len()].copy_from_slice(chunks.last().unwrap());
538        padded[chunks.last().unwrap().len()] = 0x80; // padding
539
540        for chunk in &chunks[..chunks.len() - 1] {
541            xor_blocks(&mut state, chunk);
542            let mut block = cipher::Array::from(state);
543            cipher.encrypt_block(&mut block);
544            state = block.into();
545        }
546        // Process last padded block with K2
547        xor_blocks(&mut state, &padded);
548        xor_blocks(&mut state, &k2);
549        let mut block = cipher::Array::from(state);
550        cipher.encrypt_block(&mut block);
551        state = block.into();
552    }
553
554    Ok(state.to_vec())
555}
556
557/// GHASH subkey derivation for CMAC (doubles the block in GF(2^128)).
558fn ghash_subkey(l: &[u8; 16]) -> [u8; 16] {
559    let mut result = [0u8; 16];
560    let carry = l[0] & 0x80 != 0;
561    for i in 0..16 {
562        result[i] = (l[i] << 1) | if i + 1 < 16 { l[i + 1] >> 7 } else { 0 };
563    }
564    if carry {
565        result[15] ^= 0x87; // x^128 + x^7 + x^2 + x + 1
566    }
567    result
568}
569
570/// XOR two 16-byte blocks.
571fn xor_blocks(a: &mut [u8; 16], b: &[u8]) {
572    for i in 0..16.min(b.len()) {
573        a[i] ^= b[i];
574    }
575}
576
577/// Builds a 16-byte nonce from the 12-byte IV (system_title ‖ IC).
578/// The GOST CTR mode uses a 128-bit block, so we extend the 96-bit IV
579/// with zeros to form the counter initial value.
580fn build_gost_nonce(iv: &[u8; 12]) -> [u8; 16] {
581    let mut nonce = [0u8; 16];
582    nonce[..12].copy_from_slice(iv);
583    nonce
584}
585
586/// Increments a 128-bit counter in big-endian.
587fn increment_counter(counter: &mut [u8; 16]) {
588    for i in (0..16).rev() {
589        counter[i] = counter[i].wrapping_add(1);
590        if counter[i] != 0 {
591            break;
592        }
593    }
594}
595
596// ============================================================================
597// GOST GMAC (Kuznyechik GCM-like mode)
598// ============================================================================
599
600/// GOST GMAC: Kuznyechik in GCM-like mode (CTR + GHASH).
601///
602/// This is an alternative to CTR+CMAC that provides:
603/// - Encryption: Kuznyechik in CTR mode
604/// - Authentication: GHASH (Galois field multiplication over GF(2^128))
605///
606/// The GHASH function uses Kuznyechik as the underlying block cipher,
607/// computing authentication tags over AAD and ciphertext.
608pub fn gost_gmac_tag(key: &[u8], iv: &[u8; 12], aad: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, CipherError> {
609    if key.len() != 32 {
610        return Err(CipherError::InvalidKey);
611    }
612
613    let cipher = Kuznyechik::new_from_slice(key).map_err(|_| CipherError::InvalidKey)?;
614
615    // Generate hash subkey H = E(K, 0^128)
616    let mut h = cipher::Array::from([0u8; 16]);
617    cipher.encrypt_block(&mut h);
618    let _h_bytes: [u8; 16] = h.into();
619
620    // Compute GHASH over AAD || ciphertext || len(AAD)||len(ciphertext)
621    let mut state = [0u8; 16];
622
623    // Process AAD
624    for chunk in aad.chunks(16) {
625        let mut block = [0u8; 16];
626        block[..chunk.len()].copy_from_slice(chunk);
627        if chunk.len() < 16 {
628            block[chunk.len()] = 0x80; // padding
629        }
630        xor_blocks(&mut state, &block);
631        let mut block_arr = cipher::Array::from(state);
632        cipher.encrypt_block(&mut block_arr);
633        state = block_arr.into();
634    }
635
636    // Process ciphertext
637    for chunk in plaintext.chunks(16) {
638        let mut block = [0u8; 16];
639        block[..chunk.len()].copy_from_slice(chunk);
640        if chunk.len() < 16 {
641            block[chunk.len()] = 0x80; // padding
642        }
643        xor_blocks(&mut state, &block);
644        let mut block_arr = cipher::Array::from(state);
645        cipher.encrypt_block(&mut block_arr);
646        state = block_arr.into();
647    }
648
649    // Process lengths block: len(AAD) || len(ciphertext) in bits
650    let aad_bit_len = (aad.len() as u64) * 8;
651    let ct_bit_len = (plaintext.len() as u64) * 8;
652    let mut len_block = [0u8; 16];
653    len_block[0..8].copy_from_slice(&aad_bit_len.to_be_bytes());
654    len_block[8..16].copy_from_slice(&ct_bit_len.to_be_bytes());
655    xor_blocks(&mut state, &len_block);
656    let mut block_arr = cipher::Array::from(state);
657    cipher.encrypt_block(&mut block_arr);
658    state = block_arr.into();
659
660    // Final: tag = GHASH(H, AAD, ciphertext) ⊕ E(K, IV || 0^32)
661    // For GMAC, we use the IV directly as the counter block
662    let mut enc_block = cipher::Array::from(build_gmac_counter(iv));
663    cipher.encrypt_block(&mut enc_block);
664    let enc_bytes: [u8; 16] = enc_block.into();
665    xor_blocks(&mut state, &enc_bytes);
666
667    Ok(state.to_vec())
668}
669
670/// Builds the 128-bit counter block for GOST GMAC.
671/// The counter is IV (12 bytes) || 0x00000001 (4 bytes).
672fn build_gmac_counter(iv: &[u8; 12]) -> [u8; 16] {
673    let mut counter = [0u8; 16];
674    counter[..12].copy_from_slice(iv);
675    counter[15] = 0x01; // counter starts at 1
676    counter
677}
678
679/// GOST GMAC encryption (CTR mode) for use with GMAC authentication.
680pub fn gost_gmac_encrypt(key: &[u8], iv: &[u8; 12], plaintext: &[u8]) -> Result<Vec<u8>, CipherError> {
681    // CTR mode encryption with counter starting at 1
682    let cipher = Kuznyechik::new_from_slice(key).map_err(|_| CipherError::InvalidKey)?;
683    let mut ciphertext = plaintext.to_vec();
684    let mut counter = build_gmac_counter(iv);
685
686    for chunk in ciphertext.chunks_mut(16) {
687        let mut keystream = cipher::Array::from(counter);
688        cipher.encrypt_block(&mut keystream);
689        let ks: [u8; 16] = keystream.into();
690        for (i, byte) in chunk.iter_mut().enumerate() {
691            *byte ^= ks[i];
692        }
693        increment_counter(&mut counter);
694    }
695    Ok(ciphertext)
696}
697
698/// GOST GMAC decryption (CTR mode) for use with GMAC authentication.
699pub fn gost_gmac_decrypt(key: &[u8], iv: &[u8; 12], ciphertext: &[u8]) -> Result<Vec<u8>, CipherError> {
700    // CTR mode decryption is identical to encryption
701    gost_gmac_encrypt(key, iv, ciphertext)
702}
703
704/// Protects an APDU using GOST GMAC (Kuznyechik GCM-like mode).
705pub fn gost_gmac_protect(ctx: &SecurityContext, ciphered_tag: u8, plaintext: &[u8]) -> Result<Vec<u8>, CipherError> {
706    ctx.check_send_ic()?;
707    if ctx.encryption_key.len() != 32 {
708        return Err(CipherError::InvalidKey);
709    }
710    let sc = ctx.security_control;
711    let iv = ctx.iv()?;
712
713    let mut protected = Vec::new();
714    match (ctx.authentication(), ctx.encryption()) {
715        (true, true) => {
716            // Encrypt with CTR, then compute GMAC over SC ‖ AK ‖ ciphertext.
717            let ciphertext = gost_gmac_encrypt(&ctx.encryption_key, &iv, plaintext)?;
718            let aad = [[sc].as_ref(), &ctx.authentication_key].concat();
719            let tag = gost_gmac_tag(&ctx.encryption_key, &iv, &aad, &ciphertext)?;
720            protected.extend_from_slice(&ciphertext);
721            protected.extend_from_slice(&tag);
722        }
723        (true, false) => {
724            // Authentication only: GMAC over SC ‖ AK ‖ plaintext.
725            let aad = [[sc].as_ref(), &ctx.authentication_key].concat();
726            let tag = gost_gmac_tag(&ctx.encryption_key, &iv, &aad, plaintext)?;
727            protected.extend_from_slice(plaintext);
728            protected.extend_from_slice(&tag);
729        }
730        (false, true) => {
731            // Encryption only: no tag.
732            let ciphertext = gost_gmac_encrypt(&ctx.encryption_key, &iv, plaintext)?;
733            protected.extend_from_slice(&ciphertext);
734        }
735        (false, false) => protected.extend_from_slice(plaintext),
736    }
737
738    let mut body = Vec::with_capacity(5 + protected.len());
739    body.push(sc);
740    body.extend_from_slice(&ctx.invocation_counter.to_be_bytes());
741    body.extend_from_slice(&protected);
742
743    let mut apdu = vec![ciphered_tag];
744    push_length(body.len(), &mut apdu);
745    apdu.extend_from_slice(&body);
746    Ok(apdu)
747}
748
749/// Removes GOST GMAC protection from an APDU. Rejects a replayed or
750/// reordered-backward invocation counter before any decryption is
751/// attempted; see [`unprotect`].
752pub fn gost_gmac_unprotect(ctx: &mut SecurityContext, apdu: &[u8]) -> Result<(u8, Vec<u8>), CipherError> {
753    let ciphered_tag = *apdu.first().ok_or(CipherError::Truncated)?;
754    let (len, header) = read_length(&apdu[1..]).ok_or(CipherError::Truncated)?;
755    let body = apdu.get(1 + header..1 + header + len).ok_or(CipherError::Truncated)?;
756    if body.len() < 5 {
757        return Err(CipherError::Truncated);
758    }
759    let sc = body[0];
760    let ic = u32::from_be_bytes([body[1], body[2], body[3], body[4]]);
761    ctx.check_replay(ic)?;
762    ctx.security_control = sc;
763    ctx.invocation_counter = ic;
764    let protected = &body[5..];
765    let iv = ctx.iv()?;
766
767    let plaintext = match (ctx.authentication(), ctx.encryption()) {
768        (true, true) => {
769            if protected.len() < 16 {
770                return Err(CipherError::Truncated);
771            }
772            let (ct, tag) = protected.split_at(protected.len() - 16);
773            let aad = [[sc].as_ref(), &ctx.authentication_key].concat();
774            let expected_tag = gost_gmac_tag(&ctx.encryption_key, &iv, &aad, ct)?;
775            if tag != expected_tag.as_slice() {
776                return Err(CipherError::AuthenticationFailed);
777            }
778            gost_gmac_decrypt(&ctx.encryption_key, &iv, ct)?
779        }
780        (true, false) => {
781            if protected.len() < 16 {
782                return Err(CipherError::Truncated);
783            }
784            let (plain, tag) = protected.split_at(protected.len() - 16);
785            let aad = [[sc].as_ref(), &ctx.authentication_key].concat();
786            let expected_tag = gost_gmac_tag(&ctx.encryption_key, &iv, &aad, plain)?;
787            if tag != expected_tag.as_slice() {
788                return Err(CipherError::AuthenticationFailed);
789            }
790            plain.to_vec()
791        }
792        (false, true) => gost_gmac_decrypt(&ctx.encryption_key, &iv, protected)?,
793        (false, false) => protected.to_vec(),
794    };
795    ctx.accept_peer_ic(ic);
796    Ok((ciphered_tag, plaintext))
797}
798
799/// Encrypts `buf` in place and returns the 12-octet authentication tag.
800fn gcm_encrypt_in_place(key: &[u8], iv: &[u8; 12], aad: &[u8], buf: &mut [u8]) -> Result<[u8; 12], CipherError> {
801    let nonce = Nonce::<U12>::from(*iv);
802    let tag = match key.len() {
803        16 => Aes128Gcm12::new_from_slice(key)
804            .map_err(|_| CipherError::InvalidKey)?
805            .encrypt_inout_detached(&nonce, aad, buf.into())
806            .map_err(|_| CipherError::CryptoError)?,
807        32 => Aes256Gcm12::new_from_slice(key)
808            .map_err(|_| CipherError::InvalidKey)?
809            .encrypt_inout_detached(&nonce, aad, buf.into())
810            .map_err(|_| CipherError::CryptoError)?,
811        _ => return Err(CipherError::InvalidKey),
812    };
813    let mut out = [0u8; 12];
814    out.copy_from_slice(&tag);
815    Ok(out)
816}
817
818/// Decrypts `ct` and verifies the 12-octet `tag`, returning the plaintext.
819fn gcm_decrypt(key: &[u8], iv: &[u8; 12], aad: &[u8], ct: &[u8], tag: &[u8]) -> Result<Vec<u8>, CipherError> {
820    let nonce = Nonce::<U12>::from(*iv);
821    let tag = Tag::<U12>::try_from(tag).map_err(|_| CipherError::InvalidKey)?;
822    let mut buf = ct.to_vec();
823    match key.len() {
824        16 => Aes128Gcm12::new_from_slice(key)
825            .map_err(|_| CipherError::InvalidKey)?
826            .decrypt_inout_detached(&nonce, aad, buf.as_mut_slice().into(), &tag)
827            .map_err(|_| CipherError::AuthenticationFailed)?,
828        32 => Aes256Gcm12::new_from_slice(key)
829            .map_err(|_| CipherError::InvalidKey)?
830            .decrypt_inout_detached(&nonce, aad, buf.as_mut_slice().into(), &tag)
831            .map_err(|_| CipherError::AuthenticationFailed)?,
832        _ => return Err(CipherError::InvalidKey),
833    }
834    Ok(buf)
835}
836
837/// Decrypts `buf` in place with encryption only (no tag verification): recompute
838/// the keystream by "encrypting" against an all-zero tag placeholder is not
839/// possible, so decrypt with a throwaway tag over empty AAD via GCM's CTR core.
840fn gcm_decrypt_no_tag(key: &[u8], iv: &[u8; 12], buf: &mut [u8]) -> Result<(), CipherError> {
841    // GCM decryption is CTR-mode keystream XOR; recover the plaintext by
842    // encrypting the ciphertext with the same key/nonce (CTR is symmetric).
843    let nonce = Nonce::<U12>::from(*iv);
844    match key.len() {
845        16 => {
846            Aes128Gcm12::new_from_slice(key)
847                .map_err(|_| CipherError::InvalidKey)?
848                .encrypt_inout_detached(&nonce, &[], buf.into())
849                .map_err(|_| CipherError::CryptoError)?;
850        }
851        32 => {
852            Aes256Gcm12::new_from_slice(key)
853                .map_err(|_| CipherError::InvalidKey)?
854                .encrypt_inout_detached(&nonce, &[], buf.into())
855                .map_err(|_| CipherError::CryptoError)?;
856        }
857        _ => return Err(CipherError::InvalidKey),
858    }
859    Ok(())
860}
861
862/// Writes a BER length octet (short or long form).
863#[allow(clippy::cast_possible_truncation)] // length < 128 and n in 1..=8 always fit u8
864fn push_length(length: usize, out: &mut Vec<u8>) {
865    if length < 128 {
866        out.push(length as u8);
867    } else {
868        let bytes = (length as u64).to_be_bytes();
869        let first = bytes.iter().position(|&b| b != 0).unwrap_or(7);
870        let n = 8 - first;
871        out.push(0x80 | n as u8);
872        out.extend_from_slice(&bytes[first..]);
873    }
874}
875
876fn read_length(bytes: &[u8]) -> Option<(usize, usize)> {
877    let first = *bytes.first()?;
878    if first < 128 {
879        Some((first as usize, 1))
880    } else {
881        let n = (first & 0x7F) as usize;
882        let slice = bytes.get(1..1 + n)?;
883        let mut len = 0usize;
884        for &b in slice {
885            len = (len << 8) | b as usize;
886        }
887        Some((len, 1 + n))
888    }
889}
890
891#[cfg(test)]
892mod tests {
893    use super::*;
894
895    fn hex(s: &[u8]) -> Vec<u8> {
896        fn nib(c: u8) -> u8 {
897            match c {
898                b'0'..=b'9' => c - b'0',
899                b'A'..=b'F' => c - b'A' + 10,
900                b'a'..=b'f' => c - b'a' + 10,
901                _ => panic!("bad hex"),
902            }
903        }
904        s.chunks(2).map(|p| (nib(p[0]) << 4) | nib(p[1])).collect()
905    }
906
907    fn ctx() -> SecurityContext {
908        SecurityContext {
909            security_control: security_control::AUTHENTICATED_ENCRYPTION,
910            encryption_key: hex(b"000102030405060708090A0B0C0D0E0F"),
911            authentication_key: hex(b"D0D1D2D3D4D5D6D7D8D9DADBDCDDDEDF"),
912            system_title: hex(b"4D4D4D0000BC614E"),
913            invocation_counter: 0x01234567,
914            last_peer_ic: 0,
915            ic_valid: false,
916        }
917    }
918
919    #[test]
920    fn protect_matches_blue_book_e5_vector() {
921        // IEC 62056-5-3 Annex E.5: authenticated encryption of an InitiateResponse.
922        let plaintext = hex(b"0800065F1F0400007C1F04000007");
923        let apdu = protect(&ctx(), glo::INITIATE_RESPONSE, &plaintext).unwrap();
924        let expected = hex(b"281F30012345678912\
92514A0845E475714383F65BC19745CA235906525E4F3E1C893");
926        assert_eq!(apdu, expected);
927    }
928
929    #[test]
930    fn protect_then_unprotect_round_trips() {
931        let plaintext = hex(b"0800065F1F0400007C1F04000007");
932        let apdu = protect(&ctx(), glo::GET_RESPONSE, &plaintext).unwrap();
933        let (tag, recovered) = unprotect(&mut ctx(), &apdu).unwrap();
934        assert_eq!(tag, glo::GET_RESPONSE);
935        assert_eq!(recovered, plaintext);
936    }
937
938    #[test]
939    fn unprotect_detects_tampering() {
940        let plaintext = hex(b"0800065F1F0400007C1F04000007");
941        let mut apdu = protect(&ctx(), glo::GET_RESPONSE, &plaintext).unwrap();
942        let n = apdu.len();
943        apdu[n - 1] ^= 0x01; // corrupt the tag
944        assert_eq!(unprotect(&mut ctx(), &apdu), Err(CipherError::AuthenticationFailed));
945    }
946
947    #[test]
948    fn unprotect_rejects_replayed_or_reordered_ic() {
949        let mut tx = ctx();
950        let mut rx = ctx();
951        let plaintext = hex(b"C001C100080000010000FF0200");
952
953        // First: a valid APDU with IC=5 establishes the peer's baseline.
954        tx.invocation_counter = 5;
955        let apdu = protect(&tx, glo::GET_REQUEST, &plaintext).unwrap();
956        let (_, recovered) = unprotect(&mut rx, &apdu).unwrap();
957        assert_eq!(recovered, plaintext);
958        assert_eq!(rx.last_peer_ic, 5);
959
960        // Replaying the same APDU (IC=5 again) must be rejected.
961        assert_eq!(unprotect(&mut rx, &apdu), Err(CipherError::ReplayDetected));
962
963        // A lower IC (3) — an out-of-order or replayed older APDU — is
964        // rejected too, even though it is otherwise well-formed.
965        tx.invocation_counter = 3;
966        let older = protect(&tx, glo::GET_REQUEST, &plaintext).unwrap();
967        assert_eq!(unprotect(&mut rx, &older), Err(CipherError::ReplayDetected));
968        // Rejection must not disturb the recorded baseline.
969        assert_eq!(rx.last_peer_ic, 5);
970
971        // A higher IC (6) is accepted and advances the baseline.
972        tx.invocation_counter = 6;
973        let next = protect(&tx, glo::GET_REQUEST, &plaintext).unwrap();
974        assert!(unprotect(&mut rx, &next).is_ok());
975        assert_eq!(rx.last_peer_ic, 6);
976    }
977
978    #[test]
979    fn protect_rejects_exhausted_invocation_counter() {
980        let mut tx = ctx();
981        tx.invocation_counter = u32::MAX;
982        assert_eq!(protect(&tx, glo::GET_REQUEST, b"x"), Err(CipherError::InvocationCounterExhausted));
983    }
984
985    #[test]
986    fn key_rotation_needed_flags_approaching_overflow() {
987        let mut c = ctx();
988        c.invocation_counter = 0;
989        assert!(!c.key_rotation_needed());
990        c.invocation_counter = u32::MAX - 1000;
991        assert!(c.key_rotation_needed());
992        c.invocation_counter = u32::MAX;
993        assert!(c.key_rotation_needed());
994    }
995
996    #[test]
997    fn for_suite_validates_key_length_and_builds_sc() {
998        use crate::security::{SecurityPolicy, SecuritySuite};
999        // Suite 2 requires a 32-octet key; a 16-octet one is rejected.
1000        assert_eq!(
1001            SecurityContext::for_suite(
1002                SecurityPolicy::AuthenticationEncryption,
1003                SecuritySuite::Suite2,
1004                vec![0u8; 16],
1005                vec![0u8; 16],
1006                vec![0u8; 8],
1007                0,
1008            )
1009            .unwrap_err(),
1010            CipherError::InvalidKey
1011        );
1012        // Suite 0 authenticated encryption → SC = 0x30.
1013        let ctx = SecurityContext::for_suite(
1014            SecurityPolicy::AuthenticationEncryption,
1015            SecuritySuite::Suite0,
1016            vec![0u8; 16],
1017            vec![0u8; 16],
1018            vec![0u8; 8],
1019            0,
1020        )
1021        .unwrap();
1022        assert_eq!(ctx.security_control, 0x30);
1023        // Suite 2 encryption-only → SC = 0x22.
1024        let ctx2 = SecurityContext::for_suite(
1025            SecurityPolicy::Encryption,
1026            SecuritySuite::Suite2,
1027            vec![0u8; 32],
1028            vec![0u8; 32],
1029            vec![0u8; 8],
1030            0,
1031        )
1032        .unwrap();
1033        assert_eq!(ctx2.security_control, 0x22);
1034    }
1035
1036    #[test]
1037    fn authentication_only_round_trips() {
1038        let mut c = ctx();
1039        c.security_control = security_control::AUTHENTICATION;
1040        let plaintext = hex(b"C001C100080000010000FF0200");
1041        let apdu = protect(&c, glo::GET_REQUEST, &plaintext).unwrap();
1042        // Plaintext (after tag|len|SC|IC = 7 octets) is carried in the clear.
1043        assert_eq!(&apdu[7..7 + plaintext.len()], plaintext.as_slice());
1044        let (_, recovered) = unprotect(&mut c, &apdu).unwrap();
1045        assert_eq!(recovered, plaintext);
1046    }
1047
1048    // ========================================================================
1049    // GOST ciphering tests (Р 1323565.1: Kuznyechik CTR+CMAC)
1050    // ========================================================================
1051
1052    fn gost_ctx() -> SecurityContext {
1053        SecurityContext {
1054            security_control: security_control::AUTHENTICATED_ENCRYPTION | GOST_SUITE_ID,
1055            encryption_key: hex(b"8899aabbccddeeff00112233445566778899aabbccddeeff0011223344556677"),
1056            authentication_key: hex(b"bddc7e4ac4e164e40785d8c147b4a883bddc7e4ac4e164e40785d8c147b4a883"),
1057            system_title: hex(b"4D4D4D0000BC614E"),
1058            invocation_counter: 0x01234567,
1059            last_peer_ic: 0,
1060            ic_valid: false,
1061        }
1062    }
1063
1064    #[test]
1065    fn gost_protect_unprotect_round_trip() {
1066        let plaintext = hex(b"C001C100080000010000FF0200");
1067        let apdu = gost_protect(&gost_ctx(), glo::GET_REQUEST, &plaintext).unwrap();
1068        let (tag, recovered) = gost_unprotect(&mut gost_ctx(), &apdu).unwrap();
1069        assert_eq!(tag, glo::GET_REQUEST);
1070        assert_eq!(recovered, plaintext);
1071    }
1072
1073    #[test]
1074    fn gost_unprotect_rejects_replayed_ic() {
1075        let mut tx = gost_ctx();
1076        let mut rx = gost_ctx();
1077        let plaintext = hex(b"C001C100080000010000FF0200");
1078
1079        tx.invocation_counter = 5;
1080        let apdu = gost_protect(&tx, glo::GET_REQUEST, &plaintext).unwrap();
1081        assert!(gost_unprotect(&mut rx, &apdu).is_ok());
1082        assert_eq!(gost_unprotect(&mut rx, &apdu), Err(CipherError::ReplayDetected));
1083    }
1084
1085    #[test]
1086    fn gost_protect_unprotect_with_auth_only() {
1087        let mut c = gost_ctx();
1088        c.security_control = security_control::AUTHENTICATION | GOST_SUITE_ID;
1089        let plaintext = hex(b"0800065F1F0400007C1F04000007");
1090        let apdu = gost_protect(&c, glo::GET_RESPONSE, &plaintext).unwrap();
1091        // Plaintext should be visible in the clear (auth only, no encryption)
1092        assert_eq!(&apdu[7..7 + plaintext.len()], plaintext.as_slice());
1093        let (_, recovered) = gost_unprotect(&mut c, &apdu).unwrap();
1094        assert_eq!(recovered, plaintext);
1095    }
1096
1097    #[test]
1098    fn gost_protect_unprotect_encryption_only() {
1099        let mut c = gost_ctx();
1100        c.security_control = security_control::ENCRYPTION | GOST_SUITE_ID;
1101        let plaintext = hex(b"C001C100080000010000FF0200");
1102        let apdu = gost_protect(&c, glo::SET_REQUEST, &plaintext).unwrap();
1103        // Ciphertext should not match plaintext
1104        assert_ne!(&apdu[7..7 + plaintext.len()], plaintext.as_slice());
1105        let (_, recovered) = gost_unprotect(&mut c, &apdu).unwrap();
1106        assert_eq!(recovered, plaintext);
1107    }
1108
1109    #[test]
1110    fn gost_detects_tampering() {
1111        let plaintext = hex(b"0800065F1F0400007C1F04000007");
1112        let mut apdu = gost_protect(&gost_ctx(), glo::GET_RESPONSE, &plaintext).unwrap();
1113        let n = apdu.len();
1114        apdu[n - 1] ^= 0x01; // corrupt the CMAC tag
1115        assert_eq!(gost_unprotect(&mut gost_ctx(), &apdu), Err(CipherError::AuthenticationFailed));
1116    }
1117
1118    #[test]
1119    fn gost_wrong_key_fails() {
1120        let mut c = gost_ctx();
1121        c.encryption_key = hex(b"0000000000000000000000000000000000000000000000000000000000000000");
1122        let plaintext = hex(b"C001C100");
1123        let apdu = gost_protect(&c, glo::GET_REQUEST, &plaintext).unwrap();
1124        // Different key should fail CMAC verification
1125        assert_eq!(gost_unprotect(&mut gost_ctx(), &apdu), Err(CipherError::AuthenticationFailed));
1126    }
1127
1128    #[test]
1129    fn is_gost_suite_detection() {
1130        assert!(is_gost_suite(GOST_SUITE_ID));
1131        assert!(is_gost_suite(0x30 | GOST_SUITE_ID));
1132        assert!(!is_gost_suite(0x30)); // AES suite 0
1133        assert!(!is_gost_suite(0x31)); // AES suite 1
1134    }
1135
1136    #[test]
1137    fn gost_counter_increment() {
1138        let mut counter = [0xFFu8; 16];
1139        increment_counter(&mut counter);
1140        assert_eq!(
1141            counter,
1142            [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1143        );
1144    }
1145
1146    #[test]
1147    fn gost_cmac_produces_16_octet_tag() {
1148        let key = hex(b"8899aabbccddeeff00112233445566778899aabbccddeeff0011223344556677");
1149        let data = hex(b"0102030405");
1150        let tag = gost_cmac_tag(&key, &data).unwrap();
1151        assert_eq!(tag.len(), 16);
1152    }
1153
1154    // ========================================================================
1155    // GOST GMAC tests (Kuznyechik GCM-like mode)
1156    // ========================================================================
1157
1158    fn gost_gmac_ctx() -> SecurityContext {
1159        SecurityContext {
1160            security_control: security_control::AUTHENTICATED_ENCRYPTION | GOST_SUITE_ID,
1161            encryption_key: hex(b"8899aabbccddeeff00112233445566778899aabbccddeeff0011223344556677"),
1162            authentication_key: hex(b"bddc7e4ac4e164e40785d8c147b4a883bddc7e4ac4e164e40785d8c147b4a883"),
1163            system_title: hex(b"4D4D4D0000BC614E"),
1164            invocation_counter: 0x01234567,
1165            last_peer_ic: 0,
1166            ic_valid: false,
1167        }
1168    }
1169
1170    #[test]
1171    fn gost_gmac_protect_unprotect_round_trip() {
1172        let plaintext = hex(b"C001C100080000010000FF0200");
1173        let apdu = gost_gmac_protect(&gost_gmac_ctx(), glo::GET_REQUEST, &plaintext).unwrap();
1174        let (tag, recovered) = gost_gmac_unprotect(&mut gost_gmac_ctx(), &apdu).unwrap();
1175        assert_eq!(tag, glo::GET_REQUEST);
1176        assert_eq!(recovered, plaintext);
1177    }
1178
1179    #[test]
1180    fn gost_gmac_unprotect_rejects_replayed_ic() {
1181        let mut tx = gost_gmac_ctx();
1182        let mut rx = gost_gmac_ctx();
1183        let plaintext = hex(b"C001C100080000010000FF0200");
1184
1185        tx.invocation_counter = 5;
1186        let apdu = gost_gmac_protect(&tx, glo::GET_REQUEST, &plaintext).unwrap();
1187        assert!(gost_gmac_unprotect(&mut rx, &apdu).is_ok());
1188        assert_eq!(gost_gmac_unprotect(&mut rx, &apdu), Err(CipherError::ReplayDetected));
1189    }
1190
1191    #[test]
1192    fn gost_gmac_protect_unprotect_with_auth_only() {
1193        let mut c = gost_gmac_ctx();
1194        c.security_control = security_control::AUTHENTICATION | GOST_SUITE_ID;
1195        let plaintext = hex(b"0800065F1F0400007C1F04000007");
1196        let apdu = gost_gmac_protect(&c, glo::GET_RESPONSE, &plaintext).unwrap();
1197        // Plaintext should be visible in the clear (auth only, no encryption)
1198        assert_eq!(&apdu[7..7 + plaintext.len()], plaintext.as_slice());
1199        let (_, recovered) = gost_gmac_unprotect(&mut c, &apdu).unwrap();
1200        assert_eq!(recovered, plaintext);
1201    }
1202
1203    #[test]
1204    fn gost_gmac_protect_unprotect_encryption_only() {
1205        let mut c = gost_gmac_ctx();
1206        c.security_control = security_control::ENCRYPTION | GOST_SUITE_ID;
1207        let plaintext = hex(b"C001C100080000010000FF0200");
1208        let apdu = gost_gmac_protect(&c, glo::SET_REQUEST, &plaintext).unwrap();
1209        // Ciphertext should not match plaintext
1210        assert_ne!(&apdu[7..7 + plaintext.len()], plaintext.as_slice());
1211        let (_, recovered) = gost_gmac_unprotect(&mut c, &apdu).unwrap();
1212        assert_eq!(recovered, plaintext);
1213    }
1214
1215    #[test]
1216    fn gost_gmac_detects_tampering() {
1217        let plaintext = hex(b"0800065F1F0400007C1F04000007");
1218        let mut apdu = gost_gmac_protect(&gost_gmac_ctx(), glo::GET_RESPONSE, &plaintext).unwrap();
1219        let n = apdu.len();
1220        apdu[n - 1] ^= 0x01; // corrupt the GMAC tag
1221        assert_eq!(gost_gmac_unprotect(&mut gost_gmac_ctx(), &apdu), Err(CipherError::AuthenticationFailed));
1222    }
1223
1224    #[test]
1225    fn gost_gmac_wrong_key_fails() {
1226        let mut c = gost_gmac_ctx();
1227        c.encryption_key = hex(b"0000000000000000000000000000000000000000000000000000000000000000");
1228        let plaintext = hex(b"C001C100");
1229        let apdu = gost_gmac_protect(&c, glo::GET_REQUEST, &plaintext).unwrap();
1230        // Different key should fail GMAC verification
1231        assert_eq!(gost_gmac_unprotect(&mut gost_gmac_ctx(), &apdu), Err(CipherError::AuthenticationFailed));
1232    }
1233
1234    #[test]
1235    fn gost_gmac_tag_produces_16_octet_tag() {
1236        let key = hex(b"8899aabbccddeeff00112233445566778899aabbccddeeff0011223344556677");
1237        let iv = hex(b"4D4D4D0000BC614E01234567");
1238        let aad = hex(b"01");
1239        let data = hex(b"0102030405060708");
1240        let tag = gost_gmac_tag(&key, &iv.try_into().unwrap(), &aad, &data).unwrap();
1241        assert_eq!(tag.len(), 16);
1242    }
1243
1244    #[test]
1245    fn gost_gmac_encrypt_decrypt_round_trip() {
1246        let key = hex(b"8899aabbccddeeff00112233445566778899aabbccddeeff0011223344556677");
1247        let iv_bytes = hex(b"4D4D4D0000BC614E01234567");
1248        let iv: [u8; 12] = iv_bytes.try_into().unwrap();
1249        let plaintext = hex(b"C001C100080000010000FF0200");
1250        let ciphertext = gost_gmac_encrypt(&key, &iv, &plaintext).unwrap();
1251        assert_ne!(ciphertext, plaintext);
1252        let recovered = gost_gmac_decrypt(&key, &iv, &ciphertext).unwrap();
1253        assert_eq!(recovered, plaintext);
1254    }
1255}