pydantic_encryption 0.0.2a2__tar.gz → 0.0.2a4__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 (20) hide show
  1. {pydantic_encryption-0.0.2a2 → pydantic_encryption-0.0.2a4}/PKG-INFO +49 -10
  2. {pydantic_encryption-0.0.2a2 → pydantic_encryption-0.0.2a4}/README.md +42 -4
  3. pydantic_encryption-0.0.2a4/pydantic_encryption/__init__.py +3 -0
  4. pydantic_encryption-0.0.2a4/pydantic_encryption/annotations.py +20 -0
  5. pydantic_encryption-0.0.2a4/pydantic_encryption/config.py +22 -0
  6. pydantic_encryption-0.0.2a4/pydantic_encryption/lib/__init__.py +2 -0
  7. pydantic_encryption-0.0.2a4/pydantic_encryption/lib/adapters/encryption/evervault.py +50 -0
  8. pydantic_encryption-0.0.2a4/pydantic_encryption/lib/adapters/encryption/fernet.py +34 -0
  9. pydantic_encryption-0.0.2a4/pydantic_encryption/lib/adapters/hashing/__init__.py +0 -0
  10. pydantic_encryption-0.0.2a4/pydantic_encryption/lib/adapters/hashing/bcrypt.py +10 -0
  11. pydantic_encryption-0.0.2a4/pydantic_encryption/models/adapters/aws.py +47 -0
  12. pydantic_encryption-0.0.2a4/pydantic_encryption/models/adapters/key_provider.py +17 -0
  13. pydantic_encryption-0.0.2a4/pydantic_encryption/models/adapters/sqlalchemy.py +44 -0
  14. {pydantic_encryption-0.0.2a2 → pydantic_encryption-0.0.2a4}/pydantic_encryption/models/secure_model.py +71 -53
  15. {pydantic_encryption-0.0.2a2 → pydantic_encryption-0.0.2a4}/pyproject.toml +10 -5
  16. pydantic_encryption-0.0.2a2/pydantic_encryption/__init__.py +0 -1
  17. pydantic_encryption-0.0.2a2/pydantic_encryption/config.py +0 -34
  18. {pydantic_encryption-0.0.2a2 → pydantic_encryption-0.0.2a4}/LICENSE +0 -0
  19. {pydantic_encryption-0.0.2a2 → pydantic_encryption-0.0.2a4}/pydantic_encryption/models/__init__.py +0 -0
  20. {pydantic_encryption-0.0.2a2 → pydantic_encryption-0.0.2a4}/pydantic_encryption/models/base.py +0 -0
@@ -1,31 +1,32 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: pydantic_encryption
3
- Version: 0.0.2a2
3
+ Version: 0.0.2a4
4
4
  Summary: Encryption and hashing models for Pydantic
5
5
  Author: Julien Kmec
6
6
  Author-email: me@julien.dev
7
- Requires-Python: >=3.9,<4.0.0
7
+ Requires-Python: >=3.10,<4.0.0
8
8
  Classifier: Programming Language :: Python :: 3
9
- Classifier: Programming Language :: Python :: 3.9
10
9
  Classifier: Programming Language :: Python :: 3.10
11
10
  Classifier: Programming Language :: Python :: 3.11
12
11
  Classifier: Programming Language :: Python :: 3.12
13
12
  Classifier: Programming Language :: Python :: 3.13
14
13
  Provides-Extra: all
15
- Provides-Extra: evervault
16
14
  Provides-Extra: generics
17
15
  Provides-Extra: test
18
16
  Requires-Dist: bcrypt (>=4.3.0,<5.0.0)
17
+ Requires-Dist: boto3 (>=1.38.3,<2.0.0)
19
18
  Requires-Dist: coverage (>=7.8.0) ; extra == "all"
20
19
  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"
20
+ Requires-Dist: evervault (>=4.4.1)
23
21
  Requires-Dist: pydantic (>=2.10.6)
24
22
  Requires-Dist: pydantic-settings (>=2.9.1)
25
23
  Requires-Dist: pytest (>=8.3.5) ; extra == "all"
26
24
  Requires-Dist: pytest (>=8.3.5) ; extra == "test"
25
+ Requires-Dist: pytest-env (>=1.1.5,<2.0.0) ; extra == "all"
26
+ Requires-Dist: pytest-env (>=1.1.5,<2.0.0) ; extra == "test"
27
27
  Requires-Dist: python-generics (>=0.2.3) ; extra == "all"
