pydantic_encryption 0.3.2__tar.gz → 0.5.0__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.
- pydantic_encryption-0.5.0/PKG-INFO +310 -0
- pydantic_encryption-0.5.0/README.md +263 -0
- {pydantic_encryption-0.3.2 → pydantic_encryption-0.5.0}/pydantic_encryption/__init__.py +28 -5
- {pydantic_encryption-0.3.2 → pydantic_encryption-0.5.0}/pydantic_encryption/adapters/base.py +10 -1
- pydantic_encryption-0.5.0/pydantic_encryption/adapters/blind_index/__init__.py +8 -0
- pydantic_encryption-0.5.0/pydantic_encryption/adapters/blind_index/argon2.py +34 -0
- pydantic_encryption-0.5.0/pydantic_encryption/adapters/blind_index/hmac_sha256.py +23 -0
- {pydantic_encryption-0.3.2 → pydantic_encryption-0.5.0}/pydantic_encryption/adapters/hashing/argon2.py +1 -5
- {pydantic_encryption-0.3.2 → pydantic_encryption-0.5.0}/pydantic_encryption/config.py +4 -1
- pydantic_encryption-0.5.0/pydantic_encryption/integrations/sqlalchemy/__init__.py +10 -0
- pydantic_encryption-0.5.0/pydantic_encryption/integrations/sqlalchemy/blind_index.py +113 -0
- pydantic_encryption-0.3.2/pydantic_encryption/integrations/sqlalchemy.py → pydantic_encryption-0.5.0/pydantic_encryption/integrations/sqlalchemy/encryption.py +66 -77
- pydantic_encryption-0.5.0/pydantic_encryption/integrations/sqlalchemy/hashing.py +47 -0
- pydantic_encryption-0.5.0/pydantic_encryption/integrations/sqlalchemy/shared.py +26 -0
- {pydantic_encryption-0.3.2 → pydantic_encryption-0.5.0}/pydantic_encryption/models/base.py +69 -3
- pydantic_encryption-0.5.0/pydantic_encryption/normalization.py +36 -0
- {pydantic_encryption-0.3.2 → pydantic_encryption-0.5.0}/pydantic_encryption/types.py +41 -0
- {pydantic_encryption-0.3.2 → pydantic_encryption-0.5.0}/pyproject.toml +2 -2
- pydantic_encryption-0.3.2/PKG-INFO +0 -446
- pydantic_encryption-0.3.2/README.md +0 -399
- {pydantic_encryption-0.3.2 → pydantic_encryption-0.5.0}/LICENSE +0 -0
- {pydantic_encryption-0.3.2 → pydantic_encryption-0.5.0}/pydantic_encryption/_lazy.py +0 -0
- {pydantic_encryption-0.3.2 → pydantic_encryption-0.5.0}/pydantic_encryption/adapters/__init__.py +0 -0
- {pydantic_encryption-0.3.2 → pydantic_encryption-0.5.0}/pydantic_encryption/adapters/encryption/__init__.py +0 -0
- {pydantic_encryption-0.3.2 → pydantic_encryption-0.5.0}/pydantic_encryption/adapters/encryption/aws.py +0 -0
- {pydantic_encryption-0.3.2 → pydantic_encryption-0.5.0}/pydantic_encryption/adapters/encryption/evervault.py +0 -0
- {pydantic_encryption-0.3.2 → pydantic_encryption-0.5.0}/pydantic_encryption/adapters/encryption/fernet.py +0 -0
- {pydantic_encryption-0.3.2 → pydantic_encryption-0.5.0}/pydantic_encryption/adapters/hashing/__init__.py +0 -0
- {pydantic_encryption-0.3.2 → pydantic_encryption-0.5.0}/pydantic_encryption/integrations/__init__.py +0 -0
- {pydantic_encryption-0.3.2 → pydantic_encryption-0.5.0}/pydantic_encryption/models/__init__.py +0 -0
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pydantic_encryption
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: Encryption and Hashing Models for Pydantic
|
|
5
|
+
License-File: LICENSE
|
|
6
|
+
Author: Julien Kmec
|
|
7
|
+
Author-email: me@julien.dev
|
|
8
|
+
Requires-Python: >=3.11,<3.15
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
14
|
+
Provides-Extra: all
|
|
15
|
+
Provides-Extra: aws
|
|
16
|
+
Provides-Extra: dev
|
|
17
|
+
Provides-Extra: evervault
|
|
18
|
+
Provides-Extra: sqlalchemy
|
|
19
|
+
Requires-Dist: argon2-cffi (>=23.1.0)
|
|
20
|
+
Requires-Dist: aws-encryption-sdk[mpl] (>=4.0.1) ; extra == "all"
|
|
21
|
+
Requires-Dist: aws-encryption-sdk[mpl] (>=4.0.1) ; extra == "aws"
|
|
22
|
+
Requires-Dist: boto3 (>=1.38.8) ; extra == "all"
|
|
23
|
+
Requires-Dist: boto3 (>=1.38.8) ; extra == "aws"
|
|
24
|
+
Requires-Dist: coverage (>=7.8.0) ; extra == "dev"
|
|
25
|
+
Requires-Dist: cryptography (>=44.0.0)
|
|
26
|
+
Requires-Dist: evervault (>=4.4.1) ; extra == "all"
|
|
27
|
+
Requires-Dist: evervault (>=4.4.1) ; extra == "evervault"
|
|
28
|
+
Requires-Dist: polyfactory (>=2.0.0) ; extra == "dev"
|
|
29
|
+
Requires-Dist: psycopg2-binary (>=2.9.10) ; extra == "dev"
|
|
30
|
+
Requires-Dist: pydantic (>=2.10.6)
|
|
31
|
+
Requires-Dist: pydantic-settings (>=2.9.1)
|
|
32
|
+
Requires-Dist: pydantic-super-model (>=1.2.0)
|
|
33
|
+
Requires-Dist: pytest (>=8.3.5) ; extra == "dev"
|
|
34
|
+
Requires-Dist: pytest-asyncio (>=0.26.0) ; extra == "dev"
|
|
35
|
+
Requires-Dist: pytest-cov (>=6.1.1) ; extra == "dev"
|
|
36
|
+
Requires-Dist: pytest-docker (>=3.2.1) ; extra == "dev"
|
|
37
|
+
Requires-Dist: pytest-env (>=1.1.5) ; extra == "dev"
|
|
38
|
+
Requires-Dist: pytest-sqlalchemy (>=0.3.0) ; extra == "dev"
|
|
39
|
+
Requires-Dist: sqlalchemy (>=2.0.40) ; extra == "all"
|
|
40
|
+
Requires-Dist: sqlalchemy (>=2.0.40) ; extra == "sqlalchemy"
|
|
41
|
+
Requires-Dist: sqlalchemy-utils (>=0.41.2) ; extra == "dev"
|
|
42
|
+
Requires-Dist: sqlmodel (>=0.0.24) ; extra == "all"
|
|
43
|
+
Requires-Dist: sqlmodel (>=0.0.24) ; extra == "sqlalchemy"
|
|
44
|
+
Project-URL: Repository, https://github.com/julien777z/pydantic-encryption
|
|
45
|
+
Description-Content-Type: text/markdown
|
|
46
|
+
|
|
47
|
+
# Encryption and Hashing Models for Pydantic
|
|
48
|
+
|
|
49
|
+
Field-level encryption, decryption, hashing, and blind indexing for Pydantic models with SQLAlchemy integration.
|
|
50
|
+
|
|
51
|
+
## Installation
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
pip install pydantic_encryption
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### Optional extras
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
pip install "pydantic_encryption[sqlalchemy]" # SQLAlchemy integration
|
|
61
|
+
pip install "pydantic_encryption[aws]" # AWS KMS encryption
|
|
62
|
+
pip install "pydantic_encryption[all]" # All optional dependencies
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Quick Start
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
from typing import Annotated
|
|
69
|
+
from pydantic_encryption import BaseModel, Encrypt, Hash
|
|
70
|
+
|
|
71
|
+
class User(BaseModel):
|
|
72
|
+
name: str
|
|
73
|
+
address: Annotated[bytes, Encrypt]
|
|
74
|
+
password: Annotated[bytes, Hash]
|
|
75
|
+
|
|
76
|
+
user = User(name="John Doe", address="123456", password="secret123")
|
|
77
|
+
|
|
78
|
+
print(user.name) # plaintext
|
|
79
|
+
print(user.address) # encrypted
|
|
80
|
+
print(user.password) # hashed
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Fields marked with `Encrypt` are encrypted and fields marked with `Hash` are hashed during model initialization.
|
|
84
|
+
|
|
85
|
+
To decrypt, use the `Decrypt` annotation:
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
from pydantic_encryption import Decrypt, BaseModel
|
|
89
|
+
|
|
90
|
+
class UserResponse(BaseModel):
|
|
91
|
+
address: Annotated[str, Decrypt]
|
|
92
|
+
|
|
93
|
+
user = UserResponse(address=encrypted_bytes)
|
|
94
|
+
print(user.address) # decrypted
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Encryption Methods
|
|
98
|
+
|
|
99
|
+
Set the encryption method via environment variable:
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
ENCRYPTION_METHOD=fernet # Fernet symmetric encryption (requires ENCRYPTION_KEY)
|
|
103
|
+
ENCRYPTION_METHOD=aws # AWS KMS (requires AWS_KMS_KEY_ARN, AWS_KMS_REGION, etc.)
|
|
104
|
+
ENCRYPTION_METHOD=evervault # Evervault
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
There is no default — you must explicitly set `ENCRYPTION_METHOD` if using `Encrypt`/`Decrypt` fields.
|
|
108
|
+
|
|
109
|
+
### Fernet Setup
|
|
110
|
+
|
|
111
|
+
```bash
|
|
112
|
+
# Generate a key
|
|
113
|
+
openssl rand -base64 32
|
|
114
|
+
|
|
115
|
+
# Set environment variables
|
|
116
|
+
ENCRYPTION_METHOD=fernet
|
|
117
|
+
ENCRYPTION_KEY=your_generated_key
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### AWS KMS Setup
|
|
121
|
+
|
|
122
|
+
```bash
|
|
123
|
+
ENCRYPTION_METHOD=aws
|
|
124
|
+
AWS_KMS_KEY_ARN=arn:aws:kms:us-east-1:123456789:key/your-key-id
|
|
125
|
+
AWS_KMS_REGION=us-east-1
|
|
126
|
+
AWS_KMS_ACCESS_KEY_ID=your_access_key
|
|
127
|
+
AWS_KMS_SECRET_ACCESS_KEY=your_secret_key
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Separate encrypt/decrypt keys are supported for key rotation or read-only scenarios:
|
|
131
|
+
|
|
132
|
+
```bash
|
|
133
|
+
AWS_KMS_ENCRYPT_KEY_ARN=arn:aws:kms:...encrypt-key
|
|
134
|
+
AWS_KMS_DECRYPT_KEY_ARN=arn:aws:kms:...decrypt-key
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
See [config.py](https://github.com/julien777z/pydantic-encryption/blob/main/pydantic_encryption/config.py) for all environment variables.
|
|
138
|
+
|
|
139
|
+
## SQLAlchemy Integration
|
|
140
|
+
|
|
141
|
+
Install with `pip install "pydantic_encryption[sqlalchemy]"`.
|
|
142
|
+
|
|
143
|
+
```python
|
|
144
|
+
from sqlalchemy import create_engine
|
|
145
|
+
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
|
|
146
|
+
|
|
147
|
+
from pydantic_encryption.integrations.sqlalchemy import (
|
|
148
|
+
SQLAlchemyEncryptedValue,
|
|
149
|
+
SQLAlchemyHashed,
|
|
150
|
+
SQLAlchemyBlindIndexValue,
|
|
151
|
+
)
|
|
152
|
+
from pydantic_encryption.types import BlindIndexMethod
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class Base(DeclarativeBase):
|
|
156
|
+
pass
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class User(Base):
|
|
160
|
+
__tablename__ = "users"
|
|
161
|
+
|
|
162
|
+
id: Mapped[int] = mapped_column(primary_key=True)
|
|
163
|
+
username: Mapped[str]
|
|
164
|
+
email: Mapped[bytes] = mapped_column(SQLAlchemyEncryptedValue())
|
|
165
|
+
password: Mapped[bytes] = mapped_column(SQLAlchemyHashed())
|
|
166
|
+
blind_index_email: Mapped[bytes] = mapped_column(
|
|
167
|
+
SQLAlchemyBlindIndexValue(BlindIndexMethod.HMAC_SHA256)
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
engine = create_engine("sqlite:///:memory:")
|
|
172
|
+
Base.metadata.create_all(engine)
|
|
173
|
+
|
|
174
|
+
with Session(engine) as session:
|
|
175
|
+
user = User(
|
|
176
|
+
username="john",
|
|
177
|
+
email="john@example.com",
|
|
178
|
+
password="secret123",
|
|
179
|
+
blind_index_email="john@example.com",
|
|
180
|
+
)
|
|
181
|
+
session.add(user)
|
|
182
|
+
session.commit()
|
|
183
|
+
|
|
184
|
+
# Query by blind index — automatically hashed
|
|
185
|
+
found = session.query(User).filter(
|
|
186
|
+
User.blind_index_email == "john@example.com"
|
|
187
|
+
).first()
|
|
188
|
+
print(found.email) # decrypted
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
`SQLAlchemyBlindIndexValue` supports the same normalization options as `BlindIndex`:
|
|
192
|
+
|
|
193
|
+
```python
|
|
194
|
+
blind_index_email: Mapped[bytes] = mapped_column(
|
|
195
|
+
SQLAlchemyBlindIndexValue(
|
|
196
|
+
BlindIndexMethod.HMAC_SHA256,
|
|
197
|
+
normalize_to_lowercase=True,
|
|
198
|
+
strip_whitespace=True,
|
|
199
|
+
)
|
|
200
|
+
)
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
### Supported Types
|
|
204
|
+
|
|
205
|
+
`SQLAlchemyEncryptedValue` preserves the Python type of your data:
|
|
206
|
+
|
|
207
|
+
`str`, `bytes`, `bool`, `int`, `float`, `Decimal`, `UUID`, `date`, `datetime`, `time`, `timedelta`
|
|
208
|
+
|
|
209
|
+
### Array Support (PostgreSQL)
|
|
210
|
+
|
|
211
|
+
```python
|
|
212
|
+
from pydantic_encryption.integrations.sqlalchemy import SQLAlchemyPGEncryptedArray
|
|
213
|
+
|
|
214
|
+
tags: Mapped[list[str] | None] = mapped_column(SQLAlchemyPGEncryptedArray(), nullable=True)
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
Each element is individually encrypted. Requires PostgreSQL.
|
|
218
|
+
|
|
219
|
+
## Blind Indexes
|
|
220
|
+
|
|
221
|
+
Blind indexes enable equality searches on encrypted data by storing a deterministic keyed hash alongside the ciphertext.
|
|
222
|
+
|
|
223
|
+
**Configuration:** Set `BLIND_INDEX_SECRET_KEY` via environment variable.
|
|
224
|
+
|
|
225
|
+
### Pydantic Models
|
|
226
|
+
|
|
227
|
+
```python
|
|
228
|
+
from typing import Annotated
|
|
229
|
+
from pydantic_encryption import BaseModel, BlindIndex, BlindIndexMethod
|
|
230
|
+
|
|
231
|
+
class User(BaseModel):
|
|
232
|
+
email_index: Annotated[bytes, BlindIndex(BlindIndexMethod.HMAC_SHA256)]
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
### Normalization
|
|
236
|
+
|
|
237
|
+
You can normalize values before hashing to ensure consistent lookups:
|
|
238
|
+
|
|
239
|
+
```python
|
|
240
|
+
email_index: Annotated[bytes, BlindIndex(
|
|
241
|
+
BlindIndexMethod.HMAC_SHA256,
|
|
242
|
+
normalize_to_lowercase=True,
|
|
243
|
+
strip_whitespace=True,
|
|
244
|
+
)]
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
Available options:
|
|
248
|
+
|
|
249
|
+
| Option | Effect |
|
|
250
|
+
|--------|--------|
|
|
251
|
+
| `strip_whitespace` | Strip leading/trailing whitespace, collapse internal whitespace |
|
|
252
|
+
| `strip_non_characters` | Remove all non-letter characters (keep only a-zA-Z) |
|
|
253
|
+
| `strip_non_digits` | Remove all non-digit characters (keep only 0-9) |
|
|
254
|
+
| `normalize_to_lowercase` | Convert to lowercase |
|
|
255
|
+
| `normalize_to_uppercase` | Convert to uppercase |
|
|
256
|
+
|
|
257
|
+
### Methods
|
|
258
|
+
|
|
259
|
+
| Method | Description |
|
|
260
|
+
|--------|-------------|
|
|
261
|
+
| `BlindIndexMethod.HMAC_SHA256` | Fast HMAC-SHA256 keyed hash. Standard choice. |
|
|
262
|
+
| `BlindIndexMethod.ARGON2` | Memory-hard Argon2 hash with deterministic salt. Better brute-force resistance. |
|
|
263
|
+
|
|
264
|
+
## Disable Auto-Processing
|
|
265
|
+
|
|
266
|
+
```python
|
|
267
|
+
class UserResponse(BaseModel, disable=True):
|
|
268
|
+
address: Annotated[bytes, Encrypt]
|
|
269
|
+
|
|
270
|
+
user = UserResponse(address="123 Main St")
|
|
271
|
+
user.encrypt_data() # manual encryption
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
## Custom Encryption or Hashing
|
|
275
|
+
|
|
276
|
+
Subclass `SecureModel` to implement your own logic:
|
|
277
|
+
|
|
278
|
+
```python
|
|
279
|
+
from pydantic import BaseModel as PydanticBaseModel
|
|
280
|
+
from pydantic_encryption import SecureModel
|
|
281
|
+
|
|
282
|
+
class MySecureModel(PydanticBaseModel, SecureModel):
|
|
283
|
+
def encrypt_data(self) -> None:
|
|
284
|
+
# your encryption logic
|
|
285
|
+
pass
|
|
286
|
+
|
|
287
|
+
def model_post_init(self, context, /):
|
|
288
|
+
self.default_post_init()
|
|
289
|
+
super().model_post_init(context)
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
## Generics
|
|
293
|
+
|
|
294
|
+
```python
|
|
295
|
+
from pydantic_encryption import BaseModel
|
|
296
|
+
|
|
297
|
+
class MyModel[T](BaseModel):
|
|
298
|
+
value: T
|
|
299
|
+
|
|
300
|
+
model = MyModel[str](value="Hello")
|
|
301
|
+
print(model.get_type()) # <class 'str'>
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
## Run Tests
|
|
305
|
+
|
|
306
|
+
```bash
|
|
307
|
+
poetry install --all-extras
|
|
308
|
+
poetry run pytest -v
|
|
309
|
+
```
|
|
310
|
+
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
# Encryption and Hashing Models for Pydantic
|
|
2
|
+
|
|
3
|
+
Field-level encryption, decryption, hashing, and blind indexing for Pydantic models with SQLAlchemy integration.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install pydantic_encryption
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
### Optional extras
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install "pydantic_encryption[sqlalchemy]" # SQLAlchemy integration
|
|
15
|
+
pip install "pydantic_encryption[aws]" # AWS KMS encryption
|
|
16
|
+
pip install "pydantic_encryption[all]" # All optional dependencies
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Quick Start
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from typing import Annotated
|
|
23
|
+
from pydantic_encryption import BaseModel, Encrypt, Hash
|
|
24
|
+
|
|
25
|
+
class User(BaseModel):
|
|
26
|
+
name: str
|
|
27
|
+
address: Annotated[bytes, Encrypt]
|
|
28
|
+
password: Annotated[bytes, Hash]
|
|
29
|
+
|
|
30
|
+
user = User(name="John Doe", address="123456", password="secret123")
|
|
31
|
+
|
|
32
|
+
print(user.name) # plaintext
|
|
33
|
+
print(user.address) # encrypted
|
|
34
|
+
print(user.password) # hashed
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Fields marked with `Encrypt` are encrypted and fields marked with `Hash` are hashed during model initialization.
|
|
38
|
+
|
|
39
|
+
To decrypt, use the `Decrypt` annotation:
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from pydantic_encryption import Decrypt, BaseModel
|
|
43
|
+
|
|
44
|
+
class UserResponse(BaseModel):
|
|
45
|
+
address: Annotated[str, Decrypt]
|
|
46
|
+
|
|
47
|
+
user = UserResponse(address=encrypted_bytes)
|
|
48
|
+
print(user.address) # decrypted
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Encryption Methods
|
|
52
|
+
|
|
53
|
+
Set the encryption method via environment variable:
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
ENCRYPTION_METHOD=fernet # Fernet symmetric encryption (requires ENCRYPTION_KEY)
|
|
57
|
+
ENCRYPTION_METHOD=aws # AWS KMS (requires AWS_KMS_KEY_ARN, AWS_KMS_REGION, etc.)
|
|
58
|
+
ENCRYPTION_METHOD=evervault # Evervault
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
There is no default — you must explicitly set `ENCRYPTION_METHOD` if using `Encrypt`/`Decrypt` fields.
|
|
62
|
+
|
|
63
|
+
### Fernet Setup
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
# Generate a key
|
|
67
|
+
openssl rand -base64 32
|
|
68
|
+
|
|
69
|
+
# Set environment variables
|
|
70
|
+
ENCRYPTION_METHOD=fernet
|
|
71
|
+
ENCRYPTION_KEY=your_generated_key
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### AWS KMS Setup
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
ENCRYPTION_METHOD=aws
|
|
78
|
+
AWS_KMS_KEY_ARN=arn:aws:kms:us-east-1:123456789:key/your-key-id
|
|
79
|
+
AWS_KMS_REGION=us-east-1
|
|
80
|
+
AWS_KMS_ACCESS_KEY_ID=your_access_key
|
|
81
|
+
AWS_KMS_SECRET_ACCESS_KEY=your_secret_key
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Separate encrypt/decrypt keys are supported for key rotation or read-only scenarios:
|
|
85
|
+
|
|
86
|
+
```bash
|
|
87
|
+
AWS_KMS_ENCRYPT_KEY_ARN=arn:aws:kms:...encrypt-key
|
|
88
|
+
AWS_KMS_DECRYPT_KEY_ARN=arn:aws:kms:...decrypt-key
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
See [config.py](https://github.com/julien777z/pydantic-encryption/blob/main/pydantic_encryption/config.py) for all environment variables.
|
|
92
|
+
|
|
93
|
+
## SQLAlchemy Integration
|
|
94
|
+
|
|
95
|
+
Install with `pip install "pydantic_encryption[sqlalchemy]"`.
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
from sqlalchemy import create_engine
|
|
99
|
+
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
|
|
100
|
+
|
|
101
|
+
from pydantic_encryption.integrations.sqlalchemy import (
|
|
102
|
+
SQLAlchemyEncryptedValue,
|
|
103
|
+
SQLAlchemyHashed,
|
|
104
|
+
SQLAlchemyBlindIndexValue,
|
|
105
|
+
)
|
|
106
|
+
from pydantic_encryption.types import BlindIndexMethod
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class Base(DeclarativeBase):
|
|
110
|
+
pass
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class User(Base):
|
|
114
|
+
__tablename__ = "users"
|
|
115
|
+
|
|
116
|
+
id: Mapped[int] = mapped_column(primary_key=True)
|
|
117
|
+
username: Mapped[str]
|
|
118
|
+
email: Mapped[bytes] = mapped_column(SQLAlchemyEncryptedValue())
|
|
119
|
+
password: Mapped[bytes] = mapped_column(SQLAlchemyHashed())
|
|
120
|
+
blind_index_email: Mapped[bytes] = mapped_column(
|
|
121
|
+
SQLAlchemyBlindIndexValue(BlindIndexMethod.HMAC_SHA256)
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
engine = create_engine("sqlite:///:memory:")
|
|
126
|
+
Base.metadata.create_all(engine)
|
|
127
|
+
|
|
128
|
+
with Session(engine) as session:
|
|
129
|
+
user = User(
|
|
130
|
+
username="john",
|
|
131
|
+
email="john@example.com",
|
|
132
|
+
password="secret123",
|
|
133
|
+
blind_index_email="john@example.com",
|
|
134
|
+
)
|
|
135
|
+
session.add(user)
|
|
136
|
+
session.commit()
|
|
137
|
+
|
|
138
|
+
# Query by blind index — automatically hashed
|
|
139
|
+
found = session.query(User).filter(
|
|
140
|
+
User.blind_index_email == "john@example.com"
|
|
141
|
+
).first()
|
|
142
|
+
print(found.email) # decrypted
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
`SQLAlchemyBlindIndexValue` supports the same normalization options as `BlindIndex`:
|
|
146
|
+
|
|
147
|
+
```python
|
|
148
|
+
blind_index_email: Mapped[bytes] = mapped_column(
|
|
149
|
+
SQLAlchemyBlindIndexValue(
|
|
150
|
+
BlindIndexMethod.HMAC_SHA256,
|
|
151
|
+
normalize_to_lowercase=True,
|
|
152
|
+
strip_whitespace=True,
|
|
153
|
+
)
|
|
154
|
+
)
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
### Supported Types
|
|
158
|
+
|
|
159
|
+
`SQLAlchemyEncryptedValue` preserves the Python type of your data:
|
|
160
|
+
|
|
161
|
+
`str`, `bytes`, `bool`, `int`, `float`, `Decimal`, `UUID`, `date`, `datetime`, `time`, `timedelta`
|
|
162
|
+
|
|
163
|
+
### Array Support (PostgreSQL)
|
|
164
|
+
|
|
165
|
+
```python
|
|
166
|
+
from pydantic_encryption.integrations.sqlalchemy import SQLAlchemyPGEncryptedArray
|
|
167
|
+
|
|
168
|
+
tags: Mapped[list[str] | None] = mapped_column(SQLAlchemyPGEncryptedArray(), nullable=True)
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
Each element is individually encrypted. Requires PostgreSQL.
|
|
172
|
+
|
|
173
|
+
## Blind Indexes
|
|
174
|
+
|
|
175
|
+
Blind indexes enable equality searches on encrypted data by storing a deterministic keyed hash alongside the ciphertext.
|
|
176
|
+
|
|
177
|
+
**Configuration:** Set `BLIND_INDEX_SECRET_KEY` via environment variable.
|
|
178
|
+
|
|
179
|
+
### Pydantic Models
|
|
180
|
+
|
|
181
|
+
```python
|
|
182
|
+
from typing import Annotated
|
|
183
|
+
from pydantic_encryption import BaseModel, BlindIndex, BlindIndexMethod
|
|
184
|
+
|
|
185
|
+
class User(BaseModel):
|
|
186
|
+
email_index: Annotated[bytes, BlindIndex(BlindIndexMethod.HMAC_SHA256)]
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
### Normalization
|
|
190
|
+
|
|
191
|
+
You can normalize values before hashing to ensure consistent lookups:
|
|
192
|
+
|
|
193
|
+
```python
|
|
194
|
+
email_index: Annotated[bytes, BlindIndex(
|
|
195
|
+
BlindIndexMethod.HMAC_SHA256,
|
|
196
|
+
normalize_to_lowercase=True,
|
|
197
|
+
strip_whitespace=True,
|
|
198
|
+
)]
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
Available options:
|
|
202
|
+
|
|
203
|
+
| Option | Effect |
|
|
204
|
+
|--------|--------|
|
|
205
|
+
| `strip_whitespace` | Strip leading/trailing whitespace, collapse internal whitespace |
|
|
206
|
+
| `strip_non_characters` | Remove all non-letter characters (keep only a-zA-Z) |
|
|
207
|
+
| `strip_non_digits` | Remove all non-digit characters (keep only 0-9) |
|
|
208
|
+
| `normalize_to_lowercase` | Convert to lowercase |
|
|
209
|
+
| `normalize_to_uppercase` | Convert to uppercase |
|
|
210
|
+
|
|
211
|
+
### Methods
|
|
212
|
+
|
|
213
|
+
| Method | Description |
|
|
214
|
+
|--------|-------------|
|
|
215
|
+
| `BlindIndexMethod.HMAC_SHA256` | Fast HMAC-SHA256 keyed hash. Standard choice. |
|
|
216
|
+
| `BlindIndexMethod.ARGON2` | Memory-hard Argon2 hash with deterministic salt. Better brute-force resistance. |
|
|
217
|
+
|
|
218
|
+
## Disable Auto-Processing
|
|
219
|
+
|
|
220
|
+
```python
|
|
221
|
+
class UserResponse(BaseModel, disable=True):
|
|
222
|
+
address: Annotated[bytes, Encrypt]
|
|
223
|
+
|
|
224
|
+
user = UserResponse(address="123 Main St")
|
|
225
|
+
user.encrypt_data() # manual encryption
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
## Custom Encryption or Hashing
|
|
229
|
+
|
|
230
|
+
Subclass `SecureModel` to implement your own logic:
|
|
231
|
+
|
|
232
|
+
```python
|
|
233
|
+
from pydantic import BaseModel as PydanticBaseModel
|
|
234
|
+
from pydantic_encryption import SecureModel
|
|
235
|
+
|
|
236
|
+
class MySecureModel(PydanticBaseModel, SecureModel):
|
|
237
|
+
def encrypt_data(self) -> None:
|
|
238
|
+
# your encryption logic
|
|
239
|
+
pass
|
|
240
|
+
|
|
241
|
+
def model_post_init(self, context, /):
|
|
242
|
+
self.default_post_init()
|
|
243
|
+
super().model_post_init(context)
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
## Generics
|
|
247
|
+
|
|
248
|
+
```python
|
|
249
|
+
from pydantic_encryption import BaseModel
|
|
250
|
+
|
|
251
|
+
class MyModel[T](BaseModel):
|
|
252
|
+
value: T
|
|
253
|
+
|
|
254
|
+
model = MyModel[str](value="Hello")
|
|
255
|
+
print(model.get_type()) # <class 'str'>
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
## Run Tests
|
|
259
|
+
|
|
260
|
+
```bash
|
|
261
|
+
poetry install --all-extras
|
|
262
|
+
poetry run pytest -v
|
|
263
|
+
```
|
|
@@ -5,6 +5,9 @@ from pydantic_encryption.adapters.hashing.argon2 import Argon2Adapter
|
|
|
5
5
|
from pydantic_encryption.config import settings
|
|
6
6
|
from pydantic_encryption.models import BaseModel, SecureModel
|
|
7
7
|
from pydantic_encryption.types import (
|
|
8
|
+
BlindIndex,
|
|
9
|
+
BlindIndexMethod,
|
|
10
|
+
BlindIndexValue,
|
|
8
11
|
Decrypt,
|
|
9
12
|
DecryptedValue,
|
|
10
13
|
Encrypt,
|
|
@@ -18,20 +21,35 @@ from pydantic_encryption.types import (
|
|
|
18
21
|
if TYPE_CHECKING:
|
|
19
22
|
from pydantic_encryption.adapters.encryption.aws import AWSAdapter
|
|
20
23
|
from pydantic_encryption.adapters.encryption.evervault import EvervaultAdapter
|
|
21
|
-
from pydantic_encryption.integrations.sqlalchemy import
|
|
24
|
+
from pydantic_encryption.integrations.sqlalchemy import (
|
|
25
|
+
SQLAlchemyBlindIndexValue,
|
|
26
|
+
SQLAlchemyEncryptedValue,
|
|
27
|
+
SQLAlchemyHashed,
|
|
28
|
+
SQLAlchemyPGEncryptedArray,
|
|
29
|
+
)
|
|
22
30
|
|
|
23
31
|
|
|
24
32
|
def __getattr__(name: str):
|
|
25
|
-
if name == "
|
|
26
|
-
from pydantic_encryption.integrations.sqlalchemy import
|
|
33
|
+
if name == "SQLAlchemyEncryptedValue":
|
|
34
|
+
from pydantic_encryption.integrations.sqlalchemy import SQLAlchemyEncryptedValue
|
|
27
35
|
|
|
28
|
-
return
|
|
36
|
+
return SQLAlchemyEncryptedValue
|
|
37
|
+
|
|
38
|
+
if name == "SQLAlchemyPGEncryptedArray":
|
|
39
|
+
from pydantic_encryption.integrations.sqlalchemy import SQLAlchemyPGEncryptedArray
|
|
40
|
+
|
|
41
|
+
return SQLAlchemyPGEncryptedArray
|
|
29
42
|
|
|
30
43
|
if name == "SQLAlchemyHashed":
|
|
31
44
|
from pydantic_encryption.integrations.sqlalchemy import SQLAlchemyHashed
|
|
32
45
|
|
|
33
46
|
return SQLAlchemyHashed
|
|
34
47
|
|
|
48
|
+
if name == "SQLAlchemyBlindIndexValue":
|
|
49
|
+
from pydantic_encryption.integrations.sqlalchemy import SQLAlchemyBlindIndexValue
|
|
50
|
+
|
|
51
|
+
return SQLAlchemyBlindIndexValue
|
|
52
|
+
|
|
35
53
|
if name == "AWSAdapter":
|
|
36
54
|
from pydantic_encryption.adapters.encryption.aws import AWSAdapter
|
|
37
55
|
|
|
@@ -52,10 +70,13 @@ __all__ = [
|
|
|
52
70
|
"BaseModel",
|
|
53
71
|
"SecureModel",
|
|
54
72
|
# Annotations
|
|
73
|
+
"BlindIndex",
|
|
55
74
|
"Encrypt",
|
|
56
75
|
"Decrypt",
|
|
57
76
|
"Hash",
|
|
58
77
|
# Types
|
|
78
|
+
"BlindIndexMethod",
|
|
79
|
+
"BlindIndexValue",
|
|
59
80
|
"EncryptionMethod",
|
|
60
81
|
"EncryptedValue",
|
|
61
82
|
"DecryptedValue",
|
|
@@ -67,6 +88,8 @@ __all__ = [
|
|
|
67
88
|
"AWSAdapter",
|
|
68
89
|
"EvervaultAdapter",
|
|
69
90
|
# SQLAlchemy (optional - lazy loaded)
|
|
70
|
-
"
|
|
91
|
+
"SQLAlchemyBlindIndexValue",
|
|
92
|
+
"SQLAlchemyEncryptedValue",
|
|
93
|
+
"SQLAlchemyPGEncryptedArray",
|
|
71
94
|
"SQLAlchemyHashed",
|
|
72
95
|
]
|
{pydantic_encryption-0.3.2 → pydantic_encryption-0.5.0}/pydantic_encryption/adapters/base.py
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
from abc import ABC, abstractmethod
|
|
2
2
|
|
|
3
|
-
from pydantic_encryption.types import DecryptedValue, EncryptedValue, HashedValue
|
|
3
|
+
from pydantic_encryption.types import BlindIndexValue, DecryptedValue, EncryptedValue, HashedValue
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
class EncryptionAdapter(ABC):
|
|
@@ -24,3 +24,12 @@ class HashingAdapter(ABC):
|
|
|
24
24
|
@abstractmethod
|
|
25
25
|
def hash(cls, value: str | bytes | HashedValue) -> HashedValue:
|
|
26
26
|
"""Hash the given value."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class BlindIndexAdapter(ABC):
|
|
30
|
+
"""Abstract base class for blind index adapters."""
|
|
31
|
+
|
|
32
|
+
@classmethod
|
|
33
|
+
@abstractmethod
|
|
34
|
+
def compute_blind_index(cls, value: str | bytes, key: bytes) -> BlindIndexValue:
|
|
35
|
+
"""Compute a deterministic blind index for the given value."""
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
|
|
3
|
+
from pydantic_encryption.adapters.base import BlindIndexAdapter
|
|
4
|
+
from pydantic_encryption.types import BlindIndexValue
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Argon2BlindIndexAdapter(BlindIndexAdapter):
|
|
8
|
+
"""Blind index adapter using Argon2 with a deterministic salt."""
|
|
9
|
+
|
|
10
|
+
@classmethod
|
|
11
|
+
def compute_blind_index(cls, value: str | bytes, key: bytes) -> BlindIndexValue:
|
|
12
|
+
"""Compute a deterministic Argon2 blind index."""
|
|
13
|
+
|
|
14
|
+
if isinstance(value, BlindIndexValue):
|
|
15
|
+
return value
|
|
16
|
+
|
|
17
|
+
from argon2.low_level import Type as Argon2Type
|
|
18
|
+
from argon2.low_level import hash_secret_raw
|
|
19
|
+
|
|
20
|
+
if isinstance(value, str):
|
|
21
|
+
value = value.encode("utf-8")
|
|
22
|
+
|
|
23
|
+
salt = hashlib.sha256(key).digest()[:16]
|
|
24
|
+
digest = hash_secret_raw(
|
|
25
|
+
secret=value,
|
|
26
|
+
salt=salt,
|
|
27
|
+
time_cost=3,
|
|
28
|
+
memory_cost=65536,
|
|
29
|
+
parallelism=1,
|
|
30
|
+
hash_len=32,
|
|
31
|
+
type=Argon2Type.ID,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
return BlindIndexValue(digest)
|