libpep 0.12.0

Library for polymorphic encryption and pseudonymization
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
//! Builder pattern for constructing PEPJSONValue objects.

use serde_json::Value;
use std::collections::HashMap;

use super::data::PEPJSONValue;
#[cfg(feature = "long")]
use crate::data::long::LongPseudonym;

/// Builder for constructing PEPJSONValue objects with mixed attribute and pseudonym fields.
///
/// # Example
///
/// ```ignore
/// let pep_value = PEPJSONBuilder::new()
///     .pseudonym("id", "user1@example.com")
///     .attribute("age", json!(16))
///     .attribute("verified", json!(true))
///     .attribute("scores", json!([88, 91, 85]))
///     .build();
///
/// // Then encrypt it
/// let encrypted = encrypt(&pep_value, &keys, &mut rng);
/// ```
pub struct PEPJSONBuilder {
    fields: HashMap<String, PEPJSONValue>,
}

impl PEPJSONBuilder {
    /// Create a new builder.
    pub fn new() -> Self {
        Self {
            fields: HashMap::new(),
        }
    }

    /// Create a builder from a JSON object, marking specified fields as pseudonyms.
    ///
    /// Takes a JSON value (must be an object) and a slice of field names that should
    /// be treated as pseudonyms. All other string fields are treated as regular attributes.
    ///
    /// # Arguments
    ///
    /// * `json` - A JSON value (must be an object)
    /// * `pseudonyms` - A slice of field names that should be treated as pseudonyms
    ///
    /// # Returns
    ///
    /// A `PEPJSONBuilder` with fields populated from the JSON object.
    /// Returns `None` if the JSON value is not an object or if a pseudonym field is not a string.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use serde_json::json;
    ///
    /// let data = json!({
    ///     "id": "user@example.com",
    ///     "name": "Alice",
    ///     "age": 30
    /// });
    ///
    /// let builder = PEPJSONBuilder::from_json(&data, &["id"]).unwrap();
    /// let pep_value = builder.build();
    /// ```
    pub fn from_json(json: &Value, pseudonyms: &[&str]) -> Option<Self> {
        let obj = json.as_object()?;
        let mut builder = Self::new();

        for (key, value) in obj {
            if pseudonyms.contains(&key.as_str()) {
                // This field should be a pseudonym
                let string_value = value.as_str()?;
                builder = builder.pseudonym(key, string_value);
            } else {
                // Regular attribute
                builder = builder.attribute(key, value.clone());
            }
        }

        Some(builder)
    }

    /// Add a field as a regular attribute (from a JSON value).
    pub fn attribute(mut self, key: &str, value: Value) -> Self {
        let pep_value = PEPJSONValue::from_value(&value);
        self.fields.insert(key.to_string(), pep_value);
        self
    }

    /// Add a string field as a pseudonym.
    pub fn pseudonym(mut self, key: &str, value: &str) -> Self {
        use crate::data::padding::Padded;
        use crate::data::simple::{ElGamalEncryptable, Pseudonym};

        // Try to decode as a direct 32-byte pseudonym value (hex string)
        if let Some(pseudo) = Pseudonym::from_hex(value) {
            self.fields
                .insert(key.to_string(), PEPJSONValue::Pseudonym(pseudo));
            return self;
        }

        // Try to decode as multi-block pseudonym (hex string with multiple 64-char blocks)
        // Each block is 32 bytes = 64 hex chars
        if value.len() > 64 && value.len().is_multiple_of(64) {
            let num_blocks = value.len() / 64;
            let mut blocks = Vec::with_capacity(num_blocks);
            let mut all_decoded = true;

            for i in 0..num_blocks {
                let start = i * 64;
                let end = start + 64;
                if let Some(block) = Pseudonym::from_hex(&value[start..end]) {
                    blocks.push(block);
                } else {
                    all_decoded = false;
                    break;
                }
            }

            if all_decoded {
                self.fields.insert(
                    key.to_string(),
                    PEPJSONValue::LongPseudonym(LongPseudonym(blocks)),
                );
                return self;
            }
        }

        // Try to decode as 32 raw bytes
        if value.len() == 32 {
            if let Some(pseudo) = Pseudonym::from_slice(value.as_bytes()) {
                self.fields
                    .insert(key.to_string(), PEPJSONValue::Pseudonym(pseudo));
                return self;
            }
        }

        // Try to decode as multi-block pseudonym (raw bytes, multiple of 32)
        let bytes = value.as_bytes();
        if bytes.len() > 32 && bytes.len().is_multiple_of(32) {
            let num_blocks = bytes.len() / 32;
            let mut blocks = Vec::with_capacity(num_blocks);
            let mut all_decoded = true;

            for i in 0..num_blocks {
                let start = i * 32;
                let end = start + 32;
                if let Some(block) = Pseudonym::from_slice(&bytes[start..end]) {
                    blocks.push(block);
                } else {
                    all_decoded = false;
                    break;
                }
            }

            if all_decoded {
                self.fields.insert(
                    key.to_string(),
                    PEPJSONValue::LongPseudonym(LongPseudonym(blocks)),
                );
                return self;
            }
        }

        // Check if it fits in a single block with PKCS#7 padding (≤15 bytes)
        if bytes.len() <= 15 {
            // Use PKCS#7 padding for short strings
            match Pseudonym::from_string_padded(value) {
                Ok(pseudo) => {
                    self.fields
                        .insert(key.to_string(), PEPJSONValue::Pseudonym(pseudo));
                }
                Err(_) => {
                    // Fallback to long pseudonym if padding fails
                    let pseudo = LongPseudonym::from_string_padded(value);
                    self.fields
                        .insert(key.to_string(), PEPJSONValue::LongPseudonym(pseudo));
                }
            }
        } else {
            // Use long pseudonym for strings > 15 bytes
            let pseudo = LongPseudonym::from_string_padded(value);
            self.fields
                .insert(key.to_string(), PEPJSONValue::LongPseudonym(pseudo));
        }

        self
    }