28
28
  Requires-Dist: python-generics (>=0.2.3) ; extra == "generics"
29
+ Requires-Dist: sqlalchemy (>=2.0.40,<3.0.0)
29
30
  Description-Content-Type: text/markdown
30
31
 
31
32
  # Encryption and hashing models for Pydantic
@@ -36,12 +37,17 @@ This package provides Pydantic field annotations that encrypt, decrypt, and hash
36
37
 
37
38
  Install with Pip:
38
39
  ```bash
39
- pip install pydantic_encryption[evervault,generics]
40
+ pip install pydantic_encryption
40
41
  ```
41
42
 
43
+ ### Optional extras
44
+
45
+ - `generics`: Support for generics
46
+
42
47
  ## Features
43
48
 
44
49
  - Encrypt and decrypt specific fields
50
+ - Support for Fernet symmetric encryption and Evervault
45
51
  - Hash specific fields
46
52
  - Support for generics
47
53
 
@@ -64,9 +70,40 @@ print(user.password) # hashed
64
70
 
65
71
  ## Choose an Encryption Method
66
72
 
73
+ You can choose which encryption method to use by setting the `use_encryption_method` parameter in the class definition.
74
+
75
+ ### Example:
76
+
77
+ ```python
78
+ from typing import Annotated
79
+ from pydantic_encryption import EncryptionMethod, BaseModel, Encrypt
80
+
81
+ class User(BaseModel, use_encryption_method=EncryptionMethod.EVERVAULT):
82
+ name: str
83
+ address: Annotated[str, Encrypt] # This field will be encrypted by Evervault
84
+ ```
85
+
86
+ ### Default Encryption (Fernet Symmetric Encryption)
87
+
88
+ By default, Fernet will be used for encryption and decryption.
89
+
90
+ First you need to generate an encryption key. You can use the following command:
91
+
92
+ ```bash
93
+ openssl rand -base64 32
94
+ ```
95
+
96
+ Then set the following environment variable or add it to your `.env` file:
97
+
98
+ ```bash
99
+ ENCRYPTION_KEY=your_encryption_key
100
+ ```
101
+
67
102
  ### Evervault
68
103
 
