pydantic_encryption 0.1.3__tar.gz → 0.3.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.
Files changed (21) hide show
  1. {pydantic_encryption-0.1.3 → pydantic_encryption-0.3.0}/PKG-INFO +42 -7
  2. {pydantic_encryption-0.1.3 → pydantic_encryption-0.3.0}/README.md +41 -6
  3. {pydantic_encryption-0.1.3 → pydantic_encryption-0.3.0}/pydantic_encryption/adapters/encryption/aws.py +6 -6
  4. {pydantic_encryption-0.1.3 → pydantic_encryption-0.3.0}/pydantic_encryption/config.py +2 -2
  5. pydantic_encryption-0.3.0/pydantic_encryption/integrations/sqlalchemy.py +213 -0
  6. {pydantic_encryption-0.1.3 → pydantic_encryption-0.3.0}/pyproject.toml +1 -1
  7. pydantic_encryption-0.1.3/pydantic_encryption/integrations/sqlalchemy.py +0 -109
  8. {pydantic_encryption-0.1.3 → pydantic_encryption-0.3.0}/LICENSE +0 -0
  9. {pydantic_encryption-0.1.3 → pydantic_encryption-0.3.0}/pydantic_encryption/__init__.py +0 -0
  10. {pydantic_encryption-0.1.3 → pydantic_encryption-0.3.0}/pydantic_encryption/_lazy.py +0 -0
  11. {pydantic_encryption-0.1.3 → pydantic_encryption-0.3.0}/pydantic_encryption/adapters/__init__.py +0 -0
  12. {pydantic_encryption-0.1.3 → pydantic_encryption-0.3.0}/pydantic_encryption/adapters/base.py +0 -0
  13. {pydantic_encryption-0.1.3 → pydantic_encryption-0.3.0}/pydantic_encryption/adapters/encryption/__init__.py +0 -0
  14. {pydantic_encryption-0.1.3 → pydantic_encryption-0.3.0}/pydantic_encryption/adapters/encryption/evervault.py +0 -0
  15. {pydantic_encryption-0.1.3 → pydantic_encryption-0.3.0}/pydantic_encryption/adapters/encryption/fernet.py +0 -0
  16. {pydantic_encryption-0.1.3 → pydantic_encryption-0.3.0}/pydantic_encryption/adapters/hashing/__init__.py +0 -0
  17. {pydantic_encryption-0.1.3 → pydantic_encryption-0.3.0}/pydantic_encryption/adapters/hashing/argon2.py +0 -0
  18. {pydantic_encryption-0.1.3 → pydantic_encryption-0.3.0}/pydantic_encryption/integrations/__init__.py +0 -0
  19. {pydantic_encryption-0.1.3 → pydantic_encryption-0.3.0}/pydantic_encryption/models/__init__.py +0 -0
  20. {pydantic_encryption-0.1.3 → pydantic_encryption-0.3.0}/pydantic_encryption/models/base.py +0 -0
  21. {pydantic_encryption-0.1.3 → pydantic_encryption-0.3.0}/pydantic_encryption/types.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pydantic_encryption
