Skip to content

Ghidrust provides a hyper fast, AI native reverse engineering platform built in Rust, inspired by Ghidra. Includes experimental GPU kernels to rapidly decompile large files, a decryption suite, and network monitor for packet to binary reverse engineering.

19.5 KB
Raw Blame
//! Scan image bytes for well-known cryptographic constant tables.

use super::AnalyzerOutput;
use crate::edits::CommentKind;
use crate::error::Result;
use crate::program::{Program, ReferenceInfo};
use serde::{Deserialize, Serialize};

/// One constant-table hit in the loaded image.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CryptConstantHit {
    pub va: u64,
    pub algorithm: String,
    pub constant: String,
    pub size: usize,
}

struct Pattern {
    algorithm: &'static str,
    constant: &'static str,
    bytes: &'static [u8],
}

/// Forward AES S-box (256 bytes).
const AES_SBOX: [u8; 256] = [
    0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
    0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
    0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
    0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
    0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
    0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
    0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
    0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
    0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
    0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
    0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
    0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
    0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
    0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
    0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
    0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16,
];

/// Inverse AES S-box (first 64 bytes — distinctive enough for scanning).
const AES_INV_SBOX_PREFIX: [u8; 64] = [
    0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
    0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
    0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
    0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
];

/// TEA / XTEA delta 0x9E3779B9 (LE).
const TEA_DELTA: [u8; 4] = [0xb9, 0x79, 0x37, 0x9e];

/// MD5 init state words (LE).
const MD5_INIT: [u8; 16] = [
    0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10,
];

/// SHA-256 first eight K constants (BE words as bytes).
const SHA256_K_PREFIX: [u8; 32] = [
    0x42, 0x8a, 0x2f, 0x98, 0x71, 0x37, 0x44, 0x91, 0xb5, 0xc0, 0xfb, 0xcf, 0xe9, 0xb5, 0xdb, 0xa5,
    0x39, 0x56, 0xc2, 0x5b, 0x59, 0xf1, 0x11, 0xf1, 0x92, 0x3f, 0x82, 0xa4, 0xab, 0x1c, 0x5e, 0xd5,
];

/// ChaCha20 / Salsa20 "expand 32-byte k" sigma ASCII.
const CHACHA_SIGMA: &[u8] = b"expand 32-byte k";

/// Blowfish P-array first 8 words (BE).
const BLOWFISH_P_PREFIX: [u8; 32] = [
    0x24, 0x3f, 0x6a, 0x88, 0x85, 0xa3, 0x08, 0xd3, 0x13, 0x19, 0x8a, 0x2e, 0x03, 0x70, 0x73, 0x44,
    0xa4, 0x09, 0x38, 0x22, 0x29, 0x9f, 0x31, 0xd0, 0x08, 0x2e, 0xfa, 0x98, 0xec, 0x4e, 0x6c, 0x89,
];

/// CRC32 IEEE polynomial reflected table first 16 entries.
const CRC32_TAB_PREFIX: [u8; 64] = [
    0x00, 0x00, 0x00, 0x00, 0x96, 0x30, 0x07, 0x77, 0x2c, 0x61, 0x0e, 0xee, 0xba, 0x51, 0x09, 0x99,
    0x19, 0xc4, 0x6d, 0x07, 0x8f, 0xf4, 0x6a, 0x70, 0x35, 0xa5, 0x63, 0xe9, 0xa3, 0x95, 0x64, 0x9e,
    0x32, 0x88, 0xdb, 0x0e, 0xa4, 0xb8, 0xdc, 0x79, 0x1e, 0xe9, 0xd5, 0xe0, 0x88, 0xd9, 0xd2, 0x97,
    0x2b, 0x4c, 0xb6, 0x09, 0xbd, 0x7c, 0xb1, 0x7e, 0x07, 0x2d, 0xb8, 0xe7, 0x91, 0x1d, 0xbf, 0x90,
];

/// SHA-1 initial hash words (BE).
const SHA1_INIT: [u8; 20] = [
    0x67, 0x45, 0x23, 0x01, 0xef, 0xcd, 0xab, 0x89, 0x98, 0xba, 0xdc, 0xfe, 0x10, 0x32, 0x54, 0x76,
    0xc3, 0xd2, 0xe1, 0xf0,
];

