pydantic_encryption 0.2.0__tar.gz → 0.3.1__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.
Files changed (21) hide show
  1. {pydantic_encryption-0.2.0 → pydantic_encryption-0.3.1}/PKG-INFO +36 -1
  2. {pydantic_encryption-0.2.0 → pydantic_encryption-0.3.1}/README.md +35 -0
  3. pydantic_encryption-0.3.1/pydantic_encryption/integrations/sqlalchemy.py +213 -0
  4. {pydantic_encryption-0.2.0 → pydantic_encryption-0.3.1}/pyproject.toml +1 -1
  5. pydantic_encryption-0.2.0/pydantic_encryption/integrations/sqlalchemy.py +0 -109
  6. {pydantic_encryption-0.2.0 → pydantic_encryption-0.3.1}/LICENSE +0 -0
  7. {pydantic_encryption-0.2.0 → pydantic_encryption-0.3.1}/pydantic_encryption/__init__.py +0 -0
  8. {pydantic_encryption-0.2.0 → pydantic_encryption-0.3.1}/pydantic_encryption/_lazy.py +0 -0
  9. {pydantic_encryption-0.2.0 → pydantic_encryption-0.3.1}/pydantic_encryption/adapters/__init__.py +0 -0
  10. {pydantic_encryption-0.2.0 → pydantic_encryption-0.3.1}/pydantic_encryption/adapters/base.py +0 -0
  11. {pydantic_encryption-0.2.0 → pydantic_encryption-0.3.1}/pydantic_encryption/adapters/encryption/__init__.py +0 -0
  12. {pydantic_encryption-0.2.0 → pydantic_encryption-0.3.1}/pydantic_encryption/adapters/encryption/aws.py +0 -0
  13. {pydantic_encryption-0.2.0 → pydantic_encryption-0.3.1}/pydantic_encryption/adapters/encryption/evervault.py +0 -0
  14. {pydantic_encryption-0.2.0 → pydantic_encryption-0.3.1}/pydantic_encryption/adapters/encryption/fernet.py +0 -0
  15. {pydantic_encryption-0.2.0 → pydantic_encryption-0.3.1}/pydantic_encryption/adapters/hashing/__init__.py +0 -0
  16. {pydantic_encryption-0.2.0 → pydantic_encryption-0.3.1}/pydantic_encryption/adapters/hashing/argon2.py +0 -0
  17. {pydantic_encryption-0.2.0 → pydantic_encryption-0.3.1}/pydantic_encryption/config.py +0 -0
  18. {pydantic_encryption-0.2.0 → pydantic_encryption-0.3.1}/pydantic_encryption/integrations/__init__.py +0 -0
  19. {pydantic_encryption-0.2.0 → pydantic_encryption-0.3.1}/pydantic_encryption/models/__init__.py +0 -0
  20. {pydantic_encryption-0.2.0 → pydantic_encryption-0.3.1}/pydantic_encryption/models/base.py +0 -0
  21. {pydantic_encryption-0.2.0 → pydantic_encryption-0.3.1}/pydantic_encryption/types.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pydantic_encryption
3
- Version: 0.2.0
3
+ Version: 0.3.1
4
4
  Summary: Encryption and Hashing Models for Pydantic
5
5
  License-File: LICENSE
6
6
  Author: Julien Kmec
@@ -152,6 +152,41 @@ print(user.email) # decrypted
152
152
  print(user.password) # hashed