3
- Version: 0.1.3
3
+ Version: 0.3.0
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.
@@ -170,8 +205,8 @@ See [config.py](https://github.com/julien777z/pydantic-encryption/blob/main/pyda
170
205
  ENCRYPTION_METHOD=aws
171
206
  AWS_KMS_KEY_ARN=123
172
207
  AWS_KMS_REGION=us-east-1
173
- AWS_ACCESS_KEY_ID=123
174
- AWS_SECRET_ACCESS_KEY=123
208
+ AWS_KMS_ACCESS_KEY_ID=123
209
+ AWS_KMS_SECRET_ACCESS_KEY=123
175
210
  ```
176
211
 
177
212
  ```python
@@ -193,8 +228,8 @@ ENCRYPTION_METHOD=aws
193
228
  AWS_KMS_ENCRYPT_KEY_ARN=arn:aws:kms:us-east-1:123456789:key/encrypt-key-id
194
229
  AWS_KMS_DECRYPT_KEY_ARN=arn:aws:kms:us-east-1:123456789:key/decrypt-key-id
195
230
  AWS_KMS_REGION=us-east-1
196
- AWS_ACCESS_KEY_ID=123
197
- AWS_SECRET_ACCESS_KEY=123
231
+ AWS_KMS_ACCESS_KEY_ID=123
232
+ AWS_KMS_SECRET_ACCESS_KEY=123
198
233
  ```
199
234
 
200
235
  For read-only scenarios where you only need to decrypt data, you can specify just the decrypt key:
@@ -204,8 +239,8 @@ For read-only scenarios where you only need to decrypt data, you can specify jus
204
239
  ENCRYPTION_METHOD=aws
205
240
  AWS_KMS_DECRYPT_KEY_ARN=arn:aws:kms:us-east-1:123456789:key/decrypt-key-id
206
241
  AWS_KMS_REGION=us-east-1
207
- AWS_ACCESS_KEY_ID=123
208
- AWS_SECRET_ACCESS_KEY=123
242
+ AWS_KMS_ACCESS_KEY_ID=123
243
+ AWS_KMS_SECRET_ACCESS_KEY=123
209
244
  ```
210
245
 
211
246
  **Note:** You cannot mix `AWS_KMS_KEY_ARN` with the separate key settings. Use either the global key or the separate encrypt/decrypt keys. If you specify `AWS_KMS_ENCRYPT_KEY_ARN`, you must also specify `AWS_KMS_DECRYPT_KEY_ARN`.
@@ -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.
@@ -124,8 +159,8 @@ See [config.py](https://github.com/julien777z/pydantic-encryption/blob/main/pyda
124
159
  ENCRYPTION_METHOD=aws
125
160
  AWS_KMS_KEY_ARN=123
126
161
  AWS_KMS_REGION=us-east-1
127
- AWS_ACCESS_KEY_ID=123
128
- AWS_SECRET_ACCESS_KEY=123
162
+ AWS_KMS_ACCESS_KEY_ID=123
163
+ AWS_KMS_SECRET_ACCESS_KEY=123
129
164
  ```
130
165
 
131
166
  ```python
@@ -147,8 +182,8 @@ ENCRYPTION_METHOD=aws
147
182
  AWS_KMS_ENCRYPT_KEY_ARN=arn:aws:kms:us-east-1:123456789:key/encrypt-key-id
148
183
  AWS_KMS_DECRYPT_KEY_ARN=arn:aws:kms:us-east-1:123456789:key/decrypt-key-id
149
184
  AWS_KMS_REGION=us-east-1
150
- AWS_ACCESS_KEY_ID=123
151
- AWS_SECRET_ACCESS_KEY=123
185
+ AWS_KMS_ACCESS_KEY_ID=123
186
+ AWS_KMS_SECRET_ACCESS_KEY=123
152
187
  ```
153
188
 
154
189
  For read-only scenarios where you only need to decrypt data, you can specify just the decrypt key:
@@ -158,8 +193,8 @@ For read-only scenarios where you only need to decrypt data, you can specify jus
158
193
  ENCRYPTION_METHOD=aws
159
194
  AWS_KMS_DECRYPT_KEY_ARN=arn:aws:kms:us-east-1:123456789:key/decrypt-key-id
160
195
  AWS_KMS_REGION=us-east-1
161
- AWS_ACCESS_KEY_ID=123
162
- AWS_SECRET_ACCESS_KEY=123
196
+ AWS_KMS_ACCESS_KEY_ID=123
197
+ AWS_KMS_SECRET_ACCESS_KEY=123
163
198
  ```
164
199
 
165
200
  **Note:** You cannot mix `AWS_KMS_KEY_ARN` with the separate key settings. Use either the global key or the separate encrypt/decrypt keys. If you specify `AWS_KMS_ENCRYPT_KEY_ARN`, you must also specify `AWS_KMS_DECRYPT_KEY_ARN`.
@@ -51,20 +51,20 @@ class AWSAdapter(EncryptionAdapter):
51
51
  if not (
52
52
  has_key
53
53
  and settings.AWS_KMS_REGION
54
- and settings.AWS_ACCESS_KEY_ID
55
- and settings.AWS_SECRET_ACCESS_KEY
54
+ and settings.AWS_KMS_ACCESS_KEY_ID
55
+ and settings.AWS_KMS_SECRET_ACCESS_KEY
56
56
  ):
57
57
  raise ValueError(
58
- "AWS KMS requires AWS_KMS_REGION, AWS_ACCESS_KEY_ID, "
59
- "AWS_SECRET_ACCESS_KEY, and at least one key ARN "
58
+ "AWS KMS requires AWS_KMS_REGION, AWS_KMS_ACCESS_KEY_ID, "
59
+ "AWS_KMS_SECRET_ACCESS_KEY, and at least one key ARN "
60
60
  "(AWS_KMS_KEY_ARN, AWS_KMS_ENCRYPT_KEY_ARN, or AWS_KMS_DECRYPT_KEY_ARN) to be set."
61
61
  )
62
62
 
63
63
  cls._kms_client = boto3.client(
64
64
  "kms",
65
65
  region_name=settings.AWS_KMS_REGION,
66
- aws_access_key_id=settings.AWS_ACCESS_KEY_ID,
67
- aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
66
+ aws_access_key_id=settings.AWS_KMS_ACCESS_KEY_ID,
67
+ aws_secret_access_key=settings.AWS_KMS_SECRET_ACCESS_KEY,
68
68
  )
69
69
 
70
70
  if cls._encryption_client is None:
@@ -17,8 +17,8 @@ class Settings(BaseSettings):
17
17
  AWS_KMS_ENCRYPT_KEY_ARN: Optional[str] = None
18
18
  AWS_KMS_DECRYPT_KEY_ARN: Optional[str] = None
19
19
  AWS_KMS_REGION: Optional[str] = None
20
- AWS_ACCESS_KEY_ID: Optional[str] = None
21
- AWS_SECRET_ACCESS_KEY: Optional[str] = None
20
+ AWS_KMS_ACCESS_KEY_ID: Optional[str] = None
21
+ AWS_KMS_SECRET_ACCESS_KEY: Optional[str] = None
22
22
 
23
23
  # Evervault settings
24
24
  EVERVAULT_API_KEY: Optional[str] = None
@@ -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 value
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.1.3"
3
+ version = "0.3.0"
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