3
3
from Crypto .Cipher import AES , ChaCha20_Poly1305
4
4
5
5
from ..config import NonceLength , SymmetricAlgorithm
6
-
7
- AES_CIPHER_MODE = AES .MODE_GCM
8
- AEAD_TAG_LENGTH = 16
9
- XCHACHA20_NONCE_LENGTH = 24
6
+ from ..consts import AEAD_TAG_LENGTH , XCHACHA20_NONCE_LENGTH
10
7
11
8
12
9
def sym_encrypt (
13
10
key : bytes ,
14
11
plain_text : bytes ,
15
12
algorithm : SymmetricAlgorithm = "aes-256-gcm" ,
16
- aes_nonce_length : NonceLength = 16 ,
13
+ nonce_length : NonceLength = 16 ,
17
14
) -> bytes :
18
15
"""
19
16
Symmetric encryption. AES-256-GCM or XChaCha20-Poly1305.
@@ -33,8 +30,8 @@ def sym_encrypt(
33
30
nonce + tag(16 bytes) + encrypted data
34
31
"""
35
32
if algorithm == "aes-256-gcm" :
36
- nonce = os .urandom (aes_nonce_length )
37
- aes_cipher = AES .new (key , AES_CIPHER_MODE , nonce )
33
+ nonce = os .urandom (nonce_length )
34
+ aes_cipher = AES .new (key , AES . MODE_GCM , nonce )
38
35
encrypted , tag = aes_cipher .encrypt_and_digest (plain_text )
39
36
elif algorithm == "xchacha20" :
40
37
nonce = os .urandom (XCHACHA20_NONCE_LENGTH )
@@ -92,11 +89,11 @@ def sym_decrypt(
92
89
# If it's 16 bytes, the nonce will be used to hash, so it's meaningless to increment
93
90
94
91
if algorithm == "aes-256-gcm" :
95
- nonce , tag , ciphered_data = _split_cipher_text (cipher_text , nonce_length )
96
- aes_cipher = AES .new (key , AES_CIPHER_MODE , nonce )
92
+ nonce , tag , ciphered_data = __split_cipher_text (cipher_text , nonce_length )
93
+ aes_cipher = AES .new (key , AES . MODE_GCM , nonce )
97
94
return aes_cipher .decrypt_and_verify (ciphered_data , tag )
98
95
elif algorithm == "xchacha20" :
99
- nonce , tag , ciphered_data = _split_cipher_text (
96
+ nonce , tag , ciphered_data = __split_cipher_text (
100
97
cipher_text , XCHACHA20_NONCE_LENGTH
101
98
)
102
99
xchacha_cipher = ChaCha20_Poly1305 .new (key = key , nonce = nonce )
@@ -105,7 +102,7 @@ def sym_decrypt(
105
102
raise NotImplementedError
106
103
107
104
108
- def _split_cipher_text (cipher_text : bytes , nonce_length : int ):
105
+ def __split_cipher_text (cipher_text : bytes , nonce_length : int ):
109
106
nonce_tag_length = nonce_length + AEAD_TAG_LENGTH
110
107
nonce = cipher_text [:nonce_length ]
111
108
tag = cipher_text [nonce_length :nonce_tag_length ]
0 commit comments