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
/*
==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--

Zeros

Copyright (C) 2019-2023  Anonymous

There are several releases over multiple years,
they are listed as ranges, such as: "2019-2023".

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--
*/

//! # Argon2 _(version `1.3`)_
//!
//! _Implemetation of [Argon2](https://www.cryptolux.org/index.php/Argon2)._
//!
//! ## References
//!
//! - <https://www.cryptolux.org/images/0/0d/Argon2.pdf>
//! - <https://github.com/P-H-C/phc-winner-argon2>

#![cfg(target_endian="little")]

use {
    alloc::{
        string::String,
        vec::Vec,
    },
    core::{
        fmt::{self, Display, Formatter},
        ops::RangeInclusive,
    },
    crate::Result,
    self::blake2b::Blake2b,
};

#[cfg(not(feature="std"))]
use crate::Write;

#[cfg(feature="std")]
use std::io::Write;

pub use self::{
    memory::Memory,
    options::Options,
};

/// # Length of byte array
macro_rules! byte_array_len { () => { 1024 }}

mod blake2b;
mod block;
mod indexing_block;
mod memory;
mod options;

macro_rules! slices { () => { 4 }}

mod job;
#[cfg(test)]
mod tests;

const VERSION: u32 = 0x13;

const TAG_RANGE: RangeInclusive<u32> = 4..=u32::MAX;
const PASSWORD_LEN_RANGE: RangeInclusive<u32> = u32::MIN..=u32::MAX;
const SALT_LEN_RANGE: RangeInclusive<u32> = 8..=u32::MAX;
const SECRET_KEY_LEN_RANGE: RangeInclusive<u32> = u32::MIN..=u32::MAX;
const ASSOCIATED_DATA_LEN_RANGE: RangeInclusive<u32> = u32::MIN..=u32::MAX;
const LANE_RANGE: RangeInclusive<u32> = 1..=2_u32.pow(24) - 1;
const PASS_RANGE: RangeInclusive<u32> = 1..=u32::MAX;
const MEM_RANGE: RangeInclusive<Memory> = Memory::KiB(1)..=Memory::KiB(u32::MAX);

/// # Argon2
///
/// ## Examples
///
/// ```
/// use zeros::argon2::{Argon2, Options};
///
/// assert_eq!(
///     Argon2::I.hash("password", "some-salt", &Options::default())?,
///     [
///         0xfe, 0x35, 0x4d, 0x2e, 0x52, 0x39, 0xdf, 0x7d,
///         0x90, 0x7d, 0x5d, 0x0e, 0xbe, 0xec, 0xa1, 0xb1,
///         0xc6, 0xa7, 0xb7, 0x16, 0xd5, 0x69, 0x39, 0x70,
///         0xb2, 0x1e, 0xf4, 0x48, 0x70, 0xb6, 0x93, 0xda,
///     ],
/// );
///
/// # zeros::Result::Ok(())
/// ```
#[derive(Debug, Hash, Clone, Copy, Eq, PartialEq)]
pub enum Argon2 {

    /// # Data-dependent memory access
    D,

    /// # Data-independent memory access
    I,

    /// # Hybrid
    Id,

}

impl Argon2 {

    /// # ID
    const fn id(&self) -> u8 {
        match self {
            Self::D => 0,
            Self::I => 1,
            Self::Id => 2,
        }
    }

    /// # Hashes into a vector
    ///
    /// This function is suitable for small tag lengths. For large tags, you should use [`hash_into()`](#method.hash_into).
    pub fn hash<P, S, K, D>(&self, password: P, salt: S, options: &Options<K, D>) -> Result<Vec<u8>>
    where P: AsRef<[u8]>, S: AsRef<[u8]>, K: AsRef<[u8]>, D: AsRef<[u8]> {
        let mut result = Vec::with_capacity(options.tag_len as usize);
        self.hash_into(password, salt, options, &mut result).map(|()| result)
    }

    /// # Hashes and returns hash as a hexadecimal string, in lower-case
    ///
    /// This function is suitable for small tag lengths. For large tags, you should use [`hash_into()`](#method.hash_into).
    pub fn hash_as_hex<P, S, K, D>(&self, password: P, salt: S, options: &Options<K, D>) -> Result<String>
    where P: AsRef<[u8]>, S: AsRef<[u8]>, K: AsRef<[u8]>, D: AsRef<[u8]> {
        self.hash(password, salt, options).map(|h| crate::bytes_to_hex(h))
    }

    /// # Hashes into your output
    ///
    /// Use this function if you choose a large tag length. For small tags, you can use [`hash()`](#method.hash).
    pub fn hash_into<P, S, K, D, W>(&self, password: P, salt: S, options: &Options<K, D>, output: &mut W) -> Result<()>
    where P: AsRef<[u8]>, S: AsRef<[u8]>, K: AsRef<[u8]>, D: AsRef<[u8]>, W: Write {
        self.make_job(password, salt, options)?.run(output)
    }

