pyca / pynacl

Python binding to the Networking and Cryptography (NaCl) library
https://pynacl.readthedocs.io/
Apache License 2.0
1.05k stars 228 forks source link

Unexpected failure in key derivation #818

Closed geekygiks closed 2 months ago

geekygiks commented 2 months ago

I am getting following error in pwhash.kdf_scryptsalsa208sha256,

RuntimeError: Unexpected failure in key derivation Traceback: File "/home/admin/miniconda3/envs/iitp/lib/python3.11/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 584, in _run_script exec(code, module.dict) File "/home/admin/Project/pages/readTXT.py", line 7, in Alices_key = pwhash.kdf_scryptsalsa208sha256(secret.SecretBox.KEY_SIZE, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/admin/miniconda3/envs/iitp/lib/python3.11/site-packages/nacl/pwhash/scrypt.py", line 135, in kdf nacl.bindings.crypto_pwhash_scryptsalsa208sha256_ll( File "/home/admin/miniconda3/envs/iitp/lib/python3.11/site-packages/nacl/bindings/crypto_pwhash.py", line 316, in crypto_pwhash_scryptsalsa208sha256_ll ensure( File "/home/admin/miniconda3/envs/iitp/lib/python3.11/site-packages/nacl/exceptions.py", line 88, in ensure raise raising(*args)

Code to reproduce,

from nacl import pwhash, secret, utils ops = pwhash.SCRYPT_OPSLIMIT_SENSITIVE mem = pwhash.SCRYPT_MEMLIMIT_SENSITIVE salt = utils.random(pwhash.SCRYPT_SALTBYTES) password = b'password shared between Alice and Bob' message = b"This is a message for Bob's eyes only" Alices_key = pwhash.kdf_scryptsalsa208sha256(secret.SecretBox.KEY_SIZE, password, salt, opslimit=ops, memlimit=mem) Alices_box = secret.SecretBox(Alices_key) nonce = utils.random(secret.SecretBox.NONCE_SIZE) encrypted = Alices_box.encrypt(message, nonce)

now Alice must send to Bob both the encrypted message

and the KDF parameters: salt, opslimit and memlimit;

using the same parameters and password

Bob is able to derive the correct key to decrypt the message

Bobs_key = pwhash.kdf_scryptsalsa208sha256(secret.SecretBox.KEY_SIZE, password, salt, opslimit=ops, memlimit=mem) Bobs_box = secret.SecretBox(Bobs_key) received = Bobs_box.decrypt(encrypted) print(received)

While this run perfectly on local env, github codespace, I am getting error on amazon aws ec2 instance,

OS: Debian 12 pynacl version: 1.5 Python 3.11.8

Every other thing is same across all the setup(local/codespace/ec2).

reaperhulk commented 2 months ago

This error means the underlying libsodium library is returning an error when invoking crypto_pwhash_scryptsalsa208sha256_ll. The implementation of that is here: https://github.com/jedisct1/libsodium/blob/113781628b6e7489bcc344441759fea38694ae55/src/libsodium/crypto_pwhash/scryptsalsa208sha256/crypto_scrypt-common.c#L243-L268

There are a few scenarios that could cause this, but try lowering your memlimit first to see if it's just a memory allocation issue.

geekygiks commented 2 months ago

Thankyou. It worked. reduced the mem usage.