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
extern crate crypto;
extern crate rustc_serialize;
pub mod labels;

use std::fmt;
use crypto::digest::Digest;
use crypto::sha2::Sha256;
use crypto::pbkdf2::pbkdf2;
use crypto::hmac::Hmac;
use self::rustc_serialize::Encodable;
use self::rustc_serialize::Encoder;
use self::rustc_serialize::Decodable;
use self::rustc_serialize::Decoder;
use self::rustc_serialize::base64::{self, ToBase64};
use self::rustc_serialize::hex::FromHex;

pub struct Dono {
    min_key_length: usize,
    derived_key_length: usize,
    iterations: Vec<usize>,
    magic_salt: String
}

#[derive(PartialEq, PartialOrd, Ord, Eq)]
pub struct DonoError {
    pub field: String,
    pub code: String,
    pub description: String,
    pub message: String
}

impl fmt::Debug for DonoError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "Error {} occured on {} - {}",
            self.code, self.field, self.description
        )
    }
}

impl Encodable for DonoError {
    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
        s.emit_struct("DonoError", 2, |s| {
            try!(s.emit_struct_field("field", 0, |s| {
                s.emit_str(&self.field[..])
            }));
            try!(s.emit_struct_field("code", 1, |s| {
                s.emit_str(&self.code[..])
            }));
            try!(s.emit_struct_field("description", 2, |s| {
                s.emit_str(&self.description[..])
            }));
            try!(s.emit_struct_field("message", 3, |s| {
                s.emit_str(&self.message[..])
            }));
            Ok(())
        })
    }
}

impl Decodable for DonoError {
    fn decode<D: Decoder>(d: &mut D) -> Result<DonoError, D::Error> {
        d.read_struct("DonoError", 2, |d| {
            let field = try!(d.read_struct_field("field", 0, |d| {
                d.read_str()
            }));
            let code = try!(d.read_struct_field("code", 1, |d| {
                d.read_str()
            }));
            let description = try!(d.read_struct_field("description", 2, |d| {
                d.read_str()

            }));
            let message = try!(d.read_struct_field("message", 3, |d| {
                d.read_str()
            }));

            Ok(
                DonoError {
                    field: field.to_string(),
                    code: code.to_string(),
                    description: description.to_string(),
                    message: message.to_string()
                }
            )
        })
    }
}

impl Dono {
    pub fn new() -> Dono {
        Dono {
            min_key_length: 17,
            derived_key_length: 64,
            iterations: vec![
                // The following 7 numbers are too big to be used by the
                // cryptograpy library. These numbers won't ever be accessed as
                // they represent the number of iterations for passwords that
                // are between 0 and 6 characteres long. This is well below the
                // minimum password length, therefore these numbers can be
                // ignored.
                usize::max_value(), // 56_641_855_831_775_999_999_999_999_999,
                usize::max_value(), // 2_178_532_916_606_769_230_769_230_768,
                usize::max_value(), // 83_789_727_561_798_816_568_047_336,
                usize::max_value(), // 3_222_681_829_299_954_483_386_435,
                usize::max_value(), // 123_949_301_126_921_326_284_092,
                usize::max_value(), // 4_767_280_812_573_897_164_771,
                usize::max_value(), // 183_356_954_329_765_275_567,
                7_052_190_551_144_818_290,
                271_238_098_120_954_548,
                10_432_234_543_113_635,
                401_239_790_119_754,
                15_432_299_619_989,
                593_549_985_383,
                22_828_845_590,
                878_032_521,
                33_770_480,
                1_298_863,
                49_955,
                1_920,
                72,
                1
            ],
            magic_salt: "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127\
                b7afdeda33b".to_string()
        }
    }

    pub fn compute_password(
        &self, key: &String, label: &String
        ) -> Result<String, DonoError> {
        let label = label.to_lowercase();

        let derived_password = try!(self.derive_password(&key, &label));

        Ok(derived_password)
    }

    fn number_of_iterations_for_key(&self, key: &String
        ) -> Result<usize, DonoError> {
        if key.len() < self.min_key_length {
            let error = DonoError {
                code: "CP001".to_string(),
                field: "key".to_string(),
                message: "Key is too short".to_string(),
                description:
                    format!(
                        "The provided key is too short. The minimum key\
                        length is {} characteres.",
                        self.min_key_length
                    )
            };
            return Err(error);
        }

        let mut iterations = self.iterations.get(key.len());

        if iterations == None {
            iterations = self.iterations.last();
        }

        let iterations = iterations.unwrap();

        Ok(iterations.to_owned())
    }

    fn derive_password(
        &self, key: &String, label: &String
        ) -> Result<String, DonoError> {
        let key = key.to_owned();
        let iterations = try!(self.number_of_iterations_for_key(&key)) as u32;

        let password = key.as_bytes();

        let mut hasher = Sha256::new();
        let salt = "".to_string() + &key + label + &self.magic_salt;
        hasher.input_str(&salt);
        let salt_bytes = hasher.result_str();
        let salt = salt_bytes.as_bytes();

        let mut mac = Hmac::new(Sha256::new(), &password);
        let mut result: Vec<u8> = vec![0; 256];

        pbkdf2(&mut mac, salt, iterations, &mut result);

        // The following is a bit of a hack
        // The PBKDF2 hashing function is a bit different from the usual
        // implementation, in the sense that it leaves much more freedom to the
        // developer. To make it absolutely compliant to the RFC we need to do
        // the following
        //
        // Encode the password do Base16 - so that the ending bit will be the
        // same after we truncate the result to the desired length
        let mut password = result
            .iter()
            .map(|hex: &u8| format!("{:02x}", hex))
            .fold("".to_string(), |c, e| c + &e);

        // Truncate the length of the password
        password.truncate(self.derived_key_length);

        // Convert the resulting string to Base64 to increase entropy
        let password = password
            .from_hex()
            .unwrap()
            .to_base64(base64::STANDARD);

        Ok(password)
    }
}