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
use crate::client::{decrypt, encrypt};
use crate::data::long::{
    LongAttribute, LongEncryptedAttribute, LongEncryptedPseudonym, LongPseudonym,
};
use crate::data::py::simple::{
    PyAttribute, PyEncryptedAttribute, PyEncryptedPseudonym, PyPseudonym,
};
use crate::data::simple::{Attribute, EncryptedAttribute, EncryptedPseudonym, Pseudonym};
use crate::keys::py::types::{
    PyAttributeSessionPublicKey, PyAttributeSessionSecretKey, PyPseudonymSessionPublicKey,
    PyPseudonymSessionSecretKey,
};
use crate::keys::types::{
    AttributeSessionPublicKey, AttributeSessionSecretKey, PseudonymSessionPublicKey,
    PseudonymSessionSecretKey,
};
use derive_more::{Deref, From};
use pyo3::prelude::*;
use pyo3::types::{PyAny, PyBytes};
use pyo3::Py;

/// A collection of pseudonyms that together represent a larger pseudonym value using PKCS#7 padding.
///
/// # Privacy Warning
///
/// The length (number of blocks) of a `LongPseudonym` may reveal information about the original data.
/// Consider padding your data to a fixed size before encoding to prevent length-based information leakage.
#[pyclass(name = "LongPseudonym", from_py_object)]
#[derive(Clone, Eq, PartialEq, Debug, From, Deref)]
pub struct PyLongPseudonym(pub(crate) LongPseudonym);

#[pymethods]
impl PyLongPseudonym {
    /// Create from a vector of pseudonyms.
    #[new]
    fn new(pseudonyms: Vec<PyPseudonym>) -> Self {
        let rust_pseudonyms: Vec<Pseudonym> = pseudonyms.into_iter().map(|p| p.0).collect();
        Self(LongPseudonym(rust_pseudonyms))
    }

    /// Encodes an arbitrary-length string into a `LongPseudonym` using PKCS#7 padding.
    #[staticmethod]
    #[pyo3(name = "from_string_padded")]
    fn from_string_padded(text: &str) -> Self {
        Self(LongPseudonym::from_string_padded(text))
    }

    /// Encodes an arbitrary-length byte array into a `LongPseudonym` using PKCS#7 padding.
    #[staticmethod]
    #[pyo3(name = "from_bytes_padded")]
    fn from_bytes_padded(data: &[u8]) -> Self {
        Self(LongPseudonym::from_bytes_padded(data))
    }

    /// Decodes the `LongPseudonym` back to the original string.
    #[pyo3(name = "to_string_padded")]
    fn to_string_padded(&self) -> PyResult<String> {
        self.0
            .to_string_padded()
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Decoding failed: {e}")))
    }

    /// Decodes the `LongPseudonym` back to the original byte array.
    #[pyo3(name = "to_bytes_padded")]
    fn to_bytes_padded(&self, py: Python) -> PyResult<Py<PyAny>> {
        let result = self.0.to_bytes_padded().map_err(|e| {
            pyo3::exceptions::PyValueError::new_err(format!("Decoding failed: {e}"))
        })?;
        Ok(PyBytes::new(py, &result).into())
    }

    /// Pads this LongPseudonym to a target number of blocks for batch unlinkability.
    ///
    /// In batch transcryption, all values must have identical structure to prevent
    /// linkability attacks. This method adds external padding blocks to normalize
    /// different-sized pseudonyms to the same structure.
    ///
    /// Args:
    ///     target_blocks: The desired number of blocks (must be >= current block count)
    ///
    /// Returns:
    ///     A new LongPseudonym padded to the target number of blocks
    ///
    /// Raises:
    ///     ValueError: If the current number of blocks exceeds the target
    #[pyo3(name = "pad_to")]
    fn pad_to(&self, target_blocks: usize) -> PyResult<Self> {
        self.0
            .pad_to(target_blocks)
            .map(Self)
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Padding failed: {e}")))
    }

