paserk 0.4.0

Platform-Agnostic Serialized Keys (PASERK) for PASETO
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
//! PBKDF2-based PBKW implementation for K1/K3.
//!
//! This module implements password-based key wrapping using PBKDF2-SHA384 for
//! key derivation and AES-256-CTR + HMAC-SHA384 for authenticated encryption.

use crate::core::error::{PaserkError, PaserkResult};

/// Salt size for PBKDF2 (32 bytes).
pub const PBKDF2_SALT_SIZE: usize = 32;

/// Nonce size for AES-256-CTR (16 bytes).
pub const AES_CTR_NONCE_SIZE: usize = 16;

/// Tag size for HMAC-SHA384 (48 bytes).
pub const PBKW_K1K3_TAG_SIZE: usize = 48;

/// Output type for local (32-byte) key wrapping: (salt, nonce, ciphertext, tag).
pub type PbkwLocalOutputK1K3 = (
    [u8; PBKDF2_SALT_SIZE],
    [u8; AES_CTR_NONCE_SIZE],
    [u8; 32],
    [u8; PBKW_K1K3_TAG_SIZE],
);

/// Output type for secret key wrapping: (salt, nonce, ciphertext, tag).
/// K1 uses RSA keys (variable size), K3 uses P-384 keys (48 bytes).
pub type PbkwSecretOutputK3 = (
    [u8; PBKDF2_SALT_SIZE],
    [u8; AES_CTR_NONCE_SIZE],
    [u8; 48],
    [u8; PBKW_K1K3_TAG_SIZE],
);

/// Domain separation for PBKW encryption key derivation.
const PBKW_EK_DOMAIN: &[u8] = b"paserk-wrap.pie-local";

/// Domain separation for PBKW authentication key derivation.
const PBKW_AK_SUFFIX: &[u8] = b"auth-key-for-tag";

/// Default PBKDF2 parameters.
#[derive(Debug, Clone, Copy)]
pub struct Pbkdf2Params {
    /// Number of iterations.
    pub iterations: u32,
}

impl Default for Pbkdf2Params {
    fn default() -> Self {
        Self::moderate()
    }
}

impl Pbkdf2Params {
    /// Interactive profile: Fast, suitable for interactive logins.
    /// - Iterations: 100,000
    #[must_use]
    pub const fn interactive() -> Self {
        Self {
            iterations: 100_000,
        }
    }

    /// Moderate profile: Balanced security and performance.
    /// - Iterations: 310,000 (OWASP 2023 recommendation for SHA-384)
    #[must_use]
    pub const fn moderate() -> Self {
        Self {
            iterations: 310_000,
        }
    }

    /// Sensitive profile: High security, slower computation.
    /// - Iterations: 600,000
    #[must_use]
    pub const fn sensitive() -> Self {
        Self {
            iterations: 600_000,
        }
    }
}

/// Derives encryption and authentication keys using PBKDF2-SHA384 and HMAC-SHA384.
#[cfg(any(feature = "k1-insecure", feature = "k3"))]
fn derive_keys_k1k3(
    password: &[u8],
    salt: &[u8; PBKDF2_SALT_SIZE],
    iterations: u32,
    domain: &[u8],
) -> PaserkResult<([u8; 32], [u8; 48])> {
    use hmac::{Hmac, Mac};
    use sha2::Sha384;

    // Derive pre-shared key using PBKDF2-SHA384
    // Output is 32 bytes (256 bits) for the PSK
    let mut psk = [0u8; 32];
    pbkdf2::pbkdf2::<Hmac<Sha384>>(password, salt, iterations, &mut psk)
        .map_err(|_| PaserkError::KeyDerivationFailed)?;

    // Derive encryption key: Ek = HMAC-SHA384(psk, domain), truncated to 32 bytes
    let mut ek_mac =
        <Hmac<Sha384> as Mac>::new_from_slice(&psk).map_err(|_| PaserkError::CryptoError)?;
    ek_mac.update(domain);
    let ek_result = ek_mac.finalize().into_bytes();
    let mut encryption_key = [0u8; 32];
    encryption_key.copy_from_slice(&ek_result[..32]);

    // Derive authentication key: Ak = HMAC-SHA384(psk, domain || auth-key-for-tag)
    let mut ak_mac =
        <Hmac<Sha384> as Mac>::new_from_slice(&psk).map_err(|_| PaserkError::CryptoError)?;
    ak_mac.update(domain);
    ak_mac.update(PBKW_AK_SUFFIX);
    let auth_key: [u8; 48] = ak_mac.finalize().into_bytes().into();

    // Zeroize PSK now that we've derived the keys
    zeroize::Zeroize::zeroize(&mut psk);

    Ok((encryption_key, auth_key))
}

