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
// Copyright 2019 Alex Ostrovski
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Hierarchical secret derivation with Blake2b and random number generators.
//!
//! # How it works
//!
//! This crate provides [`SecretTree`] – a structure produced from a 32-byte seed that
//! may be converted into a secret key or a cryptographically secure
//! pseudo-random number generator (CSPRNG).
//! Besides that, an `SecretTree` can produce child trees, which are
//! identified by a string [`Name`] or an integer index. This enables creating
//! *hierarchies* of secrets (like `some_secret/0`, `some_secret/1` and `other_secret/foo/1/bar`),
//! which are ultimately derived from a single `SecretTree`. It’s enough to securely store
//! the seed of this root tree (e.g., in a passphrase-encrypted form) to recreate all secrets.
//!
//! The derived secrets cannot be linked; leakage of a derived secret does not compromise
//! sibling secrets or the parent `SecretTree`.
//!
//! # Implementation details
//!
//! `SecretTree` uses the [Blake2b] keyed hash function to derive the following kinds of data:
//!
//! - secret key
//! - CSPRNG seed (the RNG used is [`ChaChaRng`])
//! - seeds for child `SecretTree`s
//!
//! The procedure is similar to the use of Blake2b for key derivation in [libsodium]\:
//!
//! - Blake2b is used with a custom initialization block. The block has two
//! customizable parameters of interest: *salt* and *personalization* (each is 16 bytes).
//! See the table below for information how these two parameters are set for each type
//! of derived data.
//! - The key is the seed of the `SecretTree` instance used for derivation.
//! - The message is an empty bit string.
//!
//! The length of derived data is 32 bytes in all cases.
//!
//! ## Salt and personalization
//!
//! | Data type | Salt | Personalization |
//! |:----------|:-----|:----------------|
//! | Secret key | `[0; 16]` | `b"bytes\0\0...\0"` |
//! | CSPRNG seed | `[0; 16]` | `b"rng\0\0...\0"` |
//! | Seed for a named child | `name.as_bytes()` (zero-padded) | `b"name\0\0...\0"` |
//! | Seed for an indexed child | `LittleEndian(index)` | `b"index\0\0...\0"` |
//!
//! Derivation of a secret key, CSPRNG seed and seeds for indexed children are
//! all fully compatible with libsodium.
//! libsodium uses the salt section in the Blake2b initialization block to store
//! the *index* of a child key, and the personalization section to store its *context*.
//!
//! For example, the CSPRNG seed can be computed as follows (if we translate libsodium API
//! from C to Rust):
//!
//! ```
//! use rand::{SeedableRng};
//! use rand_chacha::ChaChaRng;
//! # fn crypto_kdf_derive_from_key(_: &mut [u8], _: u64, _: &[u8; 8], _: &[u8; 32]) {}
//!
//! let parent_seed: [u8; 32] = // ...
//! # [0; 32];
//! let mut rng_seed = [0; 32];
//! crypto_kdf_derive_from_key(
//! &mut rng_seed,
//! /* index */ 0,
//! /* context */ b"rng\0\0\0\0\0",
//! /* master_key */ &parent_seed,
//! );
//! let rng = ChaChaRng::from_seed(rng_seed);
//! ```
//!
//! In case of named children, we utilize the entire salt section, while libsodium
//! only uses the first 8 bytes.
//!
//! # Design motivations
//!
//! - We allow to derive RNGs besides keys in order to allow a richer variety of applications.
//! RNGs can be used in more complex use cases than fixed-size byte arrays,
//! e.g., when the length of the secret depends on previous RNG output, or RNG is used to sample
//! a complex distribution.
//! - Derivation in general (instead of using a single `SeedableRng` to create all secrets)
//! allows to add new secrets or remove old ones without worrying about compatibility.
//! - Child RNGs identified by an index can be used to derive secrets of the same type,
//! the quantity of which is unbounded. As an example, they can be used to produce
//! blinding factors for [Pedersen commitments] (e.g., in a privacy-focused cryptocurrency).
//! - Some steps are taken to make it difficult to use `SecretTree` incorrectly. For example,
//! `rng()` and `fill()` methods consume the tree instance, which makes it harder to reuse
//! the same RNG for multiple purposes (which is not intended).
//!
//! # Crate features
//!
//! The crate supports both `rand` v0.6 and v0.7 (the latter is used by default).
//! To signal the version, specify a `rand-06` or `rand-07` feature (naturally, they are mutually
//! exclusive). `rand-07` is on by default, so it is necessary to specify
//! `default-features = false` if using `rand-06`.
//!
//! [libsodium]: https://download.libsodium.org/doc/key_derivation
//! [Blake2b]: https://tools.ietf.org/html/rfc7693
//! [Pedersen commitments]: https://en.wikipedia.org/wiki/Commitment_scheme
//! [`ChaChaRng`]: https://docs.rs/rand_chacha/0.1.0/rand_chacha/
//! [`SecretTree`]: struct.SecretTree.html
//! [`Name`]: struct.Name.html
extern crate std;
use ClearOnDrop;
// Conditionally specified `rand` dependencies. It would be tempting to just specify
//
// ```toml
// [dependencies]
// rand = ">=0.6, <=0.7"
// ```
//
// in the crate manifest, but this doesn't really work, since `rand` types are present
// in the public interface of `SecretTree`. If one wants to use the crate with rand v0.6,
// he has no other choice than to manually downgrade via `cargo update rand:0.7.x --precise 0.6.x`,
// and even this may not work (v0.7 may be used elsewhere).
use ;
use fmt;
pub use SEED_LEN;
use ;
/// Maximum byte length of a `Name` (16).
pub const MAX_NAME_LEN: usize = SALT_LEN;
/// Alias for an array that contains seed bytes.
pub type Seed = ;
/// Seeded structure that can be used to produce secrets and child `SecretTree`s.
///
/// # Usage
///
/// During the program lifecycle, a root `SecretTree` should be restored from
/// a secure persistent form (e.g., a passphrase-encrypted file) and then used to derive
/// child trees and secrets. On the first use, the root should be initialized from a CSPRNG, such
/// as `rand::thread_rng()`. The tree is not needed during the program execution and can
/// be safely dropped after deriving necessary secrets (which zeroes out the tree seed).
///
/// It is possible to modify the derivation hierarchy over the course of program evolution
/// by adding new secrets or abandoning the existing ones.
/// However, the purpose of any given tree path should be fixed; that is, if some version
/// of a program used path `foo/bar` to derive an Ed25519 keypair, a newer version
/// shouldn’t use `foo/bar` to derive an AES-128 key. Violating this rule may lead
/// to leaking the secret.
///
/// # Examples
///
/// ```
/// use secret_tree::{SecretTree, Name};
/// use rand::{Rng, thread_rng};
///
/// let tree = SecretTree::new(&mut thread_rng());
/// let mut first_secret = [0_u8; 32];
/// tree.child(Name::new("first")).fill(&mut first_secret);
///
/// // We can derive hierarchical secrets. The secrets below
/// // follow logical paths `sequence/0`, `sequence/1`, .., `sequence/4`
/// // relative to the `tree`.
/// let child_store = tree.child(Name::new("sequence"));
/// let more_secrets: Vec<[u64; 4]> = (0..5)
/// .map(|i| child_store.index(i).rng().gen())
/// .collect();
///
/// // The tree is compactly stored as a single 32-byte seed.
/// let seed = *tree.seed();
/// drop(tree);
///
/// // If we restore the tree from the seed, we can restore all derived secrets.
/// let tree = SecretTree::from_seed(&seed).unwrap();
/// let mut restored_secret = [0_u8; 32];
/// tree.child(Name::new("first")).fill(&mut restored_secret);
/// assert_eq!(first_secret, restored_secret);
/// ```
/// Name of a child `SecretTree`.
///
/// Used in the `child()` method of [`SecretTree`]; see its documentation for more info.
///
/// [`SecretTree`]: struct.SecretTree.html
;