1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
extern crate rand;
extern crate regex;

// based on http://www.brandonstaggs.com/2007/07/26/implementing-a-partial-serial-number-verification-system-in-delphi/
use regex::Regex;
use rand::Rng;

#[derive(Debug, PartialEq)]
pub enum Status {
    Good,
    Invalid,
    Blacklisted,
    Phony
}

fn get_key_byte(seed: &i64, a: i16, b: i16, c: i16) -> String {
    let a_shift = a % 25;
    let b_shift = b % 3;
    let mut result;

    if a_shift % 2 == 0 {
        result = ((seed >> a_shift) & 0x000000FF) ^ ((seed >> b_shift) | c as i64);
    } else {
        result = ((seed >> a_shift) & 0x000000FF) ^ ((seed >> b_shift) & c as i64);
    }

    result = result & 0xFF;

    // formats to uppercase hex, must be 2 chars with leading 0s
    // https://doc.rust-lang.org/std/fmt/#width
    format!("{:01$X}", result, 2)
}

fn get_checksum(s: &str) -> String {
    let mut left = 0x0056; // 101
    let mut right: u16 = 0x00AF; // 175

    for ch in s.chars() {
        right += ch as u16;
        if right > 0x00FF {
            right -= 0x00FF;
        }

        left += right;
        if left > 0x00FF {
            left -= 0x00FF;
        }
    }

    let sum = (left << 8) + right;

    // format as upperhex with leading 0s, must be 4 chars long
    format!("{:01$X}", sum, 4)
}

pub fn make_key(seed: &i64, num_bytes: &i8, byte_shifts: &Vec<(i16, i16, i16)>) -> String {
    let mut key_bytes: Vec<String> = vec![];

    for i in 0..*num_bytes {
        let index = i as usize;
        let shift = byte_shifts[index];
        key_bytes.push(get_key_byte(&seed, shift.0, shift.1, shift.2));
    }

    let mut result = format!("{:01$X}", seed, 8);
    for byte in key_bytes {
        result = format!("{}{}", result, byte);
    }

    result = format!("{}{}", result, get_checksum(&result[..]));

    // keys should always be 20 digits, but use chunks rather than loop to be sure
    let subs: Vec<&str> = result.split("").filter(|s| s.len() > 0).collect();
    let mut key: Vec<String> = vec![];
    for chunk in subs.chunks(4) {
        key.push(chunk.join(""));
    }

    key.join("-")
}

pub fn check_key_checksum(key: &str, num_bytes: &i8) -> bool {
    let s = key.replace("-", "").to_uppercase();
    let length = s.len();

    // length = 8 (seed) + 4 (checksum) + 2 * num_bytes
    if length != (12 + (2 * num_bytes)) as usize {
        return false;
    }

    let checksum = &s[length - 4..length];
    let slice = &s[..length - 4];

    checksum == get_checksum(&slice)
}

pub fn check_key(s: &str, blacklist: &Vec<String>, num_bytes: &i8, byte_shifts: &Vec<(i16, i16, i16)>, positions: Option<Vec<i16>>) -> Status {
    if !check_key_checksum(s, num_bytes) {
        return Status::Invalid;
    }

    if *num_bytes < 3 {
        return Status::Invalid;
    }

    let key = s.replace("-", "").to_uppercase();
    let seed: String = key.chars().take(8).collect();

    for item in blacklist {
        if seed == item.to_uppercase() {
            return Status::Blacklisted;
        }
    }

    let re = Regex::new(r"[A-F0-9]{8}").unwrap();
    if !re.is_match(&seed) {
        return Status::Phony;
    }

    let seed_num = match i64::from_str_radix(&seed[..], 16) {
        Err(_) => return Status::Invalid,
        Ok(s) => s
    };

    match positions {
        Some(pos) => check_bytes(key, seed_num, byte_shifts, pos),
        None => check_random_bytes(key, seed_num, num_bytes, byte_shifts)
    }
}

/// Check specific bytes: this means you don't need to pass all the byte shifts in every check
/// Also need to pass array of byte positions to check
/// ie key: 4206-1A9F-FDD6-4D48-A1C8-ED15-FB36
/// expected byte shifts: [(74, 252, 42), (42, 116, 226)]
/// byte positions to check: [0, 4]
/// this will check FD and A1 match (74, 252, 42) and (42, 116, 226) respectively
fn check_bytes(key: String, seed_num: i64, byte_shifts: &Vec<(i16, i16, i16)>, positions: Vec<i16>) -> Status {
    if positions.len() < 2 {
        println!("Must check at least 2 bytes");
        return Status::Invalid;
    }

    for (i, pos) in positions.into_iter().enumerate() {
        let start = ((pos * 2) + 8) as usize;
        let end = start + 2;

        if end > key.len() {
            return Status::Invalid;
        }

        let key_byte = &key[start..end];
        let shifts = &byte_shifts[i as usize];

        let byte = get_key_byte(&seed_num, shifts.0, shifts.1, shifts.2);
        if key_byte != byte {
            return Status::Phony;
        }
    }

    Status::Good
}

