use cbc::cipher::block_padding::NoPadding;
use cipher::{Array, BlockCipherDecrypt, BlockCipherEncrypt, BlockModeEncrypt, KeyInit, KeyIvInit};
use des::Des;
use thiserror::Error;
pub const DES_BLOCK_SIZE: usize = 8;
pub const MAC_ALG3_KEY1_LEN: usize = 16;
pub const MAC_ALG3_KEY2_LEN: usize = 24;
pub const MAC_ALG3_DIGEST_LEN: usize = DES_BLOCK_SIZE;
#[derive(Debug, Error)]
pub enum Iso9797Error {
#[error("ISO9797 key length must be 16 or 24 bytes, got {0}")]
InvalidKeyLength(usize),
#[error("ISO9797 data length must be a multiple of {DES_BLOCK_SIZE} bytes, got {0}")]
InvalidDataLength(usize),
#[error("ISO9797 block size must be greater than zero")]
InvalidBlockSize,
#[error("ISO9797 unpad failed: malformed Padding Method 2 (no 0x80 marker)")]
UnpadFailed,
}
pub fn pad(data: &[u8], block_size: usize) -> Result<Vec<u8>, Iso9797Error> {
if block_size == 0 {
return Err(Iso9797Error::InvalidBlockSize);
}
let pad_len = block_size - (data.len() % block_size);
let mut padded = Vec::with_capacity(data.len() + pad_len);
padded.extend_from_slice(data);
padded.push(0x80);
padded.extend(std::iter::repeat_n(0x00, pad_len - 1));
Ok(padded)
}
pub fn unpad(data: &[u8], block_size: usize) -> Result<&[u8], Iso9797Error> {
if block_size != 0 && (data.is_empty() || !data.len().is_multiple_of(block_size)) {
return Err(Iso9797Error::UnpadFailed);
}
let mut i = data.len();
while i > 0 && data[i - 1] == 0x00 {
i -= 1;
}
if i == 0 || data[i - 1] != 0x80 {
return Err(Iso9797Error::UnpadFailed);
}
let pad_len = data.len() - (i - 1);
if block_size != 0 && pad_len > block_size {
return Err(Iso9797Error::UnpadFailed);
}
Ok(&data[..i - 1])
}
pub fn mac_alg3(key: &[u8], msg: &[u8], pad_msg: bool) -> Result<Vec<u8>, Iso9797Error> {
if key.len() != MAC_ALG3_KEY1_LEN && key.len() != MAC_ALG3_KEY2_LEN {
return Err(Iso9797Error::InvalidKeyLength(key.len()));
}
let ka = &key[0..8];
let kb = &key[8..16];
let kc = if key.len() == MAC_ALG3_KEY1_LEN {
ka
} else {
&key[16..24]
};
let data = if pad_msg {
pad(msg, DES_BLOCK_SIZE)?
} else {
msg.to_vec()
};
if data.len() % DES_BLOCK_SIZE != 0 {
return Err(Iso9797Error::InvalidDataLength(data.len()));
}
if data.is_empty() {
return Err(Iso9797Error::InvalidDataLength(0));
}
let mut mac = cbc_encrypt_des(ka, &[0u8; DES_BLOCK_SIZE], &data);
mac = mac[mac.len() - DES_BLOCK_SIZE..].to_vec();
mac = ecb_decrypt_des(kb, &mac);
mac = ecb_encrypt_des(kc, &mac);
Ok(mac)
}
fn cbc_encrypt_des(key: &[u8], iv: &[u8], data: &[u8]) -> Vec<u8> {
cbc::Encryptor::<Des>::new_from_slices(key, iv)
.expect("valid DES key/iv")
.encrypt_padded_vec::<NoPadding>(data)
}
fn ecb_encrypt_des(key: &[u8], block: &[u8]) -> Vec<u8> {
let cipher = Des::new_from_slice(key).expect("valid DES key");
let mut b = Array::try_from(block).expect("DES block");
cipher.encrypt_block(&mut b);
b.to_vec()
}
fn ecb_decrypt_des(key: &[u8], block: &[u8]) -> Vec<u8> {
let cipher = Des::new_from_slice(key).expect("valid DES key");
let mut b = Array::try_from(block).expect("DES block");
cipher.decrypt_block(&mut b);
b.to_vec()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pad_empty_data() {
let padded = pad(&[], DES_BLOCK_SIZE).unwrap();
assert_eq!(padded, vec![0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
}
#[test]
fn pad_three_bytes() {
let padded = pad(&[0x01, 0x02, 0x03], DES_BLOCK_SIZE).unwrap();
assert_eq!(padded, vec![0x01, 0x02, 0x03, 0x80, 0x00, 0x00, 0x00, 0x00]);
assert_eq!(padded.len(), DES_BLOCK_SIZE);
}
#[test]
fn pad_full_block_adds_new_block() {
let input = vec![0xAA; DES_BLOCK_SIZE];
let padded = pad(&input, DES_BLOCK_SIZE).unwrap();
assert_eq!(padded.len(), 2 * DES_BLOCK_SIZE);
assert_eq!(padded[DES_BLOCK_SIZE], 0x80);
assert!(padded[DES_BLOCK_SIZE + 1..].iter().all(|&b| b == 0x00));
}
#[test]
fn pad_seven_bytes_adds_one_padding_byte() {
let input: Vec<u8> = (1u8..=7).collect();
let padded = pad(&input, DES_BLOCK_SIZE).unwrap();
assert_eq!(padded.len(), DES_BLOCK_SIZE);
assert_eq!(padded[7], 0x80);
}
#[test]
fn pad_result_multiple_of_block_size() {
for len in 0..=24 {
let input = vec![0xBBu8; len];
let padded = pad(&input, DES_BLOCK_SIZE).unwrap();
assert_eq!(
padded.len() % DES_BLOCK_SIZE,
0,
"pad({len}) is not a multiple of block size"
);
}
}
#[test]
fn pad_zero_block_size_errors() {
assert!(matches!(
pad(&[0x01], 0),
Err(Iso9797Error::InvalidBlockSize)
));
}
#[test]
fn unpad_three_bytes() {
let data = vec![0x01, 0x02, 0x03, 0x80, 0x00, 0x00, 0x00, 0x00];
assert_eq!(unpad(&data, 8).unwrap(), &[0x01, 0x02, 0x03]);
}
#[test]
fn unpad_roundtrip() {
for len in 0..=24usize {
let original: Vec<u8> = (0..len as u8).collect();
let padded = pad(&original, DES_BLOCK_SIZE).unwrap();
let unpadded = unpad(&padded, 8).unwrap();
assert_eq!(
unpadded,
original.as_slice(),
"roundtrip failed for len={len}"
);
}
}
#[test]
fn unpad_empty_padding_block() {
let data = vec![0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
assert_eq!(unpad(&data, 8).unwrap(), &[] as &[u8]);
}
#[test]
fn unpad_no_marker_errors() {
let data = vec![0x01, 0x02, 0x03];
assert!(matches!(unpad(&data, 8), Err(Iso9797Error::UnpadFailed)));
}
#[test]
fn unpad_padding_run_longer_than_block_errors() {
let data = vec![
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00,
];
assert!(matches!(unpad(&data, 8), Err(Iso9797Error::UnpadFailed)));
assert_eq!(
unpad(&data, 0).unwrap(),
&[0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]
);
}
#[test]
fn unpad_non_block_aligned_input_errors() {
assert!(matches!(
unpad(&[0x01, 0x80], 8),
Err(Iso9797Error::UnpadFailed)
));
}
#[test]
fn unpad_all_zeros_errors() {
let data = vec![0x00; 8];
assert!(matches!(unpad(&data, 8), Err(Iso9797Error::UnpadFailed)));
}
#[test]
fn unpad_empty_errors() {
let data: Vec<u8> = Vec::new();
assert!(matches!(unpad(&data, 8), Err(Iso9797Error::UnpadFailed)));
}
#[test]
fn mac_alg3_bouncy_castle_vector() {
let key = hex::decode("7CA110454A1A6E570131D9619DC1376E").unwrap();
let msg = b"Hello World !!!!".to_vec(); let expected = hex::decode("F09B856213BAB83B").unwrap();
let mac = mac_alg3(&key, &msg, false).unwrap();
assert_eq!(mac, expected);
}
#[test]
fn mac_alg3_icao_d3_eifd_vector() {
let key = hex::decode("7962D9ECE03D1ACD4C76089DCE131543").unwrap();
let msg = hex::decode("72C29C2371CC9BDB65B779B8E8D37B29ECC154AA56A8799FAE2F498F76ED92F2")
.unwrap();
let expected = hex::decode("5F1448EEA8AD90A7").unwrap();
let mac = mac_alg3(&key, &msg, true).unwrap();
assert_eq!(mac, expected);
}
#[test]
fn mac_alg3_invalid_key_length_errors() {
let key = vec![0u8; 8]; assert!(matches!(
mac_alg3(&key, &[], true),
Err(Iso9797Error::InvalidKeyLength(8))
));
}
#[test]
fn mac_alg3_unpadded_non_block_aligned_errors() {
let key = vec![0u8; 16];
let msg = vec![0u8; 5]; assert!(matches!(
mac_alg3(&key, &msg, false),
Err(Iso9797Error::InvalidDataLength(5))
));
}
#[test]
fn mac_alg3_empty_unpadded_errors() {
let key = vec![0u8; 16];
assert!(matches!(
mac_alg3(&key, &[], false),
Err(Iso9797Error::InvalidDataLength(0))
));
}
#[test]
fn mac_alg3_produces_eight_bytes() {
let key = vec![0u8; 16];
let mac = mac_alg3(&key, &[0u8; 8], false).unwrap();
assert_eq!(mac.len(), MAC_ALG3_DIGEST_LEN);
}
#[test]
fn mac_alg3_with_padding_produces_eight_bytes() {
let key = vec![0u8; 16];
let mac = mac_alg3(&key, &[0u8; 3], true).unwrap();
assert_eq!(mac.len(), MAC_ALG3_DIGEST_LEN);
}
#[test]
fn mac_alg3_24_byte_key_produces_eight_bytes() {
let key = vec![0u8; 24];
let mac = mac_alg3(&key, &[0u8; 8], false).unwrap();
assert_eq!(mac.len(), MAC_ALG3_DIGEST_LEN);
}
fn ks_mac_d3() -> Vec<u8> {
hex::decode("F1CB1F1FB5ADF208806B89DC579DC1F8").unwrap()
}
#[test]
fn icao_d41_n_vector_matches() {
let n = hex::decode("887022120C06C2270CA4020C800000008709016375432908C044F6").unwrap();
let mac = mac_alg3(&ks_mac_d3(), &n, true).unwrap();
assert_eq!(hex::encode_upper(&mac), "BF8B92D635FF24F8");
}
#[test]
fn icao_d41_k_vector_matches() {
let k = hex::decode("887022120C06C22899029000").unwrap();
let mac = mac_alg3(&ks_mac_d3(), &k, true).unwrap();
assert_eq!(hex::encode_upper(&mac), "FA855A5D4C50A8ED");
}
#[test]
fn icao_d42_n_vector_matches() {
let n = hex::decode("887022120C06C2290CB0000080000000970104").unwrap();
let mac = mac_alg3(&ks_mac_d3(), &n, true).unwrap();
assert_eq!(hex::encode_upper(&mac), "ED6705417E96BA55");
}
#[test]
fn icao_d42_k_vector_matches() {
let k = hex::decode("887022120C06C22A8709019FF0EC34F992265199029000").unwrap();
let mac = mac_alg3(&ks_mac_d3(), &k, true).unwrap();
assert_eq!(hex::encode_upper(&mac), "AD55CC17140B2DED");
}
#[test]
fn icao_d43_n_vector_matches() {
let n = hex::decode("887022120C06C22B0CB0000480000000970112").unwrap();
let mac = mac_alg3(&ks_mac_d3(), &n, true).unwrap();
assert_eq!(hex::encode_upper(&mac), "2EA28A70F3C7B535");
}
#[test]
fn icao_d43_k_vector_matches() {
let k = hex::decode(
"887022120C06C22C871901FB9235F4E4037F2327DCC8964F1F9B8C30F42C8E2FFF224A99029000",
)
.unwrap();
let mac = mac_alg3(&ks_mac_d3(), &k, true).unwrap();
assert_eq!(hex::encode_upper(&mac), "C8B2787EAEA07D74");
}
}