Team Ai
Apppublic

devin15/cursor2api-rust

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
checksum.rs292 linesDownload Raw Back to utils
1use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};2use rand::Rng;3use sha2::{Digest, Sha256};4 5pub fn generate_hash() -> String {6    let random_bytes = rand::thread_rng().gen::<[u8; 32]>();7    let mut hasher = Sha256::new();8    hasher.update(random_bytes);9    hex::encode(hasher.finalize())10}11 12fn obfuscate_bytes(bytes: &mut [u8]) {13    let mut prev: u8 = 165;14    for (idx, byte) in bytes.iter_mut().enumerate() {15        let old_value = *byte;16        *byte = (old_value ^ prev).wrapping_add((idx % 256) as u8);17        prev = *byte;18    }19}20 21fn deobfuscate_bytes(bytes: &mut [u8]) {22    let mut prev: u8 = 165;23    for (idx, byte) in bytes.iter_mut().enumerate() {24        let temp = *byte;25        *byte = (*byte).wrapping_sub((idx % 256) as u8) ^ prev;26        prev = temp;27    }28}29 30pub fn generate_timestamp_header() -> String {31    let timestamp = std::time::SystemTime::now()32        .duration_since(std::time::UNIX_EPOCH)33        .unwrap()34        .as_secs()35        / 1_000;36 37    let mut timestamp_bytes = vec![38        ((timestamp >> 8) & 0xFF) as u8,39        (0xFF & timestamp) as u8,40        ((timestamp >> 24) & 0xFF) as u8,41        ((timestamp >> 16) & 0xFF) as u8,42        ((timestamp >> 8) & 0xFF) as u8,43        (0xFF & timestamp) as u8,44    ];45 46    obfuscate_bytes(&mut timestamp_bytes);47    BASE64.encode(&timestamp_bytes)48}49 50fn generate_checksum(device_id: &str, mac_addr: Option<&str>) -> String {51    let encoded = generate_timestamp_header();52    match mac_addr {53        Some(mac) => format!("{}{}/{}", encoded, device_id, mac),54        None => format!("{}{}", encoded, device_id),55    }56}57 58pub fn generate_checksum_with_default() -> String {59    generate_checksum(&generate_hash(), Some(&generate_hash()))60}61 62pub fn generate_checksum_with_repair(checksum: &str) -> String {63    // 预校验:检查字符串是否为空或只包含合法的Base64字符和'/'64    if checksum.is_empty()65        || !checksum66            .chars()67            .all(|c| (c.is_ascii_alphanumeric() || c == '/' || c == '+' || c == '='))68    {69        return generate_checksum_with_default();70    }71 72    // 尝试修复时间戳头的函数73    fn try_fix_timestamp(timestamp_base64: &str) -> Option<String> {74        if let Ok(timestamp_bytes) = BASE64.decode(timestamp_base64) {75            if timestamp_bytes.len() == 6 {76                let mut fixed_bytes = timestamp_bytes.clone();77                deobfuscate_bytes(&mut fixed_bytes);78 79                // 检查前3位是否为080                if fixed_bytes[0..3].iter().all(|&x| x == 0) {81                    // 从后四位构建时间戳82                    let timestamp = ((fixed_bytes[2] as u64) << 24)83                        | ((fixed_bytes[3] as u64) << 16)84                        | ((fixed_bytes[4] as u64) << 8)85                        | (fixed_bytes[5] as u64);86 87                    let current_timestamp = std::time::SystemTime::now()88                        .duration_since(std::time::UNIX_EPOCH)89                        .unwrap()90                        .as_secs()91                        / 1_000;92 93                    if timestamp <= current_timestamp {94                        // 修复时间戳字节95                        fixed_bytes[0] = fixed_bytes[4];96                        fixed_bytes[1] = fixed_bytes[5];97 98                        obfuscate_bytes(&mut fixed_bytes);99                        return Some(BASE64.encode(&fixed_bytes));100                    }101                }102            }103        }104        None105    }106 107    if checksum.len() == 8 {108        // 尝试修复时间戳头109        if let Some(fixed_timestamp) = try_fix_timestamp(checksum) {110            return format!("{}{}/{}", fixed_timestamp, generate_hash(), generate_hash());111        }112 113        // 验证原始时间戳114        if let Some(timestamp) = extract_time_ks(checksum) {115            let current_timestamp = std::time::SystemTime::now()116                .duration_since(std::time::UNIX_EPOCH)117                .unwrap()118                .as_secs()119                / 1_000;120 121            if timestamp <= current_timestamp {122                return format!("{}{}/{}", checksum, generate_hash(), generate_hash());123            }124        }125    } else if checksum.len() > 8 {126        // 处理可能包含hash的情况127        let parts: Vec<&str> = checksum.split('/').collect();128        match parts.len() {129            1 => {130                let timestamp_base64 = &checksum[..8];131                let device_id = &checksum[8..];132 133                if is_valid_hash(device_id) {134                    // 先尝试修复时间戳135                    if let Some(fixed_timestamp) = try_fix_timestamp(timestamp_base64) {136                        return format!("{}{}/{}", fixed_timestamp, device_id, generate_hash());137                    }138 139                    // 验证原始时间戳140                    if let Some(timestamp) = extract_time_ks(timestamp_base64) {141                        let current_timestamp = std::time::SystemTime::now()142                            .duration_since(std::time::UNIX_EPOCH)143                            .unwrap()144                            .as_secs()145                            / 1_000;146 147                        if timestamp <= current_timestamp {148                            return format!(149                                "{}{}/{}",150                                generate_timestamp_header(),151                                device_id,152                                generate_hash()153                            );154                        }155                    }156                }157            }158            2 => {159                let first_part = parts[0];160                let mac_hash = parts[1];161 162                if is_valid_hash(mac_hash) && first_part.len() == mac_hash.len() + 8 {163                    let timestamp_base64 = &first_part[..8];164                    let device_id = &first_part[8..];165 166                    if is_valid_hash(device_id) {167                        // 先尝试修复时间戳168                        if let Some(fixed_timestamp) = try_fix_timestamp(timestamp_base64) {169                            return format!("{}{}/{}", fixed_timestamp, device_id, mac_hash);170                        }171 172                        // 验证原始时间戳173                        if let Some(timestamp) = extract_time_ks(timestamp_base64) {174                            let current_timestamp = std::time::SystemTime::now()175                                .duration_since(std::time::UNIX_EPOCH)176                                .unwrap()177                                .as_secs()178                                / 1_000;179 180                            if timestamp <= current_timestamp {181                                return format!(182                                    "{}{}/{}",183                                    generate_timestamp_header(),184                                    device_id,185                                    mac_hash186                                );187                            }188                        }189                    }190                }191            }192            _ => {}193        }194    }195 196    // 如果所有修复尝试都失败,返回默认值197    generate_checksum_with_default()198}199 200pub fn extract_time_ks(timestamp_base64: &str) -> Option<u64> {201    let mut timestamp_bytes = BASE64.decode(timestamp_base64).ok()?;202 203    if timestamp_bytes.len() != 6 {204        return None;205    }206 207    deobfuscate_bytes(&mut timestamp_bytes);208 209    if timestamp_bytes[0] != timestamp_bytes[4] || timestamp_bytes[1] != timestamp_bytes[5] {210        return None;211    }212 213    // 使用后四位还原 timestamp214    Some(215        ((timestamp_bytes[2] as u64) << 24)216            | ((timestamp_bytes[3] as u64) << 16)217            | ((timestamp_bytes[4] as u64) << 8)218            | (timestamp_bytes[5] as u64),219    )220}221 222pub fn validate_checksum(checksum: &str) -> bool {223    // 预校验:检查字符串是否为空或只包含合法的Base64字符和'/'224    if checksum.is_empty()225        || !checksum226            .chars()227            .all(|c| (c.is_ascii_alphanumeric() || c == '/' || c == '+' || c == '='))228    {229        return false;230    }231    // 首先检查是否包含基本的 base64 编码部分和 hash 格式的 device_id232    let parts: Vec<&str> = checksum.split('/').collect();233 234    match parts.len() {235        // 没有 MAC 地址的情况236        1 => {237            if checksum.len() < 72 {238                // 8 + 64 = 72239                return false;240            }241 242            // 解码前8个字符的base64时间戳243            let timestamp_base64 = &checksum[..8];244            let timestamp = match extract_time_ks(timestamp_base64) {245                Some(ts) => ts,246                None => return false,247            };248 249            let current_timestamp = std::time::SystemTime::now()250                .duration_since(std::time::UNIX_EPOCH)251                .unwrap()252                .as_secs()253                / 1_000;254 255            if current_timestamp < timestamp {256                return false;257            }258 259            // 验证 device_id hash 部分260            is_valid_hash(&checksum[8..])261        }262        // 包含 MAC hash 的情况263        2 => {264            let first_part = parts[0];265            let mac_hash = parts[1];266 267            // MAC hash 必须是64字符的十六进制268            if !is_valid_hash(mac_hash) {269                return false;270            }271 272            // 检查第一部分比MAC hash多8个字符273            if first_part.len() != mac_hash.len() + 8 {274                return false;275            }276 277            // 递归验证第一部分278            validate_checksum(first_part)279        }280        _ => false,281    }282}283 284fn is_valid_hash(hash: &str) -> bool {285    if hash.len() < 64 {286        return false;287    }288 289    // 检查是否都是有效的十六进制字符290    hash.chars().all(|c| c.is_ascii_hexdigit())291}292