/// Pick random bytes in the key and check that they're as expected
/// This means you don't check the same keys in each run, but also means you need to pass all the
/// byte shifts with every call (compared with `check_bytes` where not all the byte shifts are exposed with each call)
fn check_random_bytes(key: String, seed_num: i64, num_bytes: &i8, byte_shifts: &Vec<(i16, i16, i16)>) -> Status {
    let mut bytes_to_check = 3;
    if *num_bytes > 5 {
        bytes_to_check = num_bytes / 2;
    }

    // pick random unchecked entry in bytes array and check it
    let mut checked: Vec<i8> = Vec::new();

    for _ in 0..bytes_to_check {
        let mut byte_to_check = rand::thread_rng().gen_range(0, num_bytes - 1);
        while checked.contains(&byte_to_check) {
            byte_to_check = rand::thread_rng().gen_range(0, num_bytes - 1);
        }
        checked.push(byte_to_check);

        let start = ((byte_to_check * 2) + 8) as usize;
        let end = start + 2;

        if end > key.len() {
            return Status::Invalid;
        }


        let key_byte = &key[start..end];
        println!("num {:?}, shifts {:?}", &byte_to_check, &byte_shifts);

        let shifts = &byte_shifts[byte_to_check as usize];

        let byte = get_key_byte(&seed_num, shifts.0, shifts.1, shifts.2);
        if key_byte != byte {
            return Status::Phony;
        }
    }

    Status::Good
}

#[cfg(test)]
mod test {
    #[test]
    fn test_bytes() {
        let seed = 0xA2791717;
        assert_eq!(super::get_key_byte(&seed, 24, 3, 200), "7D");
        assert_eq!(super::get_key_byte(&seed, 10, 0, 56), "7A");
        assert_eq!(super::get_key_byte(&seed, 1, 2, 91), "CA");
        assert_eq!(super::get_key_byte(&seed, 7, 1, 100), "2E");
    }

    #[test]
    fn test_get_checksum() {
        let key = "A279-1717-7D7A-CA2E-7154";
        assert_eq!(super::get_checksum(key), "49DA");

        let second_key = "3ABC-9099-E39D-4E65-E060";
        assert_eq!(super::get_checksum(second_key), "82F0");
    }

    #[test]
    fn test_make_key() {
        let seed = 0x3abc9099;
        let num_bytes = 4;
        let byte_shifts = vec![(24, 3, 200), (10, 0, 56), (1, 2, 91), (7, 1, 100)];
        assert_eq!("3ABC-9099-E39D-4E65-E060", super::make_key(&seed, &num_bytes, &byte_shifts));
    }

    #[test]
    fn test_check_key() {
        let key = "3ABC-9099-E39D-4E65-E060";
        let blacklist = vec![];
        let num_bytes = 4;
        let byte_shifts = vec![(24, 3, 200), (10, 0, 56), (1, 2, 91), (7, 1, 100)];
        assert_eq!(super::check_key(&key, &blacklist, &num_bytes, &byte_shifts, Option::None), super::Status::Good);

        let byte_shifts = vec![(24, 3, 200), (1, 2, 91)];
        let positions = Option::Some(vec![0, 2]);
        assert_eq!(super::check_key(&key, &blacklist, &num_bytes, &byte_shifts, positions), super::Status::Good);

        let byte_shifts = vec![(1, 2, 91), (10, 0, 56)];
        let positions = Option::Some(vec![2, 1]);
        assert_eq!(super::check_key(&key, &blacklist, &num_bytes, &byte_shifts, positions), super::Status::Good);

        let inconsistent_key = "3abC-9099-e39D-4E65-E060";
        let byte_shifts = vec![(24, 3, 200), (10, 0, 56), (1, 2, 91), (7, 1, 100)];
        assert_eq!(super::check_key(&inconsistent_key, &blacklist, &num_bytes, &byte_shifts, Option::None), super::Status::Good);

        let wrong_checksum = "3ABC-9099-E39D-4E65-E061";
        assert_eq!(super::check_key(&wrong_checksum, &blacklist, &num_bytes, &byte_shifts, Option::None), super::Status::Invalid);

        let second_fake_key = "3ABC-9099-E49D-4E65-E761";
        assert_eq!(super::check_key(&second_fake_key, &blacklist, &num_bytes, &byte_shifts, Option::None), super::Status::Phony);

        let third_fake_key = "3ABC-9199-E39D-4E65-EB61";
        assert_eq!(super::check_key(&third_fake_key, &blacklist, &num_bytes, &byte_shifts, Option::None), super::Status::Phony);

        let invalid_key = "BC-9099-E39D-4E65-E061";
        assert_eq!(super::check_key(&invalid_key, &blacklist, &num_bytes, &byte_shifts, Option::None), super::Status::Invalid);

        let second_invalid_key = "3AXC-9099-E39D-4E65-E061";
        assert_eq!(super::check_key(&second_invalid_key, &blacklist, &num_bytes, &byte_shifts, Option::None), super::Status::Invalid);
    }

    #[test]
    fn test_blacklist() {
        let key = "3ABC-9099-E39D-4E65-E060";
        let blacklist = vec!["3abc9099".to_string()];
        let num_bytes = 4;
        let byte_shifts = vec![(24, 3, 200), (10, 0, 56), (1, 2, 91), (7, 1, 100)];

        assert_eq!(super::check_key(&key, &blacklist, &num_bytes, &byte_shifts, Option::None), super::Status::Blacklisted);

        let byte_shifts = vec![(24, 3, 200), (1, 2, 91)];
        let positions = Option::Some(vec![0, 2]);
        assert_eq!(super::check_key(&key, &blacklist, &num_bytes, &byte_shifts, positions), super::Status::Blacklisted);
    }
}