/// AES
/// ```ignore
///let data = "this is data".as_bytes();
///let enc_data = doe::crypto::aes::aes_ecb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
///let dec_data = doe::crypto::aes::aes_ecb_decrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),&enc_data).unwrap();
///println!("data:{:?}",&data);
///println!("enc_data:{:?}",&enc_data);
///println!("dec_data:{:?}",&dec_data);
/// ```
#[allow(warnings)]
#[cfg(feature = "crypto")]
pub mod crypto {
    /// AES
    /// ```ignore
    ///let data = "this is data".as_bytes();
    ///let enc_data = doe::crypto::aes::aes_ecb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
    ///let dec_data = doe::crypto::aes::aes_ecb_decrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),&enc_data).unwrap();
    ///println!("data:{:?}",&data);
    ///println!("enc_data:{:?}",&enc_data);
    ///println!("dec_data:{:?}",&dec_data);
    /// ```
    ///
    pub mod aes {
        pub use aes_siv::*;
        pub use ::aes::*;
        pub use xts_mode::*;
        pub use block_modes::*;
        pub use aes_gcm::*;
        pub use ctr::*;

        pub mod aes_128 {

            /// AES SIV Encrypt (AES-128)
            /// key: 必须是 32 字节
            /// nonce: 16 字节 (必需参数)
            /// aad: 关联数据
            /// data: 明文
            pub fn aes_siv_encrypt(
                key: &[u8],
                nonce: &[u8],
                aad: &[u8],
                data: &[u8],
            ) -> Result<Vec<u8>, String> {
                use aes_siv::aead::generic_array::GenericArray;
                use aes_siv::aead::{Aead, KeyInit, Payload};
                use aes_siv::Aes128SivAead;

                if key.len() != 32 {
                    return Err("SIV AES-128 requires a 32-byte key".to_string());
                }

                if nonce.len() != 16 {
                    return Err(format!(
                        "SIV AES-128 requires a 16-byte nonce, got {}",
                        nonce.len()
                    ));
                }

                let cipher = Aes128SivAead::new_from_slice(key)
                    .map_err(|e| format!("Failed to create SIV cipher: {}", e))?;

                let nonce_array = GenericArray::from_slice(nonce);

                let payload = Payload {
                    msg: data,
                    aad: aad,
                };

                cipher
                    .encrypt(nonce_array, payload)
                    .map_err(|e| format!("SIV encryption failed: {}", e))
            }

            /// AES SIV Decrypt (AES-128)
            pub fn aes_siv_decrypt(
                key: &[u8],
                nonce: &[u8],
                aad: &[u8],
                ciphertext_with_siv: &[u8],
            ) -> Result<Vec<u8>, String> {
                use aes_siv::aead::generic_array::GenericArray;
                use aes_siv::aead::{Aead, KeyInit, Payload};
                use aes_siv::Aes128SivAead;

                if key.len() != 32 {
                    return Err("SIV AES-128 requires a 32-byte key".to_string());
                }

                if nonce.len() != 16 {
                    return Err(format!(
                        "SIV AES-128 requires a 16-byte nonce, got {}",
                        nonce.len()
                    ));
                }

                let cipher = Aes128SivAead::new_from_slice(key)
                    .map_err(|e| format!("Failed to create SIV cipher: {}", e))?;

                let nonce_array = GenericArray::from_slice(nonce);

                let payload = Payload {
                    msg: ciphertext_with_siv,
                    aad: aad,
                };

                cipher
                    .decrypt(nonce_array, payload)
                    .map_err(|_| "SIV authentication failed".to_string())
            }

            /// AES XTS Encrypt (AES-128)
            ///
            /// key: 必须是 32 字节 (两个 16 字节的 AES-128 密钥拼接)
            /// tweak: 16 字节 (通常代表磁盘扇区号)
            /// data: 必须大于等于 16 字节
            pub fn aes_xts_encrypt(
                key: &[u8],
                tweak: &[u8],
                data: &[u8],
            ) -> Result<Vec<u8>, String> {
                use aes::cipher::generic_array::typenum::U16;
                use aes::cipher::generic_array::GenericArray;
                use aes::Aes128;
                use aes::NewBlockCipher;
                use xts_mode::Xts128;

                if key.len() != 32 {
                    return Err(format!(
                        "XTS AES-128 requires a 32-byte key, got {}",
                        key.len()
                    ));
                }
                if tweak.len() != 16 {
                    return Err(format!("Tweak must be 16 bytes, got {}", tweak.len()));
                }
                if data.len() < 16 {
                    return Err(format!(
                        "Data must be at least 16 bytes for XTS, got {}",
                        data.len()
                    ));
                }

                // 分别初始化两个密钥，每个16字节
                let cipher_1 = Aes128::new(GenericArray::<u8, U16>::from_slice(&key[..16]));
                let cipher_2 = Aes128::new(GenericArray::<u8, U16>::from_slice(&key[16..]));

                // 组合成 XTS 模式
                let xts = Xts128::<Aes128>::new(cipher_1, cipher_2);

                let mut buffer = data.to_vec();
                let mut tweak_arr: [u8; 16] = [0u8; 16];
                tweak_arr.copy_from_slice(tweak);

                xts.encrypt_sector(&mut buffer, tweak_arr);

                Ok(buffer)
            }

            /// AES XTS Decrypt (AES-128)
            ///
            /// key: 必须是 32 字节 (两个 16 字节的 AES-128 密钥拼接)
            /// tweak: 16 字节 (通常代表磁盘扇区号)
            /// data: 必须大于等于 16 字节
            pub fn aes_xts_decrypt(
                key: &[u8],
                tweak: &[u8],
                data: &[u8],
            ) -> Result<Vec<u8>, String> {
                use aes::cipher::generic_array::typenum::U16;
                use aes::cipher::generic_array::GenericArray;
                use aes::Aes128;
                use aes::NewBlockCipher;
                use xts_mode::Xts128;

                if key.len() != 32 {
                    return Err(format!(
                        "XTS AES-128 requires a 32-byte key, got {}",
                        key.len()
                    ));
                }
                if tweak.len() != 16 {
                    return Err(format!("Tweak must be 16 bytes, got {}", tweak.len()));
                }
                if data.len() < 16 {
                    return Err(format!(
                        "Data must be at least 16 bytes for XTS, got {}",
                        data.len()
                    ));
                }

                // 分别初始化两个密钥，每个16字节
                let cipher_1 = Aes128::new(GenericArray::<u8, U16>::from_slice(&key[..16]));
                let cipher_2 = Aes128::new(GenericArray::<u8, U16>::from_slice(&key[16..]));

                // 组合成 XTS 模式
                let xts = Xts128::<Aes128>::new(cipher_1, cipher_2);

                let mut buffer = data.to_vec();
                let mut tweak_arr: [u8; 16] = [0u8; 16];
                tweak_arr.copy_from_slice(tweak);

                xts.decrypt_sector(&mut buffer, tweak_arr);

                Ok(buffer)
            }

            /// AES PCBC Encrypt (AES-128)
            /// key: 16 bytes, iv: 16 bytes
            pub fn aes_pcbc_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::cipher::generic_array::typenum::U16;
                use aes::cipher::generic_array::typenum::U32;
                use aes::cipher::{generic_array::GenericArray, BlockEncrypt};
                use aes::Aes128;

                if key.len() != 16 {
                    return Err(format!(
                        "Invalid key length: expected 16 bytes, got {}",
                        key.len()
                    ));
                }
                if iv.len() != 16 {
                    return Err(format!(
                        "Invalid iv length: expected 16 bytes, got {}",
                        iv.len()
                    ));
                }
                if data.is_empty() {
                    return Err("Data cannot be empty".to_string());
                }
                use aes::NewBlockCipher;
                let cipher = Aes128::new(GenericArray::<u8, U16>::from_slice(key));
                let mut padded_data = data.to_vec();
                // 手动添加 PKCS7 填充
                let pad_len = 16 - (padded_data.len() % 16);
                padded_data.extend(vec![pad_len as u8; pad_len]);

                let mut prev_ciphertext: GenericArray<u8, U16> = GenericArray::clone_from_slice(iv);
                let mut prev_plaintext: GenericArray<u8, U16> = GenericArray::from([0u8; 16]);
                let mut ciphertext = Vec::with_capacity(padded_data.len());

                for chunk in padded_data.chunks(16) {
                    let mut block: GenericArray<u8, U16> = GenericArray::clone_from_slice(chunk);
                    // PCBC 核心逻辑: 异或前一个密文块 AND 前一个明文块
                    for i in 0..16 {
                        block[i] ^= prev_ciphertext[i] ^ prev_plaintext[i];
                    }
                    cipher.encrypt_block(&mut block);

                    prev_plaintext.copy_from_slice(chunk);
                    prev_ciphertext.copy_from_slice(&block);

                    ciphertext.extend_from_slice(&block);
                }

                Ok(ciphertext)
            }

            /// AES PCBC Decrypt (AES-128)
            /// key: 16 bytes, iv: 16 bytes
            pub fn aes_pcbc_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::cipher::generic_array::typenum::U16;
                use aes::cipher::generic_array::typenum::U32;
                use aes::cipher::{generic_array::GenericArray, BlockDecrypt};
                use aes::Aes128;
                use aes::NewBlockCipher;

                if key.len() != 16 {
                    return Err(format!(
                        "Invalid key length: expected 16 bytes, got {}",
                        key.len()
                    ));
                }
                if iv.len() != 16 {
                    return Err(format!(
                        "Invalid iv length: expected 16 bytes, got {}",
                        iv.len()
                    ));
                }
                if data.len() % 16 != 0 {
                    return Err(format!(
                        "Invalid data length: must be multiple of 16 bytes, got {}",
                        data.len()
                    ));
                }
                if data.is_empty() {
                    return Err("Data cannot be empty".to_string());
                }

                let cipher = Aes128::new(GenericArray::<u8, U16>::from_slice(key));
                let mut prev_ciphertext: GenericArray<u8, U16> = GenericArray::clone_from_slice(iv);
                let mut prev_plaintext: GenericArray<u8, U16> = GenericArray::from([0u8; 16]);
                let mut plaintext = Vec::with_capacity(data.len());

                for chunk in data.chunks(16) {
                    let mut block: GenericArray<u8, U16> = GenericArray::clone_from_slice(chunk);
                    cipher.decrypt_block(&mut block);

                    for i in 0..16 {
                        block[i] ^= prev_ciphertext[i] ^ prev_plaintext[i];
                    }

                    prev_plaintext.copy_from_slice(&block);
                    prev_ciphertext.copy_from_slice(chunk);

                    plaintext.extend_from_slice(&block);
                }

                // 手动移除 PKCS7 填充
                if let Some(&pad_byte) = plaintext.last() {
                    if pad_byte >= 1 && pad_byte <= 16 {
                        let pad_len = pad_byte as usize;
                        if plaintext.len() >= pad_len {
                            let padding = &plaintext[plaintext.len() - pad_len..];
                            if padding.iter().all(|&b| b == pad_byte) {
                                plaintext.truncate(plaintext.len() - pad_len);
                                return Ok(plaintext);
                            }
                        }
                    }
                }
                Err("Invalid PKCS7 padding".to_string())
            }

            /// AES ECB Encrypt
            ///
            /// key must be 16 bytes
            ///
            /// iv must be 0 bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_128::aes_ecb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
            /// ```
            pub fn aes_ecb_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::Aes128;
                use block_modes::block_padding::Pkcs7;
                use block_modes::{BlockMode, Ecb};

                type Aes128Ecb = Ecb<Aes128, Pkcs7>;

                let cipher = Aes128Ecb::new_from_slices(key, iv)
                    .map_err(|e| format!("Failed to create ECB cipher: {}", e))?;