153
153
  ```
154
154
 
155
+ ### Supported Types
156
+
157
+ `SQLAlchemyEncrypted` automatically detects and preserves the Python type of your data:
158
+
159
+ | Type | Example |
160
+ |------|---------|
161
+ | `str` | `"hello@example.com"` |
162
+ | `bytes` | `b"binary data"` |
163
+ | `bool` | `True`, `False` |
164
+ | `int` | `42` |
165
+ | `float` | `3.14159` |
166
+ | `Decimal` | `Decimal("99999.99")` |
167
+ | `UUID` | `UUID("12345678-1234-5678-1234-567812345678")` |
168
+ | `date` | `date(1990, 5, 15)` |
169
+ | `datetime` | `datetime(2025, 1, 21, 14, 30, 45)` |
170
+ | `time` | `time(14, 30, 45)` |
171
+ | `timedelta` | `timedelta(hours=2, minutes=30)` |
172
+
173
+ ```python
174
+ import uuid
175
+ from datetime import date, datetime, time, timedelta
176
+ from decimal import Decimal
177
+
178
+ class User(Base, table=True):
179
+ email: str = Field(sa_type=SQLAlchemyEncrypted())
180
+ birth_date: date = Field(sa_type=SQLAlchemyEncrypted())
181
+ last_login: datetime = Field(sa_type=SQLAlchemyEncrypted())
182
+ age: int = Field(sa_type=SQLAlchemyEncrypted())
183
+ balance: float = Field(sa_type=SQLAlchemyEncrypted())
184
+ salary: Decimal = Field(sa_type=SQLAlchemyEncrypted())
185
+ external_id: uuid.UUID = Field(sa_type=SQLAlchemyEncrypted())
186
+ login_time: time = Field(sa_type=SQLAlchemyEncrypted())
187
+ session_duration: timedelta = Field(sa_type=SQLAlchemyEncrypted())
188
+ ```
189
+
155
190
  ## Choose an Encryption Method
156
191
 
157
192
  You can choose which encryption algorithm to use by setting the `ENCRYPTION_METHOD` environment variable.
@@ -106,6 +106,41 @@ print(user.email) # decrypted
106
106
  print(user.password) # hashed
107
107
  ```
108
108
 
109
+ ### Supported Types
110
+
111
+ `SQLAlchemyEncrypted` automatically detects and preserves the Python type of your data:
112
+
113
+ | Type | Example |
114
+ |------|---------|
115
+ | `str` | `"hello@example.com"` |
116
+ | `bytes` | `b"binary data"` |
117
+ | `bool` | `True`, `False` |
118
+ | `int` | `42` |
119
+ | `float` | `3.14159` |
120
+ | `Decimal` | `Decimal("99999.99")` |
121
+ | `UUID` | `UUID("12345678-1234-5678-1234-567812345678")` |
122
+ | `date` | `date(1990, 5, 15)` |
123
+ | `datetime` | `datetime(2025, 1, 21, 14, 30, 45)` |
124
+ | `time` | `time(14, 30, 45)` |
125
+ | `timedelta` | `timedelta(hours=2, minutes=30)` |
126
+
127
+ ```python
128
+ import uuid
129
+ from datetime import date, datetime, time, timedelta
130
+ from decimal import Decimal
131
+
132
+ class User(Base, table=True):
133
+ email: str = Field(sa_type=SQLAlchemyEncrypted())
134
+ birth_date: date = Field(sa_type=SQLAlchemyEncrypted())
135
+ last_login: datetime = Field(sa_type=SQLAlchemyEncrypted())
136
+ age: int = Field(sa_type=SQLAlchemyEncrypted())
137
+ balance: float = Field(sa_type=SQLAlchemyEncrypted())
138
+ salary: Decimal = Field(sa_type=SQLAlchemyEncrypted())
139
+ external_id: uuid.UUID = Field(sa_type=SQLAlchemyEncrypted())
140
+ login_time: time = Field(sa_type=SQLAlchemyEncrypted())
141
+ session_duration: timedelta = Field(sa_type=SQLAlchemyEncrypted())
142
+ ```
143
+
109
144
  ## Choose an Encryption Method
110
145
 
111
146
  You can choose which encryption algorithm to use by setting the `ENCRYPTION_METHOD` environment variable.