69
- If you install this package with the `evervault` extra, you can use [Evervault](https://evervault.com/) to encrypt and decrypt fields.
104
+ You can optionally use [Evervault](https://evervault.com/) to encrypt and decrypt fields.
105
+
106
+ Set the `use_encryption_method` parameter to `EncryptionMethod.EVERVAULT`.
70
107
 
71
108
  You need to set the following environment variables or add them to your `.env` file:
72
109
 
@@ -76,9 +113,9 @@ EVERVAULT_API_KEY=your_api_key
76
113
  EVERVAULT_ENCRYPTION_ROLE=your_encryption_role
77
114
  ```
78
115
 
79
- ### Custom Encryption
116
+ ### Custom Encryption or Hashing
80
117
 
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.
118
+ You can define your own encryption or hashing methods by subclassing `SecureModel`. `SecureModel` provides you with the utilities to handle encryption, decryption, and hashing.
82
119
 
83
120
  `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
121
 
@@ -246,6 +283,8 @@ poetry run coverage run -m pytest -v -s
246
283
  This is an early development version. I am considering the following features:
247
284
 
248
285
  - [ ] Add optional support for other encryption providers beyond Evervault
286
+ - [ ] Add support for AWS KMS and other key management services
287
+ - [ ] Native encryption via PostgreSQL and other databases
249
288
 
250
289
  ## Feature Requests
251
290
 
@@ -6,12 +6,17 @@ This package provides Pydantic field annotations that encrypt, decrypt, and hash
6
6
 
7
7
  Install with Pip:
8
8
  ```bash
9
- pip install pydantic_encryption[evervault,generics]
9
+ pip install pydantic_encryption
10
10
  ```
11
11
 
12
+ ### Optional extras
13
+
14
+ - `generics`: Support for generics
15
+
12
16
  ## Features
13
17
 
14
18
  - Encrypt and decrypt specific fields
19
+ - Support for Fernet symmetric encryption and Evervault
15
20
  - Hash specific fields
16
21
  - Support for generics
17
22
 
@@ -34,9 +39,40 @@ print(user.password) # hashed
34
39
 
35
40
  ## Choose an Encryption Method
36
41
 
42
+ You can choose which encryption method to use by setting the `use_encryption_method` parameter in the class definition.
43
+
44
+ ### Example:
45
+
46
+ ```python
47
+ from typing import Annotated
48
+ from pydantic_encryption import EncryptionMethod, BaseModel, Encrypt
49
+
50
+ class User(BaseModel, use_encryption_method=EncryptionMethod.EVERVAULT):
51
+ name: str
52
+ address: Annotated[str, Encrypt] # This field will be encrypted by Evervault
53
+ ```
54
+
55
+ ### Default Encryption (Fernet Symmetric Encryption)
56
+
57
+ By default, Fernet will be used for encryption and decryption.
58
+
59
+ First you need to generate an encryption key. You can use the following command:
60
+
61
+ ```bash
62
+ openssl rand -base64 32
63
+ ```
64
+
65
+ Then set the following environment variable or add it to your `.env` file:
66
+
67
+ ```bash
68
+ ENCRYPTION_KEY=your_encryption_key
69
+ ```
70
+
37
71
  ### Evervault
38
72
 
39
- If you install this package with the `evervault` extra, you can use [Evervault](https://evervault.com/) to encrypt and decrypt fields.
73
+ You can optionally use [Evervault](https://evervault.com/) to encrypt and decrypt fields.
74
+
75
+ Set the `use_encryption_method` parameter to `EncryptionMethod.EVERVAULT`.
40
76
 
41
77
  You need to set the following environment variables or add them to your `.env` file:
42
78
 
@@ -46,9 +82,9 @@ EVERVAULT_API_KEY=your_api_key
46
82
  EVERVAULT_ENCRYPTION_ROLE=your_encryption_role
47
83
  ```
48
84
 
49
- ### Custom Encryption
85
+ ### Custom Encryption or Hashing
50
86
 
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.
87
+ You can define your own encryption or hashing methods by subclassing `SecureModel`. `SecureModel` provides you with the utilities to handle encryption, decryption, and hashing.
52
88
 
53
89
  `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
90
 
@@ -216,6 +252,8 @@ poetry run coverage run -m pytest -v -s
216
252
  This is an early development version. I am considering the following features:
217
253
 
218
254
  - [ ] Add optional support for other encryption providers beyond Evervault
255
+ - [ ] Add support for AWS KMS and other key management services
256
+ - [ ] Native encryption via PostgreSQL and other databases
219
257
 
220
258
  ## Feature Requests
221
259
 
@@ -0,0 +1,3 @@
1
+ from .models import *
2
+ from .annotations import *
3
+ from .lib import *
@@ -0,0 +1,20 @@
1
+ from enum import Enum
2
+
3
+
4
+ class Encrypt:
5
+ """Annotation to mark fields for encryption."""
6
+
7
+
8
+ class Decrypt:
9
+ """Annotation to mark fields for decryption."""
10
+
11
+
12
+ class Hash:
13
+ """Annotation to mark fields for hashing."""
14
+
15
+
16
+ class EncryptionMethod(Enum):
17
+ """Enum for encryption methods."""
18
+
19
+ FERNET = "fernet"
20
+ EVERVAULT = "evervault"
@@ -0,0 +1,22 @@
1
+ from typing import Any, Optional
2
+ from pydantic_settings import BaseSettings
3
+
4
+
5
+ class Settings(BaseSettings):
6
+ """Settings for the package."""
7
+
8
+ # Cryptography settings
9
+ ENCRYPTION_KEY: Optional[str] = None
10
+
11
+ # Evervault settings
12
+ EVERVAULT_API_KEY: Optional[str] = None
13
+ EVERVAULT_APP_ID: Optional[str] = None
14
+ EVERVAULT_ENCRYPTION_ROLE: Optional[str] = None
15
+
16
+ class Config:
17
+ env_file = [".env.local", ".env"]
18
+ case_sensitive = True
19
+ extra = "ignore"
20
+
21
+
22
+ settings = Settings()
@@ -0,0 +1,2 @@
1
+ from .adapters.encryption import fernet, evervault
2
+ from .adapters.hashing import bcrypt
@@ -0,0 +1,50 @@
1
+ from pydantic_encryption.config import settings
2
+
3
+ try:
4
+ import evervault
5
+ except ImportError:
6
+ evervault = None
7
+
8
+ EVERVAULT_CLIENT = None
9
+
10
+
11
+ def load_evervault_client():
12
+ """Load the Evervault encryption client."""
13
+
14
+ if not (
15
+ settings.EVERVAULT_APP_ID
16
+ and settings.EVERVAULT_API_KEY
17
+ and settings.EVERVAULT_ENCRYPTION_ROLE
18
+ ):
19
+ raise ValueError(
20
+ "Evervault settings are not configured. Please set the following environment variables: EVERVAULT_APP_ID, EVERVAULT_API_KEY, EVERVAULT_ENCRYPTION_ROLE."
21
+ )
22
+
23
+ if not evervault:
24
+ raise ValueError(
25
+ "Evervault is not available. Please install this package with the `evervault` extra."
26
+ )
27
+
28
+ global EVERVAULT_CLIENT
29
+
30
+ EVERVAULT_CLIENT = EVERVAULT_CLIENT or evervault.Client(
31
+ app_uuid=settings.EVERVAULT_APP_ID, api_key=settings.EVERVAULT_API_KEY
32
+ )
33
+
34
+ return EVERVAULT_CLIENT
35
+
36
+
37
+ def evervault_encrypt(plaintext: bytes) -> bytes:
38
+ """Encrypt data using Evervault."""
39
+
40
+ evervault_client = load_evervault_client()
41
+
42
+ return evervault_client.encrypt(plaintext, role=settings.EVERVAULT_ENCRYPTION_ROLE)
43
+
44
+
45
+ def evervault_decrypt(ciphertext: bytes) -> bytes:
46
+ """Decrypt data using Evervault."""
47
+
48
+ evervault_client = load_evervault_client()
49
+
50
+ return evervault_client.decrypt(ciphertext)
@@ -0,0 +1,34 @@
1
+ from cryptography.fernet import Fernet
2
+ from pydantic_encryption.config import settings
3
+
4
+
5
+ FERNET_CLIENT = None
6
+
7
+
8
+ def load_fernet_client() -> Fernet:
9
+ global FERNET_CLIENT
10
+
11
+ if not settings.ENCRYPTION_KEY:
12
+ raise ValueError(
13
+ "Fernet is not available. Please set the ENCRYPTION_KEY environment variable."
14
+ )
15
+
16
+ FERNET_CLIENT = FERNET_CLIENT or Fernet(settings.ENCRYPTION_KEY)
17
+
18
+ return FERNET_CLIENT
19
+
20
+
21
+ def fernet_encrypt(plaintext: bytes) -> bytes:
22
+ """Encrypt data using Fernet."""
23
+
24
+ fernet_client = load_fernet_client()
25
+
26
+ return fernet_client.encrypt(plaintext)
27
+
28
+
29
+ def fernet_decrypt(ciphertext: bytes) -> bytes:
30
+ """Decrypt data using Fernet."""
31
+
32
+ fernet_client = load_fernet_client()
33
+
34
+ return fernet_client.decrypt(ciphertext)
@@ -0,0 +1,10 @@
1
+ import bcrypt as bcrypt_provider
2
+
3
+
4
+ def bcrypt_hash_data(value: str) -> str:
5
+ """Hash data using bcrypt."""
6
+
7
+ salt = bcrypt_provider.gensalt()
8
+ hashed = bcrypt_provider.hashpw(value.encode("utf-8"), salt).decode("utf-8")
9
+
10
+ return hashed
@@ -0,0 +1,47 @@
1
+ try:
2
+ import boto3
3
+ except ImportError:
4
+ boto3 = None
5
+ else:
6
+ boto3 = boto3.client("kms", region_name=region)
7
+
8
+
9
+ class AWSKMSProvider(KeyProvider):
10
+ def __init__(self, kms_key_id: str, region: str = None):
11
+ self.kms = boto3.client("kms", region_name=region)
12
+ self.key_id = kms_key_id
13
+
14
+ def generate_data_key(self, key_id=None):
15
+ resp = self.kms.generate_data_key(
16
+ KeyId=key_id or self.key_id, KeySpec="AES_256"
17
+ )
18
+ return resp["Plaintext"], resp["CiphertextBlob"]
19
+
20
+ def encrypt(self, plaintext: bytes, key_id=None):
21
+ # direct KMS encrypt (slower, size-limited) or envelope as fallback
22
+ resp = self.kms.encrypt(KeyId=key_id or self.key_id, Plaintext=plaintext)
23
+ return resp["CiphertextBlob"]
24
+
25
+ def decrypt(self, ciphertext: bytes):
26
+ resp = self.kms.decrypt(CiphertextBlob=ciphertext)
27
+ return resp["Plaintext"]
28
+
29
+
30
+ class KMSEncryptedModel(SecureModel):
31
+ provider: ClassVar[KeyProvider] = AWSKMSProvider(settings.KMS_KEY_ID)
32
+
33
+ def encrypt_data(self):
34
+ for field, pt in self.pending_encryption_fields.items():
35
+ # envelope encrypt
36
+ dek, edek = self.provider.generate_data_key()
37
+ ct = Fernet(base64.urlsafe_b64encode(dek)).encrypt(pt.encode())
38
+ # store “edek|ct”
39
+ setattr(self, field, base64.b64encode(edek + b"|" + ct).decode())
40
+
41
+ def decrypt_data(self):
42
+ for field, blob in self.pending_decryption_fields.items():
43
+ raw = base64.b64decode(blob.encode())
44
+ edek, ct = raw.split(b"|", 1)
45
+ dek = self.provider.decrypt(edek)
46
+ pt = Fernet(base64.urlsafe_b64encode(dek)).decrypt(ct).decode()
47
+ setattr(self, field, pt)
@@ -0,0 +1,17 @@
1
+ from abc import ABC, abstractmethod
2
+
3
+
4
+ class KeyProvider(ABC):
5
+ @abstractmethod
6
+ def encrypt(self, plaintext: bytes, key_id: str, **ctx) -> bytes:
7
+ """Use the remote KMS to encrypt data-key or data directly."""
8
+
9
+ @abstractmethod
10
+ def decrypt(self, ciphertext: bytes, **ctx) -> bytes:
11
+ """Use the remote KMS to decrypt data-key or data directly."""
12
+
13
+ @abstractmethod
14
+ def generate_data_key(self, key_id: str) -> tuple[bytes, bytes]:
15
+ """
16
+ For envelope encryption: returns (plaintext_data_key, encrypted_data_key)
17
+ """
@@ -0,0 +1,44 @@
1
+ try:
2
+ from sqlalchemy import func
3
+ from sqlalchemy.dialects.postgresql import BYTEA
4
+ from sqlalchemy.types import TypeDecorator, Text
5
+ except ImportError:
6
+ sqlalchemy_available = False
7
+ else:
8
+ sqlalchemy_available = True
9
+
10
+
11
+ class PGPSymEncrypted(TypeDecorator):
12
+ """
13
+ A SQLAlchemy type that, on the bind side, wraps INSERT/UPDATE values in
14
+ pgp_sym_encrypt(val, :key) and on the result side wraps the column in
15
+ pgp_sym_decrypt(col, :key)::text
16
+ """
17
+
18
+ impl = BYTEA
19
+ cache_ok = True
20
+
21
+ def __init__(self, key, *args, **kwargs):
22
+ """
23
+ key: either a literal string or a SQLAlchemy bindparam / text() expression.
24
+ """
25
+
26
+ if not sqlalchemy_available:
27
+ raise ImportError(
28
+ "SQLAlchemy is not available. Please install this package with the `sqlalchemy` extra."
29
+ )
30
+
31
+ self._key = key
32
+ super().__init__(*args, **kwargs)
33
+
34
+ def bind_expression(self, bindvalue):
35
+ # wrap any value we bind with pgp_sym_encrypt(...)
36
+ return func.pgp_sym_encrypt(bindvalue, self._key)
37
+
38
+ def column_expression(self, col):
39
+ # whenever we SELECT, automatically decrypt and cast back to text
40
+ return func.pgp_sym_decrypt(col, self._key).cast(Text)
41
+
42
+ def copy(self, **kw):
43
+ # ensure key survives copies / caching
44
+ return PGPSymEncrypted(self._key, **kw)
@@ -1,85 +1,104 @@
1
- from typing import Any, Annotated, get_type_hints, Union, get_args, get_origin, Optional
2
- import bcrypt
3
- from pydantic_encryption.config import settings
4
- from pydantic import BaseModel
5
-
6
- try:
7
- import evervault
8
- except ImportError:
9
- evervault_client = None
10
- else:
11
- evervault_client = evervault.Client(
12
- app_uuid=settings.EVERVAULT_APP_ID, api_key=settings.EVERVAULT_API_KEY
13
- )
14
-
15
- __all__ = [
16
- "Encrypt",
17
- "Decrypt",
18
- "Hash",
19
- "SecureModel",
20
- ]
21
-
1
+ from typing import (
2
+ Annotated,
3
+ Any,
4
+ Optional,
5
+ Union,
6
+ get_args,
7
+ get_origin,
8
+ get_type_hints,
9
+ )
22
10
 
23
- class Encrypt:
24
- """Annotation to mark fields for encryption."""
25
-
26
-
27
- class Decrypt:
28
- """Annotation to mark fields for decryption."""
11
+ from pydantic import BaseModel
12
+ from pydantic_encryption.lib import bcrypt, fernet, evervault
13
+ from pydantic_encryption.annotations import (
14
+ Encrypt,
15
+ Decrypt,
16
+ Hash,
17
+ EncryptionMethod,
18
+ )
29
19
 
30
20
 
31
- class Hash:
32
- """Annotation to mark fields for hashing."""
21
+ __all__ = ["SecureModel"]
33
22
 
34
23
 
35
24
  class SecureModel:
36
25
  """Base class for encryptable and hashable models."""
37
26
 
38
27
  _disable: Optional[bool] = None
39
-
40
- def __init_subclass__(cls, disable: Optional[bool] = None, **kwargs) -> None:
28
+ _use_encryption_method: Optional[EncryptionMethod] = EncryptionMethod.FERNET
29
+
30
+ def __init_subclass__(
31
+ cls,
32
+ disable: Optional[bool] = None,
33
+ use_encryption_method: Optional[EncryptionMethod] = EncryptionMethod.FERNET,
34
+ **kwargs,
35
+ ) -> None:
41
36
  super().__init_subclass__(**kwargs)
42
37
 
43
38
  cls._disable = disable
39
+ cls._use_encryption_method = use_encryption_method
44
40
 
45
41
  def encrypt_data(self) -> None:
46
- """Encrypt data using Evervault."""
42
+ """Encrypt data using the specified encryption method."""
47
43
 
48
44
  if self._disable:
49
45
  return
50
46
 
51
- if not evervault_client:
52
- raise ValueError(
53
- "Evervault is not available. Please install this package with the `evervault` extra."
54
- )
55
-
56
47
  if not self.pending_encryption_fields:
57
48
  return
58
49
 
59
- encrypted_data_dict = evervault_client.encrypt(
60
- self.pending_encryption_fields, role=settings.EVERVAULT_ENCRYPTION_ROLE
61
- )
62
-
63
- for field_name, value in encrypted_data_dict.items():
50
+ encrypted_data: dict[str, str] = {}
51
+
52
+ match self._use_encryption_method:
53
+ case EncryptionMethod.EVERVAULT:
54
+ encrypted_data = evervault.evervault_encrypt(
55
+ self.pending_encryption_fields
56
+ )
57
+
58
+ case EncryptionMethod.FERNET:
59
+ encrypted_data = {
60
+ field_name: fernet.fernet_encrypt(value.encode("utf-8")).decode(
61
+ "utf-8"
62
+ )
63
+ for field_name, value in self.pending_encryption_fields.items()
64
+ }
65
+ case _:
66
+ raise ValueError(
67
+ f"Unknown encryption method: {self._use_encryption_method}"
68
+ )
69
+
70
+ for field_name, value in encrypted_data.items():
64
71
  setattr(self, field_name, value)
65
72
 
66
73
  def decrypt_data(self) -> None:
67
- """Decrypt data using Evervault. After this call, all decrypted fields are type str."""
74
+ """Decrypt data using the specified encryption method. After this call, all decrypted fields are type str."""
68
75
 
69
76
  if self._disable:
70
77
  return
71
78
 
72
- if not evervault_client:
73
- raise ValueError(
74
- "Evervault is not available. Please install this package with the `evervault` extra."
75
- )
76
-
77
79
  if not self.pending_decryption_fields:
78
80
  return
79
81
 
80
- decrypted_data: dict[str, str] = evervault_client.decrypt(
81
- self.pending_decryption_fields
82
- )
82
+ decrypted_data: dict[str, str] = {}
83
+
84
+ match self._use_encryption_method:
85
+ case EncryptionMethod.EVERVAULT:
86
+ decrypted_data = evervault.evervault_decrypt(
87
+ self.pending_decryption_fields
88
+ )
89
+
90
+ case EncryptionMethod.FERNET:
91
+ decrypted_data = {
92
+ field_name: fernet.fernet_decrypt(value.encode("utf-8")).decode(
93
+ "utf-8"
94
+ )
95
+ for field_name, value in self.pending_decryption_fields.items()
96
+ }
97
+
98
+ case _:
99
+ raise ValueError(
100
+ f"Unknown encryption method: {self._use_encryption_method}"
101
+ )
83
102
 
84
103
  for field_name, value in decrypted_data.items():
85
104
  setattr(self, field_name, value)
@@ -94,8 +113,7 @@ class SecureModel:
94
113
  return
95
114
 
96
115
  for field_name, value in self.pending_hash_fields.items():
97
- salt = bcrypt.gensalt()
98
- hashed = bcrypt.hashpw(value.encode("utf-8"), salt)
116
+ hashed = bcrypt.bcrypt_hash_data(value)
99
117
 
100
118
  setattr(self, field_name, hashed)
101
119
 
@@ -1,24 +1,29 @@
1
1
  [project]
2
2
  name = "pydantic_encryption"
3
- version = "0.0.2a2"
3
+ version = "0.0.2a4"
4
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.9,<4.0.0"
10
+ requires-python = ">=3.10,<4.0.0"
11
11
  dependencies = [
12
12
  "pydantic>=2.10.6",
13
13
  "pydantic-settings>=2.9.1",
14
14
  "bcrypt (>=4.3.0,<5.0.0)",
15
+ "evervault>=4.4.1",
16
+ "sqlalchemy (>=2.0.40,<3.0.0)",
17
+ "boto3 (>=1.38.3,<2.0.0)"
15
18
  ]
16
19
 
17
20
  [project.optional-dependencies]
18
- evervault = ["evervault>=4.4.1"]
19
21
  generics = ["python-generics>=0.2.3"]
20
- test = ["pytest>=8.3.5", "coverage>=7.8.0"]
21
- all = ["evervault>=4.4.1", "python-generics>=0.2.3", "pytest>=8.3.5", "coverage>=7.8.0"]
22
+ test = ["pytest>=8.3.5", "coverage>=7.8.0", "pytest-env (>=1.1.5,<2.0.0)"]
23
+ all = ["python-generics>=0.2.3", "pytest>=8.3.5", "coverage>=7.8.0", "pytest-env (>=1.1.5,<2.0.0)"]
24
+
25
+ [tool.pytest_env]
26
+ ENCRYPTION_KEY = "FF9OqqsxdRoge7b0orbJ7EZAn96bLFDgoa8icBF3GNM="
22
27
 
23
28
  [build-system]
24
29
  requires = ["poetry-core", "setuptools"]
@@ -1 +0,0 @@
1
- from .models import *
@@ -1,34 +0,0 @@
1
- from typing import Any, Optional
2
- from pydantic_settings import BaseSettings
3
-
4
-
5
- class Settings(BaseSettings):
6
- """Settings for the package."""
7
-
8
- # Evervault settings
9
- EVERVAULT_API_KEY: Optional[str] = None
10
- EVERVAULT_APP_ID: Optional[str] = None
11
- EVERVAULT_ENCRYPTION_ROLE: Optional[str] = None
12
-
13
- class Config:
14
- env_file = [".env.local", ".env"]
15
- case_sensitive = True
16
- extra = "ignore"
17
-
18
- def model_post_init(self, context: Any, /) -> None:
19
- try:
20
- import evervault # pylint: disable=unused-import
21
- except ImportError:
22
- pass
23
- else:
24
- if not (
25
- self.EVERVAULT_APP_ID
26
- and self.EVERVAULT_API_KEY
27
- and self.EVERVAULT_ENCRYPTION_ROLE
28
- ):
29
- raise ValueError("Evervault settings are not configured")
30
-
31
- return super().model_post_init(context)
32
-
33
-
34
- settings = Settings()