crypyspark 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- crypyspark-0.1.0/.gitignore +176 -0
- crypyspark-0.1.0/LICENSE +21 -0
- crypyspark-0.1.0/PKG-INFO +407 -0
- crypyspark-0.1.0/README.md +383 -0
- crypyspark-0.1.0/pyproject.toml +39 -0
- crypyspark-0.1.0/src/crypyspark/__init__.py +55 -0
- crypyspark-0.1.0/src/crypyspark/_codec.py +126 -0
- crypyspark-0.1.0/src/crypyspark/_core.py +304 -0
- crypyspark-0.1.0/src/crypyspark/_tags.py +126 -0
- crypyspark-0.1.0/src/crypyspark/databricks.py +136 -0
- crypyspark-0.1.0/tests/test_roundtrip.py +292 -0
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
share/python-wheels/
|
|
24
|
+
*.egg-info/
|
|
25
|
+
.installed.cfg
|
|
26
|
+
*.egg
|
|
27
|
+
MANIFEST
|
|
28
|
+
|
|
29
|
+
# PyInstaller
|
|
30
|
+
# Usually these files are written by a python script from a template
|
|
31
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
32
|
+
*.manifest
|
|
33
|
+
*.spec
|
|
34
|
+
|
|
35
|
+
# Installer logs
|
|
36
|
+
pip-log.txt
|
|
37
|
+
pip-delete-this-directory.txt
|
|
38
|
+
|
|
39
|
+
# Unit test / coverage reports
|
|
40
|
+
htmlcov/
|
|
41
|
+
.tox/
|
|
42
|
+
.nox/
|
|
43
|
+
.coverage
|
|
44
|
+
.coverage.*
|
|
45
|
+
.cache
|
|
46
|
+
nosetests.xml
|
|
47
|
+
coverage.xml
|
|
48
|
+
*.cover
|
|
49
|
+
*.py,cover
|
|
50
|
+
.hypothesis/
|
|
51
|
+
.pytest_cache/
|
|
52
|
+
cover/
|
|
53
|
+
|
|
54
|
+
# Translations
|
|
55
|
+
*.mo
|
|
56
|
+
*.pot
|
|
57
|
+
|
|
58
|
+
# Django stuff:
|
|
59
|
+
*.log
|
|
60
|
+
local_settings.py
|
|
61
|
+
db.sqlite3
|
|
62
|
+
db.sqlite3-journal
|
|
63
|
+
|
|
64
|
+
# Flask stuff:
|
|
65
|
+
instance/
|
|
66
|
+
.webassets-cache
|
|
67
|
+
|
|
68
|
+
# Scrapy stuff:
|
|
69
|
+
.scrapy
|
|
70
|
+
|
|
71
|
+
# Sphinx documentation
|
|
72
|
+
docs/_build/
|
|
73
|
+
|
|
74
|
+
# PyBuilder
|
|
75
|
+
.pybuilder/
|
|
76
|
+
target/
|
|
77
|
+
|
|
78
|
+
# Jupyter Notebook
|
|
79
|
+
.ipynb_checkpoints
|
|
80
|
+
|
|
81
|
+
# IPython
|
|
82
|
+
profile_default/
|
|
83
|
+
ipython_config.py
|
|
84
|
+
|
|
85
|
+
# pyenv
|
|
86
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
87
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
88
|
+
# .python-version
|
|
89
|
+
|
|
90
|
+
# pipenv
|
|
91
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
92
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
93
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
94
|
+
# install all needed dependencies.
|
|
95
|
+
#Pipfile.lock
|
|
96
|
+
|
|
97
|
+
# UV
|
|
98
|
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
99
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
100
|
+
# commonly ignored for libraries.
|
|
101
|
+
#uv.lock
|
|
102
|
+
|
|
103
|
+
# poetry
|
|
104
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
105
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
106
|
+
# commonly ignored for libraries.
|
|
107
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
108
|
+
#poetry.lock
|
|
109
|
+
|
|
110
|
+
# pdm
|
|
111
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
112
|
+
#pdm.lock
|
|
113
|
+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
|
114
|
+
# in version control.
|
|
115
|
+
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
|
|
116
|
+
.pdm.toml
|
|
117
|
+
.pdm-python
|
|
118
|
+
.pdm-build/
|
|
119
|
+
|
|
120
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
121
|
+
__pypackages__/
|
|
122
|
+
|
|
123
|
+
# Celery stuff
|
|
124
|
+
celerybeat-schedule
|
|
125
|
+
celerybeat.pid
|
|
126
|
+
|
|
127
|
+
# SageMath parsed files
|
|
128
|
+
*.sage.py
|
|
129
|
+
|
|
130
|
+
# Environments
|
|
131
|
+
.env
|
|
132
|
+
.venv
|
|
133
|
+
env/
|
|
134
|
+
venv/
|
|
135
|
+
ENV/
|
|
136
|
+
env.bak/
|
|
137
|
+
venv.bak/
|
|
138
|
+
|
|
139
|
+
# Spyder project settings
|
|
140
|
+
.spyderproject
|
|
141
|
+
.spyproject
|
|
142
|
+
|
|
143
|
+
# Rope project settings
|
|
144
|
+
.ropeproject
|
|
145
|
+
|
|
146
|
+
# mkdocs documentation
|
|
147
|
+
/site
|
|
148
|
+
|
|
149
|
+
# mypy
|
|
150
|
+
.mypy_cache/
|
|
151
|
+
.dmypy.json
|
|
152
|
+
dmypy.json
|
|
153
|
+
|
|
154
|
+
# Pyre type checker
|
|
155
|
+
.pyre/
|
|
156
|
+
|
|
157
|
+
# pytype static type analyzer
|
|
158
|
+
.pytype/
|
|
159
|
+
|
|
160
|
+
# Cython debug symbols
|
|
161
|
+
cython_debug/
|
|
162
|
+
|
|
163
|
+
# PyCharm
|
|
164
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
165
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
166
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
167
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
168
|
+
#.idea/
|
|
169
|
+
|
|
170
|
+
# PyPI configuration file
|
|
171
|
+
.pypirc
|
|
172
|
+
|
|
173
|
+
# Spark local runs
|
|
174
|
+
spark-warehouse/
|
|
175
|
+
metastore_db/
|
|
176
|
+
derby.log
|
crypyspark-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Sean Pavlak
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: crypyspark
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Type-preserving encryption and decryption for PySpark columns of any type
|
|
5
|
+
Project-URL: Homepage, https://github.com/seanpavlak/CryPySpark
|
|
6
|
+
Project-URL: Issues, https://github.com/seanpavlak/CryPySpark/issues
|
|
7
|
+
Author: Sean Pavlak
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: aes,databricks,encryption,pii,pyspark,spark,unity-catalog
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Database
|
|
16
|
+
Classifier: Topic :: Security :: Cryptography
|
|
17
|
+
Requires-Python: >=3.9
|
|
18
|
+
Provides-Extra: spark
|
|
19
|
+
Requires-Dist: pyspark>=3.5; extra == 'spark'
|
|
20
|
+
Provides-Extra: test
|
|
21
|
+
Requires-Dist: pyspark>=3.5; extra == 'test'
|
|
22
|
+
Requires-Dist: pytest; extra == 'test'
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
<div align="center">
|
|
26
|
+
|
|
27
|
+
# 🔐 CryPySpark
|
|
28
|
+
|
|
29
|
+
**Encrypt any PySpark column. Decrypt it back to the exact same value *and* type.**
|
|
30
|
+
|
|
31
|
+
Structs, arrays, maps, decimals, timestamps, binary, nested as deep as you like.<br>
|
|
32
|
+
No UDFs, one line of code, and it works with Databricks.
|
|
33
|
+
|
|
34
|
+
[](https://github.com/seanpavlak/CryPySpark/blob/main/LICENSE)
|
|
35
|
+

|
|
36
|
+

|
|
37
|
+

|
|
38
|
+

|
|
39
|
+
|
|
40
|
+
</div>
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
import crypyspark
|
|
44
|
+
|
|
45
|
+
enc = df.encrypt("ssn", "address", "orders", key="correct horse battery staple")
|
|
46
|
+
dec = enc.decrypt(key="correct horse battery staple")
|
|
47
|
+
|
|
48
|
+
assert dec.collect() == df.collect() # same values, same types, nested and all
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
---
|
|
52
|
+
|
|
53
|
+
## Contents
|
|
54
|
+
|
|
55
|
+
- [Why CryPySpark](#-why-crypyspark)
|
|
56
|
+
- [Install](#-install)
|
|
57
|
+
- [Quickstart](#-quickstart)
|
|
58
|
+
- [Databricks](#-databricks)
|
|
59
|
+
- [Supported types](#-supported-types)
|
|
60
|
+
- [How it works](#-how-it-works)
|
|
61
|
+
- [Performance](#-performance)
|
|
62
|
+
- [API reference](#-api-reference)
|
|
63
|
+
- [Security notes](#-security-notes)
|
|
64
|
+
- [FAQ](#-faq)
|
|
65
|
+
- [Development](#-development)
|
|
66
|
+
- [License](#-license)
|
|
67
|
+
|
|
68
|
+
---
|
|
69
|
+
|
|
70
|
+
## ✨ Why CryPySpark
|
|
71
|
+
|
|
72
|
+
Spark has `aes_encrypt`, but it only takes `STRING`/`BINARY` and gives back bytes. Encrypting a `struct<street:string, zip:int, geo:array<double>>` or a `map<date, array<binary>>` means writing your own serialization. Then you have to remember every column's original type to decrypt it. CryPySpark does that part for you.
|
|
73
|
+
|
|
74
|
+
| | |
|
|
75
|
+
|---|---|
|
|
76
|
+
| 🧬 **Any type, any depth** | Primitives, decimals, dates, timestamps (incl. NTZ), binary, ANSI intervals, and arbitrarily nested `struct` / `array` / `map`, including maps with non-string keys. |
|
|
77
|
+
| 🎯 **Exact round trip** | NaN, ±Infinity, `-0.0`, 38-digit decimals, microsecond timestamps, raw bytes and unicode all come back unchanged. |
|
|
78
|
+
| 🏷️ **Self-describing ciphertext** | Every encrypted cell carries a compact type tag, so a column decrypts correctly even after a trip through CSV or a `select` that dropped its metadata. |
|
|
79
|
+
| ⚡ **Fast** | Native Spark SQL expressions only, so everything runs in the JVM and Photon with no Python workers. See [Performance](#-performance). |
|
|
80
|
+
| 🧱 **Databricks-native** | Classic, shared and serverless compute (Spark Connect), keys from Databricks secrets, and Unity Catalog governance tags. |
|
|
81
|
+
| 🪶 **Tiny** | Pure Python with zero dependencies beyond the PySpark you already have. |
|
|
82
|
+
|
|
83
|
+
---
|
|
84
|
+
|
|
85
|
+
## 📦 Install
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
pip install crypyspark
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
On Databricks:
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
%pip install crypyspark
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
You can also attach the wheel as a cluster, job or serverless environment library. PySpark isn't a hard dependency, so the runtime's own PySpark is used. To install it locally, use `pip install "crypyspark[spark]"`.
|
|
98
|
+
|
|
99
|
+
---
|
|
100
|
+
|
|
101
|
+
## 🚀 Quickstart
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
import crypyspark # importing adds df.encrypt / df.decrypt
|
|
105
|
+
from pyspark.sql import functions as F
|
|
106
|
+
|
|
107
|
+
KEY = "correct horse battery staple" # any passphrase, bytes, or Column
|
|
108
|
+
|
|
109
|
+
people = spark.createDataFrame(
|
|
110
|
+
[(1, "123-45-6789", ("1 Main St", 12345), {"2024-01-01": 9.99})],
|
|
111
|
+
"id int, ssn string, address struct<street:string,zip:int>, spend map<string,double>",
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
# 🔒 Encrypt: columns become BINARY ciphertext, in place, order preserved
|
|
115
|
+
enc = people.encrypt("ssn", "address", "spend", key=KEY)
|
|
116
|
+
enc.printSchema()
|
|
117
|
+
# root
|
|
118
|
+
# |-- id: integer
|
|
119
|
+
# |-- ssn: binary
|
|
120
|
+
# |-- address: binary
|
|
121
|
+
# |-- spend: binary
|
|
122
|
+
|
|
123
|
+
# 🔓 Decrypt: original types come back automatically
|
|
124
|
+
dec = enc.decrypt(key=KEY) # no names = every column encrypt() touched
|
|
125
|
+
dec.printSchema()
|
|
126
|
+
# root
|
|
127
|
+
# |-- id: integer
|
|
128
|
+
# |-- ssn: string
|
|
129
|
+
# |-- address: struct<street:string,zip:int>
|
|
130
|
+
# |-- spend: map<string,double>
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
### Common recipes
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
# Set the key once, then forget about it
|
|
137
|
+
crypyspark.set_key(KEY)
|
|
138
|
+
enc = people.encrypt("ssn", "address")
|
|
139
|
+
dec = enc.decrypt()
|
|
140
|
+
|
|
141
|
+
# Encrypt one field inside a struct and leave the rest readable
|
|
142
|
+
enc = people.encrypt("address.zip")
|
|
143
|
+
|
|
144
|
+
# Text output for CSV / JSON sinks (base64)
|
|
145
|
+
people.encrypt("ssn", as_string=True).write.csv("/tmp/out")
|
|
146
|
+
|
|
147
|
+
# Don't fail the job on a wrong key or tampered cell: get NULL instead
|
|
148
|
+
enc.decrypt("ssn", key="wrong", on_error="null")
|
|
149
|
+
|
|
150
|
+
# Column-level API for select() / withColumn() when you know the type
|
|
151
|
+
enc = people.select("id", crypyspark.encrypt_column("ssn", "string").alias("ssn"))
|
|
152
|
+
dec = enc.select("id", crypyspark.decrypt_column("ssn", "string").alias("ssn"))
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
---
|
|
156
|
+
|
|
157
|
+
## 🧱 Databricks
|
|
158
|
+
|
|
159
|
+
### 1. Keep the key in a secret
|
|
160
|
+
|
|
161
|
+
```python
|
|
162
|
+
import crypyspark
|
|
163
|
+
|
|
164
|
+
crypyspark.set_key(crypyspark.secret_key("pii-scope", "customer-key"))
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
`secret_key` uses Databricks' SQL `secret()` function, so the key is resolved **inside the engine**. It never passes through Python and never shows up in `EXPLAIN` or the Spark UI.
|
|
168
|
+
|
|
169
|
+
> A key from `dbutils.secrets.get(...)` passed as a plain string also works. It gets derived into a constant in the query plan, though, so prefer `secret_key`.
|
|
170
|
+
|
|
171
|
+
### 2. Write encrypted tables with Unity Catalog governance tags
|
|
172
|
+
|
|
173
|
+
```python
|
|
174
|
+
from crypyspark import databricks as cdb
|
|
175
|
+
|
|
176
|
+
cdb.save_encrypted_table(
|
|
177
|
+
customers,
|
|
178
|
+
"main.crm.customers",
|
|
179
|
+
["ssn", "email", "address"],
|
|
180
|
+
extra_tags={"pii": "true", "owner": "data-platform"},
|
|
181
|
+
)
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
Each encrypted column gets [governance tags](https://docs.databricks.com/en/database-objects/tags.html):
|
|
185
|
+
|
|
186
|
+
| Tag | Value | Purpose |
|
|
187
|
+
|---|---|---|
|
|
188
|
+
| `crypyspark_encrypted` | `aes-256-gcm` | Find every encrypted column in your lakehouse, and drive tag-based (ABAC) policies |
|
|
189
|
+
| `crypyspark_type` | compact type tag, e.g. `r{"street":s,"zip":i}` | Lets readers decrypt without sampling any data |
|
|
190
|
+
| *your `extra_tags`* | anything | Classification, ownership, etc. |
|
|
191
|
+
|
|
192
|
+
They show up in Catalog Explorer and in `information_schema.column_tags`:
|
|
193
|
+
|
|
194
|
+
```sql
|
|
195
|
+
SELECT table_name, column_name, tag_value AS original_type
|
|
196
|
+
FROM main.information_schema.column_tags
|
|
197
|
+
WHERE tag_name = 'crypyspark_type';
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
### 3. Read it back decrypted
|
|
201
|
+
|
|
202
|
+
```python
|
|
203
|
+
customers = cdb.read_decrypted_table("main.crm.customers")
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
This finds the encrypted columns from the UC tags and takes their types from `crypyspark_type`, so nothing extra runs. Off Unity Catalog, it falls back to schema metadata and then to the type tag stored in the data.
|
|
207
|
+
|
|
208
|
+
### Other helpers
|
|
209
|
+
|
|
210
|
+
```python
|
|
211
|
+
cdb.tag_encrypted_columns("main.crm.customers") # tag an already-written table
|
|
212
|
+
cdb.encrypted_columns("main.crm.customers") # {"ssn": "s", "address": 'r{"street":s,"zip":i}', ...}
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
> Setting tags needs the `APPLY TAG` privilege on the table. Tags go on top-level columns. An encrypted nested field (`"address.zip"`) stays self-describing through its data.
|
|
216
|
+
|
|
217
|
+
### Compatibility
|
|
218
|
+
|
|
219
|
+
| Compute | Supported |
|
|
220
|
+
|---|---|
|
|
221
|
+
| Classic (single user / no isolation) | ✅ |
|
|
222
|
+
| Shared access mode (Unity Catalog) | ✅ |
|
|
223
|
+
| Serverless notebooks & jobs (Spark Connect) | ✅ |
|
|
224
|
+
| Databricks SQL warehouses | Data written by CryPySpark can be read; encrypt/decrypt are a Python API |
|
|
225
|
+
| Runtime | DBR 14.0+ (Spark 3.5+) |
|
|
226
|
+
|
|
227
|
+
---
|
|
228
|
+
|
|
229
|
+
## 🧬 Supported types
|
|
230
|
+
|
|
231
|
+
| Spark type | | Notes |
|
|
232
|
+
|---|:-:|---|
|
|
233
|
+
| `boolean`, `tinyint`, `smallint`, `int`, `bigint` | ✅ | |
|
|
234
|
+
| `float`, `double` | ✅ | NaN, ±Infinity and `-0.0` preserved |
|
|
235
|
+
| `decimal(p, s)` | ✅ | Full 38-digit precision, scale kept |
|
|
236
|
+
| `string`, `char`, `varchar` | ✅ | Any unicode, including control characters |
|
|
237
|
+
| `binary` | ✅ | Every byte value |
|
|
238
|
+
| `date` | ✅ | `0001-01-01` … `9999-12-31` |
|
|
239
|
+
| `timestamp` | ✅ | Microsecond-exact, independent of session time zone |
|
|
240
|
+
| `timestamp_ntz` | ✅ | Microsecond-exact |
|
|
241
|
+
| `interval day to second`, `interval year to month` | ✅ | ANSI intervals, all field ranges |
|
|
242
|
+
| `array<T>` | ✅ | Null elements preserved |
|
|
243
|
+
| `map<K, V>` | ✅ | **Any** key type (int, date, struct, ...), not just strings |
|
|
244
|
+
| `struct<...>` | ✅ | Any field names, including dots, quotes and commas |
|
|
245
|
+
| Nested combinations | ✅ | `array<map<string, struct<ts:timestamp, tags:array<map<bigint,date>>>>>` is in the test suite |
|
|
246
|
+
| `NULL` (at any level) | ✅ | Top-level NULLs are encrypted too, so whether a value is null isn't leaked |
|
|
247
|
+
| `variant`, `calendar interval` | ❌ | Raises a clear `TypeError` |
|
|
248
|
+
|
|
249
|
+
---
|
|
250
|
+
|
|
251
|
+
## 🔬 How it works
|
|
252
|
+
|
|
253
|
+
```mermaid
|
|
254
|
+
flowchart LR
|
|
255
|
+
A["any column<br/><code>struct<zip:int, ts:timestamp></code>"] --> B["JSON-safe rewrite<br/>(native expressions)"]
|
|
256
|
+
B --> C["envelope<br/><code>{"t":"r{"zip":i,"ts":T}", "v":{...}}</code>"]
|
|
257
|
+
C --> D["AES-256-GCM<br/>random IV per cell"]
|
|
258
|
+
D --> E["BINARY cell"]
|
|
259
|
+
E -. decrypt .-> F["read tag → rebuild exact type"]
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
1. **JSON-safe rewrite.** Types JSON would mangle are rewritten losslessly with native Spark functions:
|
|
263
|
+
|
|
264
|
+
| Type | Rewritten as |
|
|
265
|
+
|---|---|
|
|
266
|
+
| timestamps | epoch microseconds |
|
|
267
|
+
| dates | epoch days |
|
|
268
|
+
| binary | base64 |
|
|
269
|
+
| maps | arrays of `{k, v}` entries |
|
|
270
|
+
| `timestamp_ntz`, intervals | their exact string form |
|
|
271
|
+
|
|
272
|
+
Types JSON already handles losslessly are left alone.
|
|
273
|
+
2. **Typed envelope.** The value is wrapped with a compact type tag. Atomic types are one character (`i`, `s`, `T`…), and complex types are spelled out (`a<m<i,t>>`, `r{"zip":i}`).
|
|
274
|
+
3. **Encryption.** `aes_encrypt(..., 'GCM')` with a 32-byte key derived via SHA-256 and a fresh random IV for every cell. GCM authenticates the ciphertext, so any tampering is detected.
|
|
275
|
+
4. **Decryption.** The type is resolved in this order:
|
|
276
|
+
1. explicit `dtypes=`
|
|
277
|
+
2. schema metadata
|
|
278
|
+
3. Unity Catalog tags
|
|
279
|
+
4. the tag inside the data, read with a single `LIMIT 1` job
|
|
280
|
+
|
|
281
|
+
The value is then decrypted, parsed, and rebuilt into the original type.
|
|
282
|
+
|
|
283
|
+
---
|
|
284
|
+
|
|
285
|
+
## ⚡ Performance
|
|
286
|
+
|
|
287
|
+
Speed comes from these design choices:
|
|
288
|
+
|
|
289
|
+
- **No Python UDFs, ever.** Every step is a built-in Catalyst expression, fully code-generated and Photon-eligible. Rows never leave the JVM.
|
|
290
|
+
- **A single projection.** Encrypting or decrypting 50 columns adds **one** `select` to the plan, not 50 chained `withColumn`s.
|
|
291
|
+
- **Decrypt once per row.** The decrypted payload is bound to a lambda variable, so AES and JSON parsing run exactly once per cell no matter how many nested fields get rebuilt. This made struct decryption **~4× faster** in our benchmark.
|
|
292
|
+
- **Binary by default.** No base64 overhead unless you ask for `as_string=True`.
|
|
293
|
+
- **Compact tags.** An `int` column pays one byte of type metadata per cell.
|
|
294
|
+
- **No sampling when types are known.** With metadata or UC tags, decrypt plans without running any job.
|
|
295
|
+
|
|
296
|
+
Benchmark: 2,000,000 rows on a laptop (`local[*]`, cached input, `noop` sink):
|
|
297
|
+
|
|
298
|
+
| Operation | Time |
|
|
299
|
+
|---|---|
|
|
300
|
+
| Encrypt `string` column | ~2.0 s |
|
|
301
|
+
| Encrypt `struct<int, array<double>, timestamp>` | ~2.0 s |
|
|
302
|
+
| Decrypt `string` column | ~1.5 s |
|
|
303
|
+
| Decrypt `struct<int, array<double>, timestamp>` | ~1.7 s |
|
|
304
|
+
|
|
305
|
+
---
|
|
306
|
+
|
|
307
|
+
## 📚 API reference
|
|
308
|
+
|
|
309
|
+
### DataFrame methods (added on `import crypyspark`)
|
|
310
|
+
|
|
311
|
+
```python
|
|
312
|
+
df.encrypt(*columns, key=None, as_string=False) -> DataFrame
|
|
313
|
+
```
|
|
314
|
+
Encrypts each column in place: the column becomes `BINARY`, or `STRING` (base64) with `as_string=True`. Columns can be given as varargs or lists, and `"parent.child"` targets a struct field.
|
|
315
|
+
|
|
316
|
+
```python
|
|
317
|
+
df.decrypt(*columns, key=None, dtypes=None, on_error="raise") -> DataFrame
|
|
318
|
+
```
|
|
319
|
+
Restores original values and types. With no columns, it decrypts every column `encrypt` tagged. Use `dtypes={"col": DataType | "ddl" | "tag"}` to override type detection, and `on_error="null"` to get `NULL` for cells that fail to decrypt. Base64 string columns are handled automatically.
|
|
320
|
+
|
|
321
|
+
### Column functions
|
|
322
|
+
|
|
323
|
+
```python
|
|
324
|
+
crypyspark.encrypt_column(col, dtype, key=None, as_string=False) -> Column
|
|
325
|
+
crypyspark.decrypt_column(col, dtype, key=None, on_error="raise", as_string=False) -> Column
|
|
326
|
+
crypyspark.type_tag_column(col, key=None, as_string=False) -> Column # the tag inside each cell
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
### Keys & types
|
|
330
|
+
|
|
331
|
+
```python
|
|
332
|
+
crypyspark.set_key(key) # default for every call; None clears it
|
|
333
|
+
crypyspark.secret_key(scope, name) # Databricks secret, resolved in-engine
|
|
334
|
+
crypyspark.parse_type("array<int>") # DataType from DDL, type tag, or DataType
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
### `crypyspark.databricks`
|
|
338
|
+
|
|
339
|
+
```python
|
|
340
|
+
save_encrypted_table(df, table, columns, key=None, mode="overwrite", extra_tags=None) -> DataFrame
|
|
341
|
+
read_decrypted_table(table, key=None, columns=None, on_error="raise") -> DataFrame
|
|
342
|
+
tag_encrypted_columns(table, columns=None, extra_tags=None) -> list[str]
|
|
343
|
+
encrypted_columns(table) -> dict[str, str | None]
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
---
|
|
347
|
+
|
|
348
|
+
## 🛡️ Security notes
|
|
349
|
+
|
|
350
|
+
- **Cipher:** AES-256-GCM (authenticated encryption) via Spark's built-in `aes_encrypt`. A wrong key or modified ciphertext fails loudly, or gives `NULL` with `on_error="null"`.
|
|
351
|
+
- **Randomised:** every cell gets a fresh IV, so equal plaintexts produce different ciphertexts. You can't join or group on encrypted columns. Decrypt first.
|
|
352
|
+
- **Key derivation:** any key is passed through SHA-256 to get a 32-byte AES key. That's ideal for random secrets. If you use a human passphrase, make it long, because SHA-256 isn't a slow password hash.
|
|
353
|
+
- **Keys in plans:** keys passed as strings or bytes become literals in the Spark plan. Use `secret_key()` on Databricks to keep them out.
|
|
354
|
+
- **What's not hidden:** the approximate size of each value and whether a column is encrypted. Per-row type tags are inside the ciphertext. The `crypyspark_type` UC tag, if used, makes column types visible to anyone who can read table metadata.
|
|
355
|
+
|
|
356
|
+
---
|
|
357
|
+
|
|
358
|
+
## ❓ FAQ
|
|
359
|
+
|
|
360
|
+
<details>
|
|
361
|
+
<summary><b>Do I have to remember the column types to decrypt?</b></summary>
|
|
362
|
+
|
|
363
|
+
No. Every cell carries its own type tag. Delta preserves schema metadata, so `df.decrypt(key=...)` usually doesn't even need to touch the data to know the types.
|
|
364
|
+
</details>
|
|
365
|
+
|
|
366
|
+
<details>
|
|
367
|
+
<summary><b>Can I decrypt data that went through CSV, JSON, or another system?</b></summary>
|
|
368
|
+
|
|
369
|
+
Yes. Encrypt with `as_string=True` for text formats. On read, `decrypt` sees a string column, base64-decodes it, and recovers the type from the tag inside the data.
|
|
370
|
+
</details>
|
|
371
|
+
|
|
372
|
+
<details>
|
|
373
|
+
<summary><b>Does decrypting restore nullability flags too?</b></summary>
|
|
374
|
+
|
|
375
|
+
Values and data types are exact. Spark always marks decrypted fields as nullable, so a `NOT NULL` field comes back as nullable with the same values.
|
|
376
|
+
</details>
|
|
377
|
+
|
|
378
|
+
<details>
|
|
379
|
+
<summary><b>Can I rotate keys?</b></summary>
|
|
380
|
+
|
|
381
|
+
Yes: `df.decrypt(key=old).encrypt(cols, key=new)`. It's a single pass, and nothing touches Python.
|
|
382
|
+
</details>
|
|
383
|
+
|
|
384
|
+
<details>
|
|
385
|
+
<summary><b>Will it work in Databricks SQL?</b></summary>
|
|
386
|
+
|
|
387
|
+
The encrypt/decrypt API is Python. Tables written by CryPySpark are ordinary Delta tables, and their UC tags can be queried from SQL.
|
|
388
|
+
</details>
|
|
389
|
+
|
|
390
|
+
---
|
|
391
|
+
|
|
392
|
+
## 🛠️ Development
|
|
393
|
+
|
|
394
|
+
```bash
|
|
395
|
+
git clone https://github.com/seanpavlak/CryPySpark.git
|
|
396
|
+
cd CryPySpark
|
|
397
|
+
pip install -e ".[test]"
|
|
398
|
+
pytest # needs Java 17+ for local Spark
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
The test suite round-trips a schema containing every supported type, including edge values and deep nesting. It also covers metadata loss through CSV, nested-field encryption, wrong keys, Column keys, and type-tag parsing.
|
|
402
|
+
|
|
403
|
+
---
|
|
404
|
+
|
|
405
|
+
## 📄 License
|
|
406
|
+
|
|
407
|
+
[MIT](https://github.com/seanpavlak/CryPySpark/blob/main/LICENSE) © 2025 Sean Pavlak
|