/// Encrypts data using AES-256-CTR.
#[cfg(any(feature = "k1-insecure", feature = "k3"))]
fn aes_ctr_encrypt(key: &[u8; 32], nonce: &[u8; AES_CTR_NONCE_SIZE], data: &mut [u8]) {
    use aes::cipher::{KeyIvInit, StreamCipher};
    use ctr::Ctr128BE;

    type Aes256Ctr = Ctr128BE<aes::Aes256>;
    let mut cipher = Aes256Ctr::new(key.into(), nonce.into());
    cipher.apply_keystream(data);
}

/// Computes HMAC-SHA384 tag.
#[cfg(any(feature = "k1-insecure", feature = "k3"))]
fn compute_tag_k1k3(
    auth_key: &[u8; 48],
    header: &str,
    salt: &[u8],
    nonce: &[u8],
    ciphertext: &[u8],
) -> PaserkResult<[u8; PBKW_K1K3_TAG_SIZE]> {
    use hmac::{Hmac, Mac};
    use sha2::Sha384;

    let mut tag_mac =
        <Hmac<Sha384> as Mac>::new_from_slice(auth_key).map_err(|_| PaserkError::CryptoError)?;
    tag_mac.update(header.as_bytes());
    tag_mac.update(salt);
    tag_mac.update(nonce);
    tag_mac.update(ciphertext);
    Ok(tag_mac.finalize().into_bytes().into())
}

/// Wraps a local (symmetric) key using PBKW for K1/K3.
///
/// # Arguments
///
/// * `plaintext_key` - The 32-byte key to wrap
/// * `password` - The password to use for wrapping
/// * `params` - PBKDF2 parameters
/// * `header` - The PASERK header (e.g., "k3.local-pw.")
///
/// # Returns
///
/// A tuple of (salt, nonce, ciphertext, tag).
#[cfg(any(feature = "k1-insecure", feature = "k3"))]
pub fn pbkw_wrap_local_k1k3(
    plaintext_key: &[u8; 32],
    password: &[u8],
    params: Pbkdf2Params,
    header: &str,
) -> PaserkResult<PbkwLocalOutputK1K3> {
    use rand_core::{OsRng, TryRngCore};

    // Generate random salt and nonce
    let mut salt = [0u8; PBKDF2_SALT_SIZE];
    let mut nonce = [0u8; AES_CTR_NONCE_SIZE];
    OsRng
        .try_fill_bytes(&mut salt)
        .map_err(|_| PaserkError::CryptoError)?;
    OsRng
        .try_fill_bytes(&mut nonce)
        .map_err(|_| PaserkError::CryptoError)?;

    // Derive keys
    let (mut encryption_key, mut auth_key) =
        derive_keys_k1k3(password, &salt, params.iterations, PBKW_EK_DOMAIN)?;

    // Encrypt the plaintext key
    let mut ciphertext = *plaintext_key;
    aes_ctr_encrypt(&encryption_key, &nonce, &mut ciphertext);

    // Compute authentication tag
    let tag = compute_tag_k1k3(&auth_key, header, &salt, &nonce, &ciphertext)?;

    // Zeroize derived keys
    zeroize::Zeroize::zeroize(&mut encryption_key);
    zeroize::Zeroize::zeroize(&mut auth_key);

    Ok((salt, nonce, ciphertext, tag))
}

