I wrote a simple encryption function that uses argon2d as the KDF and XChaCha20-Poly1305 as the AEAD. Since it is very easy to not get things right when dealing with encryption, I would appreciate if someone could review my script and tell me if it has any vulnerabilities and could be used in the real world to encrypt real data.
import argon2
from Cryptodome.Cipher import ChaCha20_Poly1305
import secrets
def encrypt(password, data):
salt = secrets.token_bytes(32)
nonce = secrets.token_bytes(24)
key = argon2.low_level.hash_secret_raw(secret=password, salt=salt, time_cost=3, memory_cost=1000000, parallelism=4, hash_len=32, type=argon2.low_level.Type.D, version=19)
cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
ciphertext, tag = cipher.encrypt_and_digest(data)
return salt + nonce + ciphertext + tag
-
1\$\begingroup\$ Note for future questions: when reviewing encryption code, it's helpful to also see the corresponding decryptor (even if that's in a different language) and examples of use. Normally, your test program will show both of these, and it's a good idea to include that in your question. \$\endgroup\$Toby Speight– Toby Speight2021年01月16日 14:12:55 +00:00Commented Jan 16, 2021 at 14:12
2 Answers 2
You can add annotations in function parameters, like password: str
and so on.
-
2\$\begingroup\$ They may be called something else. \$\endgroup\$greybeard– greybeard2021年01月13日 10:17:42 +00:00Commented Jan 13, 2021 at 10:17
-
2\$\begingroup\$ @greybeard "Annotation" should be fine, although it's a bit general. From your link: "here is a simple function whose argument and return type are declared in the annotations:". The syntax is called an annotation, and they're being used as type hints here. \$\endgroup\$Carcigenicate– Carcigenicate2021年01月14日 00:09:57 +00:00Commented Jan 14, 2021 at 0:09
It's not clear whether the parameters password
and data
should be passed as strings or as byte-arrays. Use type-hint annotations, or at least a doc-comment so that users know which they should be passing.
-
\$\begingroup\$ Besides that, would the rest of the code be safe for encryption? \$\endgroup\$Bernardo1r– Bernardo1r2021年01月17日 02:50:10 +00:00Commented Jan 17, 2021 at 2:50