@@ -0,0 +1,213 @@
1
+ import base64
2
+ from datetime import date, datetime, time, timedelta
3
+ from decimal import Decimal
4
+ from enum import StrEnum
5
+ from typing import Final
6
+ from uuid import UUID
7
+
8
+ from pydantic_encryption._lazy import require_optional_dependency
9
+
10
+ require_optional_dependency("sqlalchemy", "sqlalchemy")
11
+
12
+ from sqlalchemy.types import LargeBinary, TypeDecorator
13
+
14
+ from pydantic_encryption.adapters import encryption, hashing
15
+ from pydantic_encryption.config import settings
16
+ from pydantic_encryption.types import EncryptedValue, EncryptionMethod, HashedValue
17
+
18
+ # Type alias for all supported encrypted value types
19
+ EncryptableValue = str | bytes | bool | int | float | Decimal | UUID | date | datetime | time | timedelta
20
+
21
+ _VERSION_PREFIX: Final[str] = "v1"
22
+
23
+
24
+ class _TypePrefix(StrEnum):
25
+ """Type prefixes for auto-detection of encrypted field types."""
26
+
27
+ STR = "str"
28
+ BYTES = "bytes"
29
+ BOOL = "bool"
30
+ INT = "int"
31
+ FLOAT = "float"
32
+ DECIMAL = "decimal"
33
+ UUID = "uuid"
34
+ DATE = "date"
35
+ DATETIME = "datetime"
36
+ TIME = "time"
37
+ TIMEDELTA = "timedelta"
38
+
39
+
40
+ class SQLAlchemyEncrypted(TypeDecorator):
41
+ """Type adapter for SQLAlchemy to encrypt and decrypt data using the specified encryption method."""
42
+
43
+ impl = LargeBinary
44
+ cache_ok = True
45
+
46
+ def _serialize_value(self, value: EncryptableValue) -> str:
47
+ """Serialize a value with version and type prefix for encryption.
48
+
49
+ Format: "v1:type:data"
50
+ """
51
+ match value:
52
+ case datetime():
53
+ type_data = f"{_TypePrefix.DATETIME}:{value.isoformat()}"
54
+ case date():
55
+ type_data = f"{_TypePrefix.DATE}:{value.isoformat()}"
56
+ case time():
57
+ type_data = f"{_TypePrefix.TIME}:{value.isoformat()}"
58
+ case timedelta():
59
+ type_data = f"{_TypePrefix.TIMEDELTA}:{value.days},{value.seconds},{value.microseconds}"
60
+ case bytes():
61
+ type_data = f"{_TypePrefix.BYTES}:{base64.b64encode(value).decode('ascii')}"
62
+ case bool():
63
+ type_data = f"{_TypePrefix.BOOL}:{str(value).lower()}"
64
+ case int():
65
+ type_data = f"{_TypePrefix.INT}:{value}"
66
+ case float():
67
+ type_data = f"{_TypePrefix.FLOAT}:{value!r}"
68
+ case Decimal():
69
+ type_data = f"{_TypePrefix.DECIMAL}:{value}"
70
+ case UUID():
71
+ type_data = f"{_TypePrefix.UUID}:{value}"
72
+ case _:
73
+ type_data = f"{_TypePrefix.STR}:{value}"
74
+
75
+ return f"{_VERSION_PREFIX}:{type_data}"
76
+
77
+ def _deserialize_value(self, value: str) -> EncryptableValue:
78
+ """Deserialize a decrypted value based on its version and type prefix.
79
+
80
+ Format: "v1:type:data"
81
+ If no version marker is present, returns the value as a string (legacy format).
82
+ """
83
+ version, _, remainder = value.partition(":")
84
+
85
+ if not version:
86
+ return value
87
+
88
+ if version != _VERSION_PREFIX:
89
+ raise RuntimeError("Unknown version")
90
+
91
+ type_prefix, _, data = remainder.partition(":")
92
+
93
+ match type_prefix:
94
+ case _TypePrefix.DATETIME:
95
+ return datetime.fromisoformat(data)
96
+ case _TypePrefix.DATE:
97
+ return date.fromisoformat(data)
98
+ case _TypePrefix.TIME:
99
+ return time.fromisoformat(data)
100
+ case _TypePrefix.TIMEDELTA:
101
+ parts = data.split(",")
102
+ return timedelta(days=int(parts[0]), seconds=int(parts[1]), microseconds=int(parts[2]))
103
+ case _TypePrefix.BYTES:
104
+ return base64.b64decode(data)
105
+ case _TypePrefix.BOOL:
106
+ return data == "true"
107
+ case _TypePrefix.INT:
108
+ return int(data)
109
+ case _TypePrefix.FLOAT:
110
+ return float(data)
111
+ case _TypePrefix.DECIMAL:
112
+ return Decimal(data)
113
+ case _TypePrefix.UUID:
114
+ return UUID(data)
115
+ case _TypePrefix.STR:
116
+ return data
117
+ case _:
118
+ return data
119
+
120
+ def _process_encrypt_value(self, value: EncryptableValue | None) -> EncryptedValue | None:
121
+ if value is None:
122
+ return None
123
+
124
+ serialized_value = self._serialize_value(value)
125
+
126
+ match settings.ENCRYPTION_METHOD:
127
+ case EncryptionMethod.FERNET:
128
+ return encryption.fernet.FernetAdapter.encrypt(serialized_value)
129
+ case EncryptionMethod.EVERVAULT:
130
+ return encryption.evervault.EvervaultAdapter.encrypt(serialized_value)
131
+ case EncryptionMethod.AWS:
132
+ return encryption.aws.AWSAdapter.encrypt(serialized_value)
133
+ case _:
134
+ raise ValueError(f"Unknown encryption method: {settings.ENCRYPTION_METHOD}")
135
+
136
+ def _process_decrypt_value(self, value: str | bytes | None) -> str | bytes | None:
137
+ if value is None:
138
+ return None
139
+
140
+ match settings.ENCRYPTION_METHOD:
141
+ case EncryptionMethod.FERNET:
142
+ return encryption.fernet.FernetAdapter.decrypt(value)
143
+ case EncryptionMethod.EVERVAULT:
144
+ return encryption.evervault.EvervaultAdapter.decrypt(value)
145
+ case EncryptionMethod.AWS:
146
+ return encryption.aws.AWSAdapter.decrypt(value)
147
+ case _:
148
+ raise ValueError(f"Unknown encryption method: {settings.ENCRYPTION_METHOD}")
149
+
150
+ def process_bind_param(self, value: EncryptableValue | None, dialect) -> bytes | None:
151
+ """Encrypts data before binding it to the database."""
152
+
153
+ return self._process_encrypt_value(value)
154
+
155
+ def process_literal_param(self, value: EncryptableValue | None, dialect) -> bytes | None:
156
+ """Encrypts data for literal SQL expressions."""
157
+
158
+ return self._process_encrypt_value(value)
159
+
160
+ def process_result_value(self, value: str | bytes | None, dialect) -> EncryptableValue | None:
161
+ """Decrypts data after retrieving it from the database."""
162
+
163
+ if value is None:
164
+ return None
165
+
166
+ decrypted_value = self._process_decrypt_value(value)
167
+
168
+ return self._deserialize_value(decrypted_value)
169
+
170
+ @property
171
+ def python_type(self):
172
+ """Return the Python type this is bound to."""
173
+
174
+ return self.impl.python_type
175
+
176
+
177
+ class SQLAlchemyHashed(TypeDecorator):
178
+ """Type adapter for SQLAlchemy to hash strings using Argon2."""
179
+
180
+ impl = LargeBinary
181
+ cache_ok = True
182
+
183
+ def process_bind_param(self, value: str | bytes | None, dialect) -> bytes | None:
184
+ """Hashes a string before binding it to the database."""
185
+
186
+ if value is None:
187
+ return None
188
+
189
+ return hashing.argon2.Argon2Adapter.hash(value)
190
+
191
+ def process_literal_param(self, value: str | bytes | None, dialect) -> HashedValue | None:
192
+ """Hashes a string for literal SQL expressions."""
193
+
194
+ if value is None:
195
+ return None
196
+
197
+ processed = hashing.argon2.Argon2Adapter.hash(value)
198
+
199
+ return dialect.literal_processor(self.impl)(processed)
200
+
201
+ def process_result_value(self, value: str | bytes | None, dialect) -> HashedValue | None:
202
+ """Returns the hash value as-is from the database, wrapped as a HashedValue."""
203
+
204
+ if value is None:
205
+ return None
206
+
207
+ return HashedValue(value)
208
+
209
+ @property
210
+ def python_type(self):
211
+ """Return the Python type this is bound to (str)."""
212
+
213
+ return self.impl.python_type
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pydantic_encryption"
3
- version = "0.2.0"
3
+ version = "0.3.1"
4
4
  description = "Encryption and Hashing Models for Pydantic"
