/**
 * AES 加密工具
 * 使用 AES-128-CBC 模式，PKCS7/PKCS5 填充
 */

// 加密密钥和 IV（与后端保持一致）
const KEY_STR = 'richwaykey000000'
const IV_STR = 'richway-iv000000'

/**
 * AES 加密
 * @param word 需要加密的字符串
 * @returns 加密后的 Base64 字符串
 */
export const encryptAES = (word: string): string => {
    // #ifdef APP-ANDROID
    return encryptAESAndroid(word, KEY_STR, IV_STR)
    // #endif
    
    // #ifdef APP-HARMONY
    return encryptAESHarmony(word, KEY_STR, IV_STR)
    // #endif
    
    // #ifdef WEB
    return encryptAESWeb(word, KEY_STR, IV_STR)
    // #endif
    
    // #ifndef APP-ANDROID || APP-HARMONY || WEB
    // 其他平台暂时返回原文
    console.warn('当前平台暂不支持 AES 加密，返回原文')
    return word
    // #endif
}

/**
 * AES 解密
 * @param word 需要解密的 Base64 字符串
 * @returns 解密后的字符串
 */
export const decryptAES = (word: string): string => {
    // #ifdef APP-ANDROID
    return decryptAESAndroid(word, KEY_STR, IV_STR)
    // #endif
    
    // #ifdef APP-HARMONY
    return decryptAESHarmony(word, KEY_STR, IV_STR)
    // #endif
    
    // #ifdef WEB
    return decryptAESWeb(word, KEY_STR, IV_STR)
    // #endif
    
    // #ifndef APP-ANDROID || APP-HARMONY || WEB
    // 其他平台暂时返回原文
    console.warn('当前平台暂不支持 AES 解密，返回原文')
    return word
    // #endif
}

// Android 平台实现（使用条件编译）
// #ifdef APP-ANDROID

/**
 * Android 平台 AES 加密实现
 */
function encryptAESAndroid(plainText: string, keyStr: string, ivStr: string): string {
    try {
        // 转换密钥和 IV 为字节数组
        const keyBytes = new java.lang.String(keyStr).getBytes("UTF-8")
        const ivBytes = new java.lang.String(ivStr).getBytes("UTF-8")
        
        // 创建密钥规范和 IV 规范
        const secretKeySpec = new javax.crypto.spec.SecretKeySpec(keyBytes, "AES")
        const ivParameterSpec = new javax.crypto.spec.IvParameterSpec(ivBytes)
        
        // 创建 Cipher 实例并初始化为加密模式
        // 注意：Java 中使用 PKCS5Padding，但在 AES 中它等同于 PKCS7Padding
        const cipher = javax.crypto.Cipher.getInstance("AES/CBC/PKCS5Padding")
        cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec)
        
        // 加密数据
        const plainBytes = new java.lang.String(plainText).getBytes("UTF-8")
        const encryptedBytes = cipher.doFinal(plainBytes)
        
        // 转为 Base64 字符串
        const base64Str = android.util.Base64.encodeToString(encryptedBytes, android.util.Base64.NO_WRAP)
        return base64Str.toString()
    } catch (e) {
        console.error('AES 加密失败', e)
        return plainText
    }
}

/**
 * Android 平台 AES 解密实现
 */
function decryptAESAndroid(cipherText: string, keyStr: string, ivStr: string): string {
    try {
        // 转换密钥和 IV 为字节数组
        const keyBytes = new java.lang.String(keyStr).getBytes("UTF-8")
        const ivBytes = new java.lang.String(ivStr).getBytes("UTF-8")
        
        // 创建密钥规范和 IV 规范
        const secretKeySpec = new javax.crypto.spec.SecretKeySpec(keyBytes, "AES")
        const ivParameterSpec = new javax.crypto.spec.IvParameterSpec(ivBytes)
        
        // 创建 Cipher 实例并初始化为解密模式
        // 注意：Java 中使用 PKCS5Padding，但在 AES 中它等同于 PKCS7Padding
        const cipher = javax.crypto.Cipher.getInstance("AES/CBC/PKCS5Padding")
        cipher.init(javax.crypto.Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec)
        
        // 解密数据
        const cipherBytes = android.util.Base64.decode(cipherText, android.util.Base64.NO_WRAP)
        const decryptedBytes = cipher.doFinal(cipherBytes)
        
        // 转为字符串
        const decryptedStr = new java.lang.String(decryptedBytes, "UTF-8")
        return decryptedStr.toString()
    } catch (e) {
        console.error('AES 解密失败', e)
        return cipherText
    }
}
// #endif

