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
use crate::arithmetic::py::group_elements::PyGroupElement;
use crate::core::py::elgamal::PyElGamal;
use crate::data::padding::Padded;
use crate::data::simple::*;
use derive_more::{Deref, From, Into};
use pyo3::prelude::*;
use pyo3::types::{PyAny, PyBytes};
use pyo3::Py;

/// A pseudonym that can be used to identify a user
/// within a specific domain, which can be encrypted, rekeyed and reshuffled.
#[pyclass(name = "Pseudonym", from_py_object)]
#[derive(Copy, Clone, Eq, PartialEq, Debug, From, Into, Deref)]
pub struct PyPseudonym(pub(crate) Pseudonym);

#[pymethods]
#[allow(clippy::wrong_self_convention)]
impl PyPseudonym {
    /// Create from a [`PyGroupElement`].
    #[new]
    fn new(x: PyGroupElement) -> Self {
        Self(Pseudonym::from_point(x.0))
    }

    /// Convert to a [`PyGroupElement`].
    #[pyo3(name = "to_point")]
    fn to_point(&self) -> PyGroupElement {
        self.0.value.into()
    }

    /// Generate a random pseudonym.
    #[staticmethod]
    #[pyo3(name = "random")]
    fn random() -> Self {
        let mut rng = rand::rng();
        Self(Pseudonym::random(&mut rng))
    }

    /// Encode the pseudonym as a byte array.
    #[pyo3(name = "to_bytes")]
    fn encode(&self, py: Python) -> Py<PyAny> {
        PyBytes::new(py, &self.0.to_bytes()).into()
    }

    /// Encode the pseudonym as a hexadecimal string.
    #[pyo3(name = "to_hex")]
    fn as_hex(&self) -> String {
        self.0.to_hex()
    }

    /// Decode a pseudonym from a byte array.
    #[staticmethod]
    #[pyo3(name = "from_bytes")]
    fn decode(bytes: &[u8]) -> Option<Self> {
        Pseudonym::from_slice(bytes).map(Self)
    }

    /// Decode a pseudonym from a hexadecimal string.
    #[staticmethod]
    #[pyo3(name = "from_hex")]
    fn from_hex(hex: &str) -> Option<Self> {
        Pseudonym::from_hex(hex).map(Self)
    }

    /// Decode a pseudonym from a 64-byte hash value
    #[staticmethod]
    #[pyo3(name = "from_hash")]
    fn from_hash(v: &[u8]) -> PyResult<Self> {
        if v.len() != 64 {
            return Err(pyo3::exceptions::PyValueError::new_err(
                "Hash must be 64 bytes",
            ));
        }
        let mut arr = [0u8; 64];
        arr.copy_from_slice(v);
        Ok(Pseudonym::from_hash(&arr).into())
    }

    /// Decode from a byte array of length 16 using lizard encoding.
    /// This is useful for creating a pseudonym from an existing identifier,
    /// as it accepts any 16-byte value.
    #[staticmethod]
    #[pyo3(name = "from_lizard")]
    fn from_lizard(data: &[u8]) -> PyResult<Self> {
        if data.len() != 16 {
            return Err(pyo3::exceptions::PyValueError::new_err(
                "Data must be 16 bytes",
            ));
        }
        let mut arr = [0u8; 16];
        arr.copy_from_slice(data);
        Ok(Self(Pseudonym::from_lizard(&arr)))
    }

    /// Encode as a byte array of length 16 using lizard encoding.
    /// Returns `None` if the point is not a valid lizard encoding of a 16-byte value.
    /// If the value was created using [`PyPseudonym::from_lizard`], this will return a valid value,
    /// but otherwise it will most likely return `None`.
    #[pyo3(name = "to_lizard")]
    fn to_lizard(&self, py: Python) -> Option<Py<PyAny>> {
        self.0.to_lizard().map(|x| PyBytes::new(py, &x).into())
    }

    /// Encodes a byte array (up to 15 bytes) into a `Pseudonym` using PKCS#7 padding.
    #[staticmethod]
    #[pyo3(name = "from_bytes_padded")]
    fn from_bytes_padded(data: &[u8]) -> PyResult<Self> {
        Pseudonym::from_bytes_padded(data)
            .map(Self)
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Encoding failed: {e}")))
    }