/// Unwraps a local (symmetric) key using PBKW for K1/K3.
///
/// # Arguments
///
/// * `salt` - The 32-byte PBKDF2 salt
/// * `nonce` - The 16-byte AES-CTR nonce
/// * `ciphertext` - The 32-byte encrypted key
/// * `tag` - The 48-byte authentication tag
/// * `password` - The password used for wrapping
/// * `params` - PBKDF2 parameters (must match those used for wrapping)
/// * `header` - The PASERK header (e.g., "k3.local-pw.")
///
/// # Returns
///
/// The unwrapped 32-byte plaintext key.
#[cfg(any(feature = "k1-insecure", feature = "k3"))]
pub fn pbkw_unwrap_local_k1k3(
    salt: &[u8; PBKDF2_SALT_SIZE],
    nonce: &[u8; AES_CTR_NONCE_SIZE],
    ciphertext: &[u8; 32],
    tag: &[u8; PBKW_K1K3_TAG_SIZE],
    password: &[u8],
    params: Pbkdf2Params,
    header: &str,
) -> PaserkResult<[u8; 32]> {
    use subtle::ConstantTimeEq;

    // Derive keys
    let (mut encryption_key, mut auth_key) =
        derive_keys_k1k3(password, salt, params.iterations, PBKW_EK_DOMAIN)?;

    // Verify authentication tag
    let computed_tag = compute_tag_k1k3(&auth_key, header, salt, nonce, ciphertext)?;

    // Zeroize auth key after computing tag
    zeroize::Zeroize::zeroize(&mut auth_key);

    if computed_tag.ct_eq(tag).into() {
        // Decrypt the ciphertext
        let mut plaintext = *ciphertext;
        aes_ctr_encrypt(&encryption_key, nonce, &mut plaintext);

        // Zeroize encryption key
        zeroize::Zeroize::zeroize(&mut encryption_key);

        Ok(plaintext)
    } else {
        // Zeroize encryption key on error path
        zeroize::Zeroize::zeroize(&mut encryption_key);
        Err(PaserkError::AuthenticationFailed)
    }
}

/// Wraps a P-384 secret key using PBKW for K3.
#[cfg(feature = "k3")]
pub fn pbkw_wrap_secret_k3(
    plaintext_key: &[u8; 48],
    password: &[u8],
    params: Pbkdf2Params,
    header: &str,
) -> PaserkResult<PbkwSecretOutputK3> {
    use rand_core::{OsRng, TryRngCore};

    const PBKW_SECRET_DOMAIN: &[u8] = b"paserk-wrap.pie-secret";

    // Generate random salt and nonce
    let mut salt = [0u8; PBKDF2_SALT_SIZE];
    let mut nonce = [0u8; AES_CTR_NONCE_SIZE];
    OsRng
        .try_fill_bytes(&mut salt)
        .map_err(|_| PaserkError::CryptoError)?;
    OsRng
        .try_fill_bytes(&mut nonce)
        .map_err(|_| PaserkError::CryptoError)?;

    // Derive keys
    let (mut encryption_key, mut auth_key) =
        derive_keys_k1k3(password, &salt, params.iterations, PBKW_SECRET_DOMAIN)?;

    // Encrypt the plaintext key
    let mut ciphertext = *plaintext_key;
    aes_ctr_encrypt(&encryption_key, &nonce, &mut ciphertext);

    // Compute authentication tag
    let tag = compute_tag_k1k3(&auth_key, header, &salt, &nonce, &ciphertext)?;

    // Zeroize derived keys
    zeroize::Zeroize::zeroize(&mut encryption_key);
    zeroize::Zeroize::zeroize(&mut auth_key);

    Ok((salt, nonce, ciphertext, tag))
}

/// Unwraps a P-384 secret key using PBKW for K3.
#[cfg(feature = "k3")]
pub fn pbkw_unwrap_secret_k3(
    salt: &[u8; PBKDF2_SALT_SIZE],
    nonce: &[u8; AES_CTR_NONCE_SIZE],
    ciphertext: &[u8; 48],
    tag: &[u8; PBKW_K1K3_TAG_SIZE],
    password: &[u8],
    params: Pbkdf2Params,
    header: &str,
) -> PaserkResult<[u8; 48]> {
    use subtle::ConstantTimeEq;

    const PBKW_SECRET_DOMAIN: &[u8] = b"paserk-wrap.pie-secret";

    // Derive keys
    let (mut encryption_key, mut auth_key) =
        derive_keys_k1k3(password, salt, params.iterations, PBKW_SECRET_DOMAIN)?;

    // Verify authentication tag
    let computed_tag = compute_tag_k1k3(&auth_key, header, salt, nonce, ciphertext)?;

    // Zeroize auth key after computing tag
    zeroize::Zeroize::zeroize(&mut auth_key);

    if computed_tag.ct_eq(tag).into() {
        // Decrypt the ciphertext
        let mut plaintext = *ciphertext;
        aes_ctr_encrypt(&encryption_key, nonce, &mut plaintext);

        // Zeroize encryption key
        zeroize::Zeroize::zeroize(&mut encryption_key);

        Ok(plaintext)
    } else {
        // Zeroize encryption key on error path
        zeroize::Zeroize::zeroize(&mut encryption_key);
        Err(PaserkError::AuthenticationFailed)
    }
}