    /// # Makes new job
    fn make_job<P, S, K, D>(&self, password: P, salt: S, options: &Options<K, D>) -> Result<Job>
    where P: AsRef<[u8]>, S: AsRef<[u8]>, K: AsRef<[u8]>, D: AsRef<[u8]> {
        let initial_hash = self.verify_options_and_hash(password, salt, options)?;

        let mem_blocks = (|| Some({
            let tmp = options.lanes.checked_mul(4)?;
            (options.lanes * 2).checked_mul(slices!())?.max(options.memory.to_kib().unwrap() / tmp * tmp)
        }))().ok_or_else(|| err!())?;
        let mem_blocks = (|| Some({
            let tmp = options.lanes.checked_mul(slices!())?;
            mem_blocks / tmp * tmp
        }))().ok_or_else(|| err!())?;

        let rows = usize::try_from(options.lanes).map_err(|_| err!())?;
        let columns = usize::try_from(mem_blocks / options.lanes).map_err(|_| err!())?;

        Ok(Job {
            argon2: *self,
            passes: options.passes,
            lanes: options.lanes,
            tag_len: options.tag_len,
            mem_blocks,
            rows,
            columns,
            initial_hash,
        })
    }

    /// # Verifies options and hashes the first digest
    fn verify_options_and_hash<P, S, K, D>(&self, password: P, salt: S, options: &Options<K, D>) -> Result<Vec<u8>>
    where P: AsRef<[u8]>, S: AsRef<[u8]>, K: AsRef<[u8]>, D: AsRef<[u8]> {
        let password = password.as_ref();
        let salt = salt.as_ref();
        let secret_key = options.secret_key.as_ref().map(|k| k.as_ref());
        let associated_data = options.associated_data.as_ref().map(|a| a.as_ref());
        let kib = match options.memory.to_kib() {
            Some(kib) if MEM_RANGE.contains(&options.memory) => kib,
            _ => return Err(err!(
                "Invalid memory: {memory}. Supported: [{min}, {max}]", memory=options.memory, min=MEM_RANGE.start(), max=MEM_RANGE.end(),
            )),
        };

        if PASS_RANGE.contains(&options.passes) == false {
            return Err(err!("Invalid passes: {passes}. Supported: {pass_range:?}", passes=options.passes, pass_range=PASS_RANGE));
        }
        if LANE_RANGE.contains(&options.lanes) == false {
            return Err(err!("Invalid lanes: {lanes}. Supported: {lane_range:?}", lanes=options.lanes, lane_range=LANE_RANGE));
        }

        Blake2b::hash_iter([
            &options.lanes.to_le_bytes()[..],
            &if TAG_RANGE.contains(&options.tag_len) {
                options.tag_len.to_le_bytes()
            } else {
                return Err(err!("Output tag length is too short. Supported: {:?}", TAG_RANGE));
            },
            &kib.to_le_bytes(),
            &options.passes.to_le_bytes(),
            &VERSION.to_le_bytes(),
            &u32::from(self.id()).to_le_bytes(),
            &u32::try_from(password.len()).map_err(|_| err!("Password is too large. Supported: {:?}", PASSWORD_LEN_RANGE))?.to_le_bytes(),
            password,
            &match u32::try_from(salt.len()) {
                Ok(n) => if SALT_LEN_RANGE.contains(&n) {
                    n.to_le_bytes()
                } else {
                    return Err(err!("Salt is too short. Supported: {:?}", SALT_LEN_RANGE));
                },
                Err(_) => return Err(err!("Salt is too large. Supported: {:?}", SALT_LEN_RANGE)),
            },
            salt,
            &match secret_key {
                None => u32::MIN,
                Some(secret_key) => match u32::try_from(secret_key.len()) {
                    Ok(n) => n,
                    Err(_) => return Err(err!("Secret key is too large. Supported: {:?}", SECRET_KEY_LEN_RANGE)),
                },
            }.to_le_bytes(),
            secret_key.unwrap_or(&[]),
            &match associated_data {
                None => u32::MIN,
                Some(associated_data) => match u32::try_from(associated_data.len()) {
                    Ok(n) => n,
                    Err(_) => return Err(err!("Associated data is too large. Supported: {:?}", ASSOCIATED_DATA_LEN_RANGE)),
                },
            }.to_le_bytes(),
            associated_data.unwrap_or(&[]),
        ])
    }

}

impl Display for Argon2 {

    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        macro_rules! prefix { () => { "Argon2" }}
        f.write_str(match self {
            Self::D => concat!(prefix!(), "d"),
            Self::I => concat!(prefix!(), "i"),
            Self::Id => concat!(prefix!(), "id"),
        })
    }

}

/// # Job
#[derive(Debug)]
struct Job {
    argon2: Argon2,
    passes: u32,
    lanes: u32,
    tag_len: u32,
    mem_blocks: u32,
    rows: usize,
    columns: usize,
    initial_hash: Vec<u8>,
}