/// RC5 magic P32/Q32 (LE).
const RC5_PQ: [u8; 8] = [0x63, 0xb1, 0xe1, 0xb7, 0xb9, 0x79, 0x37, 0x9e];

/// DES S-box S1 first row (distinctive).
const DES_S1_ROW0: [u8; 16] = [14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7];

/// Salsa20 tau "expand 16-byte k".
const SALSA_TAU: &[u8] = b"expand 16-byte k";

/// Camellia sigma0 (first 8 bytes of key schedule constant).
const CAMELLIA_SIGMA0: [u8; 8] = [0xa0, 0x9e, 0x66, 0x7f, 0x3b, 0xcc, 0x90, 0x8b];

/// SM4 S-box prefix.
const SM4_SBOX_PREFIX: [u8; 32] = [
    0xd6, 0x90, 0xe9, 0xfe, 0xcc, 0xe1, 0x3d, 0xb7, 0x16, 0xb6, 0x14, 0xc2, 0x28, 0xfb, 0x2c, 0x05,
    0x2b, 0x67, 0x9a, 0x76, 0x2a, 0xbe, 0x04, 0xc3, 0xaa, 0x44, 0x13, 0x26, 0x49, 0x86, 0x06, 0x99,
];

/// zlib length code base table prefix (compression-adjacent).
const ZLIB_LEN_BASE_PREFIX: [u8; 16] = [
    0x03, 0x00, 0x04, 0x00, 0x05, 0x00, 0x06, 0x00, 0x07, 0x00, 0x08, 0x00, 0x09, 0x00, 0x0a, 0x00,
];

/// AES Te0 first four entries (big-endian word table prefix).
const AES_TE0_PREFIX: [u8; 16] = [
    0xc6, 0x63, 0x63, 0xa5, 0xf8, 0x7c, 0x7c, 0x84, 0xee, 0x77, 0x77, 0x99, 0xf6, 0x7b, 0x7b, 0x8d,
];

/// AES Te1 through Te3 first four entries (big-endian word table prefixes).
const AES_TE1_PREFIX: [u8; 16] = [
    0xa5, 0xc6, 0x63, 0x63, 0x84, 0xf8, 0x7c, 0x7c, 0x99, 0xee, 0x77, 0x77, 0x8d, 0xf6, 0x7b, 0x7b,
];
const AES_TE2_PREFIX: [u8; 16] = [
    0x63, 0xa5, 0xc6, 0x63, 0x7c, 0x84, 0xf8, 0x7c, 0x77, 0x99, 0xee, 0x77, 0x7b, 0x8d, 0xf6, 0x7b,
];
const AES_TE3_PREFIX: [u8; 16] = [
    0x63, 0x63, 0xa5, 0xc6, 0x7c, 0x7c, 0x84, 0xf8, 0x77, 0x77, 0x99, 0xee, 0x7b, 0x7b, 0x8d, 0xf6,
];

/// AES Td0 through Td3 first four entries (big-endian word table prefixes).
const AES_TD0_PREFIX: [u8; 16] = [
    0x51, 0xf4, 0xa7, 0x50, 0x7e, 0x41, 0x65, 0x53, 0x1a, 0x17, 0xa4, 0xc3, 0x3a, 0x27, 0x5e, 0x96,
];
const AES_TD1_PREFIX: [u8; 16] = [
    0x50, 0x51, 0xf4, 0xa7, 0x53, 0x7e, 0x41, 0x65, 0xc3, 0x1a, 0x17, 0xa4, 0x96, 0x3a, 0x27, 0x5e,
];
const AES_TD2_PREFIX: [u8; 16] = [
    0xa7, 0x50, 0x51, 0xf4, 0x65, 0x53, 0x7e, 0x41, 0xa4, 0xc3, 0x1a, 0x17, 0x5e, 0x96, 0x3a, 0x27,
];
const AES_TD3_PREFIX: [u8; 16] = [
    0xf4, 0xa7, 0x50, 0x51, 0x41, 0x65, 0x53, 0x7e, 0x17, 0xa4, 0xc3, 0x1a, 0x27, 0x5e, 0x96, 0x3a,
];

