human_key 0.1.0-alpha.1

Pure Rust implementation of human-derived attribute fingerprinting for cryptographic key derivation.
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
use argon2::{Algorithm, Argon2, Version};
use attrkey::{Attributes, Keyspace};
use chacha20::ChaCha20Rng;
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use subtle::{Choice, ConstantTimeEq};
use zeroize::Zeroize;

use crate::attributes::AttributeKind;
use crate::errors::HkErr;
use crate::params::Params;

/// A [Crockford Base32](https://www.crockford.com/base32.html) alphabet.
///
/// Used to encode confirmation codes.
pub const CROCKFORD_BASE32: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";

/// A collection of raw human-derived attribute values, keyed by kind: the
/// signals that can be hardened into a [Fingerprint].
pub struct Profile<K> {
    inner: BTreeMap<K, Vec<u8>>,
}

impl<K: AttributeKind> Profile<K> {
    /// Construct a new, empty `Profile`.
    pub fn new() -> Self {
        Self {
            inner: BTreeMap::new(),
        }
    }

    /// Insert an attribute value under the given kind.
    ///
    /// Overwrites any existing value already inserted for `kind`.
    pub fn insert(&mut self, kind: K, value: impl Into<Vec<u8>>) {
        self.inner.insert(kind, value.into());
    }

    /// Harden this `Profile`'s attribute values into a [Fingerprint],
    /// consuming this profile.
    ///
    /// Captures the sorted key order, then hashes each attribute value with
    /// Argon2id, producing a keyspace carrying the given proof-of-work
    /// constraint.
    ///
    /// Returns the hardened `Fingerprint` on success, or an error when the
    /// profile has too few attributes or `params` are invalid.
    pub fn harden(mut self, params: &Params) -> Result<Fingerprint<K>, HkErr> {
        // Capture the sorted key order before consuming the map
        let order: Vec<K> = self.inner.keys().copied().collect();

        // Take the raw values without cloning, leaving `self.inner` empty
        let values: Vec<Vec<u8>> =
            std::mem::take(&mut self.inner).into_values().collect();

        let argon2_params = argon2::Params::new(
            params.m_cost,
            params.t_cost,
            params.p_cost,
            None,
        )?;

        let hasher =
            Argon2::new(Algorithm::Argon2id, Version::V0x13, argon2_params);
        let collection = Attributes::<_, ChaCha20Rng>::new(values, hasher)?;
        let keyspace =
            collection.harden(params.constraint, params.context.as_deref())?;

        Ok(Fingerprint {
            keyspace,
            order,
            chars: params.chars,
        })
    }
}

impl<K> Drop for Profile<K> {
    fn drop(&mut self) {
        for value in self.inner.values_mut() {
            value.zeroize();
        }
    }
}

impl<K: AttributeKind> Extend<(K, Vec<u8>)> for Profile<K> {
    fn extend<T: IntoIterator<Item = (K, Vec<u8>)>>(&mut self, iter: T) {
        self.inner.extend(iter);
    }
}

impl<K: AttributeKind> FromIterator<(K, Vec<u8>)> for Profile<K> {
    fn from_iter<T: IntoIterator<Item = (K, Vec<u8>)>>(iter: T) -> Self {
        Self {
            inner: BTreeMap::from_iter(iter),
        }
    }
}

/// A hardened collection of attribute values as a fingerprint, analogous to a
/// browser or device fingerprint but based on human-derived attributes, from
/// which selection-sensitive attribute-based keys can be derived.
pub struct Fingerprint<K> {
    keyspace: Keyspace<ChaCha20Rng>,
    order: Vec<K>,
    chars: u8,
}

