pydantic_encryption 0.0.2a1__tar.gz → 0.0.2a2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,253 @@
1
+ Metadata-Version: 2.3
2
+ Name: pydantic_encryption
3
+ Version: 0.0.2a2
4
+ Summary: Encryption and hashing models for Pydantic
5
+ Author: Julien Kmec
6
+ Author-email: me@julien.dev
7
+ Requires-Python: >=3.9,<4.0.0
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.9
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Provides-Extra: all
15
+ Provides-Extra: evervault
16
+ Provides-Extra: generics
17
+ Provides-Extra: test
18
+ Requires-Dist: bcrypt (>=4.3.0,<5.0.0)
19
+ Requires-Dist: coverage (>=7.8.0) ; extra == "all"
20
+ Requires-Dist: coverage (>=7.8.0) ; extra == "test"
21
+ Requires-Dist: evervault (>=4.4.1) ; extra == "all"
22
+ Requires-Dist: evervault (>=4.4.1) ; extra == "evervault"
23
+ Requires-Dist: pydantic (>=2.10.6)
24
+ Requires-Dist: pydantic-settings (>=2.9.1)
25
+ Requires-Dist: pytest (>=8.3.5) ; extra == "all"
26
+ Requires-Dist: pytest (>=8.3.5) ; extra == "test"
27
+ Requires-Dist: python-generics (>=0.2.3) ; extra == "all"
28
+ Requires-Dist: python-generics (>=0.2.3) ; extra == "generics"
29
+ Description-Content-Type: text/markdown
30
+
31
+ # Encryption and hashing models for Pydantic
32
+
33
+ This package provides Pydantic field annotations that encrypt, decrypt, and hash field values.
34
+
35
+ ## Installation
36
+
37
+ Install with Pip:
38
+ ```bash
39
+ pip install pydantic_encryption[evervault,generics]
40
+ ```
41
+
42
+ ## Features
43
+
44
+ - Encrypt and decrypt specific fields
45
+ - Hash specific fields
46
+ - Support for generics
47
+
48
+ ## Example
49
+
50
+ ```python
51
+ from pydantic_encryption import BaseModel, Encrypt, Hash, Annotated
52
+
53
+ class User(BaseModel):
54
+ name: str
55
+ address: Annotated[str, Encrypt] # This field will be encrypted
56
+ password: Annotated[str, Hash] # This field will be hashed
57
+
58
+ user = User(name="John Doe", address="123456", password="secret123")
59
+
60
+ print(user.name) # plaintext (untouched)
61
+ print(user.address) # encrypted
62
+ print(user.password) # hashed
63
+ ```
64
+
65
+ ## Choose an Encryption Method
66
+
67
+ ### Evervault
68
+
69
+ If you install this package with the `evervault` extra, you can use [Evervault](https://evervault.com/) to encrypt and decrypt fields.
70
+
71
+ You need to set the following environment variables or add them to your `.env` file:
72
+
73
+ ```bash
74
+ EVERVAULT_APP_ID=your_app_id
75
+ EVERVAULT_API_KEY=your_api_key
76
+ EVERVAULT_ENCRYPTION_ROLE=your_encryption_role
77
+ ```
78
+
79
+ ### Custom Encryption
80
+
81
+ You can define your own encryption and decryption methods by subclassing `SecureModel`. `SecureModel` provides you with the utilities to handle encryption, decryption, and hashing.
82
+
83
+ `self.pending_encryption_fields`, `self.pending_decryption_fields`, and `self.pending_hash_fields` are dictionaries of field names to field values that need to be encrypted, decrypted, or hashed, i.e., fields annotated with `Encrypt`, `Decrypt`, or `Hash`.
84
+
85
+ You can override the `encrypt_data`, `decrypt_data`, and `hash_data` methods to implement your own encryption, decryption, and hashing logic. You then need to override `model_post_init` to call these methods.
86
+
87
+ First, define a custom secure model:
88
+
89
+ ```python
90
+ from typing import Any, override
91
+ from pydantic import BaseModel as PydanticBaseModel
92
+ from pydantic_encryption import SecureModel
93
+
94
+ class MySecureModel(PydanticBaseModel, SecureModel):
95
+ @override
96
+ def encrypt_data(self) -> None:
97
+ # Your encryption logic here
98
+ pass
99
+
100
+ @override
101
+ def decrypt_data(self) -> None:
102
+ # Your decryption logic here
103
+ pass
104
+
105
+ @override
106
+ def hash_data(self) -> None:
107
+ # Your hashing logic here
108
+ pass
109
+
110
+ @override
111
+ def model_post_init(self, context: Any, /) -> None:
112
+ if not self._disable:
113
+ if self.pending_decryption_fields:
114
+ self.decrypt_data()
115
+
116
+ if self.pending_encryption_fields:
117
+ self.encrypt_data()
118
+
119
+ if self.pending_hash_fields:
120
+ self.hash_data()
121
+
122
+ super().model_post_init(context)
123
+ ```
124
+
125
+ Then use it:
126
+
127
+ ```python
128
+ from typing import Annotated
129
+ from pydantic import BaseModel # Here, we don't use the BaseModel provided by the library, but the native one from Pydantic
130
+ from pydantic_encryption import Encrypt
131
+
132
+ class MyModel(BaseModel, MySecureModel):
133
+ username: str
134
+ address: Annotated[str, Encrypt]
135
+
136
+ model = MyModel(username="john_doe", address="123456")
137
+ print(model.address) # encrypted
138
+ ```
139
+
140
+ ## Encryption
141
+
142
+ You can encrypt any field by using the `Encrypt` annotation with `Annotated` and inheriting from `BaseModel`.
143
+
144
+ ```python
145
+ from typing import Annotated
146
+ from pydantic_encryption import Encrypt, BaseModel
147
+
148
+ class User(BaseModel):
149
+ name: str
150
+ address: Annotated[str, Encrypt] # This field will be encrypted
151
+
152
+ user = User(name="John Doe", address="123456")
153
+ print(user.address) # encrypted
154
+ print(user.name) # plaintext (untouched)
155
+ ```
156
+
157
+ The fields marked with `Encrypt` are automatically encrypted during model initialization.
158
+
159
+ ## Decryption
160
+
161
+ Similar to encryption, you can decrypt any field by using the `Decrypt` annotation with `Annotated` and inheriting from `BaseModel`.
162
+
163
+ ```python
164
+ from typing import Annotated
165
+ from pydantic_encryption import Decrypt, BaseModel
166
+
167
+ class UserResponse(BaseModel):
168
+ name: str
169
+ address: Annotated[str, Decrypt] # This field will be decrypted
170
+
171
+ user = UserResponse(**user_data) # encrypted value
172
+ print(user.address) # decrypted
173
+ print(user.name) # plaintext (untouched)
174
+ ```
175
+
176
+ Fields marked with `Decrypt` are automatically decrypted during model initialization.
177
+
178
+
179
+ ## Hashing
180
+
181
+ You can hash sensitive data like passwords by using the `Hash` annotation.
182
+
183
+ ```python
184
+ from typing import Annotated
185
+ from pydantic_encryption import Hash, BaseModel
186
+
187
+ class User(BaseModel):
188
+ username: str
189
+ password: Annotated[str, Hash] # This field will be hashed
190
+
191
+ user = User(username="john_doe", password="secret123")
192
+ print(user.password) # hashed value
193
+ ```
194
+
195
+ Fields marked with `Hash` are automatically hashed using bcrypt during model initialization.
196
+
197
+ ## Disable Auto Processing
198
+
199
+ You can disable automatic encryption/decryption/hashing by setting `disable` to `True` in the class definition.
200
+
201
+ ```python
202
+ from typing import Annotated
203
+ from pydantic_encryption import Encrypt, BaseModel
204
+
205
+ class UserResponse(BaseModel, disable=True):
206
+ name: str
207
+ address: Annotated[str, Encrypt]
208
+
209
+ # To encrypt/decrypt/hash, call the respective methods manually:
210
+ user = UserResponse(name="John Doe", address="123 Main St")
211
+
212
+ # Manual encryption
213
+ user.encrypt_data()
214
+ print(user.address) # encrypted
215
+
216
+ # Or user.decrypt_data() to decrypt and user.hash_data() to hash
217
+ ```
218
+
219
+ ## Generics
220
+
221
+ Each BaseModel has an additional helpful method that will tell you its generic type.
222
+
223
+ To use generics, you must install this package with the `generics` extra: `pip install pydantic_encryption[generics]`.
224
+
225
+ ```py
226
+ from pydantic_encryption import BaseModel
227
+
228
+ class MyModel[T](BaseModel):
229
+ value: T
230
+
231
+ model = MyModel[str](value="Hello")
232
+ print(model.get_type()) # <class 'str'>
233
+ ```
234
+
235
+ ## Run Tests
236
+
237
+ Install [Poetry](https://python-poetry.org/docs/) and run:
238
+
239
+ ```bash
240
+ poetry install --with test
241
+ poetry run coverage run -m pytest -v -s
242
+ ```
243
+
244
+ ## Roadmap
245
+
246
+ This is an early development version. I am considering the following features:
247
+
248
+ - [ ] Add optional support for other encryption providers beyond Evervault
249
+
250
+ ## Feature Requests
251
+
252
+ If you have any feature requests, please open an issue.
253
+
@@ -0,0 +1,222 @@
1
+ # Encryption and hashing models for Pydantic
2
+
3
+ This package provides Pydantic field annotations that encrypt, decrypt, and hash field values.
4
+
5
+ ## Installation
6
+
7
+ Install with Pip:
8
+ ```bash
9
+ pip install pydantic_encryption[evervault,generics]
10
+ ```
11
+
12
+ ## Features
13
+
14
+ - Encrypt and decrypt specific fields
15
+ - Hash specific fields
16
+ - Support for generics
17
+
18
+ ## Example
19
+
20
+ ```python
21
+ from pydantic_encryption import BaseModel, Encrypt, Hash, Annotated
22
+
23
+ class User(BaseModel):
24
+ name: str
25
+ address: Annotated[str, Encrypt] # This field will be encrypted
26
+ password: Annotated[str, Hash] # This field will be hashed
27
+
28
+ user = User(name="John Doe", address="123456", password="secret123")
29
+
30
+ print(user.name) # plaintext (untouched)
31
+ print(user.address) # encrypted
32
+ print(user.password) # hashed
33
+ ```
34
+
35
+ ## Choose an Encryption Method
36
+
37
+ ### Evervault
38
+
39
+ If you install this package with the `evervault` extra, you can use [Evervault](https://evervault.com/) to encrypt and decrypt fields.
40
+
41
+ You need to set the following environment variables or add them to your `.env` file:
42
+
43
+ ```bash
44
+ EVERVAULT_APP_ID=your_app_id
45
+ EVERVAULT_API_KEY=your_api_key
46
+ EVERVAULT_ENCRYPTION_ROLE=your_encryption_role
47
+ ```
48
+
49
+ ### Custom Encryption
50
+
51
+ You can define your own encryption and decryption methods by subclassing `SecureModel`. `SecureModel` provides you with the utilities to handle encryption, decryption, and hashing.
52
+
53
+ `self.pending_encryption_fields`, `self.pending_decryption_fields`, and `self.pending_hash_fields` are dictionaries of field names to field values that need to be encrypted, decrypted, or hashed, i.e., fields annotated with `Encrypt`, `Decrypt`, or `Hash`.
54
+
55
+ You can override the `encrypt_data`, `decrypt_data`, and `hash_data` methods to implement your own encryption, decryption, and hashing logic. You then need to override `model_post_init` to call these methods.
56
+
57
+ First, define a custom secure model:
58
+
59
+ ```python
60
+ from typing import Any, override
61
+ from pydantic import BaseModel as PydanticBaseModel
62
+ from pydantic_encryption import SecureModel
63
+
64
+ class MySecureModel(PydanticBaseModel, SecureModel):
65
+ @override
66
+ def encrypt_data(self) -> None:
67
+ # Your encryption logic here
68
+ pass
69
+
70
+ @override
71
+ def decrypt_data(self) -> None:
72
+ # Your decryption logic here
73
+ pass
74
+
75
+ @override
76
+ def hash_data(self) -> None:
77
+ # Your hashing logic here
78
+ pass
79
+
80
+ @override
81
+ def model_post_init(self, context: Any, /) -> None:
82
+ if not self._disable:
83
+ if self.pending_decryption_fields:
84
+ self.decrypt_data()
85
+
86
+ if self.pending_encryption_fields:
87
+ self.encrypt_data()
88
+
89
+ if self.pending_hash_fields:
90
+ self.hash_data()
91
+
92
+ super().model_post_init(context)
93
+ ```
94
+
95
+ Then use it:
96
+
97
+ ```python
98
+ from typing import Annotated
99
+ from pydantic import BaseModel # Here, we don't use the BaseModel provided by the library, but the native one from Pydantic
100
+ from pydantic_encryption import Encrypt
101
+
102
+ class MyModel(BaseModel, MySecureModel):
103
+ username: str
104
+ address: Annotated[str, Encrypt]
105
+
106
+ model = MyModel(username="john_doe", address="123456")
107
+ print(model.address) # encrypted
108
+ ```
109
+
110
+ ## Encryption
111
+
112
+ You can encrypt any field by using the `Encrypt` annotation with `Annotated` and inheriting from `BaseModel`.
113
+
114
+ ```python
115
+ from typing import Annotated
116
+ from pydantic_encryption import Encrypt, BaseModel
117
+
118
+ class User(BaseModel):
119
+ name: str
120
+ address: Annotated[str, Encrypt] # This field will be encrypted
121
+
122
+ user = User(name="John Doe", address="123456")
123
+ print(user.address) # encrypted
124
+ print(user.name) # plaintext (untouched)
125
+ ```
126
+
127
+ The fields marked with `Encrypt` are automatically encrypted during model initialization.
128
+
129
+ ## Decryption
130
+
131
+ Similar to encryption, you can decrypt any field by using the `Decrypt` annotation with `Annotated` and inheriting from `BaseModel`.
132
+
133
+ ```python
134
+ from typing import Annotated
135
+ from pydantic_encryption import Decrypt, BaseModel
136
+
137
+ class UserResponse(BaseModel):
138
+ name: str
139
+ address: Annotated[str, Decrypt] # This field will be decrypted
140
+
141
+ user = UserResponse(**user_data) # encrypted value
142
+ print(user.address) # decrypted
143
+ print(user.name) # plaintext (untouched)
144
+ ```
145
+
146
+ Fields marked with `Decrypt` are automatically decrypted during model initialization.
147
+
148
+
149
+ ## Hashing
150
+
151
+ You can hash sensitive data like passwords by using the `Hash` annotation.
152
+
153
+ ```python
154
+ from typing import Annotated
155
+ from pydantic_encryption import Hash, BaseModel
156
+
157
+ class User(BaseModel):
158
+ username: str
159
+ password: Annotated[str, Hash] # This field will be hashed
160
+
161
+ user = User(username="john_doe", password="secret123")
162
+ print(user.password) # hashed value
163
+ ```
164
+
165
+ Fields marked with `Hash` are automatically hashed using bcrypt during model initialization.
166
+
167
+ ## Disable Auto Processing
168
+
169
+ You can disable automatic encryption/decryption/hashing by setting `disable` to `True` in the class definition.
170
+
171
+ ```python
172
+ from typing import Annotated
173
+ from pydantic_encryption import Encrypt, BaseModel
174
+
175
+ class UserResponse(BaseModel, disable=True):
176
+ name: str
177
+ address: Annotated[str, Encrypt]
178
+
179
+ # To encrypt/decrypt/hash, call the respective methods manually:
180
+ user = UserResponse(name="John Doe", address="123 Main St")
181
+
182
+ # Manual encryption
183
+ user.encrypt_data()
184
+ print(user.address) # encrypted
185
+
186
+ # Or user.decrypt_data() to decrypt and user.hash_data() to hash
187
+ ```
188
+
189
+ ## Generics
190
+
191
+ Each BaseModel has an additional helpful method that will tell you its generic type.
192
+
193
+ To use generics, you must install this package with the `generics` extra: `pip install pydantic_encryption[generics]`.
194
+
195
+ ```py
196
+ from pydantic_encryption import BaseModel
197
+
198
+ class MyModel[T](BaseModel):
199
+ value: T
200
+
201
+ model = MyModel[str](value="Hello")
202
+ print(model.get_type()) # <class 'str'>
203
+ ```
204
+
205
+ ## Run Tests
206
+
207
+ Install [Poetry](https://python-poetry.org/docs/) and run:
208
+
209
+ ```bash
210
+ poetry install --with test
211
+ poetry run coverage run -m pytest -v -s
212
+ ```
213
+
214
+ ## Roadmap
215
+
216
+ This is an early development version. I am considering the following features:
217
+
218
+ - [ ] Add optional support for other encryption providers beyond Evervault
219
+
220
+ ## Feature Requests
221
+
222
+ If you have any feature requests, please open an issue.
@@ -1,4 +1,4 @@
1
- from typing import override, Any
1
+ from typing import Any, Optional
2
2
  from pydantic_settings import BaseSettings
3
3
 
4
4
 
@@ -6,16 +6,15 @@ class Settings(BaseSettings):
6
6
  """Settings for the package."""
7
7
 
8
8
  # Evervault settings
9
- EVERVAULT_API_KEY: str | None = None
10
- EVERVAULT_APP_ID: str | None = None
11
- EVERVAULT_ENCRYPTION_ROLE: str | None = None
9
+ EVERVAULT_API_KEY: Optional[str] = None
10
+ EVERVAULT_APP_ID: Optional[str] = None
11
+ EVERVAULT_ENCRYPTION_ROLE: Optional[str] = None
12
12
 
13
13
  class Config:
14
14
  env_file = [".env.local", ".env"]
15
15
  case_sensitive = True
16
16
  extra = "ignore"
17
17
 
18
- @override
19
18
  def model_post_init(self, context: Any, /) -> None:
20
19
  try:
21
20
  import evervault # pylint: disable=unused-import
@@ -0,0 +1,2 @@
1
+ from .secure_model import *
2
+ from .base import *
@@ -1,6 +1,6 @@
1
- from typing import Any, override
1
+ from typing import Any, Optional
2
2
  from pydantic import BaseModel as PydanticBaseModel
3
- from .encryption import EncryptableObject
3
+ from . import SecureModel
4
4
 
5
5
  try:
6
6
  from generics import get_filled_type
@@ -10,12 +10,11 @@ except ImportError:
10
10
  __all__ = ["BaseModel"]
11
11
 
12
12
 
13
- class BaseModel(PydanticBaseModel, EncryptableObject):
13
+ class BaseModel(PydanticBaseModel, SecureModel):
14
14
  """Base model for encryptable models."""
15
15
 
16
16
  _generic_type_value: Any = None
17
17
 
18
- @override
19
18
  def model_post_init(self, context: Any, /) -> None:
20
19
  if not self._disable:
21
20
  if self.pending_decryption_fields:
@@ -24,9 +23,12 @@ class BaseModel(PydanticBaseModel, EncryptableObject):
24
23
  if self.pending_encryption_fields:
25
24
  self.encrypt_data()
26
25
 
26
+ if self.pending_hash_fields:
27
+ self.hash_data()
28
+
27
29
  super().model_post_init(context)
28
30
 
29
- def get_type(self) -> type | None:
31
+ def get_type(self) -> Optional[type]:
30
32
  """Get the type of the model."""
31
33
 
32
34
  if not get_filled_type:
@@ -1,12 +1,7 @@
1
- from typing import (
2
- Any,
3
- Annotated,
4
- get_type_hints,
5
- Union,
6
- get_args,
7
- get_origin,
8
- )
1
+ from typing import Any, Annotated, get_type_hints, Union, get_args, get_origin, Optional
2
+ import bcrypt
9
3
  from pydantic_encryption.config import settings
4
+ from pydantic import BaseModel
10
5
 
11
6
  try:
12
7
  import evervault
@@ -18,34 +13,31 @@ else:
18
13
  )
19
14
 
20
15
  __all__ = [
21
- "EncryptField",
22
- "DecryptField",
23
- "EncryptableObject",
16
+ "Encrypt",
17
+ "Decrypt",
18
+ "Hash",
19
+ "SecureModel",
24
20
  ]
25
21
 
26
22
 
27
- class _EncryptedFieldValue:
28
- pass
23
+ class Encrypt:
24
+ """Annotation to mark fields for encryption."""
29
25
 
30
26
 
31
- class _DecryptedFieldValue:
32
- pass
27
+ class Decrypt:
28
+ """Annotation to mark fields for decryption."""
33
29
 
34
30
 
35
- EncryptField = Annotated[
36
- str, _EncryptedFieldValue
37
- ] # Fields with this annotation will be encrypted
38
- DecryptField = Annotated[
39
- str, _DecryptedFieldValue
40
- ] # Fields with this annotation will be decrypted
31
+ class Hash:
32
+ """Annotation to mark fields for hashing."""
41
33
 
42
34
 
43
- class EncryptableObject:
44
- """Base class for encryptable models."""
35
+ class SecureModel:
36
+ """Base class for encryptable and hashable models."""
45
37
 
46
- _disable: bool | None = None
38
+ _disable: Optional[bool] = None
47
39
 
48
- def __init_subclass__(cls, disable: bool | None = None, **kwargs):
40
+ def __init_subclass__(cls, disable: Optional[bool] = None, **kwargs) -> None:
49
41
  super().__init_subclass__(**kwargs)
50
42
 
51
43
  cls._disable = disable
@@ -92,9 +84,24 @@ class EncryptableObject:
92
84
  for field_name, value in decrypted_data.items():
93
85
  setattr(self, field_name, value)
94
86
 
87
+ def hash_data(self) -> None:
88
+ """Hash fields marked with `Hash` annotation."""
89
+
90
+ if self._disable:
91
+ return
92
+
93
+ if not self.pending_hash_fields:
94
+ return
95
+
96
+ for field_name, value in self.pending_hash_fields.items():
97
+ salt = bcrypt.gensalt()
98
+ hashed = bcrypt.hashpw(value.encode("utf-8"), salt)
99
+
100
+ setattr(self, field_name, hashed)
101
+
95
102
  @staticmethod
96
103
  def get_annotated_fields(
97
- instance: "BaseModel", obj: dict[str, Any] | None = None, *annotations: type
104
+ instance: "BaseModel", obj: Optional[dict[str, Any]] = None, *annotations: type
98
105
  ) -> dict[str, str]:
99
106
  """Get fields that have the specified annotations, handling union types.
100
107
 
@@ -163,10 +170,16 @@ class EncryptableObject:
163
170
  def pending_encryption_fields(self) -> dict[str, str]:
164
171
  """Get all encrypted fields from the model."""
165
172
 
166
- return self.get_annotated_fields(self, None, _EncryptedFieldValue)
173
+ return self.get_annotated_fields(self, None, Encrypt)
167
174
 
168
175
  @property
169
176
  def pending_decryption_fields(self) -> dict[str, str]:
170
177
  """Get all decrypted fields from the model."""
171
178
 
172
- return self.get_annotated_fields(self, None, _DecryptedFieldValue)
179
+ return self.get_annotated_fields(self, None, Decrypt)
180
+
181
+ @property
182
+ def pending_hash_fields(self) -> dict[str, str]:
183
+ """Get all hashable fields from the model."""
184
+
185
+ return self.get_annotated_fields(self, None, Hash)
@@ -1,16 +1,17 @@
1
1
  [project]
2
2
  name = "pydantic_encryption"
3
- version = "0.0.2a1"
4
- description = "Encryption models for Pydantic"
3
+ version = "0.0.2a2"
4
+ description = "Encryption and hashing models for Pydantic"
5
5
  authors = [
6
6
  { name = "Julien Kmec", email = "me@julien.dev" },
7
7
  ]
8
8
  readme = "README.md"
9
9
  packages = [{include = "pydantic_encryption"}]
10
- requires-python = ">=3.11,<4.0.0"
10
+ requires-python = ">=3.9,<4.0.0"
11
11
  dependencies = [
12
12
  "pydantic>=2.10.6",
13
13
  "pydantic-settings>=2.9.1",
14
+ "bcrypt (>=4.3.0,<5.0.0)",
14
15
  ]
15
16
 
16
17
  [project.optional-dependencies]
@@ -1,215 +0,0 @@
1
- Metadata-Version: 2.3
2
- Name: pydantic_encryption
3
- Version: 0.0.2a1
4
- Summary: Encryption models for Pydantic
5
- Author: Julien Kmec
6
- Author-email: me@julien.dev
7
- Requires-Python: >=3.11,<4.0.0
8
- Classifier: Programming Language :: Python :: 3
9
- Classifier: Programming Language :: Python :: 3.11
10
- Classifier: Programming Language :: Python :: 3.12
11
- Classifier: Programming Language :: Python :: 3.13
12
- Provides-Extra: all
13
- Provides-Extra: evervault
14
- Provides-Extra: generics
15
- Provides-Extra: test
16
- Requires-Dist: coverage (>=7.8.0) ; extra == "all"
17
- Requires-Dist: coverage (>=7.8.0) ; extra == "test"
18
- Requires-Dist: evervault (>=4.4.1) ; extra == "all"
19
- Requires-Dist: evervault (>=4.4.1) ; extra == "evervault"
20
- Requires-Dist: pydantic (>=2.10.6)
21
- Requires-Dist: pydantic-settings (>=2.9.1)
22
- Requires-Dist: pytest (>=8.3.5) ; extra == "all"
23
- Requires-Dist: pytest (>=8.3.5) ; extra == "test"
24
- Requires-Dist: python-generics (>=0.2.3) ; extra == "all"
25
- Requires-Dist: python-generics (>=0.2.3) ; extra == "generics"
26
- Description-Content-Type: text/markdown
27
-
28
- # Encryption models for Pydantic
29
-
30
- This package provides Pydantic field types that encrypt and decrypt the field values.
31
-
32
- ## Installation
33
-
34
- Install with Pip:
35
- ```bash
36
- pip install pydantic_encryption[evervault,generics]
37
- ```
38
-
39
- ## Features
40
-
41
- - Encrypt and decrypt specific fields
42
- - Support for generics
43
-
44
- ## Example
45
-
46
- ```py
47
- from pydantic_encryption import BaseModel, EncryptField
48
-
49
- class User(BaseModel):
50
- name: str
51
- password: EncryptField # This field will be encrypted
52
-
53
- user = User(name="John Doe", password="123456")
54
- print(user.password) # encrypted
55
- ```
56
-
57
- ## Choose an Encryption Method
58
-
59
- ### Evervault
60
-
61
- If you install this package with the `evervault` extra, you can use [Evervault](https://evervault.com/) to encrypt and decrypt fields.
62
-
63
- You need to set the following environment variables or add them to your `.env` file:
64
-
65
- ```bash
66
- EVERVAULT_APP_ID=your_app_id
67
- EVERVAULT_API_KEY=your_api_key
68
- EVERVAULT_ENCRYPTION_ROLE=your_encryption_role
69
- ```
70
-
71
- ### Custom Encryption
72
-
73
- You can define your own encryption and decryption methods by subclassing `EncryptableObject`. `EncryptableObject` provides you with the utilities to handle encryption and decryption.
74
-
75
- `self.pending_encryption_fields` and `self.pending_decryption_fields` are dictionaries of field names to field values that need to be encrypted or decrypted, i.e., fields annotated with `EncryptField` or `DecryptField`.
76
-
77
- You can override the `encrypt_data` and `decrypt_data` methods to implement your own encryption and decryption logic. You then need to override `model_post_init` to call `self.encrypt_data()` and/or `self.decrypt_data()`.
78
-
79
-
80
- First, define a custom encryptable object:
81
-
82
- ```py
83
- from typing import override
84
- from pydantic_encryption import EncryptableObject
85
-
86
- class MyEncryptableObject(EncryptableObject):
87
- @override
88
- def encrypt_data(self) -> None:
89
- # Your encryption logic here
90
- pass
91
-
92
- @override
93
- def decrypt_data(self) -> None:
94
- # Your decryption logic here
95
- pass
96
-
97
- @override
98
- def model_post_init(self, context: Any, /) -> None:
99
- if not self._disable:
100
- if self.pending_decryption_fields:
101
- self.decrypt_data()
102
-
103
- if self.pending_encryption_fields:
104
- self.encrypt_data()
105
-
106
- super().model_post_init(context)
107
- ```
108
-
109
- Then use it:
110
-
111
- ```py
112
- from pydantic import BaseModel # Here, we don't use the BaseModel provided by the library, but the native one from Pydantic
113
- from pydantic_encryption import EncryptField
114
-
115
- class MyModel(BaseModel, MyEncryptableObject):
116
- username: str
117
- password: EncryptField
118
-
119
- model = MyModel(username="john_doe", password="123456")
120
- print(model.password) # encrypted
121
- ```
122
-
123
- ## Encryption
124
-
125
- You can encrypt any field by annotating with `EncryptField` and inheriting from `BaseModel`.
126
-
127
- ```py
128
- from pydantic_encryption import EncryptField, BaseModel
129
-
130
- class User(BaseModel):
131
- name: str
132
- password: EncryptField # This field will be encrypted
133
-
134
- user = User(name="John Doe", password="123456")
135
- print(user.password) # encrypted
136
- print(user.name) # plaintext (untouched)
137
- ```
138
-
139
- Internally, `EncryptField` is an alias of `str`, so the model can be serialized by Pydantic.
140
-
141
- ## Decryption
142
-
143
- Similar to encryption, you can decrypt any field by annotating with `DecryptField` and inheriting from `BaseModel`.
144
-
145
- ```py
146
- from pydantic_encryption import DecryptField, BaseModel
147
-
148
- class User(BaseModel):
149
- name: str
150
- password: DecryptField # This field will be decrypted
151
-
152
- user = User(name="John Doe", password="123456")
153
- print(user.password) # decrypted
154
- print(user.name) # plaintext (untouched)
155
-
156
- ```
157
-
158
-
159
- ## Disable Auto-Encryption/Decryption
160
-
161
- You can disable auto-encryption/decryption by setting `disable` to `True` in the class definition.
162
-
163
- ```py
164
- from pydantic_encryption import EncryptField, BaseModel
165
-
166
- class UserResponse(BaseModel, disable=True):
167
- name: str
168
- password: EncryptField
169
-
170
- # To encrypt/decrypt, call `encrypt_data()` or `decrypt_data()`:
171
- user = UserResponse(name="John Doe", password="ENCRYPTED_PASSWORD")
172
-
173
- user.decrypt_data()
174
- print(user.password) # decrypted
175
-
176
- user.encrypt_data()
177
- print(user.password) # encrypted
178
- ```
179
-
180
- ## Generics
181
-
182
- Each BaseModel has an additional helpful method that will tell you its generic type.
183
-
184
- To use generics, you must install this package with the `generics` extra: `pip install pydantic_encryption[generics]`.
185
-
186
- ```py
187
- from pydantic_encryption import BaseModel
188
-
189
- class MyModel[T](BaseModel):
190
- value: T
191
-
192
- model = MyModel[str](value="Hello")
193
- print(model.get_type()) # <class 'str'>
194
- ```
195
-
196
- ## Run Tests
197
-
198
- Install [Poetry](https://python-poetry.org/docs/) and run:
199
-
200
- ```bash
201
- poetry install --with test
202
- poetry run coverage run -m pytest -v -s
203
- ```
204
-
205
- ## Roadmap
206
-
207
- This is an early development version. I am considering the following features:
208
-
209
- - [ ] Add optional support for other types of encryption
210
- - [ ] Add support for other types of fields, i.e., bool, int, float, etc.
211
-
212
- ## Feature Requests
213
-
214
- If you have any feature requests, please open an issue.
215
-
@@ -1,187 +0,0 @@
1
- # Encryption models for Pydantic
2
-
3
- This package provides Pydantic field types that encrypt and decrypt the field values.
4
-
5
- ## Installation
6
-
7
- Install with Pip:
8
- ```bash
9
- pip install pydantic_encryption[evervault,generics]
10
- ```
11
-
12
- ## Features
13
-
14
- - Encrypt and decrypt specific fields
15
- - Support for generics
16
-
17
- ## Example
18
-
19
- ```py
20
- from pydantic_encryption import BaseModel, EncryptField
21
-
22
- class User(BaseModel):
23
- name: str
24
- password: EncryptField # This field will be encrypted
25
-
26
- user = User(name="John Doe", password="123456")
27
- print(user.password) # encrypted
28
- ```
29
-
30
- ## Choose an Encryption Method
31
-
32
- ### Evervault
33
-
34
- If you install this package with the `evervault` extra, you can use [Evervault](https://evervault.com/) to encrypt and decrypt fields.
35
-
36
- You need to set the following environment variables or add them to your `.env` file:
37
-
38
- ```bash
39
- EVERVAULT_APP_ID=your_app_id
40
- EVERVAULT_API_KEY=your_api_key
41
- EVERVAULT_ENCRYPTION_ROLE=your_encryption_role
42
- ```
43
-
44
- ### Custom Encryption
45
-
46
- You can define your own encryption and decryption methods by subclassing `EncryptableObject`. `EncryptableObject` provides you with the utilities to handle encryption and decryption.
47
-
48
- `self.pending_encryption_fields` and `self.pending_decryption_fields` are dictionaries of field names to field values that need to be encrypted or decrypted, i.e., fields annotated with `EncryptField` or `DecryptField`.
49
-
50
- You can override the `encrypt_data` and `decrypt_data` methods to implement your own encryption and decryption logic. You then need to override `model_post_init` to call `self.encrypt_data()` and/or `self.decrypt_data()`.
51
-
52
-
53
- First, define a custom encryptable object:
54
-
55
- ```py
56
- from typing import override
57
- from pydantic_encryption import EncryptableObject
58
-
59
- class MyEncryptableObject(EncryptableObject):
60
- @override
61
- def encrypt_data(self) -> None:
62
- # Your encryption logic here
63
- pass
64
-
65
- @override
66
- def decrypt_data(self) -> None:
67
- # Your decryption logic here
68
- pass
69
-
70
- @override
71
- def model_post_init(self, context: Any, /) -> None:
72
- if not self._disable:
73
- if self.pending_decryption_fields:
74
- self.decrypt_data()
75
-
76
- if self.pending_encryption_fields:
77
- self.encrypt_data()
78
-
79
- super().model_post_init(context)
80
- ```
81
-
82
- Then use it:
83
-
84
- ```py
85
- from pydantic import BaseModel # Here, we don't use the BaseModel provided by the library, but the native one from Pydantic
86
- from pydantic_encryption import EncryptField
87
-
88
- class MyModel(BaseModel, MyEncryptableObject):
89
- username: str
90
- password: EncryptField
91
-
92
- model = MyModel(username="john_doe", password="123456")
93
- print(model.password) # encrypted
94
- ```
95
-
96
- ## Encryption
97
-
98
- You can encrypt any field by annotating with `EncryptField` and inheriting from `BaseModel`.
99
-
100
- ```py
101
- from pydantic_encryption import EncryptField, BaseModel
102
-
103
- class User(BaseModel):
104
- name: str
105
- password: EncryptField # This field will be encrypted
106
-
107
- user = User(name="John Doe", password="123456")
108
- print(user.password) # encrypted
109
- print(user.name) # plaintext (untouched)
110
- ```
111
-
112
- Internally, `EncryptField` is an alias of `str`, so the model can be serialized by Pydantic.
113
-
114
- ## Decryption
115
-
116
- Similar to encryption, you can decrypt any field by annotating with `DecryptField` and inheriting from `BaseModel`.
117
-
118
- ```py
119
- from pydantic_encryption import DecryptField, BaseModel
120
-
121
- class User(BaseModel):
122
- name: str
123
- password: DecryptField # This field will be decrypted
124
-
125
- user = User(name="John Doe", password="123456")
126
- print(user.password) # decrypted
127
- print(user.name) # plaintext (untouched)
128
-
129
- ```
130
-
131
-
132
- ## Disable Auto-Encryption/Decryption
133
-
134
- You can disable auto-encryption/decryption by setting `disable` to `True` in the class definition.
135
-
136
- ```py
137
- from pydantic_encryption import EncryptField, BaseModel
138
-
139
- class UserResponse(BaseModel, disable=True):
140
- name: str
141
- password: EncryptField
142
-
143
- # To encrypt/decrypt, call `encrypt_data()` or `decrypt_data()`:
144
- user = UserResponse(name="John Doe", password="ENCRYPTED_PASSWORD")
145
-
146
- user.decrypt_data()
147
- print(user.password) # decrypted
148
-
149
- user.encrypt_data()
150
- print(user.password) # encrypted
151
- ```
152
-
153
- ## Generics
154
-
155
- Each BaseModel has an additional helpful method that will tell you its generic type.
156
-
157
- To use generics, you must install this package with the `generics` extra: `pip install pydantic_encryption[generics]`.
158
-
159
- ```py
160
- from pydantic_encryption import BaseModel
161
-
162
- class MyModel[T](BaseModel):
163
- value: T
164
-
165
- model = MyModel[str](value="Hello")
166
- print(model.get_type()) # <class 'str'>
167
- ```
168
-
169
- ## Run Tests
170
-
171
- Install [Poetry](https://python-poetry.org/docs/) and run:
172
-
173
- ```bash
174
- poetry install --with test
175
- poetry run coverage run -m pytest -v -s
176
- ```
177
-
178
- ## Roadmap
179
-
180
- This is an early development version. I am considering the following features:
181
-
182
- - [ ] Add optional support for other types of encryption
183
- - [ ] Add support for other types of fields, i.e., bool, int, float, etc.
184
-
185
- ## Feature Requests
186
-
187
- If you have any feature requests, please open an issue.
@@ -1,2 +0,0 @@
1
- from .encryption import *
2
- from .base import *