/// Blowfish S-boxes S0 and S1 first eight words (big-endian).
const BLOWFISH_S0_PREFIX: [u8; 32] = [
    0xd1, 0x31, 0x0b, 0xa6, 0x98, 0xdf, 0xb5, 0xac, 0x2f, 0xfd, 0x72, 0xdb, 0xd0, 0x1a, 0xdf, 0xb7,
    0xb8, 0xe1, 0xaf, 0xed, 0x6a, 0x26, 0x7e, 0x96, 0xba, 0x7c, 0x90, 0x45, 0xf1, 0x2c, 0x7f, 0x99,
];
const BLOWFISH_S1_PREFIX: [u8; 32] = [
    0x4b, 0x7a, 0x70, 0xe9, 0xb5, 0xb3, 0x29, 0x44, 0xdb, 0x75, 0x09, 0x2e, 0xc4, 0x19, 0x26, 0x23,
    0xad, 0x6e, 0xa6, 0xb0, 0x49, 0xa7, 0xdf, 0x7d, 0x9c, 0xee, 0x60, 0xb8, 0x8f, 0xed, 0xb2, 0x66,
];

/// DES initial permutation table.
const DES_IP: [u8; 64] = [
    58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6,
    64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61,
    53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7,
];

/// SHA-512 initial state and first four round constants (big-endian).
const SHA512_INIT: [u8; 64] = [
    0x6a, 0x09, 0xe6, 0x67, 0xf3, 0xbc, 0xc9, 0x08, 0xbb, 0x67, 0xae, 0x85, 0x84, 0xca, 0xa7, 0x3b,
    0x3c, 0x6e, 0xf3, 0x72, 0xfe, 0x94, 0xf8, 0x2b, 0xa5, 0x4f, 0xf5, 0x3a, 0x5f, 0x1d, 0x36, 0xf1,
    0x51, 0x0e, 0x52, 0x7f, 0xad, 0xe6, 0x82, 0xd1, 0x9b, 0x05, 0x68, 0x8c, 0x2b, 0x3e, 0x6c, 0x1f,
    0x1f, 0x83, 0xd9, 0xab, 0xfb, 0x41, 0xbd, 0x6b, 0x5b, 0xe0, 0xcd, 0x19, 0x13, 0x7e, 0x21, 0x79,
];
const SHA512_K_PREFIX: [u8; 32] = [
    0x42, 0x8a, 0x2f, 0x98, 0xd7, 0x28, 0xae, 0x22, 0x71, 0x37, 0x44, 0x91, 0x23, 0xef, 0x65, 0xcd,
    0xb5, 0xc0, 0xfb, 0xcf, 0xec, 0x4d, 0x3b, 0x2f, 0xe9, 0xb5, 0xdb, 0xa5, 0x81, 0x89, 0xdb, 0xbc,
];

/// MD2 substitution table prefix.
const MD2_S_PREFIX: [u8; 32] = [
    0x29, 0x2e, 0x43, 0xc9, 0xa2, 0xd8, 0x7c, 0x01, 0x3d, 0x36, 0x54, 0xa1, 0xec, 0xf0, 0x06, 0x13,
    0x62, 0xa7, 0x05, 0xf3, 0xc0, 0xc7, 0x73, 0x8c, 0x98, 0x93, 0x2b, 0xd9, 0xbc, 0x4c, 0x82, 0xca,
];

/// Twofish q0 permutation table prefix.
const TWOFISH_Q0_PREFIX: [u8; 32] = [
    0xa9, 0x67, 0xb3, 0xe8, 0x04, 0xfd, 0xa3, 0x76, 0x9a, 0x92, 0x80, 0x78, 0xe4, 0xdd, 0xd1, 0x38,
    0x0d, 0xc6, 0x35, 0x98, 0x18, 0xf7, 0xec, 0x6c, 0x43, 0x75, 0x37, 0x26, 0xfa, 0x13, 0x94, 0x48,
];

