Skip to content

Custom notebook


Secure Data Encryption in Custom Python/PySpark Notebooks

Before you start, make sure you have completed the Initialization steps. This ensures your environment is ready for secure encryption and decryption operations, including access to the Key Vault that holds the KEK and the wrapped DEKs.

Encrypting Data in Your Notebook

To protect sensitive information, use the encrypt_df() function from the nccutils module. Encryption uses envelope encryption: the KEK and a DEK per entity are created and managed automatically in the Key Vault, so you do not need to retrieve or pass an encryption key yourself. For details about its usage and parameters, see the Data Privacy documentation.

Step-by-step: Encrypt Data in a PySpark Notebook

Ensure the following prerequisites:

  • df is a PySpark DataFrame containing your data.
  • privacyColumns,columnMappings, primary_key_columns, no_history_columns and exclude_columns are defined from the entity configuration.
  • EncryptionKeyVault is the name of the Key Vault that holds the KEK and the wrapped DEKs, stored in tenant variables within CMP
1. Import the required functions

the new encryption functions are in a new module nccutils.encryption_v2.encryption_v2, the old function remain available

import json

from nccutils.encryption_v2.encryption_v2 import (
    apply_column_mapping,
    privacy_columns_with_column_mapping,
    dataquality_deduplicate,
    create_n7_hashes,
    encrypt_df,
)

2. Apply the column mapping
if privacyColumns:
    df = apply_column_mapping(
        df=df,
        column_mapping=columnMappings
    )
    privacyColumns = privacy_columns_with_column_mapping(columnMappings, privacyColumns)
3. Deduplicate the data
DQ_Deduplication_Mode = json.loads(EntityValues).get('DQ_Deduplication_Mode', 'None')

df = dataquality_deduplicate(
    df=df,
    primary_keys=primary_key_columns,
    deduplication_mode=DQ_Deduplication_Mode
)
4. Create the hashes
if primary_key_columns:
    df = create_n7_hashes(
        df,
        primary_key_columns,
        no_history_columns,
        exclude_columns
    )
5. Encrypt the DataFrame

Determine the columns to encrypt and the foreign key columns from privacyColumns, and encrypt the DataFrame:

parsed = json.loads(privacyColumns)

foreign_key_columns = ";".join(
    (c.get("targetColumn") or c.get("sourceColumn"))
    for c in parsed
    if c.get("isForeignKey")
)

privacy_columns_encrypt = json.dumps([
    {"columnname": (c.get("targetColumn") or c.get("sourceColumn"))}
    for c in parsed
    if c.get("privacyOption") == "Encrypt"
])

if df.count() > 0 and privacy_columns_encrypt:
    output_data = encrypt_df(
        input_dataframe=df,
        privacy_columns=privacy_columns_encrypt,
        entity_table_path=TargetFileName,
        foreign_key_columns=foreign_key_columns,
        EncryptionKeyVault=EncryptionKeyVault
    )
else:
    output_data = df

df = output_data

This approach encrypts the sensitive columns in your DataFrame using the NCC configuration. If the Key Vault does not yet contain a KEK or a wrapped DEK for the entity, they are created automatically. For further details on encryption and available options, refer to the Data Privacy documentation.

Existing customers: crypto_key

Customers that were already encrypting data before the switch to envelope encryption pass their existing crypto_key to encrypt_df(). This key is then reused as the DEK, so existing encrypted data stays readable. To get a unique DEK per entity, switch your decryption logic to the wrapped DEK method and remove the crypto_key. See encryption migration existing customers.

Decrypting Data in Your Notebook

To read encrypted data back in clear text, retrieve the wrapped DEK of the entity from the Key Vault and pass it to decrypt_dataframe(). The wrapped DEK is stored as a secret named wrapped-dek-<entity>, and decrypt_dataframe() uses the KEK in the Key Vault to unwrap it.

import base64
from azure.keyvault.secrets import SecretClient
from nccutils.encryption_v2.encryption_v2 import NotebookUtilsCredential, decrypt_dataframe

credential = NotebookUtilsCredential()
vault_url = "https://<key-vault-name>.vault.azure.net/"
secret_client = SecretClient(vault_url=vault_url, credential=credential)

# Secret name: wrapped-dek-<entity>
wrapped_dek_secret = secret_client.get_secret("wrapped-dek-<entity>")
wrapped_dek_bytes = base64.b64decode(wrapped_dek_secret.value)

decrypted_df = decrypt_dataframe(
    df=encrypted_df,
    crypto_key=wrapped_dek_bytes,
    kek_keyvault="<key-vault-name>",  #Optional. It is needed if you want it decrypt using KEK/DEK, if you want decrypt using the old crypto key, this can be left empyu.
)

Replace <key-vault-name> with the name of your EncryptionKeyVault and <entity> with the name of the entity whose columns you want to decrypt.


NCC Configuration

For more information about configuring entities in NCC, see NCC Data Privacy under the 'Encryption' section.