    /// Encodes a string (up to 15 bytes) into a `Pseudonym` using PKCS#7 padding.
    #[staticmethod]
    #[pyo3(name = "from_string_padded")]
    fn from_string_padded(text: &str) -> PyResult<Self> {
        Pseudonym::from_string_padded(text)
            .map(Self)
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Encoding failed: {e}")))
    }

    /// Decodes the `Pseudonym` 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 `Pseudonym` 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())
    }

    fn __repr__(&self) -> String {
        format!("Pseudonym({})", self.as_hex())
    }

    fn __str__(&self) -> String {
        self.as_hex()
    }

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

/// An attribute which should not be identifiable
/// and can be encrypted and rekeyed, but not reshuffled.
#[pyclass(name = "Attribute", from_py_object)]
#[derive(Copy, Clone, Eq, PartialEq, Debug, From, Into, Deref)]
pub struct PyAttribute(pub(crate) Attribute);

#[pymethods]
#[allow(clippy::wrong_self_convention)]
impl PyAttribute {
    /// Create from a [`PyGroupElement`].
    #[new]
    fn new(x: PyGroupElement) -> Self {
        Self(Attribute::from_point(x.0))
    }

    /// Convert to a [`PyGroupElement`].
    #[pyo3(name = "to_point")]
    fn to_point(&self) -> PyGroupElement {
        self.0.value.into()
    }

    /// Generate a random attribute.
    #[staticmethod]
    #[pyo3(name = "random")]
    fn random() -> Self {
        let mut rng = rand::rng();
        Self(Attribute::random(&mut rng))
    }

    /// Encode the attribute as a byte array.
    #[pyo3(name = "to_bytes")]
    fn encode(&self, py: Python) -> Py<PyAny> {
        PyBytes::new(py, &self.0.to_bytes()).into()
    }

    /// Encode the attribute as a hexadecimal string.
    #[pyo3(name = "to_hex")]
    fn as_hex(&self) -> String {
        self.0.to_hex()
    }

    /// Decode an attribute from a byte array.
    #[staticmethod]
    #[pyo3(name = "from_bytes")]
    fn decode(bytes: &[u8]) -> Option<Self> {
        Attribute::from_slice(bytes).map(Self)
    }

    /// Decode an attribute from a hexadecimal string.
    #[staticmethod]
    #[pyo3(name = "from_hex")]
    fn from_hex(hex: &str) -> Option<Self> {
        Attribute::from_hex(hex).map(Self)
    }

    /// Decode an attribute from a 64-byte hash value
    #[staticmethod]
    #[pyo3(name = "from_hash")]
    fn from_hash(v: &[u8]) -> PyResult<Self> {
        if v.len() != 64 {
            return Err(pyo3::exceptions::PyValueError::new_err(
                "Hash must be 64 bytes",
            ));
        }
        let mut arr = [0u8; 64];
        arr.copy_from_slice(v);
        Ok(Attribute::from_hash(&arr).into())
    }

    /// Decode from a byte array of length 16 using lizard encoding.
    /// This is useful for encoding attributes,
    /// as it accepts any 16-byte value.
    #[staticmethod]
    #[pyo3(name = "from_lizard")]
    fn from_lizard(data: &[u8]) -> PyResult<Self> {
        if data.len() != 16 {
            return Err(pyo3::exceptions::PyValueError::new_err(
                "Data must be 16 bytes",
            ));
        }
        let mut arr = [0u8; 16];
        arr.copy_from_slice(data);
        Ok(Self(Attribute::from_lizard(&arr)))
    }

    /// Encode as a byte array of length 16 using lizard encoding.
    /// Returns `None` if the point is not a valid lizard encoding of a 16-byte value.
    /// If the value was created using [`PyAttribute::from_lizard`], this will return a valid value,
    /// but otherwise it will most likely return `None`.
    #[pyo3(name = "to_lizard")]
    fn to_lizard(&self, py: Python) -> Option<Py<PyAny>> {
        self.0.to_lizard().map(|x| PyBytes::new(py, &x).into())
    }

    /// Encodes a byte array (up to 15 bytes) into an `Attribute` using PKCS#7 padding.
    #[staticmethod]
    #[pyo3(name = "from_bytes_padded")]
    fn from_bytes_padded(data: &[u8]) -> PyResult<Self> {
        Attribute::from_bytes_padded(data)
            .map(Self)
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Encoding failed: {e}")))
    }

