attrkey 0.1.0-alpha.2

Pure Rust implementation of a Selection-Sensitive Attribute-Based Key Derivation Scheme.
Documentation
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
use annihilation::AnnihlKey;
use hkdf::{Hkdf, hmac::digest::OutputSizeUser};
use rand_core::{Rng, SeedableRng};
use sha2::Sha256;
use std::marker::PhantomData;
use zeroize::{Zeroize, ZeroizeOnDrop};

use crate::errors::AttrkeyError;

const MIN_CONSTRAINT: u8 = 1;

/// A `Keyspace` represents a collection of hardened attribute values from
/// which attribute-based cryptographic keys can be derived.
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
pub struct Keyspace<R> {
    arr: Vec<Vec<u8>>,
    constraint: u8,
    context: Vec<u8>,
    _rng: PhantomData<R>,
}

impl<R> Keyspace<R>
where
    R: SeedableRng + Rng + Sync,
    R::Seed: AsMut<[u8]> + Default + Zeroize,
{
    /// Construct a new `Keyspace` from a collection of hardened attributes,
    /// proof-of-work constraint, and optional context.
    pub fn new(
        arr: Vec<Vec<u8>>,
        constraint: u8,
        context: Option<&[u8]>,
    ) -> Result<Self, AttrkeyError> {
        if constraint < MIN_CONSTRAINT {
            return Err(AttrkeyError::ConstraintTooSmall);
        }

        Ok(Self {
            arr,
            constraint,
            context: context.map(|c| c.to_vec()).unwrap_or_default(),
            _rng: PhantomData,
        })
    }

    /// Derive a cryptographic key from a selection of attribute indices.
    ///
    /// Partitions the keyspace into selected and remaining attributes, then
    /// computes an [annihilation key](annihilation::AnnihlKey::to_annihilation)
    /// from the partition, used as a seed for RNG expansion.
    ///
    /// Returns the derived key on success (default length = 32), or an error
    /// when the selection is invalid or partition annihilation fails.
    pub fn derive_key(
        &self,
        selection: &[usize],
        output_len: Option<usize>,
    ) -> Result<Vec<u8>, AttrkeyError> {
        let seed = self.derive_seed(selection)?;

        let mut rng = R::from_seed(seed);

        let dst_len = output_len.unwrap_or(32);
        let mut dst = vec![0u8; dst_len];
        rng.fill_bytes(&mut dst);
        Ok(dst)
    }

    /// Derive a cryptographic key from a selection of attribute indices into a
    /// provided buffer.
    ///
    /// Partitions the keyspace into selected and remaining attributes, then
    /// computes an [annihilation key](annihilation::AnnihlKey::to_annihilation)
    /// from the partition, used as a seed for RNG expansion.
    ///
    /// Fills the provided buffer with the derived bytes on success, or an error
    /// when the selection is invalid or partition annihilation fails.
    pub fn derive_key_into(
        &self,
        selection: &[usize],
        dst: &mut [u8],
    ) -> Result<(), AttrkeyError> {
        let seed = self.derive_seed(selection)?;

        let mut rng = R::from_seed(seed);

        rng.fill_bytes(dst);
        Ok(())
    }

    /// Extract an [annihilative pair](annihilation::AnnihlKey::new_pair) from
    /// an attribute selection.
    ///
    /// Partitions attributes by the selection indices, concatenating selected
    /// attributes as key material and remaining attributes as antikey
    /// material, then mines for a pair that satisfies the keyspace's
    /// proof-of-work constraint.
    ///
    /// Returns the annihilative pair on success, or an error when the
    /// selection is empty, selects all attributes, or contains out-of-bound
    /// indices.
    pub fn extract_pair(
        &self,
        selection: &[usize],
    ) -> Result<(AnnihlKey, AnnihlKey), AttrkeyError> {
        if selection.is_empty() {
            return Err(AttrkeyError::IndicesTooFew);
        }
        if selection.len() >= self.arr.len() {
            return Err(AttrkeyError::IndicesTooMany);
        }
        if selection.iter().any(|&index| index >= self.arr.len()) {
            return Err(AttrkeyError::IndexOutOfBounds);
        }

        let (selected, remaining): (Vec<_>, Vec<_>) = self
            .arr
            .iter()
            .enumerate()
            .partition(|(index, _)| selection.contains(index));

        let mut ikm: Vec<u8> = selected
            .into_iter()
            .flat_map(|(_, arr)| arr.iter().copied())
            .collect();
        let mut iam: Vec<u8> = remaining
            .into_iter()
            .flat_map(|(_, arr)| arr.iter().copied())
            .collect();

        let pair = AnnihlKey::new_pair(&ikm, &iam, self.constraint);
        ikm.zeroize();
        iam.zeroize();

        Ok(pair)
    }

    fn derive_seed(
        &self,
        selection: &[usize],
    ) -> Result<R::Seed, AttrkeyError> {
        let (key, antikey) = self.extract_pair(selection)?;

        let mut prk = key
            .into_annihilation(antikey)
            .map_err(|_| AttrkeyError::Annihilation)?;

        let seed_len = R::Seed::default().as_mut().len();
        let max_okm_len = 255 * <Sha256 as OutputSizeUser>::output_size();
        if seed_len > max_okm_len {
            prk.zeroize();
            return Err(AttrkeyError::SeedTooLong);
        }

        let hk = Hkdf::<Sha256>::from_prk(&prk)
            .expect("annihilation PRK is always 32 bytes");

        let mut tmp = vec![0u8; seed_len];
        hk.expand(&self.context, &mut tmp)
            .expect("seed length is within HKDF-SHA256 bounds");

        let mut seed = R::Seed::default();
        seed.as_mut().copy_from_slice(&tmp);
        prk.zeroize();
        tmp.zeroize();

        Ok(seed)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chacha20::ChaCha20Rng;
    use rand_core::TryRng;
    use scrypt::{Params, Scrypt};

    use crate::attributes::Attributes;

    /// Testing Keyspace type.
    type TestKeyspace = Keyspace<ChaCha20Rng>;

    /// Seed type for [LargeSeedRng] exceeding HKDF-SHA256's
    /// maximum OKM length (255 * 32).
    #[derive(Clone)]
    struct LargeSeed([u8; 8161]);

    impl Default for LargeSeed {
        fn default() -> Self {
            Self([0u8; 8161])
        }
    }

    impl AsRef<[u8]> for LargeSeed {
        fn as_ref(&self) -> &[u8] {
            &self.0
        }
    }

    impl AsMut<[u8]> for LargeSeed {
        fn as_mut(&mut self) -> &mut [u8] {
            &mut self.0
        }
    }

    impl Zeroize for LargeSeed {
        fn zeroize(&mut self) {
            self.0.iter_mut().for_each(|b| *b = 0);
        }
    }

    /// Triggers the [SeedTooLong](AttrkeyError::SeedTooLong) error path
    /// for [Keyspace] methods.
    struct LargeSeedRng;

    impl SeedableRng for LargeSeedRng {
        type Seed = LargeSeed;

        fn from_seed(_seed: Self::Seed) -> Self {
            LargeSeedRng
        }
    }

    impl TryRng for LargeSeedRng {
        type Error = core::convert::Infallible;

        fn try_fill_bytes(
            &mut self,
            _dst: &mut [u8],
        ) -> Result<(), Self::Error> {
            Ok(())
        }

        fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
            Ok(0)
        }

        fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
            Ok(0)
        }
    }

    fn get_arr() -> Vec<Vec<u8>> {
        vec![
            b"Pigs on the Wing I".to_vec(),
            b"Dogs".to_vec(),
            b"Pigs (Three Different Ones)".to_vec(),
            b"Sheep".to_vec(),
            b"Pigs on the Wing II".to_vec(),
        ]
    }

    fn produce_keyspace() -> TestKeyspace {
        let params = Params::new(4, 8, 1).unwrap();
        let scrypt = Scrypt::new_with_params(params);

        Attributes::<Scrypt, ChaCha20Rng>::new(get_arr(), scrypt)
            .expect("should construct collection")
            .harden(4, None)
            .expect("hardening should produce keyspace")
    }

    fn produce_large_seed_keyspace() -> Keyspace<LargeSeedRng> {
        let params = Params::new(4, 8, 1).unwrap();
        let scrypt = Scrypt::new_with_params(params);

        Attributes::<Scrypt, LargeSeedRng>::new(get_arr(), scrypt)
            .expect("should construct collection")
            .harden(4, None)
            .expect("hardening should produce keyspace")
    }

    #[test]
    fn new_constructs_keyspace() {
        let result = TestKeyspace::new(get_arr(), 4, None);
        assert!(result.is_ok());
    }

    #[test]
    fn new_with_context_constructs_keyspace() {
        let result = TestKeyspace::new(get_arr(), 4, Some(b"Animals"));
        assert!(result.is_ok());
    }

    #[test]
    fn new_fails_constraint_too_small() {
        let result = TestKeyspace::new(get_arr(), 0, None);
        assert!(matches!(result, Err(AttrkeyError::ConstraintTooSmall)));
    }

    #[test]
    fn derive_key_produces_key() {
        let keyspace = produce_keyspace();

        // Key derivation must succeed for valid attribute selection
        let result = keyspace.derive_key(&[1, 3], None);
        assert!(result.is_ok());

        // Derived key must default to 32 byes when length is None
        assert_eq!(result.unwrap().len(), 32);
    }

    #[test]
    fn derive_key_with_output_len_produces_key() {
        let keyspace = produce_keyspace();

        // Key derivation must succeed for valid attribute selection
        let result = keyspace.derive_key(&[1, 3], Some(48));
        assert!(result.is_ok());

        // Derived key length must match provided output length
        assert_eq!(result.unwrap().len(), 48);
    }

    #[test]
    fn derive_key_fails_too_few_indices() {
        let keyspace = produce_keyspace();

        // Empty selection must result in an error
        let result = keyspace.derive_key(&[], None);
        assert_eq!(result, Err(AttrkeyError::IndicesTooFew));
    }

    #[test]
    fn derive_key_fails_too_many_indices() {
        let keyspace = produce_keyspace();
        let selection: Vec<usize> = (0..keyspace.arr.len()).collect();

        // Selecting all attributes must result in an error
        let result = keyspace.derive_key(&selection, None);
        assert_eq!(result, Err(AttrkeyError::IndicesTooMany));
    }

    #[test]
    fn derive_key_fails_out_of_bounds() {
        let keyspace = produce_keyspace();
        let selection: Vec<usize> = [0, keyspace.arr.len() + 1].to_vec();

        // Out of bounds index in selection must result in an error
        let result = keyspace.derive_key(&selection, None);
        assert_eq!(result, Err(AttrkeyError::IndexOutOfBounds));
    }

    #[test]
    fn derive_key_fails_seed_too_long() {
        let keyspace = produce_large_seed_keyspace();

        // RNG seed exceeding HKDF-SHA256 OKM limit must result in an error
        let result = keyspace.derive_key(&[1, 3], None);
        assert_eq!(result, Err(AttrkeyError::SeedTooLong));
    }

    #[test]
    fn derive_key_into_fills_buffer() {
        let keyspace = produce_keyspace();
        let mut dst = [0u8; 48];

        // Key derivation must succeed for valid attribute selection
        let result = keyspace.derive_key_into(&[1, 3], &mut dst);
        assert!(result.is_ok());
    }

    #[test]
    fn derive_key_into_fails_too_few_indices() {
        let keyspace = produce_keyspace();
        let mut dst = [0u8; 48];

        // Empty selection must result in an error
        let result = keyspace.derive_key_into(&[], &mut dst);
        assert_eq!(result, Err(AttrkeyError::IndicesTooFew));
    }

    #[test]
    fn derive_key_into_fails_too_many_indices() {
        let keyspace = produce_keyspace();
        let mut dst = [0u8; 48];
        let selection: Vec<usize> = (0..keyspace.arr.len()).collect();

        // Selecting all attributes must result in an error
        let result = keyspace.derive_key_into(&selection, &mut dst);
        assert_eq!(result, Err(AttrkeyError::IndicesTooMany));
    }

    #[test]
    fn derive_key_into_fails_out_of_bounds() {
        let keyspace = produce_keyspace();
        let mut dst = [0u8; 48];
        let selection: Vec<usize> = [0, keyspace.arr.len() + 1].to_vec();

        // Out of bounds index in selection must result in an error
        let result = keyspace.derive_key_into(&selection, &mut dst);
        assert_eq!(result, Err(AttrkeyError::IndexOutOfBounds));
    }

    #[test]
    fn derive_key_into_fails_seed_too_long() {
        let keyspace = produce_large_seed_keyspace();
        let mut dst = [0u8; 48];

        // RNG seed exceeding HKDF-SHA256 OKM limit must result in an error
        let result = keyspace.derive_key_into(&[1, 3], &mut dst);
        assert_eq!(result, Err(AttrkeyError::SeedTooLong));
    }

    #[test]
    fn extract_pair_produces_pair() {
        let keyspace = produce_keyspace();

        // Valid selection must return an annihilative pair
        let result = keyspace.extract_pair(&[1, 3]);
        assert!(result.is_ok());
    }

    #[test]
    fn extract_pair_fails_empty_selection() {
        let keyspace = produce_keyspace();

        // Empty selection must result in an error
        let result = keyspace.extract_pair(&[]);
        assert_eq!(result, Err(AttrkeyError::IndicesTooFew));
    }

    #[test]
    fn extract_pair_fails_too_many_indices() {
        let keyspace = produce_keyspace();
        let selection: Vec<usize> = (0..keyspace.arr.len()).collect();

        // Selecting all attributes must result in an error
        let result = keyspace.extract_pair(&selection);
        assert_eq!(result, Err(AttrkeyError::IndicesTooMany));
    }

    #[test]
    fn extract_pair_fails_out_of_bounds() {
        let keyspace = produce_keyspace();
        let selection: Vec<usize> = [0, keyspace.arr.len() + 1].to_vec();

        // Out of bounds index in selection must result in an error
        let result = keyspace.extract_pair(&selection);
        assert_eq!(result, Err(AttrkeyError::IndexOutOfBounds));
    }
}