impl<K: AttributeKind> Fingerprint<K> {
    /// Produce a [Confirmation] for a given selection of special attributes.
    ///
    /// Returns a `Confirmation` pairing a human-readable code with the
    /// selection, for display or comparison before committing to key
    /// derivation. Returns an error when a selected attribute kind is not
    /// present in this fingerprint, the selection is empty, or covers every
    /// attribute.
    pub fn confirm(&self, selection: &[K]) -> Result<Confirmation<K>, HkErr> {
        let indices = self.resolve(selection)?;

        let (key, _) = self.keyspace.extract_pair(&indices)?;
        let mut key_bytes = key.to_bytes();
        let digest = Sha256::digest(key_bytes);
        let code = digest
            .iter()
            .take(self.chars as usize)
            .map(|b| CROCKFORD_BASE32[(b % 32) as usize] as char)
            .collect();
        key_bytes.zeroize();

        Ok(Confirmation {
            code,
            selection: selection.to_vec(),
        })
    }

    /// Derive a key using a previously produced [Confirmation].
    ///
    /// Rejects the call if the `Confirmation` is tampered or mismatched.
    /// The selected and remaining attributes are bound into an
    /// [annihilative pair](https://docs.rs/annihilation/), under the
    /// fingerprint's proof-of-work constraint, so that different selections of
    /// special attributes yield independent keys even where they overlap.
    ///
    /// Returns the derived key on success, or an error when the confirmation
    /// does not match this fingerprint, or a selected attribute kind is not
    /// present in this fingerprint.
    ///
    /// # Arguments
    /// - `confirmation`: a confirmation previously produced by the
    /// [confirm](Self::confirm) method.
    /// - `output_len`: derived key length in bytes; defaults to 32 if `None`.
    pub fn derive_key(
        &self,
        confirmation: &Confirmation<K>,
        output_len: Option<usize>,
    ) -> Result<Vec<u8>, HkErr> {
        let indices = self.verify(confirmation)?;
        Ok(self.keyspace.derive_key(&indices, output_len)?)
    }

    /// Derive a key directly from a selection of special attributes, without
    /// the confirmation check performed by the [derive_key](Self::derive_key)
    /// method.
    ///
    /// Returns the derived key on success, or an error if a selected attribute
    /// kind is not present in this fingerprint.
    ///
    /// # Arguments
    /// - `selection`: the attribute kinds selected for key derivation.
    /// - `output_len`: derived key length in bytes; defaults to 32 if `None`.
    #[cfg(feature = "unchecked")]
    pub fn derive_key_unchecked(
        &self,
        selection: &[K],
        output_len: Option<usize>,
    ) -> Result<Vec<u8>, HkErr> {
        let indices = self.resolve(selection)?;
        Ok(self.keyspace.derive_key(&indices, output_len)?)
    }

    /// Derive a key using a previously produced [Confirmation] into a provided
    /// buffer. Completes the same confirmation check and annihilative pair
    /// binding as the [derive_key](Self::derive_key) method.
    ///
    /// Returns an error when the confirmation does not match this fingerprint,
    /// or a selected attribute kind is not present in this fingerprint.
    ///
    /// # Arguments
    /// - `confirmation`: a confirmation previously produced by the
    /// [confirm](Self::confirm) method.
    /// - `dst`: buffer to fill with the derived key.
    pub fn derive_key_into(
        &self,
        confirmation: &Confirmation<K>,
        dst: &mut [u8],
    ) -> Result<(), HkErr> {
        let indices = self.verify(confirmation)?;
        Ok(self.keyspace.derive_key_into(&indices, dst)?)
    }

    /// Derive a key directly from a selection of special attributes into a
    /// provided buffer, without the confirmation check performed by the
    /// [derive_key_into](Self::derive_key_into) method.
    ///
    /// Returns an error if a selected attribute kind is not present in this
    /// fingerprint.
    ///
    /// # Arguments
    /// - `selection`: the attribute kinds selected for key derivation.
    /// - `dst`: buffer to fill with the derived key.
    #[cfg(feature = "unchecked")]
    pub fn derive_key_into_unchecked(
        &self,
        selection: &[K],
        dst: &mut [u8],
    ) -> Result<(), HkErr> {
        let indices = self.resolve(selection)?;
        Ok(self.keyspace.derive_key_into(&indices, dst)?)
    }