5
5
  authors = [
6
6
  { name = "Julien Kmec", email = "me@julien.dev" },
@@ -1,109 +0,0 @@
1
- from pydantic_encryption._lazy import require_optional_dependency
2
-
3
- require_optional_dependency("sqlalchemy", "sqlalchemy")
4
-
5
- from sqlalchemy.types import LargeBinary, TypeDecorator
6
-
7
- from pydantic_encryption.adapters import encryption, hashing
8
- from pydantic_encryption.config import settings
9
- from pydantic_encryption.types import DecryptedValue, EncryptedValue, EncryptionMethod, HashedValue
10
-
11
-
12
- class SQLAlchemyEncrypted(TypeDecorator):
13
- """Type adapter for SQLAlchemy to encrypt and decrypt strings using the specified encryption method."""
14
-
15
- impl = LargeBinary
16
- cache_ok = True
17
-
18
- def _process_encrypt_value(self, value: str | bytes | None) -> EncryptedValue | None:
19
- if value is None:
20
- return None
21
-
22
- match settings.ENCRYPTION_METHOD:
23
- case EncryptionMethod.FERNET:
24
- return encryption.fernet.FernetAdapter.encrypt(value)
25
- case EncryptionMethod.EVERVAULT:
26
- return encryption.evervault.EvervaultAdapter.encrypt(value)
27
- case EncryptionMethod.AWS:
28
- return encryption.aws.AWSAdapter.encrypt(value)
29
- case _:
30
- raise ValueError(f"Unknown encryption method: {settings.ENCRYPTION_METHOD}")
31
-
32
- def _process_decrypt_value(self, value: str | bytes | None) -> str | bytes | None:
33
- if value is None:
34
- return None
35
-
36
- match settings.ENCRYPTION_METHOD:
37
- case EncryptionMethod.FERNET:
38
- return encryption.fernet.FernetAdapter.decrypt(value)
39
- case EncryptionMethod.EVERVAULT:
40
- return encryption.evervault.EvervaultAdapter.decrypt(value)
41
- case EncryptionMethod.AWS:
42
- return encryption.aws.AWSAdapter.decrypt(value)
43
- case _:
44
- raise ValueError(f"Unknown encryption method: {settings.ENCRYPTION_METHOD}")
45
-
46
- def process_bind_param(self, value: str | bytes | None, dialect) -> str | bytes | None:
47
- """Encrypts a string before binding it to the database."""
48
-
49
- return self._process_encrypt_value(value)
50
-
51
- def process_literal_param(self, value: str | bytes | None, dialect) -> str | bytes | None:
52
- """Encrypts a string for literal SQL expressions."""
53
-
54
- return self._process_encrypt_value(value)
55
-
56
- def process_result_value(self, value: str | bytes | None, dialect) -> DecryptedValue | None:
57
- """Decrypts a string after retrieving it from the database."""
58
-
59
- if value is None:
60
- return None
61
-
62
- decrypted_value = self._process_decrypt_value(value)
63
-
64
- return DecryptedValue(decrypted_value)
65
-
66
- @property
67
- def python_type(self):
68
- """Return the Python type this is bound to (str)."""
69
-
70
- return self.impl.python_type
71
-
72
-
73
- class SQLAlchemyHashed(TypeDecorator):
74
- """Type adapter for SQLAlchemy to hash strings using Argon2."""
75
-
76
- impl = LargeBinary
77
- cache_ok = True
78
-
79
- def process_bind_param(self, value: str | bytes | None, dialect) -> bytes | None:
80
- """Hashes a string before binding it to the database."""
81
-
82
- if value is None:
83
- return None
84
-
85
- return hashing.argon2.Argon2Adapter.hash(value)
86
-
87
- def process_literal_param(self, value: str | bytes | None, dialect) -> HashedValue | None:
88
- """Hashes a string for literal SQL expressions."""
89
-
90
- if value is None:
91
- return None
92
-
93
- processed = hashing.argon2.Argon2Adapter.hash(value)
94
-
95
- return dialect.literal_processor(self.impl)(processed)
96
-
97
- def process_result_value(self, value: str | bytes | None, dialect) -> HashedValue | None:
98
- """Returns the hash value as-is from the database, wrapped as a HashedValue."""
99
-
100
- if value is None:
101
- return None
102
-
103
- return HashedValue(value)
104
-
105
- @property
106
- def python_type(self):
107
- """Return the Python type this is bound to (str)."""
108
-
109
- return self.impl.python_type