// 鸿蒙平台 AES 加密实现
// #ifdef APP-HARMONY

/**
 * 鸿蒙平台 AES 加密实现
 * 使用纯 TypeScript 实现 AES-128-CBC
 */
function encryptAESHarmony(plainText: string, keyStr: string, ivStr: string): string {
    try {
        return encryptAESPure(plainText, keyStr, ivStr)
    } catch (e) {
        console.error('AES 加密失败（鸿蒙）', e)
        return plainText
    }
}

/**
 * 鸿蒙平台 AES 解密实现
 */
function decryptAESHarmony(cipherText: string, keyStr: string, ivStr: string): string {
    try {
        return decryptAESPure(cipherText, keyStr, ivStr)
    } catch (e) {
        console.error('AES 解密失败（鸿蒙）', e)
        return cipherText
    }
}
// #endif

// Web 平台 AES 加密实现
// #ifdef WEB

/**
 * Web 平台 AES 加密实现
 * 使用纯 TypeScript 实现 AES-128-CBC
 */
function encryptAESWeb(plainText: string, keyStr: string, ivStr: string): string {
    try {
        return encryptAESPure(plainText, keyStr, ivStr)
    } catch (e) {
        console.error('加密失败（Web）', e)
        return plainText
    }
}

/**
 * Web 平台 AES 解密实现
 */
function decryptAESWeb(cipherText: string, keyStr: string, ivStr: string): string {
    try {
        return decryptAESPure(cipherText, keyStr, ivStr)
    } catch (e) {
        console.error('解密失败（Web）', e)
        return cipherText
    }
}
// #endif

// 纯 TypeScript 实现的 AES 加密（用于 Web 和鸿蒙平台）
// #ifndef APP-ANDROID

/**
 * 纯 TypeScript AES 加密实现（简化版 CryptoJS 逻辑）
 */
function encryptAESPure(plainText: string, keyStr: string, ivStr: string): string {
    // 将字符串转为字节数组
    const plainBytes = stringToBytes(plainText)
    const keyBytes = stringToBytes(keyStr)
    const ivBytes = stringToBytes(ivStr)
    
    // PKCS7 填充
    const paddedBytes = pkcs7Pad(plainBytes)
    
    // AES-CBC 加密
    const encryptedBytes = aesCBCEncrypt(paddedBytes, keyBytes, ivBytes)
    
    // 转为 Base64
    return bytesToBase64(encryptedBytes)
}

/**
 * 纯 TypeScript AES 解密实现
 */
function decryptAESPure(cipherText: string, keyStr: string, ivStr: string): string {
    // Base64 转字节数组
    const cipherBytes = base64ToBytes(cipherText)
    const keyBytes = stringToBytes(keyStr)
    const ivBytes = stringToBytes(ivStr)
    
    // AES-CBC 解密
    const decryptedBytes = aesCBCDecrypt(cipherBytes, keyBytes, ivBytes)
    
    // 去除 PKCS7 填充
    const unpaddedBytes = pkcs7Unpad(decryptedBytes)
    
    // 转为字符串
    return bytesToString(unpaddedBytes)
}

// ============ 辅助函数 ============

/**
 * 字符串转字节数组（UTF-8）
 */
function stringToBytes(str: string): number[] {
    const bytes: number[] = []
    for (let i = 0; i < str.length; i++) {
        const charCode = str.charCodeAt(i)
        if (charCode < 0x80) {
            bytes.push(charCode)
        } else if (charCode < 0x800) {
            bytes.push(0xc0 | (charCode >> 6))
            bytes.push(0x80 | (charCode & 0x3f))
        } else if (charCode < 0xd800 || charCode >= 0xe000) {
            bytes.push(0xe0 | (charCode >> 12))
            bytes.push(0x80 | ((charCode >> 6) & 0x3f))
            bytes.push(0x80 | (charCode & 0x3f))
        } else {
            // UTF-16 代理对
            i++
            const surrogate = 0x10000 + (((charCode & 0x3ff) << 10) | (str.charCodeAt(i) & 0x3ff))
            bytes.push(0xf0 | (surrogate >> 18))
            bytes.push(0x80 | ((surrogate >> 12) & 0x3f))
            bytes.push(0x80 | ((surrogate >> 6) & 0x3f))
            bytes.push(0x80 | (surrogate & 0x3f))
        }
    }
    return bytes
}

