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
//! Rust library to generate and check software serial-numbers.
//!
//! [Source 1](http://www.brandonstaggs.com/2007/07/26/implementing-a-partial-serial-number-verification-system-in-delphi/)
//! [Source 2](https://github.com/garethrbrown/.net-licence-key-generator/blob/master/AppSoftware.LicenceEngine.KeyGenerator/PkvLicenceKeyGenerator.cs)


use std::fmt;
use std::mem;
use std::str;
use std::u8;
use std::i64;
use std::num;
use std::error;

pub type Seed = i64;

pub type Byte = u8;

#[derive(Debug)]
pub enum Error {
    NotEnoughItems,
    InvalidFragment,
    InvalidFormat,
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::NotEnoughItems => "not enough items",
            Error::InvalidFragment => "invalid fragment",
            Error::InvalidFormat => "invalid format",
        }
    }

    fn cause(&self) -> Option<&error::Error> {
        None
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use std::error::Error;

        write!(f, "{}", self.description())
    }
}

impl From<num::ParseIntError> for Error {
    fn from(_: num::ParseIntError) -> Self {
        Error::InvalidFormat
    }
}

#[derive(Clone)]
pub struct Secret(Vec<Group<Block>>);

impl str::FromStr for Secret {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let fragments: Vec<&str> = s.split("-").collect();
        let mut groups = Vec::new();
        for fragment in fragments {
            if fragment.len() != 12 {
                return Err(Error::InvalidFragment);
            }
            let left_a = try!(u8::from_str_radix(&fragment[0..2], 16));
            let left_b = try!(u8::from_str_radix(&fragment[2..4], 16));
            let left_c = try!(u8::from_str_radix(&fragment[4..6], 16));
            let right_a = try!(u8::from_str_radix(&fragment[6..8], 16));
            let right_b = try!(u8::from_str_radix(&fragment[8..10], 16));
            let right_c = try!(u8::from_str_radix(&fragment[10..12], 16));
            let group = Group {
                left: Block::new(left_a, left_b, left_c),
                right: Block::new(right_a, right_b, right_c),
            };
            groups.push(group);
        }
        Ok(Secret(groups))
    }
}

#[derive(PartialEq, Debug)]
pub struct Key {
    seed: Seed,
    groups: Vec<Group<Byte>>,
    checksum: Group<Byte>,
}

impl Key {
    pub fn new(seed: Seed, &Secret(ref blocks): &Secret) -> Self {
        let groups: Vec<Group<Byte>> = blocks.iter().map(|g| g.produce(seed)).collect();
        let checksum = checksum(seed, &groups);
        Key {
            seed: seed,
            groups: groups,
            checksum: checksum,
        }
    }

    pub fn valid(&self, secret: &Secret) -> bool {
        let valid_key = Key::new(self.seed, secret);
        self == &valid_key
    }
}

impl fmt::Display for Key {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "{:04X}", self.seed));
        for group in &self.groups {
            try!(write!(f, "-{}", group));
        }
        write!(f, "-{}", self.checksum)
    }
}

impl str::FromStr for Key {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let items: Vec<&str> = s.split("-").collect();
        if items.len() < 3 {
            return Err(Error::NotEnoughItems);
        }
        if let Some((seed, tail)) = items.split_first() {
            let seed = try!(i64::from_str_radix(&seed, 16));
            let mut groups = Vec::new();
            for fragment in tail {
                if fragment.len() != 4 {
                    return Err(Error::InvalidFragment);
                }
                let left = try!(u8::from_str_radix(&fragment[0..2], 16));
                let right = try!(u8::from_str_radix(&fragment[2..4], 16));
                let group = Group {
                    left: left,
                    right: right,
                };
                groups.push(group);
            }
            let checksum = groups.pop().unwrap();
            let key = Key {
                seed: seed,
                groups: groups,
                checksum: checksum,
            };
            Ok(key)
        } else {
            Err(Error::NotEnoughItems)
        }
    }
}

#[derive(PartialEq, Debug, Clone)]
pub struct Group<T> {
    left: T,
    right: T,
}

impl Group<Block> {
    fn produce(&self, seed: Seed) -> Group<Byte> {
        Group {
            left: self.left.produce(seed),
            right: self.right.produce(seed),
        }
    }
}

impl fmt::Display for Group<Byte> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:02X}{:02X}", self.left, self.right)
    }
}

#[derive(Clone)]
pub struct Block {
    a: Byte,
    b: Byte,
    c: Byte,
}

impl Block {

    pub fn new(a: Byte, b: Byte, c: Byte) -> Self {
        Block {
            a: a,
            b: b,
            c: c,
        }
    }

    fn produce(&self, seed: Seed) -> Byte {
        let a = (seed >> (self.a % 25)) as Byte;
        let b = (seed >> (self.b % 3)) as Byte;
        let c = if self.a % 2 == 0 { b | self.c } else { b & self.c };
        a ^ c
    }
}

fn checksum(seed: Seed, groups: &[Group<Byte>]) -> Group<Byte> {
    let mut left: u16 = 0x56;
    let mut right: u16 = 0xAF;
    {
        let mut update = |slice: &[u8]| {
            for byte in slice {
                right = right + *byte as u16;

                if right > 0xFF {
                    right -= 0xFF;
                }

                left += right;

                if left > 0xFF {
                    left -= 0xFF;
                }
            }
        };
        let bytes: [u8; 8] = unsafe { mem::transmute(seed.to_be()) };
        update(&bytes);
        for item in groups {
            update(&[item.left, item.right]);
        }
    }
    Group {
        left: left as Byte,
        right: right as Byte,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::str::FromStr;

    #[test]
    fn test_generate() {
        let secret = Secret::from_str("0A6BBFAA6793-ABB734930FCD").unwrap();
        let key = Key::new(123, &secret);
        let right_key = Key::from_str("007B-BFBF-3049-E324").unwrap();
        let wrong_key = Key::from_str("0070-BFBF-3049-E324").unwrap();
        assert_eq!(key, right_key);
        assert!(!wrong_key.valid(&secret));
    }

    #[test]
    fn test_restore() {
        let key = Key::from_str("1233-A5B6-4324").unwrap();
        assert_eq!(&format!("{}", key), "1233-A5B6-4324");
    }

}