/// SM4 fixed key words and round-constant prefix (big-endian).
const SM4_FK: [u8; 16] = [
    0xa3, 0xb1, 0xba, 0xc6, 0x56, 0xaa, 0x33, 0x50, 0x67, 0x7d, 0x91, 0x97, 0xb2, 0x70, 0x22, 0xdc,
];
const SM4_CK_PREFIX: [u8; 32] = [
    0x00, 0x07, 0x0e, 0x15, 0x1c, 0x23, 0x2a, 0x31, 0x38, 0x3f, 0x46, 0x4d, 0x54, 0x5b, 0x62, 0x69,
    0x70, 0x77, 0x7e, 0x85, 0x8c, 0x93, 0x9a, 0xa1, 0xa8, 0xaf, 0xb6, 0xbd, 0xc4, 0xcb, 0xd2, 0xd9,
];

/// Camellia S-box and key-schedule constant prefixes.
const CAMELLIA_SBOX1_PREFIX: [u8; 32] = [
    0x70, 0x82, 0x2c, 0xec, 0xb3, 0x27, 0xc0, 0xe5, 0xe4, 0x85, 0x57, 0x35, 0xea, 0x0c, 0xae, 0x41,
    0x23, 0xef, 0x6b, 0x93, 0x45, 0x19, 0xa5, 0x21, 0xed, 0x0e, 0x4f, 0x4e, 0x1d, 0x65, 0x92, 0xbd,
];
const CAMELLIA_SIGMA: [u8; 32] = [
    0xa0, 0x9e, 0x66, 0x7f, 0x3b, 0xcc, 0x90, 0x8b, 0xb6, 0x7a, 0xe8, 0x58, 0x4c, 0xaa, 0x73, 0xb2,
    0xc6, 0xef, 0x37, 0x2f, 0xe9, 0x4f, 0x82, 0xbe, 0x54, 0xff, 0x53, 0xa5, 0xf1, 0xd3, 0x6f, 0x1c,
];

/// Skipjack F-table prefix.
const SKIPJACK_FTABLE_PREFIX: [u8; 32] = [
    0xa3, 0xd7, 0x09, 0x83, 0xf8, 0x48, 0xf6, 0xf4, 0xd3, 0x8a, 0x39, 0xdb, 0x5a, 0x1f, 0x33, 0xab,
    0x77, 0xf1, 0x43, 0x68, 0xc8, 0xb6, 0x95, 0x25, 0x1c, 0x22, 0x94, 0x21, 0x80, 0x2d, 0xb0, 0xee,
];