    /// Get the underlying pseudonyms.
    #[pyo3(name = "pseudonyms")]
    fn pseudonyms(&self) -> Vec<PyPseudonym> {
        self.0 .0.iter().map(|p| PyPseudonym(*p)).collect()
    }

    /// Get the number of pseudonym blocks.
    fn __len__(&self) -> usize {
        self.0 .0.len()
    }

    fn __repr__(&self) -> String {
        format!("LongPseudonym({} blocks)", self.0 .0.len())
    }

    fn __eq__(&self, other: &PyLongPseudonym) -> bool {
        self.0 == other.0
    }
}

/// A collection of attributes that together represent a larger data value using PKCS#7 padding.
///
/// # Privacy Warning
///
/// The length (number of blocks) of a `LongAttribute` may reveal information about the original data.
/// Consider padding your data to a fixed size before encoding to prevent length-based information leakage.
#[pyclass(name = "LongAttribute", from_py_object)]
#[derive(Clone, Eq, PartialEq, Debug, From, Deref)]
pub struct PyLongAttribute(pub(crate) LongAttribute);

#[pymethods]
impl PyLongAttribute {
    /// Create from a vector of attributes.
    #[new]
    fn new(attributes: Vec<PyAttribute>) -> Self {
        let rust_attributes: Vec<Attribute> = attributes.into_iter().map(|a| a.0).collect();
        Self(LongAttribute(rust_attributes))
    }

    /// Encodes an arbitrary-length string into a `LongAttribute` using PKCS#7 padding.
    #[staticmethod]
    #[pyo3(name = "from_string_padded")]
    fn from_string_padded(text: &str) -> Self {
        Self(LongAttribute::from_string_padded(text))
    }

    /// Encodes an arbitrary-length byte array into a `LongAttribute` using PKCS#7 padding.
    #[staticmethod]
    #[pyo3(name = "from_bytes_padded")]
    fn from_bytes_padded(data: &[u8]) -> Self {
        Self(LongAttribute::from_bytes_padded(data))
    }

    /// Decodes the `LongAttribute` back to the original string.
    #[pyo3(name = "to_string_padded")]
    fn to_string_padded(&self) -> PyResult<String> {
        self.0
            .to_string_padded()
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Decoding failed: {e}")))
    }

    /// Decodes the `LongAttribute` back to the original byte array.
    #[pyo3(name = "to_bytes_padded")]
    fn to_bytes_padded(&self, py: Python) -> PyResult<Py<PyAny>> {
        let result = self.0.to_bytes_padded().map_err(|e| {
            pyo3::exceptions::PyValueError::new_err(format!("Decoding failed: {e}"))
        })?;
        Ok(PyBytes::new(py, &result).into())
    }

    /// Pads this LongAttribute to a target number of blocks for batch operations.
    ///
    /// This is useful for batch operations where all attributes must have the same structure.
    /// The padding blocks are automatically detected and skipped during decoding.
    ///
    /// Args:
    ///     target_blocks: The desired number of blocks (must be >= current block count)
    ///
    /// Returns:
    ///     A new LongAttribute padded to the target number of blocks
    ///
    /// Raises:
    ///     ValueError: If the current number of blocks exceeds the target
    #[pyo3(name = "pad_to")]
    fn pad_to(&self, target_blocks: usize) -> PyResult<Self> {
        self.0
            .pad_to(target_blocks)
            .map(Self)
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Padding failed: {e}")))
    }

    /// Get the underlying attributes.
    #[pyo3(name = "attributes")]
    fn attributes(&self) -> Vec<PyAttribute> {
        self.0 .0.iter().map(|a| PyAttribute(*a)).collect()
    }

    /// Get the number of attribute blocks.
    fn __len__(&self) -> usize {
        self.0 .0.len()
    }

