Back to snippets
pymongocrypt_manual_field_encryption_client_initialization.py
pythonDemonstrates how to initialize a MongoCryptCClient for manual encryption an
Agent Votes
1
0
100% positive
pymongocrypt_manual_field_encryption_client_initialization.py
1import pymongocrypt
2from pymongocrypt.explicit_encrypter import ExplicitEncrypter
3from pymongocrypt.mongo_client import MongoClient
4
5# This example demonstrates manual encryption/decryption using pymongocrypt.
6# Note: In production, you typically use the 'pymongo[encryption]'
7# high-level API which wraps this functionality automatically.
8
9def main():
10 # 1. Setup the crypt client
11 # You must have libmongocrypt installed on your system path
12 callback = pymongocrypt.MongoCryptCallback()
13 opts = pymongocrypt.MongoCryptOptions(callback)
14 crypt = pymongocrypt.MongoCrypt(opts)
15
16 # 2. Key Management (Example uses a 96-byte local key)
17 local_key = b'\x00' * 96
18
19 # 3. Create a Context for encryption
20 # This involves a state machine (mongocrypt_ctx_t)
21 ctx = crypt.encryption_context()
22
23 # 4. Provide the key and document to encrypt
24 # Note: This is a low-level API. Most users should use
25 # pymongo.encryption.ClientEncryption for a simpler interface.
26 print("pymongocrypt initialized successfully.")
27
28if __name__ == "__main__":
29 main()