    fn resolve(&self, kinds: &[K]) -> Result<Vec<usize>, HkErr> {
        kinds
            .iter()
            .map(|kind| {
                self.order
                    .binary_search(kind)
                    .map_err(|_| HkErr::AttributeNotFound(format!("{kind:?}")))
            })
            .collect()
    }

    fn verify(
        &self,
        confirmation: &Confirmation<K>,
    ) -> Result<Vec<usize>, HkErr> {
        let mut expected = self.confirm(&confirmation.selection)?;

        if expected.ct_ne(confirmation).into() {
            return Err(HkErr::BadConfirmation);
        }
        expected.zeroize();

        self.resolve(&confirmation.selection)
    }
}

/// A confirmation code paired with the special attribute selection it covers.
#[derive(Debug, PartialEq, Eq, Zeroize)]
pub struct Confirmation<K> {
    code: String,
    #[zeroize(skip)]
    selection: Vec<K>,
}

impl<K: AttributeKind> Confirmation<K> {
    /// Return this `Confirmation`'s alphanumeric code, for display or
    /// comparison.
    pub fn code(&self) -> &str {
        &self.code
    }

    /// Return the special attribute selection this `Confirmation` covers.
    pub fn selection(&self) -> &[K] {
        &self.selection
    }
}

impl<K: AttributeKind> ConstantTimeEq for Confirmation<K> {
    fn ct_eq(&self, other: &Self) -> Choice {
        let code_eq = self.code.as_bytes().ct_eq(other.code.as_bytes());
        let selection_eq =
            Choice::from((self.selection == other.selection) as u8);

        code_eq & selection_eq
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use attrkey::AttrkeyError;

    use crate::attributes::Attribute;
    use crate::params::Params;

    fn get_params() -> Params {
        Params::new(1024, 1, 1, 8, None, None).expect("valid params")
    }

    fn make_profile() -> Profile<Attribute> {
        let mut profile = Profile::new();

        profile.insert(Attribute::Name, b"MUSTERMANN");
        profile.insert(Attribute::GivenName, b"ERIKA");
        profile.insert(Attribute::BirthName, b"GABLER");
        profile.insert(Attribute::DateOfBirth, b"12.08.1964");
        profile.insert(Attribute::Nationality, b"DEUTSCH");
        profile.insert(Attribute::CityOfBirth, b"BERLIN");
        profile.insert(Attribute::EyeColor, b"GREEN");
        profile.insert(Attribute::Height, b"160CM");

        profile
    }

    fn make_fingerprint() -> Fingerprint<Attribute> {
        let params = get_params();

        make_profile()
            .harden(&params)
            .expect("hardening should produce a fingerprint")
    }

    #[test]
    fn drop_zeroizes_remaining_values() {
        let mut profile = Profile::new();
        profile.insert(Attribute::Name, b"MUSTERMANN");
        profile.insert(Attribute::GivenName, b"ERIKA");
        profile.insert(Attribute::DateOfBirth, b"12.08.1964");

        drop(profile);
    }

    #[test]
    fn extend_adds_attributes() {
        let mut profile = Profile::new();
        profile.insert(Attribute::Name, b"MUSTERMANN");

        profile.extend([
            (Attribute::GivenName, b"ERIKA".to_vec()),
            (Attribute::DateOfBirth, b"12.08.1964".to_vec()),
        ]);
        assert_eq!(profile.inner.len(), 3);
    }

    #[test]
    fn collects_into_profile_from_iterator() {
        let data = [
            (Attribute::Name, b"MUSTERMANN".to_vec()),
            (Attribute::GivenName, b"ERIKA".to_vec()),
            (Attribute::DateOfBirth, b"12.08.1964".to_vec()),
        ];

        let profile: Profile<Attribute> = data.into_iter().collect();
        assert_eq!(profile.inner.len(), 3);
    }

    #[test]
    fn harden_produces_fingerprint() {
        let params = get_params();
        let result = make_profile().harden(&params);
        assert!(result.is_ok())
    }

    #[test]
    fn harden_fails_empty_profile() {
        let empty: Profile<Attribute> = Profile::new();
        let params = get_params();

        // Hardening an empty profile must result in an error
        let result = empty.harden(&params);
        assert!(matches!(
            result,
            Err(HkErr::Attrkey(AttrkeyError::AttributesTooFew))
        ))
    }

    #[test]
    fn confirm_produces_confirmation() {
        let fingerprint = make_fingerprint();
        let selection = [Attribute::Name, Attribute::EyeColor];

        let result = fingerprint.confirm(&selection);
        assert!(result.is_ok());

        // Produced confirmation must include a code and selection
        let confirmation = result.unwrap();
        assert!(!confirmation.code().is_empty());
        assert!(
            confirmation
                .code()
                .bytes()
                .all(|b| CROCKFORD_BASE32.contains(&b))
        );
        assert_eq!(confirmation.selection(), selection.as_slice());
    }

    #[test]
    fn confirm_fails_empty_selection() {
        let fingerprint = make_fingerprint();

        // Confirming an empty selection must result in an error
        let result = fingerprint.confirm(&[]);
        assert!(matches!(
            result,
            Err(HkErr::Attrkey(AttrkeyError::IndicesTooFew))
        ));
    }

    #[test]
    fn confirm_fails_attribute_not_found() {
        let fingerprint = make_fingerprint();
        let selection = [Attribute::Employer];

        // Confirming selection outside the profile must result in an error
        let result = fingerprint.confirm(&selection);
        let expected = format!("{:?}", Attribute::Employer);
        assert_eq!(result, Err(HkErr::AttributeNotFound(expected)))
    }

    #[test]
    fn confirm_fails_selecting_all_attributes() {
        let fingerprint = make_fingerprint();
        let selection = [
            Attribute::Name,
            Attribute::GivenName,
            Attribute::BirthName,
            Attribute::DateOfBirth,
            Attribute::Nationality,
            Attribute::CityOfBirth,
            Attribute::EyeColor,
            Attribute::Height,
        ];

        // Selecting all attributes for confirmation must result in an error
        let result = fingerprint.confirm(&selection);
        assert!(matches!(
            result,
            Err(HkErr::Attrkey(AttrkeyError::IndicesTooMany))
        ));
    }

    #[test]
    fn derive_key_produces_key() {
        let fingerprint = make_fingerprint();
        let selection = [Attribute::Name, Attribute::EyeColor];

        let result = fingerprint.confirm(&selection);
        assert!(result.is_ok());
        let confirmation = result.unwrap();

        // Derivation with valid confirmation must yield Ok result
        let result = fingerprint.derive_key(&confirmation, None);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), 32);
    }

    #[test]
    fn derive_key_with_output_len_produces_key() {
        let fingerprint = make_fingerprint();
        let selection = [Attribute::Name, Attribute::EyeColor];

        let result = fingerprint.confirm(&selection);
        assert!(result.is_ok());
        let confirmation = result.unwrap();

        // Derivation with confirmation and output len must yield Ok result
        let result = fingerprint.derive_key(&confirmation, Some(48));
        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), 48);
    }

    #[test]
    fn derive_key_fails_bad_confirmation_tampered_code() {
        let fingerprint = make_fingerprint();
        let selection = [Attribute::Name, Attribute::EyeColor];

        let result = fingerprint.confirm(&selection);
        assert!(result.is_ok());
        let mut confirmation = result.unwrap();
        confirmation.code = "ZZZZZZ".to_string();

        // Invalid confirmation code must result in an error
        let result = fingerprint.derive_key(&confirmation, None);
        assert_eq!(result, Err(HkErr::BadConfirmation));
    }

    #[test]
    fn derive_key_fails_bad_confirmation_tampered_selection() {
        let fingerprint = make_fingerprint();
        let selection = [Attribute::Name, Attribute::EyeColor];

        let result = fingerprint.confirm(&selection);
        assert!(result.is_ok());
        let mut confirmation = result.unwrap();
        confirmation.selection =
            vec![Attribute::DateOfBirth, Attribute::Nationality];

        // Invalid confirmation selection must result in an error
        let result = fingerprint.derive_key(&confirmation, None);
        assert_eq!(result, Err(HkErr::BadConfirmation));
    }

    #[cfg(feature = "unchecked")]
    #[test]
    fn derive_key_unchecked_produces_key() {
        let fingerprint = make_fingerprint();
        let selection = [Attribute::Name, Attribute::EyeColor];

        // Unchecked derivation over selection must yield Ok result
        let result = fingerprint.derive_key_unchecked(&selection, None);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), 32);
    }

    #[cfg(feature = "unchecked")]
    #[test]
    fn derive_key_unchecked_fails_attribute_not_found() {
        let fingerprint = make_fingerprint();
        let selection = [Attribute::Employer];

        // Unchecked derivation over bad selection must result in an error
        let result = fingerprint.derive_key_unchecked(&selection, None);
        let expected = format!("{:?}", Attribute::Employer);
        assert_eq!(result, Err(HkErr::AttributeNotFound(expected)))
    }

    #[cfg(feature = "unchecked")]
    #[test]
    fn derive_key_unchecked_fails_empty_selection() {
        let fingerprint = make_fingerprint();

        // Unchecked derivation over empty selection must result in an error
        let result = fingerprint.derive_key_unchecked(&[], None);
        assert_eq!(result, Err(HkErr::Attrkey(AttrkeyError::IndicesTooFew)));
    }

    #[cfg(feature = "unchecked")]
    #[test]
    fn derive_key_unchecked_fails_selecting_all_attributes() {
        let fingerprint = make_fingerprint();
        let selection = [
            Attribute::Name,
            Attribute::GivenName,
            Attribute::BirthName,
            Attribute::DateOfBirth,
            Attribute::Nationality,
            Attribute::CityOfBirth,
            Attribute::EyeColor,
            Attribute::Height,
        ];

        // Selecting all attributes for derivation must result in an error
        let result = fingerprint.derive_key_unchecked(&selection, None);
        assert_eq!(result, Err(HkErr::Attrkey(AttrkeyError::IndicesTooMany)));
    }

    #[test]
    fn derive_key_into_fills_buffer() {
        let fingerprint = make_fingerprint();
        let selection = [Attribute::Name, Attribute::EyeColor];
        let mut dst = [0u8; 48];

        let result = fingerprint.confirm(&selection);
        assert!(result.is_ok());
        let confirmation = result.unwrap();

        // Filling buffer using confirmation must yield Ok result
        let result = fingerprint.derive_key_into(&confirmation, &mut dst);
        assert!(result.is_ok());
    }

    #[test]
    fn derive_key_into_fails_bad_confirmation() {
        let fingerprint = make_fingerprint();
        let selection = [Attribute::Name, Attribute::EyeColor];
        let mut dst = [0u8; 48];

        let result = fingerprint.confirm(&selection);
        assert!(result.is_ok());
        let mut confirmation = result.unwrap();
        confirmation.code = "ZZZZZZ".to_string();

        // Filling buffer using bad confirmation must result in an error
        let result = fingerprint.derive_key_into(&confirmation, &mut dst);
        assert_eq!(result, Err(HkErr::BadConfirmation));
    }

    #[cfg(feature = "unchecked")]
    #[test]
    fn derive_key_into_unchecked_fills_buffer() {
        let fingerprint = make_fingerprint();
        let selection = [Attribute::Name, Attribute::EyeColor];
        let mut dst = [0u8; 48];

        // Unchecked buffer filling must yield Ok result
        let result =
            fingerprint.derive_key_into_unchecked(&selection, &mut dst);
        assert!(result.is_ok());
    }
}