    fn __repr__(&self) -> String {
        format!("LongAttribute({} blocks)", self.0 .0.len())
    }

    fn __eq__(&self, other: &PyLongAttribute) -> bool {
        self.0 == other.0
    }
}

/// A collection of encrypted pseudonyms that can be serialized as a pipe-delimited string.
#[pyclass(name = "LongEncryptedPseudonym", from_py_object)]
#[derive(Clone, Eq, PartialEq, Debug, From, Deref)]
pub struct PyLongEncryptedPseudonym(pub(crate) LongEncryptedPseudonym);

#[pymethods]
impl PyLongEncryptedPseudonym {
    /// Create from a vector of encrypted pseudonyms.
    #[new]
    fn new(encrypted_pseudonyms: Vec<PyEncryptedPseudonym>) -> Self {
        let rust_enc_pseudonyms: Vec<EncryptedPseudonym> =
            encrypted_pseudonyms.into_iter().map(|p| p.0).collect();
        Self(LongEncryptedPseudonym(rust_enc_pseudonyms))
    }

    /// Serializes to a pipe-delimited base64 string.
    #[pyo3(name = "serialize")]
    fn serialize(&self) -> String {
        self.0.serialize()
    }

    /// Deserializes from a pipe-delimited base64 string.
    #[staticmethod]
    #[pyo3(name = "deserialize")]
    fn deserialize(s: &str) -> PyResult<Self> {
        LongEncryptedPseudonym::deserialize(s)
            .map(Self)
            .map_err(|e| {
                pyo3::exceptions::PyValueError::new_err(format!("Deserialization failed: {e}"))
            })
    }

    /// Get the underlying encrypted pseudonyms.
    #[pyo3(name = "encrypted_pseudonyms")]
    fn encrypted_pseudonyms(&self) -> Vec<PyEncryptedPseudonym> {
        self.0 .0.iter().map(|p| PyEncryptedPseudonym(*p)).collect()
    }

    /// Get the number of encrypted pseudonym blocks.
    fn __len__(&self) -> usize {
        self.0 .0.len()
    }

    fn __repr__(&self) -> String {
        format!("LongEncryptedPseudonym({} blocks)", self.0 .0.len())
    }

    fn __eq__(&self, other: &PyLongEncryptedPseudonym) -> bool {
        self.0 == other.0
    }
}

/// A collection of encrypted attributes that can be serialized as a pipe-delimited string.
#[pyclass(name = "LongEncryptedAttribute", from_py_object)]
#[derive(Clone, Eq, PartialEq, Debug, From, Deref)]
pub struct PyLongEncryptedAttribute(pub(crate) LongEncryptedAttribute);

#[pymethods]
impl PyLongEncryptedAttribute {
    /// Create from a vector of encrypted attributes.
    #[new]
    fn new(encrypted_attributes: Vec<PyEncryptedAttribute>) -> Self {
        let rust_enc_attributes: Vec<EncryptedAttribute> =
            encrypted_attributes.into_iter().map(|a| a.0).collect();
        Self(LongEncryptedAttribute(rust_enc_attributes))
    }

    /// Serializes to a pipe-delimited base64 string.
    #[pyo3(name = "serialize")]
    fn serialize(&self) -> String {
        self.0.serialize()
    }

    /// Deserializes from a pipe-delimited base64 string.
    #[staticmethod]
    #[pyo3(name = "deserialize")]
    fn deserialize(s: &str) -> PyResult<Self> {
        LongEncryptedAttribute::deserialize(s)
            .map(Self)
            .map_err(|e| {
                pyo3::exceptions::PyValueError::new_err(format!("Deserialization failed: {e}"))
            })
    }

    /// Get the underlying encrypted attributes.
    #[pyo3(name = "encrypted_attributes")]
    fn encrypted_attributes(&self) -> Vec<PyEncryptedAttribute> {
        self.0 .0.iter().map(|a| PyEncryptedAttribute(*a)).collect()
    }