    /// Build the final PEPJSONValue object.
    pub fn build(self) -> PEPJSONValue {
        PEPJSONValue::Object(self.fields)
    }
}

impl Default for PEPJSONBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::client::{decrypt, encrypt};
    use crate::factors::contexts::EncryptionContext;
    use crate::factors::EncryptionSecret;
    use crate::keys::{
        make_attribute_global_keys, make_attribute_session_keys, make_pseudonym_global_keys,
        make_pseudonym_session_keys, AttributeSessionKeys, PseudonymSessionKeys, SessionKeys,
    };
    use serde_json::json;

    fn make_test_keys() -> SessionKeys {
        let mut rng = rand::rng();
        let (_, attr_global_secret) = make_attribute_global_keys(&mut rng);
        let (_, pseudo_global_secret) = make_pseudonym_global_keys(&mut rng);
        let enc_secret = EncryptionSecret::from("test-secret".as_bytes().to_vec());
        let session = EncryptionContext::from("session-1");

        let (attr_public, attr_secret) =
            make_attribute_session_keys(&attr_global_secret, &session, &enc_secret);
        let (pseudo_public, pseudo_secret) =
            make_pseudonym_session_keys(&pseudo_global_secret, &session, &enc_secret);

        SessionKeys {
            attribute: AttributeSessionKeys {
                public: attr_public,
                secret: attr_secret,
            },
            pseudonym: PseudonymSessionKeys {
                public: pseudo_public,
                secret: pseudo_secret,
            },
        }
    }

    #[test]
    fn builder_with_pseudonym_id() {
        let mut rng = rand::rng();
        let keys = make_test_keys();

        let pep_value = PEPJSONBuilder::new()
            .pseudonym("id", "user1@example.com")
            .attribute("age", json!(16))
            .attribute("verified", json!(true))
            .attribute("scores", json!([88, 91, 85]))
            .build();

        let encrypted = encrypt(&pep_value, &keys, &mut rng);
        #[cfg(feature = "elgamal3")]
        let decrypted = decrypt(&encrypted, &keys).unwrap();

        #[cfg(not(feature = "elgamal3"))]
        let decrypted = decrypt(&encrypted, &keys);

        let expected = json!({
            "id": "user1@example.com",
            "age": 16,
            "verified": true,
            "scores": [88, 91, 85]
        });

        assert_eq!(expected, decrypted.to_value().unwrap());
    }

    #[test]
    fn builder_empty_object() {
        let mut rng = rand::rng();
        let keys = make_test_keys();

        let pep_value = PEPJSONBuilder::new().build();

        let encrypted = encrypt(&pep_value, &keys, &mut rng);
        #[cfg(feature = "elgamal3")]
        let decrypted = decrypt(&encrypted, &keys).unwrap();

        #[cfg(not(feature = "elgamal3"))]
        let decrypted = decrypt(&encrypted, &keys);

        assert_eq!(json!({}), decrypted.to_value().unwrap());
    }

    #[test]
    fn builder_only_attributes() {
        let mut rng = rand::rng();
        let keys = make_test_keys();

        let pep_value = PEPJSONBuilder::new()
            .attribute("name", json!("Alice"))
            .attribute("age", json!(30))
            .build();

        let encrypted = encrypt(&pep_value, &keys, &mut rng);
        #[cfg(feature = "elgamal3")]
        let decrypted = decrypt(&encrypted, &keys).unwrap();

        #[cfg(not(feature = "elgamal3"))]
        let decrypted = decrypt(&encrypted, &keys);

        let expected = json!({
            "name": "Alice",
            "age": 30
        });

        assert_eq!(expected, decrypted.to_value().unwrap());
    }

    #[test]
    fn builder_only_pseudonyms() {
        let mut rng = rand::rng();
        let keys = make_test_keys();

        let pep_value = PEPJSONBuilder::new()
            .pseudonym("id1", "user1@example.com")
            .pseudonym("id2", "user2@example.com")
            .build();

        let encrypted = encrypt(&pep_value, &keys, &mut rng);
        #[cfg(feature = "elgamal3")]
        let decrypted = decrypt(&encrypted, &keys).unwrap();

        #[cfg(not(feature = "elgamal3"))]
        let decrypted = decrypt(&encrypted, &keys);

        let expected = json!({
            "id1": "user1@example.com",
            "id2": "user2@example.com"
        });

        assert_eq!(expected, decrypted.to_value().unwrap());
    }

    #[test]
    fn from_json_with_pseudonyms() {
        let mut rng = rand::rng();
        let keys = make_test_keys();

        let data = json!({
            "id": "user@example.com",
            "name": "Alice",
            "age": 30,
            "verified": true
        });

        let pep_value = PEPJSONBuilder::from_json(&data, &["id"]).unwrap().build();

        let encrypted = encrypt(&pep_value, &keys, &mut rng);
        #[cfg(feature = "elgamal3")]
        let decrypted = decrypt(&encrypted, &keys).unwrap();

        #[cfg(not(feature = "elgamal3"))]
        let decrypted = decrypt(&encrypted, &keys);

        assert_eq!(data, decrypted.to_value().unwrap());
    }

    #[test]
    fn from_json_multiple_pseudonyms() {
        let mut rng = rand::rng();
        let keys = make_test_keys();

        let data = json!({
            "user_id": "user@example.com",
            "email": "user@example.com",
            "name": "Alice",
            "age": 30
        });

        let pep_value = PEPJSONBuilder::from_json(&data, &["user_id", "email"])
            .unwrap()
            .build();

        let encrypted = encrypt(&pep_value, &keys, &mut rng);
        #[cfg(feature = "elgamal3")]
        let decrypted = decrypt(&encrypted, &keys).unwrap();

        #[cfg(not(feature = "elgamal3"))]
        let decrypted = decrypt(&encrypted, &keys);

        assert_eq!(data, decrypted.to_value().unwrap());
    }

    #[test]
    fn from_json_no_pseudonyms() {
        let mut rng = rand::rng();
        let keys = make_test_keys();

        let data = json!({
            "name": "Alice",
            "age": 30,
            "scores": [88, 91, 85]
        });

        let pep_value = PEPJSONBuilder::from_json(&data, &[]).unwrap().build();

        let encrypted = encrypt(&pep_value, &keys, &mut rng);
        #[cfg(feature = "elgamal3")]
        let decrypted = decrypt(&encrypted, &keys).unwrap();

        #[cfg(not(feature = "elgamal3"))]
        let decrypted = decrypt(&encrypted, &keys);

        assert_eq!(data, decrypted.to_value().unwrap());
    }

    #[test]
    fn from_json_empty_object() {
        let data = json!({});

        let pep_value = PEPJSONBuilder::from_json(&data, &[]).unwrap().build();

        // Just verify it can be built
        assert!(matches!(pep_value, PEPJSONValue::Object(_)));
    }

    #[test]
    fn from_json_non_object_returns_none() {
        let data = json!([1, 2, 3]);
        assert!(PEPJSONBuilder::from_json(&data, &[]).is_none());

        let data = json!("string");
        assert!(PEPJSONBuilder::from_json(&data, &[]).is_none());

        let data = json!(42);
        assert!(PEPJSONBuilder::from_json(&data, &[]).is_none());
    }

    #[test]
    fn from_json_pseudonym_not_string_returns_none() {
        let data = json!({
            "id": 123,
            "name": "Alice"
        });

        // "id" should be a pseudonym but it's not a string
        assert!(PEPJSONBuilder::from_json(&data, &["id"]).is_none());
    }
}