/**
 * 字节数组转字符串（UTF-8）
 */
function bytesToString(bytes: number[]): string {
    let str = ''
    let i = 0
    while (i < bytes.length) {
        const byte = bytes[i]
        if (byte < 0x80) {
            str += String.fromCharCode(byte)
            i++
        } else if (byte < 0xe0) {
            str += String.fromCharCode(((byte & 0x1f) << 6) | (bytes[i + 1] & 0x3f))
            i += 2
        } else if (byte < 0xf0) {
            str += String.fromCharCode(((byte & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f))
            i += 3
        } else {
            const codePoint = ((byte & 0x07) << 18) | ((bytes[i + 1] & 0x3f) << 12) | ((bytes[i + 2] & 0x3f) << 6) | (bytes[i + 3] & 0x3f)
            const surrogate = codePoint - 0x10000
            str += String.fromCharCode(0xd800 + (surrogate >> 10), 0xdc00 + (surrogate & 0x3ff))
            i += 4
        }
    }
    return str
}

/**
 * 字节数组转 Base64
 */
function bytesToBase64(bytes: number[]): string {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    let base64 = ''
    for (let i = 0; i < bytes.length; i += 3) {
        const byte1 = bytes[i]
        const byte2 = i + 1 < bytes.length ? bytes[i + 1] : 0
        const byte3 = i + 2 < bytes.length ? bytes[i + 2] : 0
        
        const enc1 = byte1 >> 2
        const enc2 = ((byte1 & 3) << 4) | (byte2 >> 4)
        const enc3 = ((byte2 & 15) << 2) | (byte3 >> 6)
        const enc4 = byte3 & 63
        
        base64 += chars.charAt(enc1) + chars.charAt(enc2)
        base64 += i + 1 < bytes.length ? chars.charAt(enc3) : '='
        base64 += i + 2 < bytes.length ? chars.charAt(enc4) : '='
    }
    return base64
}

/**
 * Base64 转字节数组
 */
function base64ToBytes(base64: string): number[] {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    const bytes: number[] = []
    
    for (let i = 0; i < base64.length; i += 4) {
        const enc1 = chars.indexOf(base64.charAt(i))
        const enc2 = chars.indexOf(base64.charAt(i + 1))
        const enc3 = chars.indexOf(base64.charAt(i + 2))
        const enc4 = chars.indexOf(base64.charAt(i + 3))
        
        const byte1 = (enc1 << 2) | (enc2 >> 4)
        const byte2 = ((enc2 & 15) << 4) | (enc3 >> 2)
        const byte3 = ((enc3 & 3) << 6) | enc4
        
        bytes.push(byte1)
        if (enc3 !== -1) bytes.push(byte2)
        if (enc4 !== -1) bytes.push(byte3)
    }
    
    return bytes
}

/**
 * PKCS7 填充
 */
function pkcs7Pad(bytes: number[]): number[] {
    const blockSize = 16
    const padding = blockSize - (bytes.length % blockSize)
    const paddedBytes = bytes.slice()
    for (let i = 0; i < padding; i++) {
        paddedBytes.push(padding)
    }
    return paddedBytes
}

/**
 * PKCS7 去填充
 */
function pkcs7Unpad(bytes: number[]): number[] {
    const padding = bytes[bytes.length - 1]
    return bytes.slice(0, bytes.length - padding)
}

/**
 * AES-CBC 加密
 */
function aesCBCEncrypt(plainBytes: number[], keyBytes: number[], ivBytes: number[]): number[] {
    const blocks = []
    const blockSize = 16
    let previousBlock = ivBytes.slice()
    
    // 扩展密钥
    const expandedKey = expandKey(keyBytes)
    
    // 分块加密
    for (let i = 0; i < plainBytes.length; i += blockSize) {
        const block = plainBytes.slice(i, i + blockSize)
        
        // CBC 模式：先与上一个密文块异或
        const xorBlock = xorBytes(block, previousBlock)
        
        // AES 加密
        const encryptedBlock = aesEncryptBlock(xorBlock, expandedKey)
        
        blocks.push(...encryptedBlock)
        previousBlock = encryptedBlock
    }
    
    return blocks
}

/**
 * AES-CBC 解密
 */
function aesCBCDecrypt(cipherBytes: number[], keyBytes: number[], ivBytes: number[]): number[] {
    const blocks = []
    const blockSize = 16
    let previousBlock = ivBytes.slice()
    
    // 扩展密钥
    const expandedKey = expandKey(keyBytes)
    
    // 分块解密
    for (let i = 0; i < cipherBytes.length; i += blockSize) {
        const block = cipherBytes.slice(i, i + blockSize)
        
        // AES 解密
        const decryptedBlock = aesDecryptBlock(block, expandedKey)
        
        // CBC 模式：再与上一个密文块异或
        const xorBlock = xorBytes(decryptedBlock, previousBlock)
        
        blocks.push(...xorBlock)
        previousBlock = block
    }
    
    return blocks
}

/**
 * 字节数组异或
 */
function xorBytes(a: number[], b: number[]): number[] {
    const result: number[] = []
    for (let i = 0; i < a.length; i++) {
        result.push(a[i] ^ b[i])
    }
    return result
}

/**
 * AES 密钥扩展
 */
function expandKey(key: number[]): number[][] {
    const Nk = 4  // 128-bit key
    const Nr = 10 // 10 rounds
    const w: number[][] = []
    
    // 初始化前 Nk 个字
    for (let i = 0; i < Nk; i++) {
        w[i] = [key[4 * i], key[4 * i + 1], key[4 * i + 2], key[4 * i + 3]]
    }
    
    // 扩展密钥
    for (let i = Nk; i < 4 * (Nr + 1); i++) {
        let temp = w[i - 1].slice()
        if (i % Nk === 0) {
            temp = xorWord(subWord(rotWord(temp)), rcon(i / Nk))
        }
        w[i] = xorWord(w[i - Nk], temp)
    }
    
    return w
}

/**
 * AES 加密单个块
 */
function aesEncryptBlock(block: number[], expandedKey: number[][]): number[] {
    const state = blockToState(block)
    const Nr = 10
    
    addRoundKey(state, expandedKey, 0)
    
    for (let round = 1; round < Nr; round++) {
        subBytes(state)
        shiftRows(state)
        mixColumns(state)
        addRoundKey(state, expandedKey, round)
    }
    
    subBytes(state)
    shiftRows(state)
    addRoundKey(state, expandedKey, Nr)
    
    return stateToBlock(state)
}

/**
 * AES 解密单个块
 */
function aesDecryptBlock(block: number[], expandedKey: number[][]): number[] {
    const state = blockToState(block)
    const Nr = 10
    
    addRoundKey(state, expandedKey, Nr)
    
    for (let round = Nr - 1; round > 0; round--) {
        invShiftRows(state)
        invSubBytes(state)
        addRoundKey(state, expandedKey, round)
        invMixColumns(state)
    }
    
    invShiftRows(state)
    invSubBytes(state)
    addRoundKey(state, expandedKey, 0)
    
    return stateToBlock(state)
}

// ============ AES 核心函数 ============

// S-box
const sbox = [
    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
]

// 逆 S-box
const invSbox = [
    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,
    0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
    0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
    0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
    0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
    0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
    0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
    0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
    0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
    0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
    0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
    0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
    0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d
]

// Rcon
const rcon_array = [0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]

function rcon(i: number): number[] {
    return [rcon_array[i], 0, 0, 0]
}

function rotWord(word: number[]): number[] {
    return [word[1], word[2], word[3], word[0]]
}

function subWord(word: number[]): number[] {
    return word.map(b => sbox[b])
}

function xorWord(a: number[], b: number[]): number[] {
    return [a[0] ^ b[0], a[1] ^ b[1], a[2] ^ b[2], a[3] ^ b[3]]
}

function blockToState(block: number[]): number[][] {
    const state: number[][] = []
    for (let i = 0; i < 4; i++) {
        state[i] = []
        for (let j = 0; j < 4; j++) {
            state[i][j] = block[i + 4 * j]
        }
    }
    return state
}

function stateToBlock(state: number[][]): number[] {
    const block: number[] = []
    for (let j = 0; j < 4; j++) {
        for (let i = 0; i < 4; i++) {
            block.push(state[i][j])
        }
    }
    return block
}

function addRoundKey(state: number[][], expandedKey: number[][], round: number): void {
    for (let i = 0; i < 4; i++) {
        for (let j = 0; j < 4; j++) {
            state[i][j] ^= expandedKey[round * 4 + j][i]
        }
    }
}

function subBytes(state: number[][]): void {
    for (let i = 0; i < 4; i++) {
        for (let j = 0; j < 4; j++) {
            state[i][j] = sbox[state[i][j]]
        }
    }
}

function invSubBytes(state: number[][]): void {
    for (let i = 0; i < 4; i++) {
        for (let j = 0; j < 4; j++) {
            state[i][j] = invSbox[state[i][j]]
        }
    }
}

function shiftRows(state: number[][]): void {
    let temp: number
    
    // Row 1: shift left by 1
    temp = state[1][0]
    state[1][0] = state[1][1]
    state[1][1] = state[1][2]
    state[1][2] = state[1][3]
    state[1][3] = temp
    
    // Row 2: shift left by 2
    temp = state[2][0]
    state[2][0] = state[2][2]
    state[2][2] = temp
    temp = state[2][1]
    state[2][1] = state[2][3]
    state[2][3] = temp
    
    // Row 3: shift left by 3 (or right by 1)
    temp = state[3][3]
    state[3][3] = state[3][2]
    state[3][2] = state[3][1]
    state[3][1] = state[3][0]
    state[3][0] = temp
}

function invShiftRows(state: number[][]): void {
    let temp: number
    
    // Row 1: shift right by 1
    temp = state[1][3]
    state[1][3] = state[1][2]
    state[1][2] = state[1][1]
    state[1][1] = state[1][0]
    state[1][0] = temp
    
    // Row 2: shift right by 2
    temp = state[2][0]
    state[2][0] = state[2][2]
    state[2][2] = temp
    temp = state[2][1]
    state[2][1] = state[2][3]
    state[2][3] = temp
    
    // Row 3: shift right by 3 (or left by 1)
    temp = state[3][0]
    state[3][0] = state[3][1]
    state[3][1] = state[3][2]
    state[3][2] = state[3][3]
    state[3][3] = temp
}

function mixColumns(state: number[][]): void {
    for (let j = 0; j < 4; j++) {
        const s0 = state[0][j]
        const s1 = state[1][j]
        const s2 = state[2][j]
        const s3 = state[3][j]
        
        state[0][j] = gfMul(0x02, s0) ^ gfMul(0x03, s1) ^ s2 ^ s3
        state[1][j] = s0 ^ gfMul(0x02, s1) ^ gfMul(0x03, s2) ^ s3
        state[2][j] = s0 ^ s1 ^ gfMul(0x02, s2) ^ gfMul(0x03, s3)
        state[3][j] = gfMul(0x03, s0) ^ s1 ^ s2 ^ gfMul(0x02, s3)
    }
}

function invMixColumns(state: number[][]): void {
    for (let j = 0; j < 4; j++) {
        const s0 = state[0][j]
        const s1 = state[1][j]
        const s2 = state[2][j]
        const s3 = state[3][j]
        
        state[0][j] = gfMul(0x0e, s0) ^ gfMul(0x0b, s1) ^ gfMul(0x0d, s2) ^ gfMul(0x09, s3)
        state[1][j] = gfMul(0x09, s0) ^ gfMul(0x0e, s1) ^ gfMul(0x0b, s2) ^ gfMul(0x0d, s3)
        state[2][j] = gfMul(0x0d, s0) ^ gfMul(0x09, s1) ^ gfMul(0x0e, s2) ^ gfMul(0x0b, s3)
        state[3][j] = gfMul(0x0b, s0) ^ gfMul(0x0d, s1) ^ gfMul(0x09, s2) ^ gfMul(0x0e, s3)
    }
}

/**
 * 伽罗瓦域乘法
 */
function gfMul(a: number, b: number): number {
    let p = 0
    for (let i = 0; i < 8; i++) {
        if ((b & 1) !== 0) {
            p ^= a
        }
        const hiBitSet = (a & 0x80) !== 0
        a = (a << 1) & 0xff
        if (hiBitSet) {
            a ^= 0x1b  // AES 的不可约多项式
        }
        b >>= 1
    }
    return p
}

// #endif