    /// Get the number of encrypted attribute blocks.
    fn __len__(&self) -> usize {
        self.0 .0.len()
    }

    fn __repr__(&self) -> String {
        format!("LongEncryptedAttribute({} blocks)", self.0 .0.len())
    }

    fn __eq__(&self, other: &PyLongEncryptedAttribute) -> bool {
        self.0 == other.0
    }
}

/// Encrypt a long pseudonym.
#[pyfunction]
#[pyo3(name = "encrypt_long_pseudonym")]
pub fn py_encrypt_long_pseudonym(
    message: &PyLongPseudonym,
    public_key: &PyPseudonymSessionPublicKey,
) -> PyLongEncryptedPseudonym {
    let mut rng = rand::rng();
    PyLongEncryptedPseudonym(encrypt(
        &message.0,
        &PseudonymSessionPublicKey::from(public_key.0 .0),
        &mut rng,
    ))
}

/// Decrypt a long encrypted pseudonym.
#[cfg(feature = "elgamal3")]
#[pyfunction]
#[pyo3(name = "decrypt_long_pseudonym")]
pub fn py_decrypt_long_pseudonym(
    encrypted: &PyLongEncryptedPseudonym,
    secret_key: &PyPseudonymSessionSecretKey,
) -> Option<PyLongPseudonym> {
    decrypt(
        &encrypted.0,
        &PseudonymSessionSecretKey::from(secret_key.0 .0),
    )
    .map(PyLongPseudonym)
}

/// Decrypt a long encrypted pseudonym.
#[cfg(not(feature = "elgamal3"))]
#[pyfunction]
#[pyo3(name = "decrypt_long_pseudonym")]
pub fn py_decrypt_long_pseudonym(
    encrypted: &PyLongEncryptedPseudonym,
    secret_key: &PyPseudonymSessionSecretKey,
) -> PyLongPseudonym {
    PyLongPseudonym(decrypt(
        &encrypted.0,
        &PseudonymSessionSecretKey::from(secret_key.0 .0),
    ))
}

/// Encrypt a long attribute.
#[pyfunction]
#[pyo3(name = "encrypt_long_attribute")]
pub fn py_encrypt_long_attribute(
    message: &PyLongAttribute,
    public_key: &PyAttributeSessionPublicKey,
) -> PyLongEncryptedAttribute {
    let mut rng = rand::rng();
    PyLongEncryptedAttribute(encrypt(
        &message.0,
        &AttributeSessionPublicKey::from(public_key.0 .0),
        &mut rng,
    ))
}

/// Decrypt a long encrypted attribute.
#[cfg(feature = "elgamal3")]
#[pyfunction]
#[pyo3(name = "decrypt_long_attribute")]
pub fn py_decrypt_long_attribute(
    encrypted: &PyLongEncryptedAttribute,
    secret_key: &PyAttributeSessionSecretKey,
) -> Option<PyLongAttribute> {
    decrypt(
        &encrypted.0,
        &AttributeSessionSecretKey::from(secret_key.0 .0),
    )
    .map(PyLongAttribute)
}

/// Decrypt a long encrypted attribute.
#[cfg(not(feature = "elgamal3"))]
#[pyfunction]
#[pyo3(name = "decrypt_long_attribute")]
pub fn py_decrypt_long_attribute(
    encrypted: &PyLongEncryptedAttribute,
    secret_key: &PyAttributeSessionSecretKey,
) -> PyLongAttribute {
    PyLongAttribute(decrypt(
        &encrypted.0,
        &AttributeSessionSecretKey::from(secret_key.0 .0),
    ))
}

pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
    // Register types only
    m.add_class::<PyLongPseudonym>()?;
    m.add_class::<PyLongAttribute>()?;
    m.add_class::<PyLongEncryptedPseudonym>()?;
    m.add_class::<PyLongEncryptedAttribute>()?;

    Ok(())
}