ios7crypt/
ios7crypt.rs

1//! Legacy IOS7Crypt encryptor/decryptor library
2
3extern crate rand;
4
5use std::str;
6use std::u8;
7use std::iter;
8use std::slice;
9
10/// Finite IOS7Crypt constant key
11static XLAT_PRIME : [u8; 53] = [
12  0x64, 0x73, 0x66, 0x64, 0x3b, 0x6b, 0x66, 0x6f,
13  0x41, 0x2c, 0x2e, 0x69, 0x79, 0x65, 0x77, 0x72,
14  0x6b, 0x6c, 0x64, 0x4a, 0x4b, 0x44, 0x48, 0x53,
15  0x55, 0x42, 0x73, 0x67, 0x76, 0x63, 0x61, 0x36,
16  0x39, 0x38, 0x33, 0x34, 0x6e, 0x63, 0x78, 0x76,
17  0x39, 0x38, 0x37, 0x33, 0x32, 0x35, 0x34, 0x6b,
18  0x3b, 0x66, 0x67, 0x38, 0x37
19];
20
21/// Wraparound IOS7Crypt constant key
22pub fn xlat<'a>(offset : &'a usize) -> iter::Skip<iter::Cycle<slice::Iter<'a, u8>>> {
23  return XLAT_PRIME.iter().cycle().skip(*offset);
24}
25
26/// Bitwise XOR convenience function
27pub fn xor(tp : (u8, &u8)) -> u8 {
28  let (a, b) : (u8, &u8) = tp;
29  return a ^ (*b);
30}
31
32/// Encode an ASCII password with IOS7Crypt
33pub fn encrypt<R: rand::Rng>(rng : &mut R, password : &str) -> String {
34  let seed = rng.gen_range(0, 16);
35
36  let hexpairs : Vec<String> = password.bytes()
37                                       .zip(xlat(&seed))
38                                       .map(|pair| xor(pair))
39                                       .map(|cipherbyte| format!("{:02x}", cipherbyte))
40                                       .collect();
41
42  return format!("{:02}{}", seed, hexpairs.concat());
43}
44
45/// Attempt to parse an array of ASCII hexadecimal digits
46/// to their corresponding numeric values.
47fn parse_hex(s : &[u8]) -> Option<u8> {
48  return match str::from_utf8(s) {
49    Ok(v) => match u8::from_str_radix(v, 16) {
50      Ok(w) => Some(w),
51      Err(_) => None
52    },
53    Err(_) => None
54  };
55}
56
57/// Decrypt valid IOS7Crypt hashes
58pub fn decrypt(hash : &str) -> Option<String> {
59  if hash.len() < 2 {
60    return None
61  }
62
63  let (seed_str, hash_str) : (&str, &str) = hash.split_at(2);
64
65  let seed = match usize::from_str_radix(seed_str, 10) {
66    Ok(v) => v,
67    _ => return None
68  };
69
70  let plainbytes_options : Vec<Option<u8>> = hash_str.as_bytes()
71                                                     .chunks(2)
72                                                     .map(|hexpair| parse_hex(hexpair))
73                                                     .collect();
74
75  if plainbytes_options.iter().any(|plainbyte_option| plainbyte_option.is_none()) {
76    return None
77  }
78
79  let plainbytes : iter::Map<_, _> = plainbytes_options.iter()
80                                              .map(|plainbytes_option| plainbytes_option.unwrap())
81                                              .zip(xlat(&seed))
82                                              .map(|pair| xor(pair));
83
84  return String::from_utf8(plainbytes.collect()).ok();
85}
86
87#[test]
88fn smoketest() {
89  assert_eq!(decrypt("1308181c00091d"), Some("monkey".to_string()));
90}