Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions pynuodb/crypt.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@
# In older cryptography it's still with the regular algorithms
ARC4 = algorithms.ARC4
arc4Imported = True
# default_backend() is an expensive call that carries no per-use
# state, so sharing one across all Cipher constructions is safe and
# reduces memory usage/accelerates GC for python programs that use a lot
# of connections (each connection calls this twice)
_DEFAULT_BACKEND = default_backend()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are all usages of _DEFAULT_BACKEND gated by a check of arc4Imported?

It might be better to have a helper function instead of a variable, and that function will initialize the global default_backend if none is set.

@bkelly-ndb bkelly-ndb Aug 7, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't need to pass backend=default_backend() in 3.1 onwards since its deprecated.

Perhaps make it conditional to call and pass in only for python 2.x and for python3.1 onwards by not having to call it at all and save more time?

except ImportError:
arc4Imported = False
AESImported = False
Expand Down Expand Up @@ -371,7 +376,7 @@ def __init__(self, encrypt, key, nonce):
:param nonce: The nonce for the cipher or None to create it
"""
algo = algorithms.AES(self._convert_key(key))
cipher = Cipher(algo, mode=modes.CTR(nonce), backend=default_backend())
cipher = Cipher(algo, mode=modes.CTR(nonce), backend=_DEFAULT_BACKEND)
self.cipher = cipher.encryptor() if encrypt else cipher.decryptor()

def transform(self, data):
Expand Down Expand Up @@ -485,7 +490,7 @@ def __init__(self, encrypt, key, convert=True):
# optionality of mode correctly.
# https://github.com/pyca/cryptography/issues/9464
cipher = Cipher(algo, mode=None, # type: ignore
backend=default_backend())
backend=_DEFAULT_BACKEND)
self.cipher = cipher.encryptor() if encrypt else cipher.decryptor()

def transform(self, data):
Expand Down