fn patterns() -> &'static [Pattern] {
    &[
        Pattern {
            algorithm: "AES",
            constant: "SBOX",
            bytes: &AES_SBOX,
        },
        Pattern {
            algorithm: "AES",
            constant: "INV_SBOX_PREFIX",
            bytes: &AES_INV_SBOX_PREFIX,
        },
        Pattern {
            algorithm: "AES",
            constant: "TE0_PREFIX",
            bytes: &AES_TE0_PREFIX,
        },
        Pattern {
            algorithm: "AES",
            constant: "TE1_PREFIX",
            bytes: &AES_TE1_PREFIX,
        },
        Pattern {
            algorithm: "AES",
            constant: "TE2_PREFIX",
            bytes: &AES_TE2_PREFIX,
        },
        Pattern {
            algorithm: "AES",
            constant: "TE3_PREFIX",
            bytes: &AES_TE3_PREFIX,
        },
        Pattern {
            algorithm: "AES",
            constant: "TD0_PREFIX",
            bytes: &AES_TD0_PREFIX,
        },
        Pattern {
            algorithm: "AES",
            constant: "TD1_PREFIX",
            bytes: &AES_TD1_PREFIX,
        },
        Pattern {
            algorithm: "AES",
            constant: "TD2_PREFIX",
            bytes: &AES_TD2_PREFIX,
        },
        Pattern {
            algorithm: "AES",
            constant: "TD3_PREFIX",
            bytes: &AES_TD3_PREFIX,
        },
        Pattern {
            algorithm: "TEA",
            constant: "DELTA",
            bytes: &TEA_DELTA,
        },
        Pattern {
            algorithm: "MD5",
            constant: "INIT",
            bytes: &MD5_INIT,
        },
        Pattern {
            algorithm: "SHA1",
            constant: "INIT",
            bytes: &SHA1_INIT,
        },
        Pattern {
            algorithm: "SHA256",
            constant: "K_PREFIX",
            bytes: &SHA256_K_PREFIX,
        },
        Pattern {
            algorithm: "ChaCha20",
            constant: "SIGMA",
            bytes: CHACHA_SIGMA,
        },
        Pattern {
            algorithm: "Salsa20",
            constant: "TAU",
            bytes: SALSA_TAU,
        },
        Pattern {
            algorithm: "Blowfish",
            constant: "P_PREFIX",
            bytes: &BLOWFISH_P_PREFIX,
        },
        Pattern {
            algorithm: "Blowfish",
            constant: "S0_PREFIX",
            bytes: &BLOWFISH_S0_PREFIX,
        },
        Pattern {
            algorithm: "Blowfish",
            constant: "S1_PREFIX",
            bytes: &BLOWFISH_S1_PREFIX,
        },
        Pattern {
            algorithm: "CRC32",
            constant: "TAB_PREFIX",
            bytes: &CRC32_TAB_PREFIX,
        },
        Pattern {
            algorithm: "RC5",
            constant: "PQ",
            bytes: &RC5_PQ,
        },
        Pattern {
            algorithm: "DES",
            constant: "S1_ROW0",
            bytes: &DES_S1_ROW0,
        },
        Pattern {
            algorithm: "DES",
            constant: "IP",
            bytes: &DES_IP,
        },
        Pattern {
            algorithm: "SHA512",
            constant: "INIT",
            bytes: &SHA512_INIT,
        },
        Pattern {
            algorithm: "SHA512",
            constant: "K_PREFIX",
            bytes: &SHA512_K_PREFIX,
        },
        Pattern {
            algorithm: "MD2",
            constant: "S_PREFIX",
            bytes: &MD2_S_PREFIX,
        },
        Pattern {
            algorithm: "Twofish",
            constant: "Q0_PREFIX",
            bytes: &TWOFISH_Q0_PREFIX,
        },
        Pattern {
            algorithm: "Camellia",
            constant: "SIGMA0",
            bytes: &CAMELLIA_SIGMA0,
        },
        Pattern {
            algorithm: "Camellia",
            constant: "SBOX1_PREFIX",
            bytes: &CAMELLIA_SBOX1_PREFIX,
        },
        Pattern {
            algorithm: "Camellia",
            constant: "SIGMA",
            bytes: &CAMELLIA_SIGMA,
        },
        Pattern {
            algorithm: "SM4",
            constant: "SBOX_PREFIX",
            bytes: &SM4_SBOX_PREFIX,
        },
        Pattern {
            algorithm: "SM4",
            constant: "FK",
            bytes: &SM4_FK,
        },
        Pattern {
            algorithm: "SM4",
            constant: "CK_PREFIX",
            bytes: &SM4_CK_PREFIX,
        },
        Pattern {
            algorithm: "Skipjack",
            constant: "FTABLE_PREFIX",
            bytes: &SKIPJACK_FTABLE_PREFIX,
        },
        Pattern {
            algorithm: "zlib",
            constant: "LEN_BASE_PREFIX",
            bytes: &ZLIB_LEN_BASE_PREFIX,
        },
    ]
}

/// Scan all memory blocks for cryptographic constant tables.
pub fn scan_crypt_constants(prog: &Program) -> Vec<CryptConstantHit> {
    let mut hits = Vec::new();
    for block in &prog.blocks {
        let data = &block.bytes;
        for pat in patterns() {
            if pat.bytes.len() < 4 {
                continue;
            }
            let mut start = 0usize;
            while let Some(rel) = find_subslice(&data[start..], pat.bytes) {
                let off = start + rel;
                hits.push(CryptConstantHit {
                    va: block.va + off as u64,
                    algorithm: pat.algorithm.into(),
                    constant: pat.constant.into(),
                    size: pat.bytes.len(),
                });
                start = off + 1;
                if hits.len() >= 10_000 {
                    return hits;
                }
            }
        }
    }
    hits
}

fn find_subslice(hay: &[u8], needle: &[u8]) -> Option<usize> {
    if needle.is_empty() || hay.len() < needle.len() {
        return None;
    }
    hay.windows(needle.len()).position(|w| w == needle)
}

pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {
    let hits = scan_crypt_constants(prog);
    let n = hits.len();
    prog.analysis.crypt_constants = hits.clone();
    // Annotate symbols, EOL comments, and xrefs from code → constant (seed Phase 2/4).
    for h in &hits {
        let name = format!("CRYPT_{}_{}", h.algorithm, h.constant);
        if !prog
            .analysis
            .symbols
            .iter()
            .any(|s| s.va == h.va && s.name == name)
        {
            prog.analysis.symbols.push(crate::program::SymbolInfo {
                va: h.va,
                name,
                demangled: None,
            });
        }
        let comment = format!("CRYPT {} {} ({} bytes)", h.algorithm, h.constant, h.size);
        prog.edits.set_comment(h.va, CommentKind::Eol, comment);
        for xref in crate::xrefs::xrefs_to(prog, h.va, None) {
            let exists = prog
                .analysis
                .references
                .iter()
                .any(|r| r.from == xref.from && r.to == xref.to && r.kind == "crypt_const");
            if !exists {
                prog.analysis.references.push(ReferenceInfo {
                    from: xref.from,
                    to: xref.to,
                    kind: "crypt_const".into(),
                });
            }
        }
    }
    Ok(AnalyzerOutput {
        name: "Find Crypt".into(),
        status: "ok".into(),
        message: format!("found {n} cryptographic constant hit(s)"),
        crypt_constants: Some(hits),
        ..Default::default()
    })
}

/// Function / site VAs that reference cryptographic constants (decoder seeds).
pub fn crypt_xref_seed_vas(prog: &Program) -> Vec<u64> {
    let mut out: Vec<u64> = prog
        .analysis
        .references
        .iter()
        .filter(|r| r.kind == "crypt_const")
        .map(|r| r.from)
        .collect();
    out.sort_unstable();
    out.dedup();
    out
}

/// Public AES S-box for recipe decrypt.
pub fn aes_sbox() -> &'static [u8; 256] {
    &AES_SBOX
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::program::{MemoryBlock, Program};

    #[test]
    fn finds_aes_sbox_in_block() {
        let mut prog = Program::new("t".into(), "raw");
        let mut bytes = vec![0u8; 32];
        bytes.extend_from_slice(&AES_SBOX);
        prog.blocks.push(MemoryBlock {
            name: ".rdata".into(),
            va: 0x1000,
            size: bytes.len() as u64,
            bytes,
            readable: true,
            writable: false,
            executable: false,
        });
        let hits = scan_crypt_constants(&prog);
        assert!(hits
            .iter()
            .any(|h| h.algorithm == "AES" && h.constant == "SBOX"));
        assert_eq!(
            hits.iter().find(|h| h.constant == "SBOX").unwrap().va,
            0x1020
        );
    }

    #[test]
    fn finds_tea_delta_and_new_algorithm_tables() {
        let mut prog = Program::new("t".into(), "raw");
        let mut bytes = Vec::new();
        bytes.extend_from_slice(&TEA_DELTA);
        bytes.extend_from_slice(&[0u8; 7]);
        bytes.extend_from_slice(&SHA512_K_PREFIX);
        bytes.extend_from_slice(&[0u8; 11]);
        bytes.extend_from_slice(&TWOFISH_Q0_PREFIX);
        bytes.extend_from_slice(&[0u8; 13]);
        bytes.extend_from_slice(&SM4_FK);
        prog.blocks.push(MemoryBlock {
            name: ".rdata".into(),
            va: 0x2000,
            size: bytes.len() as u64,
            bytes,
            readable: true,
            writable: false,
            executable: false,
        });

        let hits = scan_crypt_constants(&prog);
        assert!(hits
            .iter()
            .any(|h| h.algorithm == "TEA" && h.constant == "DELTA"));
        assert!(hits
            .iter()
            .any(|h| h.algorithm == "SHA512" && h.constant == "K_PREFIX"));
        assert!(hits
            .iter()
            .any(|h| h.algorithm == "Twofish" && h.constant == "Q0_PREFIX"));
        assert!(hits
            .iter()
            .any(|h| h.algorithm == "SM4" && h.constant == "FK"));
    }
}