    /// Encodes a string (up to 15 bytes) into an `Attribute` using PKCS#7 padding.
    #[staticmethod]
    #[pyo3(name = "from_string_padded")]
    fn from_string_padded(text: &str) -> PyResult<Self> {
        Attribute::from_string_padded(text)
            .map(Self)
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Encoding failed: {e}")))
    }

    /// Decodes the `Attribute` 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 `Attribute` 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())
    }

    fn __repr__(&self) -> String {
        format!("Attribute({})", self.as_hex())
    }

    fn __str__(&self) -> String {
        self.as_hex()
    }

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

/// An encrypted pseudonym, which is an [`PyElGamal`] encryption of a [`PyPseudonym`].
#[pyclass(name = "EncryptedPseudonym", from_py_object)]
#[derive(Copy, Clone, Eq, PartialEq, Debug, From, Into, Deref)]
pub struct PyEncryptedPseudonym(pub(crate) EncryptedPseudonym);

#[pymethods]
impl PyEncryptedPseudonym {
    /// Create from an [`PyElGamal`].
    #[new]
    fn new(x: PyElGamal) -> Self {
        Self(EncryptedPseudonym::from(x.0))
    }

    /// Encode the encrypted pseudonym as a byte array.
    #[pyo3(name = "to_bytes")]
    fn encode(&self, py: Python) -> Py<PyAny> {
        PyBytes::new(py, &self.0.to_bytes()).into()
    }

    /// Decode an encrypted pseudonym from a byte array.
    #[staticmethod]
    #[pyo3(name = "from_bytes")]
    fn decode(v: &[u8]) -> Option<Self> {
        use crate::core::elgamal::ElGamal;
        ElGamal::from_slice(v).map(|eg| Self(EncryptedPseudonym::from(eg)))
    }

    /// Encode the encrypted pseudonym as a base64 string.
    #[pyo3(name = "to_base64")]
    fn as_base64(&self) -> String {
        self.to_base64()
    }

    /// Decode an encrypted pseudonym from a base64 string.
    #[staticmethod]
    #[pyo3(name = "from_base64")]
    fn from_base64(s: &str) -> Option<Self> {
        EncryptedPseudonym::from_base64(s).map(Self)
    }

    fn __repr__(&self) -> String {
        format!("EncryptedPseudonym({})", self.to_base64())
    }

    fn __str__(&self) -> String {
        self.to_base64()
    }

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

/// An encrypted attribute, which is an [`PyElGamal`] encryption of a [`PyAttribute`].
#[pyclass(name = "EncryptedAttribute", from_py_object)]
#[derive(Copy, Clone, Eq, PartialEq, Debug, From, Into, Deref)]
pub struct PyEncryptedAttribute(pub(crate) EncryptedAttribute);

#[pymethods]
impl PyEncryptedAttribute {
    /// Create from an [`PyElGamal`].
    #[new]
    fn new(x: PyElGamal) -> Self {
        Self(EncryptedAttribute::from(x.0))
    }

    /// Encode the encrypted attribute as a byte array.
    #[pyo3(name = "to_bytes")]
    fn encode(&self, py: Python) -> Py<PyAny> {
        PyBytes::new(py, &self.0.to_bytes()).into()
    }

    /// Decode an encrypted attribute from a byte array.
    #[staticmethod]
    #[pyo3(name = "from_bytes")]
    fn decode(v: &[u8]) -> Option<Self> {
        use crate::core::elgamal::ElGamal;
        ElGamal::from_slice(v).map(|eg| Self(EncryptedAttribute::from(eg)))
    }

    /// Encode the encrypted attribute as a base64 string.
    #[pyo3(name = "to_base64")]
    fn as_base64(&self) -> String {
        self.to_base64()
    }

    /// Decode an encrypted attribute from a base64 string.
    #[staticmethod]
    #[pyo3(name = "from_base64")]
    fn from_base64(s: &str) -> Option<Self> {
        EncryptedAttribute::from_base64(s).map(Self)
    }

    fn __repr__(&self) -> String {
        format!("EncryptedAttribute({})", self.to_base64())
    }

    fn __str__(&self) -> String {
        self.to_base64()
    }

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

pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_class::<PyPseudonym>()?;
    m.add_class::<PyAttribute>()?;
    m.add_class::<PyEncryptedPseudonym>()?;
    m.add_class::<PyEncryptedAttribute>()?;
    Ok(())
}