#[cfg(test)]
#[allow(deprecated)]
mod tests {
    use super::*;

    // Use minimal params for fast tests
    fn test_params() -> Pbkdf2Params {
        Pbkdf2Params { iterations: 1000 }
    }

    #[test]
    #[cfg(feature = "k3")]
    fn test_pbkw_wrap_unwrap_local_k3_roundtrip() -> PaserkResult<()> {
        let plaintext_key = [0x13u8; 32];
        let password = b"hunter2";
        let params = test_params();
        let header = "k3.local-pw.";

        let (salt, nonce, ciphertext, tag) =
            pbkw_wrap_local_k1k3(&plaintext_key, password, params, header)?;

        assert_ne!(ciphertext, plaintext_key);

        let unwrapped =
            pbkw_unwrap_local_k1k3(&salt, &nonce, &ciphertext, &tag, password, params, header)?;

        assert_eq!(unwrapped, plaintext_key);
        Ok(())
    }

    #[test]
    #[cfg(feature = "k1-insecure")]
    fn test_pbkw_wrap_unwrap_local_k1_roundtrip() -> PaserkResult<()> {
        let plaintext_key = [0x13u8; 32];
        let password = b"hunter2";
        let params = test_params();
        let header = "k1.local-pw.";

        let (salt, nonce, ciphertext, tag) =
            pbkw_wrap_local_k1k3(&plaintext_key, password, params, header)?;

        assert_ne!(ciphertext, plaintext_key);

        let unwrapped =
            pbkw_unwrap_local_k1k3(&salt, &nonce, &ciphertext, &tag, password, params, header)?;

        assert_eq!(unwrapped, plaintext_key);
        Ok(())
    }

    #[test]
    #[cfg(feature = "k3")]
    fn test_pbkw_wrap_unwrap_secret_k3_roundtrip() -> PaserkResult<()> {
        let plaintext_key = [0x13u8; 48];
        let password = b"hunter2";
        let params = test_params();
        let header = "k3.secret-pw.";

        let (salt, nonce, ciphertext, tag) =
            pbkw_wrap_secret_k3(&plaintext_key, password, params, header)?;

        assert_ne!(ciphertext, plaintext_key);

        let unwrapped =
            pbkw_unwrap_secret_k3(&salt, &nonce, &ciphertext, &tag, password, params, header)?;

        assert_eq!(unwrapped, plaintext_key);
        Ok(())
    }

    #[test]
    #[cfg(feature = "k3")]
    fn test_pbkw_unwrap_wrong_password() -> PaserkResult<()> {
        let plaintext_key = [0x13u8; 32];
        let password = b"hunter2";
        let wrong_password = b"hunter3";
        let params = test_params();
        let header = "k3.local-pw.";

        let (salt, nonce, ciphertext, tag) =
            pbkw_wrap_local_k1k3(&plaintext_key, password, params, header)?;

        let result = pbkw_unwrap_local_k1k3(
            &salt,
            &nonce,
            &ciphertext,
            &tag,
            wrong_password,
            params,
            header,
        );

        assert!(matches!(result, Err(PaserkError::AuthenticationFailed)));
        Ok(())
    }

    #[test]
    #[cfg(feature = "k3")]
    fn test_pbkw_unwrap_modified_tag() -> PaserkResult<()> {
        let plaintext_key = [0x13u8; 32];
        let password = b"hunter2";
        let params = test_params();
        let header = "k3.local-pw.";

        let (salt, nonce, ciphertext, mut tag) =
            pbkw_wrap_local_k1k3(&plaintext_key, password, params, header)?;

        tag[0] ^= 0xff;

        let result =
            pbkw_unwrap_local_k1k3(&salt, &nonce, &ciphertext, &tag, password, params, header);

        assert!(matches!(result, Err(PaserkError::AuthenticationFailed)));
        Ok(())
    }

    #[test]
    fn test_pbkdf2_params_presets() {
        let interactive = Pbkdf2Params::interactive();
        assert_eq!(interactive.iterations, 100_000);

        let moderate = Pbkdf2Params::moderate();
        assert_eq!(moderate.iterations, 310_000);

        let sensitive = Pbkdf2Params::sensitive();
        assert_eq!(sensitive.iterations, 600_000);
    }
}