                Ok(cipher.encrypt_vec(data))
            }

            /// AES ECB Decrypt
            ///
            /// key must be 16 bytes
            ///
            /// iv must be 0 bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_128::aes_ecb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
            ///let dec_data = doe::crypto::aes::aes_128::aes_ecb_decrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),&enc_data).unwrap();
            /// ```
            pub fn aes_ecb_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::Aes128;
                use block_modes::block_padding::Pkcs7;
                use block_modes::{BlockMode, Ecb};

                type Aes128Ecb = Ecb<Aes128, Pkcs7>;

                let cipher = Aes128Ecb::new_from_slices(key, iv)
                    .map_err(|e| format!("Failed to create ECB cipher: {}", e))?;

                cipher
                    .decrypt_vec(data)
                    .map_err(|e| format!("AES ECB decryption failed: {}", e))
            }

            /// AES CBC Encrypt
            ///
            /// key must be 16 bytes
            ///
            /// iv must be 16 bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_128::aes_cbc_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
            /// ```
            pub fn aes_cbc_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::Aes128;
                use block_modes::block_padding::Pkcs7;
                use block_modes::{BlockMode, Cbc};

                // 验证密钥长度（AES-128需要16字节）
                if key.len() != 16 {
                    return Err(format!(
                        "Invalid key length: expected 16 bytes, got {}",
                        key.len()
                    ));
                }

                // 验证IV长度（AES块大小为16字节）
                if iv.len() != 16 {
                    return Err(format!(
                        "Invalid IV length: expected 16 bytes, got {}",
                        iv.len()
                    ));
                }

                type Aes128Cbc = Cbc<Aes128, Pkcs7>;

                let cipher = Aes128Cbc::new_from_slices(key, iv)
                    .map_err(|e| format!("Failed to create CBC cipher: {}", e))?;

                Ok(cipher.encrypt_vec(data))
            }

            /// AES CBC Decrypt
            ///
            /// key must be 16 bytes
            ///
            /// iv must be 16 bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_128::aes_cbc_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
            ///let dec_data = doe::crypto::aes::aes_128::aes_cbc_decrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),&enc_data).unwrap();
            /// ```
            pub fn aes_cbc_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::Aes128;
                use block_modes::block_padding::Pkcs7;
                use block_modes::{BlockMode, Cbc};

                // 验证密钥长度（AES-128需要16字节）
                if key.len() != 16 {
                    return Err(format!(
                        "Invalid key length: expected 16 bytes, got {}",
                        key.len()
                    ));
                }

                // 验证IV长度（AES块大小为16字节）
                if iv.len() != 16 {
                    return Err(format!(
                        "Invalid IV length: expected 16 bytes, got {}",
                        iv.len()
                    ));
                }

                type Aes128Cbc = Cbc<Aes128, Pkcs7>;

                let cipher = Aes128Cbc::new_from_slices(key, iv)
                    .map_err(|e| format!("Failed to create CBC cipher: {}", e))?;

                cipher
                    .decrypt_vec(data)
                    .map_err(|e| format!("AES CBC decryption failed: {}", e))
            }

            /// AES CFB Encrypt
            ///
            /// key must be 16 bytes
            ///
            /// iv must be 16 bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_128::aes_cfb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
            /// ```
            pub fn aes_cfb_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::Aes128;
                use block_modes::block_padding::NoPadding;
                use block_modes::{BlockMode, Cfb};

                type Aes128Cfb = Cfb<Aes128, NoPadding>;

                // 参数验证
                if key.len() != 16 {
                    return Err(format!(
                        "Invalid key length: expected 16 bytes, got {}",
                        key.len()
                    ));
                }

                if iv.len() != 16 {
                    return Err(format!(
                        "Invalid IV length: expected 16 bytes, got {}",
                        iv.len()
                    ));
                }

                let cipher = Aes128Cfb::new_from_slices(key, iv)
                    .map_err(|e| format!("Failed to create CFB cipher: {}", e))?;

                Ok(cipher.encrypt_vec(data))
            }

            /// AES CFB Decrypt
            ///
            /// key must be 16 bytes
            ///
            /// iv must be 16 bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_128::aes_cfb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
            ///let dec_data = doe::crypto::aes::aes_128::aes_cfb_decrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),&enc_data).unwrap();
            /// ```
            pub fn aes_cfb_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::Aes128;
                use block_modes::block_padding::NoPadding;
                use block_modes::{BlockMode, Cfb};

                type Aes128Cfb = Cfb<Aes128, NoPadding>;

                // 参数验证
                if key.len() != 16 {
                    return Err(format!(
                        "Invalid key length: expected 16 bytes, got {}",
                        key.len()
                    ));
                }

                if iv.len() != 16 {
                    return Err(format!(
                        "Invalid IV length: expected 16 bytes, got {}",
                        iv.len()
                    ));
                }

                let cipher = Aes128Cfb::new_from_slices(key, iv)
                    .map_err(|e| format!("Failed to create CFB cipher: {}", e))?;

                cipher
                    .decrypt_vec(data)
                    .map_err(|e| format!("AES CFB decryption failed: {}", e))
            }

            /// AES OFB Encrypt
            ///
            /// key must be 16 bytes
            ///
            /// iv must be 16 bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_128::aes_ofb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
            /// ```
            pub fn aes_ofb_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::Aes128;
                use block_modes::block_padding::NoPadding;
                use block_modes::{BlockMode, Ofb};

                type Aes128Ofb = Ofb<Aes128, NoPadding>;

                // 参数验证
                if key.len() != 16 {
                    return Err(format!(
                        "Invalid key length: expected 16 bytes, got {}",
                        key.len()
                    ));
                }

                if iv.len() != 16 {
                    return Err(format!(
                        "Invalid IV length: expected 16 bytes, got {}",
                        iv.len()
                    ));
                }

                let cipher = Aes128Ofb::new_from_slices(key, iv)
                    .map_err(|e| format!("Failed to create OFB cipher: {}", e))?;

                Ok(cipher.encrypt_vec(data))
            }

            /// AES OFB Decrypt
            ///
            /// key must be 16 bytes
            ///
            /// iv must be 16 bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_128::aes_ofb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
            ///let dec_data = doe::crypto::aes::aes_128::aes_ofb_decrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),&enc_data).unwrap();
            /// ```
            pub fn aes_ofb_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::Aes128;
                use block_modes::block_padding::NoPadding;
                use block_modes::{BlockMode, Ofb};

                type Aes128Ofb = Ofb<Aes128, NoPadding>;

                // 参数验证
                if key.len() != 16 {
                    return Err(format!(
                        "Invalid key length: expected 16 bytes, got {}",
                        key.len()
                    ));
                }

                if iv.len() != 16 {
                    return Err(format!(
                        "Invalid IV length: expected 16 bytes, got {}",
                        iv.len()
                    ));
                }

                let cipher = Aes128Ofb::new_from_slices(key, iv)
                    .map_err(|e| format!("Failed to create OFB cipher: {}", e))?;

                cipher
                    .decrypt_vec(data)
                    .map_err(|e| format!("AES OFB decryption failed: {}", e))
            }

            /// AES IGE Encrypt
            ///
            /// key must be 16 bytes
            ///
            /// iv must be 32 bytes
            ///
            /// data must be 16*n bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_128::aes_ige_encrypt("12345678123456781234567812345678".as_bytes(),"12345678123456781234567812345678".as_bytes(),data).unwrap();
            /// ```
            pub fn aes_ige_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::cipher::generic_array::typenum::U16;
                use aes::cipher::{generic_array::GenericArray, BlockEncrypt, NewBlockCipher};
                use aes::Aes128;

                // 修正：IGE需要32字节IV
                if key.len() != 16 {
                    return Err("Key must be 16 bytes".to_string());
                }
                if iv.len() != 32 {
                    // ✅ 修正为32字节
                    return Err("IV must be 32 bytes".to_string());
                }
                if data.len() % 16 != 0 {
                    return Err("Data must be a multiple of 16 bytes".to_string());
                }

                let cipher = Aes128::new(GenericArray::from_slice(key));
                let mut prev_block: GenericArray<u8, U16> =
                    GenericArray::from_slice(&iv[..16]).to_owned();
                let mut prev_prev_block: GenericArray<u8, U16> =
                    GenericArray::from_slice(&iv[16..]).to_owned();
                let mut ciphertext = Vec::with_capacity(data.len());

                for chunk in data.chunks(16) {
                    let mut block = GenericArray::clone_from_slice(chunk);

                    // IGE加密：先XOR，再加密，再XOR
                    for i in 0..16 {
                        block[i] ^= prev_block[i] ^ prev_prev_block[i];
                    }
                    cipher.encrypt_block(&mut block);
                    for i in 0..16 {
                        block[i] ^= prev_block[i];
                    }

                    ciphertext.extend_from_slice(&block);

                    // 更新状态
                    prev_prev_block.copy_from_slice(&prev_block);
                    prev_block.copy_from_slice(&block);
                }

                Ok(ciphertext)
            }

            /// AES IGE Decrypt
            ///
            /// key must be 16 bytes
            ///
            /// iv must be 32 bytes
            ///
            /// data must be 16*n bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_128::aes_ige_encrypt("12345678123456781234567812345678".as_bytes(),"12345678123456781234567812345678".as_bytes(),data).unwrap();
            ///let dec_data = doe::crypto::aes::aes_128::aes_ige_decrypt("12345678123456781234567812345678".as_bytes(),"12345678123456781234567812345678".as_bytes(),&enc_data).unwrap();
            /// ```
            pub fn aes_ige_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::cipher::generic_array::typenum::U16;
                use aes::cipher::{generic_array::GenericArray, BlockDecrypt, NewBlockCipher};
                use aes::Aes128;

                // 修正：IGE需要32字节IV
                if key.len() != 16 {
                    return Err("Key must be 16 bytes".to_string());
                }
                if iv.len() != 32 {
                    // ✅ 修正为32字节
                    return Err("IV must be 32 bytes".to_string());
                }
                if data.len() % 16 != 0 {
                    return Err("Data must be a multiple of 16 bytes".to_string());
                }

                let cipher = Aes128::new(GenericArray::from_slice(key));
                let mut prev_block: GenericArray<u8, U16> =
                    GenericArray::from_slice(&iv[..16]).to_owned();
                let mut prev_prev_block: GenericArray<u8, U16> =
                    GenericArray::from_slice(&iv[16..]).to_owned();
                let mut plaintext = Vec::with_capacity(data.len());

                for chunk in data.chunks(16) {
                    let mut block = GenericArray::clone_from_slice(chunk);
                    let original_ciphertext = block.clone(); // ✅ 保存原始密文块

                    // IGE解密：先XOR，再解密，再XOR
                    for i in 0..16 {
                        block[i] ^= prev_block[i];
                    }
                    cipher.decrypt_block(&mut block);
                    for i in 0..16 {
                        block[i] ^= prev_block[i] ^ prev_prev_block[i];
                    }

                    plaintext.extend_from_slice(&block);

                    // ✅ 修正：使用原始密文块更新状态
                    prev_prev_block.copy_from_slice(&prev_block);
                    prev_block.copy_from_slice(&original_ciphertext);
                }

                Ok(plaintext)
            }

            /// AES GCM Encrypt
            ///
            /// key must be 16 bytes for AES-128
            ///
            /// nonce must be 12 bytes (recommended), but other lengths are supported
            ///
            /// data can be any length (no padding required)
            ///
            /// The output ciphertext includes a 16-byte authentication tag appended at the end
            ///
            ///
            /// ```ignore
            /// let data = “this is data”.as_bytes();
            /// let key = b"16_bytes_secret!!"; // 16 bytes for AES-128
            /// let mut nonce = [0u8; 12]; // 12 bytes recommended
            /// // fill nonce with random data
            /// let enc_data = doe::crypto::aes::aes_128::aes_gcm_encrypt(key, &nonce, data, &[]).unwrap();
            /// let dec_data = doe::crypto::aes::aes_128::aes_gcm_decrypt(key, &nonce, &enc_data, &[]).unwrap();
            /// ```
            pub fn aes_gcm_encrypt(
                key: &[u8],
                nonce: &[u8],
                msg: &[u8],
                aad: &[u8],
            ) -> Result<Vec<u8>, String> {
                use aes_gcm::{
                    aead::{Aead, KeyInit, Payload},
                    Aes128Gcm, Nonce,
                };

                // 只给出警告，不阻止使用
                if nonce.len() != 12 {
                    eprintln!(
                        "Warning: Nonce length is {} bytes (recommended: 12 bytes)",
                        nonce.len()
                    );
                }

                let cipher =
                    Aes128Gcm::new_from_slice(key).map_err(|e| format!("Invalid key: {}", e))?;

                let nonce = Nonce::from_slice(nonce);

                cipher
                    .encrypt(nonce, Payload { msg, aad })
                    .map_err(|e| format!("Encryption error: {}", e))
            }

            /// AES GCM Decrypt
            ///
            /// key must be 16 bytes for AES-128
            ///
            /// nonce must be 12 bytes (recommended), but other lengths are supported
            ///
            /// data can be any length (no padding required)
            ///
            /// The output ciphertext includes a 16-byte authentication tag appended at the end
            ///
            ///
            /// ```ignore
            /// let data = “this is data”.as_bytes();
            /// let key = b"16_bytes_secret!!"; // 16 bytes for AES-128
            /// let mut nonce = [0u8; 12]; // 12 bytes recommended
            /// // fill nonce with random data
            /// let enc_data = doe::crypto::aes::aes_128::aes_gcm_encrypt(key, &nonce, data, &[]).unwrap();
            /// let dec_data = doe::crypto::aes::aes_128::aes_gcm_decrypt(key, &nonce, &enc_data, &[]).unwrap();
            /// ```
            pub fn aes_gcm_decrypt(
                key: &[u8],
                nonce: &[u8],
                msg: &[u8],
                aad: &[u8],
            ) -> Result<Vec<u8>, String> {
                use aes_gcm::{
                    aead::{Aead, KeyInit, Payload},
                    Aes128Gcm, Nonce,
                };

                // 只给出警告，不阻止使用
                if nonce.len() != 12 {
                    eprintln!(
                        "Warning: Nonce length is {} bytes (recommended: 12 bytes)",
                        nonce.len()
                    );
                }

                let cipher =
                    Aes128Gcm::new_from_slice(key).map_err(|e| format!("Invalid key: {}", e))?;

                let nonce = Nonce::from_slice(nonce);

                cipher
                    .decrypt(nonce, Payload { msg, aad })
                    .map_err(|e| format!("Encryption error: {}", e))
            }

            /// AES 256 CTR Encrypt
            ///
            /// key must be 16 bytes
            ///
            /// iv must be 16 bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_128::aes_ctr_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
            /// ```
            pub fn aes_ctr_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::cipher::NewCipher;
                use aes::cipher::StreamCipher;
                use aes::cipher::{generic_array::GenericArray, BlockDecrypt, BlockEncrypt};
                use aes::Aes128;
                use ctr::Ctr128BE;

                type Aes128Ctr = Ctr128BE<Aes128>;

                if key.len() != 16 {
                    return Err("Key must be 16 bytes".to_string());
                }
                if iv.len() != 16 {
                    return Err("IV must be 16 bytes".to_string());
                }

                let mut cipher =
                    Aes128Ctr::new(GenericArray::from_slice(key), GenericArray::from_slice(iv));
                let mut ciphertext = data.to_vec();
                cipher.apply_keystream(&mut ciphertext);

                Ok(ciphertext)
            }

            /// AES CTR Decrypt
            ///
            /// key must be 16 bytes
            ///
            /// iv must be 16 bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_128::aes_ctr_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
            ///let dec_data = doe::crypto::aes::aes_128::aes_ctr_decrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),&enc_data).unwrap();
            /// ```
            pub fn aes_ctr_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::cipher::NewCipher;
                use aes::cipher::StreamCipher;
                use aes::cipher::{generic_array::GenericArray, BlockDecrypt, BlockEncrypt};
                use aes::Aes128;
                use ctr::Ctr128BE;

                type Aes128Ctr = Ctr128BE<Aes128>;

                if key.len() != 16 {
                    return Err("Key must be 16 bytes".to_string());
                }
                if iv.len() != 16 {
                    return Err("IV must be 16 bytes".to_string());
                }

                let mut cipher =
                    Aes128Ctr::new(GenericArray::from_slice(key), GenericArray::from_slice(iv));
                let mut ciphertext = data.to_vec();
                cipher.apply_keystream(&mut ciphertext);

                Ok(ciphertext)
            }
        }

        pub mod aes_192 {

            /// AES XTS Encrypt (AES-192)
            ///
            /// key: 必须是 48 字节 (两个 24 字节的 AES-192 密钥拼接)
            /// tweak: 16 字节 (通常代表磁盘扇区号)
            /// data: 必须大于等于 16 字节
            pub fn aes_xts_encrypt(
                key: &[u8],
                tweak: &[u8],
                data: &[u8],
            ) -> Result<Vec<u8>, String> {
                use aes::cipher::generic_array::typenum::{U16, U24};
                use aes::cipher::generic_array::GenericArray;
                use aes::Aes192;
                use aes::NewBlockCipher;
                use xts_mode::Xts128;

                if key.len() != 48 {
                    return Err(format!(
                        "XTS AES-192 requires a 48-byte key, got {}",
                        key.len()
                    ));
                }
                if tweak.len() != 16 {
                    return Err(format!("Tweak must be 16 bytes, got {}", tweak.len()));
                }
                if data.len() < 16 {
                    return Err(format!(
                        "Data must be at least 16 bytes for XTS, got {}",
                        data.len()
                    ));
                }

                // 分别初始化两个密钥，每个24字节
                let cipher_1 = Aes192::new(GenericArray::<u8, U24>::from_slice(&key[..24]));
                let cipher_2 = Aes192::new(GenericArray::<u8, U24>::from_slice(&key[24..]));

                // 组合成 XTS 模式
                let xts = Xts128::<Aes192>::new(cipher_1, cipher_2);

                let mut buffer = data.to_vec();
                let mut tweak_arr: [u8; 16] = [0u8; 16];
                tweak_arr.copy_from_slice(tweak);

                xts.encrypt_sector(&mut buffer, tweak_arr);

                Ok(buffer)
            }

            /// AES XTS Decrypt (AES-192)
            ///
            /// key: 必须是 48 字节 (两个 24 字节的 AES-192 密钥拼接)
            /// tweak: 16 字节 (通常代表磁盘扇区号)
            /// data: 必须大于等于 16 字节
            pub fn aes_xts_decrypt(
                key: &[u8],
                tweak: &[u8],
                data: &[u8],
            ) -> Result<Vec<u8>, String> {
                use aes::cipher::generic_array::typenum::{U16, U24};
                use aes::cipher::generic_array::GenericArray;
                use aes::Aes192;
                use aes::NewBlockCipher;
                use xts_mode::Xts128;

                if key.len() != 48 {
                    return Err(format!(
                        "XTS AES-192 requires a 48-byte key, got {}",
                        key.len()
                    ));
                }
                if tweak.len() != 16 {
                    return Err(format!("Tweak must be 16 bytes, got {}", tweak.len()));
                }
                if data.len() < 16 {
                    return Err(format!(
                        "Data must be at least 16 bytes for XTS, got {}",
                        data.len()
                    ));
                }

                // 分别初始化两个密钥，每个24字节
                let cipher_1 = Aes192::new(GenericArray::<u8, U24>::from_slice(&key[..24]));
                let cipher_2 = Aes192::new(GenericArray::<u8, U24>::from_slice(&key[24..]));

                // 组合成 XTS 模式
                let xts = Xts128::<Aes192>::new(cipher_1, cipher_2);

                let mut buffer = data.to_vec();
                let mut tweak_arr: [u8; 16] = [0u8; 16];
                tweak_arr.copy_from_slice(tweak);

                xts.decrypt_sector(&mut buffer, tweak_arr);

                Ok(buffer)
            }

            /// AES PCBC Encrypt (AES-192)
            /// key: 24 bytes, iv: 16 bytes
            pub fn aes_pcbc_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::cipher::generic_array::typenum::U16;
                use aes::cipher::generic_array::typenum::U24;
                use aes::cipher::{generic_array::GenericArray, BlockEncrypt};
                use aes::Aes192;

                if key.len() != 24 {
                    return Err(format!(
                        "Invalid key length: expected 24 bytes, got {}",
                        key.len()
                    ));
                }
                if iv.len() != 16 {
                    return Err(format!(
                        "Invalid iv length: expected 16 bytes, got {}",
                        iv.len()
                    ));
                }
                if data.is_empty() {
                    return Err("Data cannot be empty".to_string());
                }
                use aes::NewBlockCipher;
                let cipher = Aes192::new(GenericArray::<u8, U24>::from_slice(key));
                let mut padded_data = data.to_vec();
                // 手动添加 PKCS7 填充
                let pad_len = 16 - (padded_data.len() % 16);
                padded_data.extend(vec![pad_len as u8; pad_len]);

                let mut prev_ciphertext: GenericArray<u8, U16> = GenericArray::clone_from_slice(iv);
                let mut prev_plaintext: GenericArray<u8, U16> = GenericArray::from([0u8; 16]);
                let mut ciphertext = Vec::with_capacity(padded_data.len());

                for chunk in padded_data.chunks(16) {
                    let mut block: GenericArray<u8, U16> = GenericArray::clone_from_slice(chunk);
                    // PCBC 核心逻辑: 异或前一个密文块 AND 前一个明文块
                    for i in 0..16 {
                        block[i] ^= prev_ciphertext[i] ^ prev_plaintext[i];
                    }
                    cipher.encrypt_block(&mut block);

                    prev_plaintext.copy_from_slice(chunk);
                    prev_ciphertext.copy_from_slice(&block);

                    ciphertext.extend_from_slice(&block);
                }

                Ok(ciphertext)
            }

            /// AES PCBC Decrypt (AES-192)
            /// key: 24 bytes, iv: 16 bytes
            pub fn aes_pcbc_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::cipher::generic_array::typenum::U16;
                use aes::cipher::generic_array::typenum::U24;
                use aes::cipher::{generic_array::GenericArray, BlockDecrypt};
                use aes::Aes192;
                use aes::NewBlockCipher;

                if key.len() != 24 {
                    return Err(format!(
                        "Invalid key length: expected 24 bytes, got {}",
                        key.len()
                    ));
                }
                if iv.len() != 16 {
                    return Err(format!(
                        "Invalid iv length: expected 16 bytes, got {}",
                        iv.len()
                    ));
                }
                if data.len() % 16 != 0 {
                    return Err(format!(
                        "Invalid data length: must be multiple of 16 bytes, got {}",
                        data.len()
                    ));
                }
                if data.is_empty() {
                    return Err("Data cannot be empty".to_string());
                }

                let cipher = Aes192::new(GenericArray::<u8, U24>::from_slice(key));
                let mut prev_ciphertext: GenericArray<u8, U16> = GenericArray::clone_from_slice(iv);
                let mut prev_plaintext: GenericArray<u8, U16> = GenericArray::from([0u8; 16]);
                let mut plaintext = Vec::with_capacity(data.len());

                for chunk in data.chunks(16) {
                    let mut block: GenericArray<u8, U16> = GenericArray::clone_from_slice(chunk);
                    cipher.decrypt_block(&mut block);

                    for i in 0..16 {
                        block[i] ^= prev_ciphertext[i] ^ prev_plaintext[i];
                    }

                    prev_plaintext.copy_from_slice(&block);
                    prev_ciphertext.copy_from_slice(chunk);

                    plaintext.extend_from_slice(&block);
                }

                // 手动移除 PKCS7 填充
                if let Some(&pad_byte) = plaintext.last() {
                    if pad_byte >= 1 && pad_byte <= 16 {
                        let pad_len = pad_byte as usize;
                        if plaintext.len() >= pad_len {
                            let padding = &plaintext[plaintext.len() - pad_len..];
                            if padding.iter().all(|&b| b == pad_byte) {
                                plaintext.truncate(plaintext.len() - pad_len);
                                return Ok(plaintext);
                            }
                        }
                    }
                }
                Err("Invalid PKCS7 padding".to_string())
            }

            /// AES ECB Encrypt (AES-192)
            ///
            /// key must be 24 bytes
            ///
            /// iv must be 0 bytes (ECB does not use an IV)
            /// ```ignore
            /// let key = b"123456781234567812345678"; // 24 bytes
            /// let data = b"this is data";
            /// let enc_data = doe::crypto::aes::aes_192::aes_ecb_encrypt(key, b"", data).unwrap();
            /// ```
            pub fn aes_ecb_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::Aes192;
                use block_modes::block_padding::Pkcs7;
                use block_modes::{BlockMode, Ecb};

                // Validate key length for AES-192 (24 bytes)
                if key.len() != 24 {
                    return Err(format!(
                        "Invalid key length: expected 24 bytes, got {}",
                        key.len()
                    ));
                }

                // ECB does not use an IV; require empty slice to avoid confusion
                if !iv.is_empty() {
                    return Err("ECB mode does not use an IV; expected empty slice".to_string());
                }

                type Aes192Ecb = Ecb<Aes192, Pkcs7>;

                // Pass an empty IV slice explicitly
                let cipher = Aes192Ecb::new_from_slices(key, Default::default())
                    .map_err(|e| format!("Failed to create ECB cipher: {}", e))?;

                Ok(cipher.encrypt_vec(data))
            }

            /// AES ECB Decrypt (AES-192)
            ///
            /// key must be 24 bytes
            ///
            /// iv must be 0 bytes (ECB does not use an IV)
            /// ```ignore
            /// let key = b"123456781234567812345678"; // 24 bytes
            /// let data = b"this is data";
            /// let enc_data = doe::crypto::aes::aes_192::aes_ecb_encrypt(key, b"", data).unwrap();
            /// let dec_data = doe::crypto::aes::aes_192::aes_ecb_decrypt(key, b"", &enc_data).unwrap();
            /// ```
            pub fn aes_ecb_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::Aes192;
                use block_modes::block_padding::Pkcs7;
                use block_modes::{BlockMode, Ecb};

                if key.len() != 24 {
                    return Err(format!(
                        "Invalid key length: expected 24 bytes, got {}",
                        key.len()
                    ));
                }

                if !iv.is_empty() {
                    return Err("ECB mode does not use an IV; expected empty slice".to_string());
                }

                type Aes192Ecb = Ecb<Aes192, Pkcs7>;

                let cipher = Aes192Ecb::new_from_slices(key, Default::default())
                    .map_err(|e| format!("Failed to create ECB cipher: {}", e))?;

                cipher
                    .decrypt_vec(data)
                    .map_err(|e| format!("AES ECB decryption failed: {}", e))
            }

            /// AES CBC Encrypt (AES-192)
            ///
            /// key must be 24 bytes
            ///
            /// iv must be 16 bytes
            /// ```ignore
            /// let key = b"123456781234567812345678"; // 24 bytes
            /// let iv = b"1234567812345678"; // 16 bytes
            /// let data = b"this is data";
            /// let enc_data = doe::crypto::aes::aes_192::aes_cbc_encrypt(key, iv, data).unwrap();
            /// ```
            pub fn aes_cbc_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::Aes192;
                use block_modes::block_padding::Pkcs7;
                use block_modes::{BlockMode, Cbc};

                if key.len() != 24 {
                    return Err(format!(
                        "Invalid key length: expected 24 bytes, got {}",
                        key.len()
                    ));
                }

                if iv.len() != 16 {
                    return Err(format!(
                        "Invalid IV length: expected 16 bytes, got {}",
                        iv.len()
                    ));
                }

                type Aes192Cbc = Cbc<Aes192, Pkcs7>;

                let cipher = Aes192Cbc::new_from_slices(key, iv)
                    .map_err(|e| format!("Failed to create CBC cipher: {}", e))?;

                Ok(cipher.encrypt_vec(data))
            }

            /// AES CBC Decrypt (AES-192)
            ///
            /// key must be 24 bytes
            ///
            /// iv must be 16 bytes
            /// ```ignore
            /// let key = b"123456781234567812345678"; // 24 bytes
            /// let iv = b"1234567812345678"; // 16 bytes
            /// let data = b"this is data";
            /// let enc_data = doe::crypto::aes::aes_192::aes_cbc_encrypt(key, iv, data).unwrap();
            /// let dec_data = doe::crypto::aes::aes_192::aes_cbc_decrypt(key, iv, &enc_data).unwrap();
            /// ```
            pub fn aes_cbc_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::Aes192;
                use block_modes::block_padding::Pkcs7;
                use block_modes::{BlockMode, Cbc};

                if key.len() != 24 {
                    return Err(format!(
                        "Invalid key length: expected 24 bytes, got {}",
                        key.len()
                    ));
                }

                if iv.len() != 16 {
                    return Err(format!(
                        "Invalid IV length: expected 16 bytes, got {}",
                        iv.len()
                    ));
                }

                type Aes192Cbc = Cbc<Aes192, Pkcs7>;

                let cipher = Aes192Cbc::new_from_slices(key, iv)
                    .map_err(|e| format!("Failed to create CBC cipher: {}", e))?;

                cipher
                    .decrypt_vec(data)
                    .map_err(|e| format!("AES CBC decryption failed: {}", e))
            }

            /// AES CFB Encrypt (AES-192)
            ///
            /// key must be 24 bytes
            ///
            /// iv must be 16 bytes
            /// ```ignore
            /// let key = b"123456781234567812345678"; // 24 bytes
            /// let iv = b"1234567812345678"; // 16 bytes
            /// let data = b"this is data";
            /// let enc_data = doe::crypto::aes::aes_192::aes_cfb_encrypt(key, iv, data).unwrap();
            /// ```
            pub fn aes_cfb_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::Aes192;
                use block_modes::block_padding::NoPadding;
                use block_modes::{BlockMode, Cfb};

                if key.len() != 24 {
                    return Err(format!(
                        "Invalid key length: expected 24 bytes, got {}",
                        key.len()
                    ));
                }

                if iv.len() != 16 {
                    return Err(format!(
                        "Invalid IV length: expected 16 bytes, got {}",
                        iv.len()
                    ));
                }

                type Aes192Cfb = Cfb<Aes192, NoPadding>;

                let cipher = Aes192Cfb::new_from_slices(key, iv)
                    .map_err(|e| format!("Failed to create CFB cipher: {}", e))?;

                Ok(cipher.encrypt_vec(data))
            }

            /// AES CFB Decrypt (AES-192)
            ///
            /// key must be 24 bytes
            ///
            /// iv must be 16 bytes
            /// ```ignore
            /// let key = b"123456781234567812345678"; // 24 bytes
            /// let iv = b"1234567812345678"; // 16 bytes
            /// let data = b"this is data";
            /// let enc_data = doe::crypto::aes::aes_192::aes_cfb_encrypt(key, iv, data).unwrap();
            /// let dec_data = doe::crypto::aes::aes_192::aes_cfb_decrypt(key, iv, &enc_data).unwrap();
            /// ```
            pub fn aes_cfb_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::Aes192;
                use block_modes::block_padding::NoPadding;
                use block_modes::{BlockMode, Cfb};

                if key.len() != 24 {
                    return Err(format!(
                        "Invalid key length: expected 24 bytes, got {}",
                        key.len()
                    ));
                }

                if iv.len() != 16 {
                    return Err(format!(
                        "Invalid IV length: expected 16 bytes, got {}",
                        iv.len()
                    ));
                }

                type Aes192Cfb = Cfb<Aes192, NoPadding>;

                let cipher = Aes192Cfb::new_from_slices(key, iv)
                    .map_err(|e| format!("Failed to create CFB cipher: {}", e))?;

                cipher
                    .decrypt_vec(data)
                    .map_err(|e| format!("AES CFB decryption failed: {}", e))
            }

            /// AES OFB Encrypt (AES-192)
            ///
            /// key must be 24 bytes
            ///
            /// iv must be 16 bytes
            /// ```ignore
            /// let key = b"123456781234567812345678"; // 24 bytes
            /// let iv = b"1234567812345678"; // 16 bytes
            /// let data = b"this is data";
            /// let enc_data = doe::crypto::aes::aes_192::aes_ofb_encrypt(key, iv, data).unwrap();
            /// ```
            pub fn aes_ofb_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::Aes192;
                use block_modes::block_padding::NoPadding;
                use block_modes::{BlockMode, Ofb};

                if key.len() != 24 {
                    return Err(format!(
                        "Invalid key length: expected 24 bytes, got {}",
                        key.len()
                    ));
                }

                if iv.len() != 16 {
                    return Err(format!(
                        "Invalid IV length: expected 16 bytes, got {}",
                        iv.len()
                    ));
                }

                type Aes192Ofb = Ofb<Aes192, NoPadding>;

                let cipher = Aes192Ofb::new_from_slices(key, iv)
                    .map_err(|e| format!("Failed to create OFB cipher: {}", e))?;

                Ok(cipher.encrypt_vec(data))
            }

            /// AES OFB Decrypt (AES-192)
            ///
            /// key must be 24 bytes
            ///
            /// iv must be 16 bytes
            /// ```ignore
            /// let key = b"123456781234567812345678"; // 24 bytes
            /// let iv = b"1234567812345678"; // 16 bytes
            /// let data = b"this is data";
            /// let enc_data = doe::crypto::aes::aes_192::aes_ofb_encrypt(key, iv, data).unwrap();
            /// let dec_data = doe::crypto::aes::aes_192::aes_ofb_decrypt(key, iv, &enc_data).unwrap();
            /// ```
            pub fn aes_ofb_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::Aes192;
                use block_modes::block_padding::NoPadding;
                use block_modes::{BlockMode, Ofb};

                if key.len() != 24 {
                    return Err(format!(
                        "Invalid key length: expected 24 bytes, got {}",
                        key.len()
                    ));
                }

                if iv.len() != 16 {
                    return Err(format!(
                        "Invalid IV length: expected 16 bytes, got {}",
                        iv.len()
                    ));
                }

                type Aes192Ofb = Ofb<Aes192, NoPadding>;

                let cipher = Aes192Ofb::new_from_slices(key, iv)
                    .map_err(|e| format!("Failed to create OFB cipher: {}", e))?;

                cipher
                    .decrypt_vec(data)
                    .map_err(|e| format!("AES OFB decryption failed: {}", e))
            }

            /// AES IGE Encrypt (AES-192)
            ///
            /// key must be 24 bytes
            ///
            /// iv must be 32 bytes (two AES blocks: one for previous ciphertext, one for previous plaintext)
            ///
            /// data length must be a multiple of 16 bytes (no padding is performed)
            /// ```ignore
            /// let key = b"123456781234567812345678"; // 24 bytes
            /// let iv = b"12345678123456781234567812345678"; // 32 bytes
            /// let data = b"this is data!!!"; // exactly 16 bytes
            /// let enc_data = doe::crypto::aes::aes_192::aes_ige_encrypt(key, iv, data).unwrap();
            /// ```
            pub fn aes_ige_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::cipher::generic_array::typenum::U16;
                use aes::cipher::{generic_array::GenericArray, BlockEncrypt, NewBlockCipher};
                use aes::Aes192;

                if key.len() != 24 {
                    return Err(format!(
                        "Invalid key length: expected 24 bytes, got {}",
                        key.len()
                    ));
                }

                if iv.len() != 32 {
                    return Err(format!(
                        "Invalid IV length: expected 32 bytes, got {}",
                        iv.len()
                    ));
                }

                if data.len() % 16 != 0 {
                    return Err("Data length must be a multiple of 16 bytes".to_string());
                }

                let cipher = Aes192::new(GenericArray::from_slice(key));
                let mut prev_block: GenericArray<u8, U16> =
                    GenericArray::from_slice(&iv[..16]).to_owned();
                let mut prev_prev_block: GenericArray<u8, U16> =
                    GenericArray::from_slice(&iv[16..]).to_owned();
                let mut ciphertext = Vec::with_capacity(data.len());

                for chunk in data.chunks(16) {
                    let mut block = GenericArray::clone_from_slice(chunk);

                    // IGE encryption: XOR with prev and prev_prev, then encrypt, then XOR with prev
                    for i in 0..16 {
                        block[i] ^= prev_block[i] ^ prev_prev_block[i];
                    }
                    cipher.encrypt_block(&mut block);
                    for i in 0..16 {
                        block[i] ^= prev_block[i];
                    }

                    ciphertext.extend_from_slice(&block);

                    // Update state: shift previous blocks
                    prev_prev_block.copy_from_slice(&prev_block);
                    prev_block.copy_from_slice(&block);
                }

                Ok(ciphertext)
            }

            /// AES IGE Decrypt (AES-192)
            ///
            /// key must be 24 bytes
            ///
            /// iv must be 32 bytes
            ///
            /// data length must be a multiple of 16 bytes
            /// ```ignore
            /// let key = b"123456781234567812345678"; // 24 bytes
            /// let iv = b"12345678123456781234567812345678"; // 32 bytes
            /// let data = b"this is data!!!"; // exactly 16 bytes
            /// let enc_data = doe::crypto::aes::aes_192::aes_ige_encrypt(key, iv, data).unwrap();
            /// let dec_data = doe::crypto::aes::aes_192::aes_ige_decrypt(key, iv, &enc_data).unwrap();
            /// ```
            pub fn aes_ige_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::cipher::generic_array::typenum::U16;
                use aes::cipher::{generic_array::GenericArray, BlockDecrypt, NewBlockCipher};
                use aes::Aes192;

                if key.len() != 24 {
                    return Err(format!(
                        "Invalid key length: expected 24 bytes, got {}",
                        key.len()
                    ));
                }

                if iv.len() != 32 {
                    return Err(format!(
                        "Invalid IV length: expected 32 bytes, got {}",
                        iv.len()
                    ));
                }

                if data.len() % 16 != 0 {
                    return Err("Data length must be a multiple of 16 bytes".to_string());
                }

                let cipher = Aes192::new(GenericArray::from_slice(key));
                let mut prev_block: GenericArray<u8, U16> =
                    GenericArray::from_slice(&iv[..16]).to_owned();
                let mut prev_prev_block: GenericArray<u8, U16> =
                    GenericArray::from_slice(&iv[16..]).to_owned();
                let mut plaintext = Vec::with_capacity(data.len());

                for chunk in data.chunks(16) {
                    let mut block = GenericArray::clone_from_slice(chunk);
                    let original_ciphertext = block.clone(); // save for state update

                    // IGE decryption: XOR with prev, then decrypt, then XOR with prev and prev_prev
                    for i in 0..16 {
                        block[i] ^= prev_block[i];
                    }
                    cipher.decrypt_block(&mut block);
                    for i in 0..16 {
                        block[i] ^= prev_block[i] ^ prev_prev_block[i];
                    }

                    plaintext.extend_from_slice(&block);

                    // Update state using the original ciphertext block
                    prev_prev_block.copy_from_slice(&prev_block);
                    prev_block.copy_from_slice(&original_ciphertext);
                }

                Ok(plaintext)
            }

            /// AES GCM Encrypt (AES-192)
            ///
            /// key must be 24 bytes
            ///
            /// nonce should be 12 bytes (recommended), other lengths are supported but may reduce security
            ///
            /// aad (additional authenticated data) can be empty
            ///
            /// Output includes a 16‑byte authentication tag appended to the ciphertext
            /// ```ignore
            /// let key = b"123456781234567812345678"; // 24 bytes
            /// let nonce = b"123456781234"; // 12 bytes recommended
            /// let data = b"this is data";
            /// let enc_data = doe::crypto::aes::aes_192::aes_gcm_encrypt(key, nonce, data, b"").unwrap();
            /// let dec_data = doe::crypto::aes::aes_192::aes_gcm_decrypt(key, nonce, &enc_data, b"").unwrap();
            /// ```
            ///

            /// AES GCM Encrypt (AES-192)
            ///
            /// key must be 24 bytes
            ///
            /// nonce should be 12 bytes (recommended), other lengths are supported but may reduce security
            ///
            /// aad (additional authenticated data) can be empty
            ///
            /// Output includes a 16‑byte authentication tag appended to the ciphertext
            /// ```ignore
            /// let key = b"123456781234567812345678"; // 24 bytes
            /// let nonce = b"123456781234"; // 12 bytes recommended
            /// let data = b"this is data";
            /// let enc_data = doe::crypto::aes::aes_192::aes_gcm_encrypt(key, nonce, data, b"").unwrap();
            /// let dec_data = doe::crypto::aes::aes_192::aes_gcm_decrypt(key, nonce, &enc_data, b"").unwrap();
            /// let dec_data_str = String::from_utf8_lossy(&dec_data);
            /// println!("Decrypted data: {}", dec_data_str);
            /// ```
            ///
            pub fn aes_gcm_encrypt(
                key: &[u8],
                nonce: &[u8],
                msg: &[u8],
                aad: &[u8],
            ) -> Result<Vec<u8>, String> {
                use aes::cipher::{generic_array::GenericArray, BlockEncrypt};
                use aes::Aes192;

                // GF(2^128) 不可约多项式
                const R: u128 = 0xE1000000000000000000000000000000;

                /// GF(2^128) 乘法
                fn gf_mul(mut x: u128, mut y: u128) -> u128 {
                    let mut z = 0u128;
                    for _ in 0..128 {
                        if y & 1 == 1 {
                            z ^= x;
                        }
                        let carry = x & 1;
                        x >>= 1;
                        if carry != 0 {
                            x ^= R;
                        }
                        y >>= 1;
                    }
                    z
                }

                /// 将 16 字节按大端序转换为 u128
                fn bytes_to_u128_be(bytes: &[u8]) -> u128 {
                    let mut arr = [0u8; 16];
                    let len = bytes.len().min(16);
                    arr[..len].copy_from_slice(&bytes[..len]);
                    u128::from_be_bytes(arr)
                }

                if key.len() != 24 {
                    return Err(format!(
                        "Invalid key length: expected 24 bytes for AES-192, got {}",
                        key.len()
                    ));
                }
                use aes::NewBlockCipher;
                let cipher = Aes192::new(GenericArray::from_slice(key));

                // 1. 计算 H = E_K(0^128)
                let mut h_block = [0u8; 16];
                cipher.encrypt_block(GenericArray::from_mut_slice(&mut h_block));
                let h = bytes_to_u128_be(&h_block);

                // 2. 计算初始计数器 J0
                let j0: u128 = if nonce.len() == 12 {
                    // J0 = nonce || 0x00000001
                    let mut nonce_padded = [0u8; 16];
                    nonce_padded[..12].copy_from_slice(nonce);
                    bytes_to_u128_be(&nonce_padded) | 1
                } else {
                    // 对于非12字节nonce，使用GHASH计算
                    // J0 = GHASH(H, nonce || 0^(s+64) || [len(nonce)]_64)
                    let s = (16 - (nonce.len() % 16)) % 16;
                    let padded_len = nonce.len() + s + 8;
                    let mut padded = vec![0u8; padded_len];
                    padded[..nonce.len()].copy_from_slice(nonce);
                    // 最后8字节是nonce的位长度（大端序）
                    padded[padded_len - 8..]
                        .copy_from_slice(&(nonce.len() as u64 * 8).to_be_bytes());

                    let mut state: u128 = 0;
                    let mut remaining = &padded[..];
                    while remaining.len() >= 16 {
                        state ^= bytes_to_u128_be(&remaining[..16]);
                        state = gf_mul(state, h);
                        remaining = &remaining[16..];
                    }
                    state
                };

                // 3. 计算标签掩码 E(K, J0)
                let mut j0_bytes = j0.to_be_bytes();
                cipher.encrypt_block(GenericArray::from_mut_slice(&mut j0_bytes));
                let mask = u128::from_be_bytes(j0_bytes);

                // 4. GHASH 处理函数
                fn ghash_update(mut state: u128, h: u128, data: &[u8]) -> u128 {
                    let mut remaining = data;
                    while remaining.len() >= 16 {
                        state ^= bytes_to_u128_be(&remaining[..16]);
                        state = gf_mul(state, h);
                        remaining = &remaining[16..];
                    }
                    // 处理最后一个不完整的块（用0填充）
                    if !remaining.is_empty() {
                        state ^= bytes_to_u128_be(remaining);
                        state = gf_mul(state, h);
                    }
                    state
                }

                // 5. GHASH 处理 AAD
                let mut ghash_state = ghash_update(0, h, aad);

                // 6. CTR 模式加密（从 J0 + 1 开始）
                let mut ciphertext = msg.to_vec();
                let mut counter = j0.wrapping_add(1);
                let mut offset = 0;

                while offset < ciphertext.len() {
                    let mut counter_bytes = counter.to_be_bytes();
                    cipher.encrypt_block(GenericArray::from_mut_slice(&mut counter_bytes));

                    let end = (offset + 16).min(ciphertext.len());
                    for i in offset..end {
                        ciphertext[i] ^= counter_bytes[i - offset];
                    }

                    counter = counter.wrapping_add(1);
                    offset = end;
                }

                // 7. GHASH 处理密文
                ghash_state = ghash_update(ghash_state, h, &ciphertext);

                // 8. 最终 GHASH：加入长度块
                // 长度块 = [len(AAD) in bits]_64 || [len(C) in bits]_64
                let len_block = ((aad.len() as u128) << 64) | ((ciphertext.len() as u128) << 3);
                ghash_state ^= len_block;
                ghash_state = gf_mul(ghash_state, h);

                // 9. 计算认证标签
                let tag = ghash_state ^ mask;

                // 10. 拼接密文和标签
                ciphertext.extend_from_slice(&tag.to_be_bytes());
                Ok(ciphertext)
            }

            /// AES GCM Decrypt (AES-192)
            ///
            /// key must be 24 bytes
            ///
            /// nonce should be 12 bytes (recommended), other lengths are supported but may reduce security
            ///
            /// aad (additional authenticated data) can be empty
            ///
            /// Input must include the 16‑byte authentication tag appended to the ciphertext
            /// ```ignore
            /// let key = b"123456781234567812345678"; // 24 bytes
            /// let nonce = b"123456781234"; // 12 bytes recommended
            /// let data = b"this is data";
            /// let enc_data = doe::crypto::aes::aes_192::aes_gcm_encrypt(key, nonce, data, b"").unwrap();
            /// let dec_data = doe::crypto::aes::aes_192::aes_gcm_decrypt(key, nonce, &enc_data, b"").unwrap();
            /// let dec_data_str = String::from_utf8_lossy(&dec_data);
            /// println!("Decrypted data: {}", dec_data_str);
            /// ```
            ///
            pub fn aes_gcm_decrypt(
                key: &[u8],
                nonce: &[u8],
                ciphertext_with_tag: &[u8],
                aad: &[u8],
            ) -> Result<Vec<u8>, String> {
                use aes::cipher::{generic_array::GenericArray, BlockEncrypt};
                use aes::Aes192;
                use aes::NewBlockCipher;

                // GF(2^128) 不可约多项式
                const R: u128 = 0xE1000000000000000000000000000000;

                /// GF(2^128) 乘法
                fn gf_mul(mut x: u128, mut y: u128) -> u128 {
                    let mut z = 0u128;
                    for _ in 0..128 {
                        if y & 1 == 1 {
                            z ^= x;
                        }
                        let carry = x & 1;
                        x >>= 1;
                        if carry != 0 {
                            x ^= R;
                        }
                        y >>= 1;
                    }
                    z
                }

                /// 将 16 字节按大端序转换为 u128
                fn bytes_to_u128_be(bytes: &[u8]) -> u128 {
                    let mut arr = [0u8; 16];
                    let len = bytes.len().min(16);
                    arr[..len].copy_from_slice(&bytes[..len]);
                    u128::from_be_bytes(arr)
                }

                if key.len() != 24 {
                    return Err(format!(
                        "Invalid key length: expected 24 bytes for AES-192, got {}",
                        key.len()
                    ));
                }

                // 密文必须至少包含 16 字节的 Tag
                if ciphertext_with_tag.len() < 16 {
                    return Err(
                        "Invalid input: ciphertext too short, missing authentication tag"
                            .to_string(),
                    );
                }

                // 1. 分离密文和标签
                let ciphertext_len = ciphertext_with_tag.len() - 16;
                let ciphertext = &ciphertext_with_tag[..ciphertext_len];
                let received_tag_bytes = &ciphertext_with_tag[ciphertext_len..];
                let received_tag = u128::from_be_bytes(received_tag_bytes.try_into().unwrap());

                let cipher = Aes192::new(GenericArray::from_slice(key));

                // 2. 计算 H = E_K(0^128)
                let mut h_block = [0u8; 16];
                cipher.encrypt_block(GenericArray::from_mut_slice(&mut h_block));
                let h = bytes_to_u128_be(&h_block);

                // 3. 计算初始计数器 J0 (与加密完全一致)
                let j0: u128 = if nonce.len() == 12 {
                    let mut nonce_padded = [0u8; 16];
                    nonce_padded[..12].copy_from_slice(nonce);
                    bytes_to_u128_be(&nonce_padded) | 1
                } else {
                    let s = (16 - (nonce.len() % 16)) % 16;
                    let padded_len = nonce.len() + s + 8;
                    let mut padded = vec![0u8; padded_len];
                    padded[..nonce.len()].copy_from_slice(nonce);
                    padded[padded_len - 8..]
                        .copy_from_slice(&(nonce.len() as u64 * 8).to_be_bytes());

                    let mut state: u128 = 0;
                    let mut remaining = &padded[..];
                    while remaining.len() >= 16 {
                        state ^= bytes_to_u128_be(&remaining[..16]);
                        state = gf_mul(state, h);
                        remaining = &remaining[16..];
                    }
                    state
                };

                // 4. 计算标签掩码 E(K, J0)
                let mut j0_bytes = j0.to_be_bytes();
                cipher.encrypt_block(GenericArray::from_mut_slice(&mut j0_bytes));
                let mask = u128::from_be_bytes(j0_bytes);

                // 5. GHASH 处理函数 (与加密完全一致)
                fn ghash_update(mut state: u128, h: u128, data: &[u8]) -> u128 {
                    let mut remaining = data;
                    while remaining.len() >= 16 {
                        state ^= bytes_to_u128_be(&remaining[..16]);
                        state = gf_mul(state, h);
                        remaining = &remaining[16..];
                    }
                    if !remaining.is_empty() {
                        state ^= bytes_to_u128_be(remaining);
                        state = gf_mul(state, h);
                    }
                    state
                }

                // 6. 计算期望的 GHASH 状态
                let mut ghash_state = ghash_update(0, h, aad);
                ghash_state = ghash_update(ghash_state, h, ciphertext);

                // 7. 最终 GHASH：加入长度块
                let len_block = ((aad.len() as u128) << 64) | ((ciphertext.len() as u128) << 3);
                ghash_state ^= len_block;
                ghash_state = gf_mul(ghash_state, h);

                // 8. 计算期望的认证标签
                let expected_tag = ghash_state ^ mask;

                // 9. 常量时间验证标签 (防止时序攻击)
                // 不要直接使用 expected_tag == received_tag，因为那会引入分支和时序泄露
                let expected_bytes = expected_tag.to_be_bytes();
                let mut diff = 0u8;
                for i in 0..16 {
                    diff |= expected_bytes[i] ^ received_tag_bytes[i];
                }

                if diff != 0 {
                    return Err("Authentication failed: invalid tag".to_string());
                }

                // 10. 验证通过，执行 CTR 模式解密（从 J0 + 1 开始）
                // 注意：CTR 的解密和加密操作完全相同，都是与密钥流异或
                let mut plaintext = ciphertext.to_vec();
                let mut counter = j0.wrapping_add(1);
                let mut offset = 0;

                while offset < plaintext.len() {
                    let mut counter_bytes = counter.to_be_bytes();
                    cipher.encrypt_block(GenericArray::from_mut_slice(&mut counter_bytes));

                    let end = (offset + 16).min(plaintext.len());
                    for i in offset..end {
                        plaintext[i] ^= counter_bytes[i - offset];
                    }

                    counter = counter.wrapping_add(1);
                    offset = end;
                }

                Ok(plaintext)
            }

            /// AES CTR Encrypt / Decrypt (AES-192)
            ///
            /// key must be 24 bytes
            ///
            /// iv must be 16 bytes
            ///
            /// CTR mode is a stream cipher: encryption and decryption are identical.
            /// ```ignore
            /// let key = b"123456781234567812345678"; // 24 bytes
            /// let iv = b"1234567812345678"; // 16 bytes
            /// let data = b"this is data";
            /// let enc_data = doe::crypto::aes::aes_192::aes_ctr_encrypt(key, iv, data).unwrap();
            /// let dec_data = doe::crypto::aes::aes_192::aes_ctr_decrypt(key, iv, &enc_data).unwrap();
            /// assert_eq!(data.to_vec(), dec_data);
            /// ```
            pub fn aes_ctr_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::cipher::{generic_array::GenericArray, BlockDecrypt, BlockEncrypt};
                use aes::cipher::{NewCipher, StreamCipher};
                use aes::Aes192;
                use ctr::Ctr128BE;

                type Aes192Ctr = Ctr128BE<Aes192>;

                if key.len() != 24 {
                    return Err(format!(
                        "Invalid key length: expected 24 bytes, got {}",
                        key.len()
                    ));
                }

                if iv.len() != 16 {
                    return Err(format!(
                        "Invalid IV length: expected 16 bytes, got {}",
                        iv.len()
                    ));
                }

                let mut cipher =
                    Aes192Ctr::new(GenericArray::from_slice(key), GenericArray::from_slice(iv));
                let mut ciphertext = data.to_vec();
                cipher.apply_keystream(&mut ciphertext);

                Ok(ciphertext)
            }

            /// AES CTR Decrypt (AES-192)
            ///
            /// key must be 24 bytes
            ///
            /// iv must be 16 bytes
            ///
            /// CTR mode decryption is identical to encryption.
            /// ```ignore
            /// let key = b"123456781234567812345678"; // 24 bytes
            /// let iv = b"1234567812345678"; // 16 bytes
            /// let data = b"this is data";
            /// let enc_data = doe::crypto::aes::aes_192::aes_ctr_encrypt(key, iv, data).unwrap();
            /// let dec_data = doe::crypto::aes::aes_192::aes_ctr_decrypt(key, iv, &enc_data).unwrap();
            /// assert_eq!(data.to_vec(), dec_data);
            /// ```
            pub fn aes_ctr_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                // Decryption in CTR mode is the same as encryption
                aes_ctr_encrypt(key, iv, data)
            }
        }

        pub mod aes_256 {

            /// AES SIV Encrypt (AES-256)
            /// key: 必须是 64 字节
            /// nonce: 16 字节 (必需参数)
            /// aad: 关联数据
            /// data: 明文
            pub fn aes_siv_encrypt(
                key: &[u8],
                nonce: &[u8],
                aad: &[u8],
                data: &[u8],
            ) -> Result<Vec<u8>, String> {
                use aes_siv::aead::generic_array::GenericArray;
                use aes_siv::aead::{Aead, KeyInit, Payload};
                use aes_siv::Aes256SivAead;

                if key.len() != 64 {
                    return Err("SIV AES-256 requires a 64-byte key".to_string());
                }

                if nonce.len() != 16 {
                    return Err(format!(
                        "SIV AES-256 requires a 16-byte nonce, got {}",
                        nonce.len()
                    ));
                }

                let cipher = Aes256SivAead::new_from_slice(key)
                    .map_err(|e| format!("Failed to create SIV cipher: {}", e))?;

                // 构造nonce的GenericArray
                let nonce_array = GenericArray::from_slice(nonce);

                // 构造标准 AEAD 负载
                let payload = Payload {
                    msg: data, // 只有这部分会被加密
                    aad: aad,  // 这部分只参与认证，不加密
                };

                // 输出 = 16字节SIV标签 + 密文
                cipher
                    .encrypt(nonce_array, payload)
                    .map_err(|e| format!("SIV encryption failed: {}", e))
            }

            /// AES SIV Decrypt (AES-256)
            pub fn aes_siv_decrypt(
                key: &[u8],
                nonce: &[u8],
                aad: &[u8],
                ciphertext_with_siv: &[u8],
            ) -> Result<Vec<u8>, String> {
                use aes_siv::aead::generic_array::GenericArray;
                use aes_siv::aead::{Aead, KeyInit, Payload};
                use aes_siv::Aes256SivAead;

                if key.len() != 64 {
                    return Err("SIV AES-256 requires a 64-byte key".to_string());
                }

                if nonce.len() != 16 {
                    return Err(format!(
                        "SIV AES-256 requires a 16-byte nonce, got {}",
                        nonce.len()
                    ));
                }

                let cipher = Aes256SivAead::new_from_slice(key)
                    .map_err(|e| format!("Failed to create SIV cipher: {}", e))?;

                // 构造nonce的GenericArray
                let nonce_array = GenericArray::from_slice(nonce);

                let payload = Payload {
                    msg: ciphertext_with_siv, // 传入包含 tag 的密文
                    aad: aad,
                };

                // decrypt 会自动剥离 16 字节的 tag，验证它，并返回真实的明文
                cipher
                    .decrypt(nonce_array, payload)
                    .map_err(|_| "SIV authentication failed".to_string())
            }

            /// AES XTS Encrypt (AES-256)
            ///
            /// key: 必须是 64 字节 (两个 32 字节的 AES-256 密钥拼接)
            /// tweak: 16 字节 (通常代表磁盘扇区号)
            /// data: 必须大于等于 16 字节
            pub fn aes_xts_encrypt(
                key: &[u8],
                tweak: &[u8],
                data: &[u8],
            ) -> Result<Vec<u8>, String> {
                use aes::cipher::generic_array::GenericArray;
                use aes::Aes256;
                // 使用你环境中已经验证可用的 NewBlockCipher，避免 KeyInit 版本冲突
                use aes::NewBlockCipher;
                use xts_mode::Xts128;

                if key.len() != 64 {
                    return Err("XTS AES-256 requires a 64-byte key".to_string());
                }
                if tweak.len() != 16 {
                    return Err("Tweak must be 16 bytes".to_string());
                }
                if data.len() < 16 {
                    return Err("Data must be at least 16 bytes for XTS".to_string());
                }

                // 分别初始化两个密钥
                let cipher_1 = Aes256::new(GenericArray::from_slice(&key[..32]));
                let cipher_2 = Aes256::new(GenericArray::from_slice(&key[32..]));

                // 组合成 XTS 模式
                let xts = Xts128::<Aes256>::new(cipher_1, cipher_2);

                let mut buffer = data.to_vec();
                let mut tweak_arr = [0u8; 16];
                tweak_arr.copy_from_slice(tweak);

                xts.encrypt_sector(&mut buffer, tweak_arr);

                Ok(buffer)
            }

            /// AES XTS Decrypt (AES-256)
            ///
            /// key: 必须是 64 字节 (两个 32 字节的 AES-256 密钥拼接)
            /// tweak: 16 字节 (通常代表磁盘扇区号)
            /// data: 必须大于等于 16 字节
            pub fn aes_xts_decrypt(
                key: &[u8],
                tweak: &[u8],
                data: &[u8],
            ) -> Result<Vec<u8>, String> {
                use aes::cipher::generic_array::GenericArray;
                use aes::Aes256;
                // 使用你环境中已经验证可用的 NewBlockCipher，避免 KeyInit 版本冲突
                use aes::NewBlockCipher;
                use xts_mode::Xts128;

                if key.len() != 64 {
                    return Err("XTS AES-256 requires a 64-byte key".to_string());
                }
                if tweak.len() != 16 {
                    return Err("Tweak must be 16 bytes".to_string());
                }
                if data.len() < 16 {
                    return Err("Data must be at least 16 bytes for XTS".to_string());
                }

                let cipher_1 = Aes256::new(GenericArray::from_slice(&key[..32]));
                let cipher_2 = Aes256::new(GenericArray::from_slice(&key[32..]));

                let xts = Xts128::<Aes256>::new(cipher_1, cipher_2);

                let mut buffer = data.to_vec();
                let mut tweak_arr = [0u8; 16];
                tweak_arr.copy_from_slice(tweak);

                xts.decrypt_sector(&mut buffer, tweak_arr);

                Ok(buffer)
            }

            /// AES PCBC Encrypt (AES-256)
            /// key: 32 bytes, iv: 16 bytes
            pub fn aes_pcbc_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::cipher::generic_array::typenum::U16;
                use aes::cipher::generic_array::typenum::U32;
                use aes::cipher::{generic_array::GenericArray, BlockEncrypt};
                use aes::Aes256;

                if key.len() != 32 {
                    return Err(format!(
                        "Invalid key length: expected 32 bytes, got {}",
                        key.len()
                    ));
                }
                if iv.len() != 16 {
                    return Err(format!(
                        "Invalid iv length: expected 16 bytes, got {}",
                        iv.len()
                    ));
                }
                if data.is_empty() {
                    return Err("Data cannot be empty".to_string());
                }
                use aes::NewBlockCipher;
                let cipher = Aes256::new(GenericArray::<u8, U32>::from_slice(key));
                let mut padded_data = data.to_vec();
                // 手动添加 PKCS7 填充
                let pad_len = 16 - (padded_data.len() % 16);
                padded_data.extend(vec![pad_len as u8; pad_len]);

                let mut prev_ciphertext: GenericArray<u8, U16> = GenericArray::clone_from_slice(iv);
                let mut prev_plaintext: GenericArray<u8, U16> = GenericArray::from([0u8; 16]);
                let mut ciphertext = Vec::with_capacity(padded_data.len());

                for chunk in padded_data.chunks(16) {
                    let mut block: GenericArray<u8, U16> = GenericArray::clone_from_slice(chunk);
                    // PCBC 核心逻辑: 异或前一个密文块 AND 前一个明文块
                    for i in 0..16 {
                        block[i] ^= prev_ciphertext[i] ^ prev_plaintext[i];
                    }
                    cipher.encrypt_block(&mut block);

                    prev_plaintext.copy_from_slice(chunk);
                    prev_ciphertext.copy_from_slice(&block);

                    ciphertext.extend_from_slice(&block);
                }

                Ok(ciphertext)
            }

            /// AES PCBC Decrypt (AES-256)
            pub fn aes_pcbc_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::cipher::generic_array::typenum::U16;
                use aes::cipher::generic_array::typenum::U32;
                use aes::cipher::{generic_array::GenericArray, BlockDecrypt};
                use aes::Aes256;
                use aes::NewBlockCipher;

                if key.len() != 32 {
                    return Err(format!(
                        "Invalid key length: expected 32 bytes, got {}",
                        key.len()
                    ));
                }
                if iv.len() != 16 {
                    return Err(format!(
                        "Invalid iv length: expected 16 bytes, got {}",
                        iv.len()
                    ));
                }
                if data.len() % 16 != 0 {
                    return Err(format!(
                        "Invalid data length: must be multiple of 16 bytes, got {}",
                        data.len()
                    ));
                }
                if data.is_empty() {
                    return Err("Data cannot be empty".to_string());
                }

                let cipher = Aes256::new(GenericArray::<u8, U32>::from_slice(key));
                let mut prev_ciphertext: GenericArray<u8, U16> = GenericArray::clone_from_slice(iv);
                let mut prev_plaintext: GenericArray<u8, U16> = GenericArray::from([0u8; 16]);
                let mut plaintext = Vec::with_capacity(data.len());

                for chunk in data.chunks(16) {
                    let mut block: GenericArray<u8, U16> = GenericArray::clone_from_slice(chunk);
                    cipher.decrypt_block(&mut block);

                    for i in 0..16 {
                        block[i] ^= prev_ciphertext[i] ^ prev_plaintext[i];
                    }

                    prev_plaintext.copy_from_slice(&block);
                    prev_ciphertext.copy_from_slice(chunk);

                    plaintext.extend_from_slice(&block);
                }

                // 手动移除 PKCS7 填充
                if let Some(&pad_byte) = plaintext.last() {
                    if pad_byte >= 1 && pad_byte <= 16 {
                        let pad_len = pad_byte as usize;
                        if plaintext.len() >= pad_len {
                            let padding = &plaintext[plaintext.len() - pad_len..];
                            if padding.iter().all(|&b| b == pad_byte) {
                                plaintext.truncate(plaintext.len() - pad_len);
                                return Ok(plaintext);
                            }
                        }
                    }
                }
                Err("Invalid PKCS7 padding".to_string())
            }

            /// AES ECB Encrypt
            ///
            /// key must be 32 bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_256::aes_ecb_encrypt("12345678123456781234567812345678".as_bytes(), data).unwrap();
            /// ```
            pub fn aes_ecb_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::cipher::generic_array::GenericArray;
                use aes::Aes256;
                use block_modes::block_padding::Pkcs7;
                use block_modes::{BlockMode, Ecb};

                type Aes256Ecb = Ecb<Aes256, Pkcs7>;

                // ECB mode does not use an IV
                let cipher = Aes256Ecb::new_from_slices(key, iv)
                    .map_err(|e| format!("Failed to create ECB cipher: {}", e))?;
                Ok(cipher.encrypt_vec(data))
            }

            /// AES ECB Decrypt
            ///
            /// key must be 32 bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_256::aes_ecb_encrypt("12345678123456781234567812345678".as_bytes(), data).unwrap();
            ///let dec_data = doe::crypto::aes::aes_256::aes_ecb_decrypt("12345678123456781234567812345678".as_bytes(), &enc_data).unwrap();
            /// ```
            pub fn aes_ecb_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::cipher::generic_array::GenericArray;
                use aes::Aes256;
                use block_modes::block_padding::Pkcs7;
                use block_modes::{BlockMode, Ecb};

                type Aes256Ecb = Ecb<Aes256, Pkcs7>;

                let cipher = Aes256Ecb::new_from_slices(key, iv)
                    .map_err(|e| format!("Failed to create ECB cipher: {}", e))?;

                cipher
                    .decrypt_vec(data)
                    .map_err(|e| format!("AES ECB decryption failed: {}", e))
            }

            /// AES CBC Encrypt
            ///
            /// key must be 32 bytes
            ///
            /// iv must be 16 bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_256::aes_cbc_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
            /// ```
            pub fn aes_cbc_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::Aes256;
                use block_modes::block_padding::Pkcs7;
                use block_modes::{BlockMode, Cbc};

                type Aes256Cbc = Cbc<Aes256, Pkcs7>;

                let cipher = Aes256Cbc::new_from_slices(key, iv)
                    .map_err(|e| format!("Failed to create CBC cipher: {}", e))?;

                Ok(cipher.encrypt_vec(data))
            }

            /// AES CBC Decrypt
            ///
            /// key must be 32 bytes
            ///
            /// iv must be 16 bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_256::aes_cbc_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
            ///let dec_data = doe::crypto::aes::aes_256::aes_cbc_decrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),&enc_data).unwrap();
            /// ```
            pub fn aes_cbc_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::Aes256;
                use block_modes::block_padding::Pkcs7;
                use block_modes::{BlockMode, Cbc};

                type Aes256Cbc = Cbc<Aes256, Pkcs7>;

                let cipher = Aes256Cbc::new_from_slices(key, iv)
                    .map_err(|e| format!("Failed to create CBC cipher: {}", e))?;

                cipher
                    .decrypt_vec(data)
                    .map_err(|e| format!("AES CBC decryption failed: {}", e))
            }

            /// AES CFB Encrypt
            ///
            /// key must be 32 bytes
            ///
            /// iv must be 16 bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_256::aes_cfb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
            /// ```
            pub fn aes_cfb_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::Aes256;
                use block_modes::block_padding::NoPadding;

                use block_modes::{BlockMode, Cfb};

                // CFB is a stream cipher mode and does NOT use padding
                type Aes256Cfb = Cfb<Aes256, NoPadding>;

                let cipher = Aes256Cfb::new_from_slices(key, iv)
                    .map_err(|e| format!("Failed to create CFB cipher: {}", e))?;

                Ok(cipher.encrypt_vec(data))
            }

            /// AES CFB Decrypt
            ///
            /// key must be 32 bytes
            ///
            /// iv must be 16 bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_256::aes_cfb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
            ///let dec_data = doe::crypto::aes::aes_256::aes_cfb_decrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),&enc_data).unwrap();
            /// ```
            pub fn aes_cfb_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::Aes256;
                use block_modes::block_padding::NoPadding;
                use block_modes::{BlockMode, Cfb};
                type Aes256Cfb = Cfb<Aes256, NoPadding>;

                let cipher = Aes256Cfb::new_from_slices(key, iv)
                    .map_err(|e| format!("Failed to create CFB cipher: {}", e))?;

                cipher
                    .decrypt_vec(data)
                    .map_err(|e| format!("AES CFB decryption failed: {}", e))
            }

            /// AES OFB Encrypt
            ///
            /// key must be 32 bytes
            ///
            /// iv must be 16 bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_256::aes_ofb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
            /// ```
            pub fn aes_ofb_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::Aes256;
                use block_modes::block_padding::NoPadding;
                use block_modes::{BlockMode, Ofb};

                // OFB is a stream cipher mode and does NOT use padding
                type Aes256Ofb = Ofb<Aes256, NoPadding>;

                let cipher = Aes256Ofb::new_from_slices(key, iv)
                    .map_err(|e| format!("Failed to create OFB cipher: {}", e))?;

                Ok(cipher.encrypt_vec(data))
            }

            /// AES OFB Decrypt
            ///
            /// key must be 32 bytes
            ///
            /// iv must be 16 bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_256::aes_ofb_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
            ///let dec_data = doe::crypto::aes::aes_256::aes_ofb_decrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),&enc_data).unwrap();
            /// ```
            pub fn aes_ofb_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::Aes256;
                use block_modes::block_padding::NoPadding;
                use block_modes::{BlockMode, Ofb};

                type Aes256Ofb = Ofb<Aes256, NoPadding>;

                let cipher = Aes256Ofb::new_from_slices(key, iv)
                    .map_err(|e| format!("Failed to create OFB cipher: {}", e))?;

                cipher
                    .decrypt_vec(data)
                    .map_err(|e| format!("AES OFB decryption failed: {}", e))
            }

            /// AES IGE Encrypt
            ///
            /// key must be 32 bytes
            ///
            /// iv must be 32 bytes
            ///
            /// data must be 16*n bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_256::aes_ige_encrypt("12345678123456781234567812345678".as_bytes(),"12345678123456781234567812345678".as_bytes(),data).unwrap();
            /// ```
            pub fn aes_ige_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::cipher::generic_array::typenum::U16;
                use aes::cipher::{generic_array::GenericArray, BlockEncrypt};
                use aes::Aes256;

                if key.len() != 32 {
                    return Err("Key must be 32 bytes".to_string());
                }
                if iv.len() != 32 {
                    return Err("IV must be 32 bytes".to_string());
                }
                if data.len() % 16 != 0 {
                    return Err("Data must be a multiple of 16 bytes".to_string());
                }
                use aes::NewBlockCipher;

                let cipher = Aes256::new(GenericArray::from_slice(key));
                let mut prev_block: GenericArray<u8, U16> =
                    GenericArray::from_slice(&iv[..16]).to_owned();
                let mut prev_prev_block: GenericArray<u8, U16> =
                    GenericArray::from_slice(&iv[16..]).to_owned();
                let mut ciphertext = Vec::with_capacity(data.len());

                for chunk in data.chunks(16) {
                    let mut block = GenericArray::clone_from_slice(chunk);
                    for i in 0..16 {
                        block[i] ^= prev_block[i] ^ prev_prev_block[i];
                    }
                    cipher.encrypt_block(&mut block);
                    for i in 0..16 {
                        block[i] ^= prev_block[i];
                    }
                    ciphertext.extend_from_slice(&block);
                    prev_prev_block.copy_from_slice(&prev_block);
                    prev_block.copy_from_slice(&block);
                }

                Ok(ciphertext)
            }

            /// AES IGE Decrypt
            ///
            /// key must be 32 bytes
            ///
            /// iv must be 32 bytes
            ///
            /// data must be 16*n bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_256::aes_ige_encrypt("12345678123456781234567812345678".as_bytes(),"12345678123456781234567812345678".as_bytes(),data).unwrap();
            ///let dec_data = doe::crypto::aes::aes_256::aes_ige_decrypt("12345678123456781234567812345678".as_bytes(),"12345678123456781234567812345678".as_bytes(),&enc_data).unwrap();
            /// ```
            pub fn aes_ige_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::cipher::generic_array::typenum::U16;
                use aes::cipher::{generic_array::GenericArray, BlockDecrypt};
                use aes::Aes256;

                if key.len() != 32 {
                    return Err("Key must be 32 bytes".to_string());
                }
                if iv.len() != 32 {
                    return Err("IV must be 32 bytes".to_string());
                }
                if data.len() % 16 != 0 {
                    return Err("Data must be a multiple of 16 bytes".to_string());
                }
                use aes::NewBlockCipher;

                let cipher = Aes256::new(GenericArray::from_slice(key));
                let mut prev_block: GenericArray<u8, U16> =
                    GenericArray::from_slice(&iv[..16]).to_owned();
                let mut prev_prev_block: GenericArray<u8, U16> =
                    GenericArray::from_slice(&iv[16..]).to_owned();
                let mut plaintext = Vec::with_capacity(data.len());

                for chunk in data.chunks(16) {
                    let mut block = GenericArray::clone_from_slice(chunk);
                    for i in 0..16 {
                        block[i] ^= prev_block[i];
                    }
                    cipher.decrypt_block(&mut block);
                    for i in 0..16 {
                        block[i] ^= prev_block[i] ^ prev_prev_block[i];
                    }
                    plaintext.extend_from_slice(&block);
                    prev_prev_block.copy_from_slice(&prev_block);
                    prev_block.copy_from_slice(chunk);
                }

                Ok(plaintext)
            }

            /// AES 256 CTR Encrypt
            ///
            /// key must be 32 bytes
            ///
            /// iv must be 16 bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_256::aes_ctr_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
            /// ```
            pub fn aes_ctr_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::cipher::generic_array::GenericArray;
                use aes::cipher::{NewCipher, StreamCipher};
                use aes::Aes256;
                use ctr::Ctr128BE;

                type Aes256Ctr = Ctr128BE<Aes256>;

                if key.len() != 32 {
                    return Err("Key must be 32 bytes".to_string());
                }
                if iv.len() != 16 {
                    return Err("IV must be 16 bytes".to_string());
                }

                let mut cipher =
                    Aes256Ctr::new(GenericArray::from_slice(key), GenericArray::from_slice(iv));
                let mut ciphertext = data.to_vec();
                cipher.apply_keystream(&mut ciphertext);

                Ok(ciphertext)
            }

            /// AES CTR Decrypt
            ///
            /// key must be 32 bytes
            ///
            /// iv must be 16 bytes
            /// ```ignore
            ///let data = "this is data".as_bytes();
            ///let enc_data = doe::crypto::aes::aes_256::aes_ctr_encrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),data).unwrap();
            ///let dec_data = doe::crypto::aes::aes_256::aes_ctr_decrypt("12345678123456781234567812345678".as_bytes(),"1234567812345678".as_bytes(),&enc_data).unwrap();
            /// ```
            pub fn aes_ctr_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
                use aes::cipher::generic_array::GenericArray;
                use aes::cipher::{NewCipher, StreamCipher};
                use aes::Aes256;
                use ctr::Ctr128BE;

                type Aes256Ctr = Ctr128BE<Aes256>;

                if key.len() != 32 {
                    return Err("Key must be 32 bytes".to_string());
                }
                if iv.len() != 16 {
                    return Err("IV must be 16 bytes".to_string());
                }

                let mut cipher =
                    Aes256Ctr::new(GenericArray::from_slice(key), GenericArray::from_slice(iv));
                let mut plaintext = data.to_vec();
                cipher.apply_keystream(&mut plaintext);

                Ok(plaintext)
            }
        }
    }
    ///RSA example
    ///```ignore
    ///let priv_key = doe::crypto::rsa::gen_priv_key(2048).unwrap();
    ///let pub_key = doe::crypto::rsa::gen_pub_key(&priv_key);
    ///let data = b"hello world";
    ///let enc_data = doe::crypto::rsa::encrypt(&pub_key, data).unwrap();
    ///let dec_data = doe::crypto::rsa::decrypt(&priv_key, &enc_data).unwrap();
    ///assert_eq!(data, dec_data.as_slice());
    /// ```
    ///
    pub mod rsa {
        use rsa::pkcs8::DecodePrivateKey;
        pub use rsa::*;

        ///RSA example
        ///```ignore
        ///let priv_key = doe::crypto::rsa::gen_priv_key(2048).unwrap();
        ///let pub_key = doe::crypto::rsa::gen_pub_key(&priv_key);
        ///let data = b"hello world";
        ///let enc_data = doe::crypto::rsa::encrypt(&pub_key, data).unwrap();
        ///let dec_data = doe::crypto::rsa::decrypt(&priv_key, &enc_data).unwrap();
        ///assert_eq!(data, dec_data.as_slice());
        /// ```
        ///
        pub fn gen_priv_key(bits: usize) -> std::result::Result<RsaPrivateKey, String> {
            let mut rng = rand::thread_rng();
            RsaPrivateKey::new(&mut rng, bits)
                .map_err(|e| format!("Failed to generate RSA private key: {}", e))
        }

        ///RSA example
        ///```ignore
        ///let pem = "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----";
        ///let priv_key = doe::crypto::rsa::gen_priv_key_from_pkcs8_pem(pem).unwrap();
        ///let pub_key = doe::crypto::rsa::gen_pub_key(&priv_key);
        ///let data = b"hello world";
        ///let enc_data = doe::crypto::rsa::encrypt(&pub_key, data).unwrap();
        ///let dec_data = doe::crypto::rsa::decrypt(&priv_key, &enc_data).unwrap();
        ///assert_eq!(data, dec_data.as_slice());
        /// ```
        pub fn gen_priv_key_from_pkcs8_pem(s: &str) -> std::result::Result<RsaPrivateKey, String> {
            RsaPrivateKey::from_pkcs8_pem(s)
                .map_err(|e| format!("Failed to parse RSA private key from PEM: {}", e))
        }

        ///RSA example
        ///```ignore
        ///let priv_key = doe::crypto::rsa::gen_priv_key(2048).unwrap();
        ///let pub_key = doe::crypto::rsa::gen_pub_key(&priv_key);
        ///let data = b"hello world";
        ///let enc_data = doe::crypto::rsa::encrypt(&pub_key, data).unwrap();
        ///let dec_data = doe::crypto::rsa::decrypt(&priv_key, &enc_data).unwrap();
        ///assert_eq!(data, dec_data.as_slice());
        /// ```
        ///
        pub fn gen_pub_key(priv_key: &RsaPrivateKey) -> RsaPublicKey {
            RsaPublicKey::from(priv_key)
        }

        ///RSA example
        ///```ignore
        ///let priv_key = doe::crypto::rsa::gen_priv_key(2048).unwrap();
        ///let pub_key = doe::crypto::rsa::gen_pub_key(&priv_key);
        ///let data = b"hello world";
        ///let enc_data = doe::crypto::rsa::encrypt(&pub_key, data).unwrap();
        ///let dec_data = doe::crypto::rsa::decrypt(&priv_key, &enc_data).unwrap();
        ///assert_eq!(data, dec_data.as_slice());
        /// ```
        ///
        pub fn encrypt(
            pub_key: &RsaPublicKey,
            data: &[u8],
        ) -> std::result::Result<Vec<u8>, String> {
            let mut rng = rand::thread_rng();
            pub_key
                .encrypt(&mut rng, Pkcs1v15Encrypt, data)
                .map_err(|e| format!("RSA encryption failed: {}", e))
        }

        ///RSA example
        ///```ignore
        ///let priv_key = doe::crypto::rsa::gen_priv_key(2048).unwrap();
        ///let pub_key = doe::crypto::rsa::gen_pub_key(&priv_key);
        ///let data = b"hello world";
        ///let enc_data = doe::crypto::rsa::encrypt(&pub_key, data).unwrap();
        ///let dec_data = doe::crypto::rsa::decrypt(&priv_key, &enc_data).unwrap();
        ///assert_eq!(data, dec_data.as_slice());
        /// ```
        ///
        pub fn decrypt(
            priv_key: &RsaPrivateKey,
            enc_data: &[u8],
        ) -> std::result::Result<Vec<u8>, String> {
            priv_key
                .decrypt(Pkcs1v15Encrypt, enc_data)
                .map_err(|e| format!("RSA decryption failed: {}", e))
        }
    }

    pub mod sha1 {
        pub use sha1::*;

        /// not secure
        /// ```ignore
        /// let hash = doe::crypto::sha1::sha1(b"hello world");
        /// println!("SHA1 hash: {}", hash);
        /// ```
        pub fn sha1(data: &[u8]) -> String {
            use sha1::{Digest, Sha1};
            let mut hasher = Sha1::new();
            hasher.update(data);
            let result = hasher.finalize();
            hex::encode(result)
        }
    }

    pub mod sha2 {
        pub use sha2::*;

        /// ```ignore
        /// let hash = doe::crypto::sha2::sha_224(b"hello world");
        /// println!("SHA224 hash: {}", hash);
        /// ```
        pub fn sha_224(data: &[u8]) -> String {
            use sha2::{Digest, Sha224};
            let mut hasher = Sha224::new();
            hasher.update(data);
            let result = hasher.finalize();
            hex::encode(result)
        }

        /// ```ignore
        /// let hash = doe::crypto::sha2::sha_256(b"hello world");
        /// println!("SHA256 hash: {}", hash);
        /// ```
        fn sha_256(data: &[u8]) -> String {
            use sha2::{Digest, Sha256};
            let mut hasher = Sha256::new();
            hasher.update(data);
            let result = hasher.finalize();
            hex::encode(result)
        }

        /// ```ignore
        /// let hash = doe::crypto::sha2::sha_512_224(b"hello world");
        /// println!("SHA512/224 hash: {}", hash);
        /// ```
        fn sha_512_224(data: &[u8]) -> String {
            use sha2::{Digest, Sha512_224};
            let mut hasher = Sha512_224::new();
            hasher.update(data);
            let result = hasher.finalize();
            hex::encode(result)
        }

        /// ```ignore
        /// let hash = doe::crypto::sha2::sha_512_256(b"hello world");
        /// println!("SHA512/256 hash: {}", hash);
        /// ```
        fn sha_512_256(data: &[u8]) -> String {
            use sha2::{Digest, Sha512_256};
            let mut hasher = Sha512_256::new();
            hasher.update(data);
            let result = hasher.finalize();
            hex::encode(result)
        }

        /// ```ignore
        /// let hash = doe::crypto::sha2::sha_384(b"hello world");
        /// println!("SHA384 hash: {}", hash);
        /// ```
        fn sha_384(data: &[u8]) -> String {
            use sha2::{Digest, Sha384};
            let mut hasher = Sha384::new();
            hasher.update(data);
            let result = hasher.finalize();
            hex::encode(result)
        }

        /// ```ignore
        /// let hash = doe::crypto::sha2::sha_512(b"hello world");
        /// println!("SHA512 hash: {}", hash);
        /// ```
        pub fn sha_512(data: &[u8]) -> String {
            use sha2::{Digest, Sha512};
            let mut hasher = Sha512::new();
            hasher.update(data);
            let result = hasher.finalize().to_vec();
            hex::encode_upper(result)
        }
    }

    pub mod sha3 {
        pub use sha3::*;
        /// ```ignore
        /// let hash = doe::crypto::sha3::sha_224(b"hello world");
        /// println!("SHA3-224 hash: {}", hash);
        /// ```
        pub fn sha_224(data: &[u8]) -> String {
            use sha3::{Digest, Sha3_224};
            let mut hasher = Sha3_224::new();
            hasher.update(data);
            let result = hasher.finalize().to_vec();
            hex::encode_upper(result)
        }

        /// ```ignore
        /// let hash = doe::crypto::sha3::sha_256(b"hello world");
        /// println!("SHA3-256 hash: {}", hash);
        /// ```
        pub fn sha_256(data: &[u8]) -> String {
            use sha3::{Digest, Sha3_256};
            let mut hasher = Sha3_256::new();
            hasher.update(data);
            let result = hasher.finalize().to_vec();
            hex::encode_upper(result)
        }

        /// ```ignore
        /// let hash = doe::crypto::sha3::sha_384(b"hello world");
        /// println!("SHA3-384 hash: {}", hash);
        /// ```
        pub fn sha_384(data: &[u8]) -> String {
            use sha3::{Digest, Sha3_384};
            let mut hasher = Sha3_384::new();
            hasher.update(data);
            let result = hasher.finalize().to_vec();
            hex::encode_upper(result)
        }

        /// ```ignore
        /// let hash = doe::crypto::sha3::sha_512(b"hello world");
        /// println!("SHA3-512 hash: {}", hash);
        /// ```
        pub fn sha_512(data: &[u8]) -> String {
            use sha3::{Digest, Sha3_512};
            let mut hasher = Sha3_512::new();
            hasher.update(data);
            let result = hasher.finalize().to_vec();
            hex::encode_upper(result)
        }

        /// ```ignore
        /// let hash = doe::crypto::sha3::shake_128(b"hello world");
        /// println!("SHAKE128 hash: {}", hash);
        /// ```
        pub fn shake_128(data: &[u8]) -> String {
            use sha3::{
                digest::{ExtendableOutput, Update, XofReader},
                Shake128,
            };
            let mut hasher = Shake128::default();
            hasher.update(data);
            let mut reader = hasher.finalize_xof();
            // 128 bytes of output
            let mut result = [0u8; 128];
            reader.read(&mut result);
            hex::encode_upper(result)
        }

        /// ```ignore
        /// let hash = doe::crypto::sha3::shake_256(b"hello world");
        /// println!("SHAKE256 hash: {}", hash);
        /// ```
        pub fn shake_256(data: &[u8]) -> String {
            use sha3::{
                digest::{ExtendableOutput, Update, XofReader},
                Shake256,
            };
            let mut hasher = Shake256::default();
            hasher.update(data);
            let mut reader = hasher.finalize_xof();
            // 256 bytes of output
            let mut result = [0u8; 256];
            reader.read(&mut result);
            hex::encode_upper(result)
        }
    }

    pub mod sm {
        pub use sm_crypto::*;
        /// SM3 哈希算法 (中国国密散列算法标准)
        ///
        /// 返回小写 16 进制字符串
        /// ```ignore
        /// let hash = doe::crypto::sm::sm3_hash(b"abc");
        /// assert_eq!(hash, "66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0");
        /// ```
        pub fn sm3_hash(data: &[u8]) -> String {
            sm_crypto::sm3::sm3_hash(data)
        }

        /// SM2 生成密钥对
        ///
        /// 返回 (私钥, 公钥)。公钥为 16 进制字符串，不含 "04" 前缀。
        /// ```ignore
        /// let (sk, pk) = doe::crypto::sm::sm2_gen_keypair();
        /// ```
        pub fn sm2_gen_keypair() -> (String, String) {
            sm_crypto::sm2::gen_keypair()
        }

        /// SM2 签名
        ///
        /// sk: 私钥 (16进制字符串)
        /// id: 是否使用默认 ID (默认为 "1234567812345678")
        /// ```ignore
        /// let (sk, _) = doe::crypto::sm::sm2_gen_keypair();
        /// let sign = doe::crypto::sm::sm2_sign(&sk, b"abc", true);
        /// ```
        pub fn sm2_sign(sk: &str, data: &[u8], id: bool) -> String {
            let sign_ctx = sm_crypto::sm2::Sign::new(sk);
            use num_bigint::BigUint;
            fn to_fixed_bytes(num: &BigUint, len: usize) -> Vec<u8> {
                let bytes = num.to_bytes_be(); // 大端字节
                if bytes.len() >= len {
                    // 如果字节数超过所需长度，取最后 len 个字节（通常不会发生，但安全起见）
                    bytes[bytes.len() - len..].to_vec()
                } else {
                    // 前面补零
                    let mut padded = vec![0u8; len - bytes.len()];
                    padded.extend_from_slice(&bytes);
                    padded
                }
            }
            let (r, s): (BigUint, BigUint) = sign_ctx.sign(data, id);
            // 将 r 和 s 转为固定 32 字节的大端字节数组（不足补零）
            let r_bytes = to_fixed_bytes(&r, 32);
            let s_bytes = to_fixed_bytes(&s, 32);

            // 拼接 r + s 得到完整签名（64 字节）
            let mut signature = Vec::with_capacity(64);
            signature.extend_from_slice(&r_bytes);
            signature.extend_from_slice(&s_bytes);

            // 转为 hex 字符串
            let hex_sig = hex::encode(&signature);
            hex_sig
        }

        /// SM2 验签
        ///
        /// pk: 公钥 (16进制字符串，不带04前缀)
        /// ```ignore
        /// let (_, pk) = doe::crypto::sm::sm2_gen_keypair();
        /// let verify = doe::crypto::sm::sm2_verify(&pk, b"abc", &sign, true);
        /// ```
        use num_bigint::BigUint;
        use sm_crypto::sm2::Verify;

        pub fn sm2_verify(pk: &str, data: &[u8], sign: &str, id: bool) -> bool {
            // 1. 将签名hex字符串转换为 (BigUint, BigUint)
            let sig_bytes = hex::decode(sign).expect("Invalid hex signature");
            let (r, s) = (
                BigUint::from_bytes_be(&sig_bytes[0..32]),
                BigUint::from_bytes_be(&sig_bytes[32..64]),
            );

            // 2. 创建验签上下文并执行验签
            let verify_ctx = sm_crypto::sm2::Verify::new(pk);
            verify_ctx.verify(data, (r, s), id) // id 参数现在是 bool 类型
        }

        /// SM2 加密
        ///
        /// pk: 公钥 (16进制字符串，不带04前缀)
        /// ```ignore
        /// let (_, pk) = doe::crypto::sm::sm2_gen_keypair();
        /// let enc = doe::crypto::sm::sm2_encrypt(&pk, b"abc").unwrap();
        /// ```
        pub fn sm2_encrypt(pk: &str, data: &[u8]) -> Result<Vec<u8>, String> {
            let enc_ctx = sm_crypto::sm2::Encrypt::new(pk);
            Ok(enc_ctx.encrypt(data))
        }

        /// SM2 解密
        ///
        /// sk: 私钥 (16进制字符串)
        /// ```ignore
        /// let (sk, _) = doe::crypto::sm::sm2_gen_keypair();
        /// let dec = doe::crypto::sm::sm2_decrypt(&sk, &enc).unwrap();
        /// ```
        pub fn sm2_decrypt(sk: &str, data: &[u8]) -> Result<Vec<u8>, String> {
            let dec_ctx = sm_crypto::sm2::Decrypt::new(sk);
            // sm_crypto 的 decrypt 方法本身返回 Vec<u8>，内部如果失败可能会 panic
            // 这里包一层 Result 以保持 API 风格统一
            Ok(dec_ctx.decrypt(data))
        }

        /// SM4 ECB 模式加密
        ///
        /// key 必须为 16 字节
        /// 内部自动处理 PKCS7 填充
        /// ```ignore
        /// let key = b"1234567812345678";
        /// let enc = doe::crypto::sm::sm4_ecb_encrypt(key, b"abc").unwrap();
        /// ```
        pub fn sm4_ecb_encrypt(key: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
            if key.len() != 16 {
                return Err("SM4 key must be 16 bytes".to_string());
            }
            let sm4_ecb = sm_crypto::sm4::CryptSM4ECB::new(key);
            Ok(sm4_ecb.encrypt_ecb(data))
        }

        /// SM4 ECB 模式解密
        ///
        /// key 必须为 16 字节
        /// ```ignore
        /// let key = b"1234567812345678";
        /// let dec = doe::crypto::sm::sm4_ecb_decrypt(key, &enc).unwrap();
        /// ```
        pub fn sm4_ecb_decrypt(key: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
            if key.len() != 16 {
                return Err("SM4 key must be 16 bytes".to_string());
            }
            let sm4_ecb = sm_crypto::sm4::CryptSM4ECB::new(key);
            Ok(sm4_ecb.decrypt_ecb(data))
        }

        /// SM4 CBC 模式加密
        ///
        /// key 必须为 16 字节
        /// iv 必须为 16 字节
        /// 内部自动处理 PKCS7 填充
        /// ```ignore
        /// let key = b"1234567812345678";
        /// let iv = b"0000000000000000";
        /// let enc = doe::crypto::sm::sm4_cbc_encrypt(key, iv, b"abc").unwrap();
        /// ```
        pub fn sm4_cbc_encrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
            if key.len() != 16 {
                return Err("SM4 key must be 16 bytes".to_string());
            }
            if iv.len() != 16 {
                return Err("SM4 IV must be 16 bytes".to_string());
            }
            let sm4_cbc = sm_crypto::sm4::CryptSM4CBC::new(key, iv);
            Ok(sm4_cbc.encrypt_cbc(data))
        }

        /// SM4 CBC 模式解密
        ///
        /// key 必须为 16 字节
        /// iv 必须为 16 字节
        /// ```ignore
        /// let key = b"1234567812345678";
        /// let iv = b"0000000000000000";
        /// let dec = doe::crypto::sm::sm4_cbc_decrypt(key, iv, &enc).unwrap();
        /// ```
        pub fn sm4_cbc_decrypt(key: &[u8], iv: &[u8], data: &[u8]) -> Result<Vec<u8>, String> {
            if key.len() != 16 {
                return Err("SM4 key must be 16 bytes".to_string());
            }
            if iv.len() != 16 {
                return Err("SM4 IV must be 16 bytes".to_string());
            }
            let sm4_cbc = sm_crypto::sm4::CryptSM4CBC::new(key, iv);
            Ok(sm4_cbc.decrypt_cbc(data))
        }
    }

    /// ```ignore
    /// let hash = doe::crypto::md5(b"hello world");
    /// println!("MD5 hash: {}", hash);
    /// ```
    pub fn md5(data: &[u8]) -> String {
        use md5::compute;
        let result = compute(data);
        result
            .to_vec()
            .iter()
            .map(|x| format!("{:02x}", x))
            .collect::<String>()
    }

    /// in defalut 32 bytes
    /// ```ignore
    /// let hash = doe::crypto::blake3(b"hello world");
    /// println!("BLAKE3 hash: {}", hash);
    /// ```
    pub fn blake3(data: &[u8]) -> String {
        let hasher = blake3::hash(data);
        hex::encode_upper(hasher.as_bytes())
    }

    /// can set the output size
    /// ```ignore
    /// let hash = doe::crypto::blake3_xof(b"hello world", 64);
    /// println!("BLAKE3 XOF hash: {}", hash);
    /// ```
    pub fn blake3_xof(data: &[u8], size: usize) -> String {
        let hasher = blake3::Hasher::new();
        let mut reader = hasher.finalize_xof();
        let mut result = vec![0u8; size];
        reader.fill(&mut result);
        hex::encode_upper(result)
    }
}

#[cfg(feature = "crypto")]
pub use crypto::*;
