krishto 0.2__tar.gz → 1.0.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.
- {krishto-0.2 → krishto-1.0.0}/LICENCE +1 -1
- krishto-1.0.0/PKG-INFO +162 -0
- krishto-1.0.0/README.md +143 -0
- krishto-1.0.0/krishto/__init__.py +35 -0
- krishto-1.0.0/krishto/backends.py +171 -0
- krishto-1.0.0/krishto/cli.py +72 -0
- krishto-1.0.0/krishto/codec.py +22 -0
- krishto-1.0.0/krishto/core.py +68 -0
- krishto-1.0.0/krishto/exceptions.py +14 -0
- krishto-1.0.0/krishto/kdf.py +18 -0
- krishto-1.0.0/krishto/py.typed +0 -0
- krishto-1.0.0/krishto/vault.py +46 -0
- krishto-1.0.0/krishto.egg-info/PKG-INFO +162 -0
- krishto-1.0.0/krishto.egg-info/SOURCES.txt +21 -0
- krishto-1.0.0/krishto.egg-info/entry_points.txt +2 -0
- krishto-1.0.0/krishto.egg-info/requires.txt +7 -0
- krishto-1.0.0/pyproject.toml +26 -0
- krishto-1.0.0/setup.py +32 -0
- krishto-1.0.0/tests/test_krishto.py +72 -0
- krishto-0.2/PKG-INFO +0 -51
- krishto-0.2/README.md +0 -33
- krishto-0.2/krishto/__init__.py +0 -3
- krishto-0.2/krishto.egg-info/PKG-INFO +0 -51
- krishto-0.2/krishto.egg-info/SOURCES.txt +0 -8
- krishto-0.2/setup.py +0 -33
- {krishto-0.2 → krishto-1.0.0}/krishto.egg-info/dependency_links.txt +0 -0
- {krishto-0.2 → krishto-1.0.0}/krishto.egg-info/top_level.txt +0 -0
- {krishto-0.2 → krishto-1.0.0}/setup.cfg +0 -0
krishto-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: krishto
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Modern, versioned, authenticated encryption for Python
|
|
5
|
+
Author: K.A. Ishan Oshada
|
|
6
|
+
Author-email: "K.A. Ishan Oshada" <ic31908@gmail.com>
|
|
7
|
+
License: MIT
|
|
8
|
+
Requires-Python: >=3.9
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENCE
|
|
11
|
+
Provides-Extra: fast
|
|
12
|
+
Requires-Dist: cryptography>=42; extra == "fast"
|
|
13
|
+
Provides-Extra: dev
|
|
14
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
15
|
+
Requires-Dist: cryptography>=42; extra == "dev"
|
|
16
|
+
Dynamic: author
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
Dynamic: requires-python
|
|
19
|
+
|
|
20
|
+
# krishto 1.0
|
|
21
|
+
|
|
22
|
+
Modern, versioned, authenticated encryption for Python.
|
|
23
|
+
|
|
24
|
+
Krishto 1.0 replaces the original 0.2 implementation with a clean cryptographic API,
|
|
25
|
+
backward-compatible names, secure defaults, an encrypted vault, file helpers, and a CLI.
|
|
26
|
+
It does not preserve or reproduce the 0.2 cipher format.
|
|
27
|
+
|
|
28
|
+
## Highlights
|
|
29
|
+
|
|
30
|
+
- AES-256-GCM and ChaCha20-Poly1305 through `cryptography`
|
|
31
|
+
- Zero-dependency HMAC-SHA256 Encrypt-then-MAC stdlib backend
|
|
32
|
+
- scrypt key derivation
|
|
33
|
+
- Versioned `KRSH` envelopes
|
|
34
|
+
- Authenticated associated data (AAD) for binding ciphertext to identity or context
|
|
35
|
+
- Atomic encrypted vault storage
|
|
36
|
+
- File encryption with `.krs` output
|
|
37
|
+
- Legacy 0.2 method names
|
|
38
|
+
- Type annotations and PEP 561 marker
|
|
39
|
+
- CLI for text, files, and vaults
|
|
40
|
+
|
|
41
|
+
## Install
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
pip install krishto
|
|
45
|
+
pip install "krishto[fast]"
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
The stdlib backend works without dependencies. `fast` enables AES-GCM and ChaCha20-Poly1305.
|
|
49
|
+
|
|
50
|
+
## Python API
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from krishto import Krishto
|
|
54
|
+
|
|
55
|
+
k = Krishto("use-a-strong-unique-password")
|
|
56
|
+
token = k.encrypt("hello", aad="user:42")
|
|
57
|
+
assert k.decrypt(token, aad="user:42") == "hello"
|
|
58
|
+
|
|
59
|
+
k.encrypt_file("secrets.env")
|
|
60
|
+
k.decrypt_file("secrets.env.krs")
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Encryption creates a fresh random salt and nonce each time, so encrypting identical
|
|
64
|
+
text twice produces different tokens. Keep the password safe: Krishto cannot recover
|
|
65
|
+
data if you lose it.
|
|
66
|
+
|
|
67
|
+
Choose an explicit backend:
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
Krishto("password", backend="stdlib")
|
|
71
|
+
Krishto("password", backend="aesgcm")
|
|
72
|
+
Krishto("password", backend="chacha20")
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Usage Examples
|
|
76
|
+
|
|
77
|
+
The [`examples/`](./examples/) folder contains five complete scripts covering text,
|
|
78
|
+
files, vault storage, encrypted Python code, and the legacy API. Install Krishto and
|
|
79
|
+
run an example from the project root:
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
python -m pip install -e ".[fast]"
|
|
83
|
+
python examples/encrypt_text.py
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Each script prompts for a password instead of storing one in source code. You can
|
|
87
|
+
also set `KRISHTO_PASSWORD` in your environment for local automation; avoid putting
|
|
88
|
+
passwords directly in shell history or committed files.
|
|
89
|
+
|
|
90
|
+
| Script | Demonstrates |
|
|
91
|
+
|---|---|
|
|
92
|
+
| [`encrypt_text.py`](./examples/encrypt_text.py) | Text encryption, decryption, and AAD context binding |
|
|
93
|
+
| [`encrypt_file.py`](./examples/encrypt_file.py) | File encryption and decryption |
|
|
94
|
+
| [`vault_usage.py`](./examples/vault_usage.py) | Encrypted JSON-like key-value storage |
|
|
95
|
+
| [`encrypted_module.py`](./examples/encrypted_module.py) | Compile and load a trusted encrypted Python module |
|
|
96
|
+
| [`legacy_api.py`](./examples/legacy_api.py) | Compatibility with the 0.2 API names |
|
|
97
|
+
|
|
98
|
+
For example, encrypt a file with:
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
python examples/encrypt_file.py path/to/private.txt
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Encrypted Vault
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
from krishto import Vault
|
|
108
|
+
|
|
109
|
+
vault = Vault("secrets.krs", "a strong password")
|
|
110
|
+
vault.set("api_key", "abc123")
|
|
111
|
+
vault.set("config", {"region": "eu"})
|
|
112
|
+
|
|
113
|
+
assert Vault("secrets.krs", "a strong password").get("api_key") == "abc123"
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Vault writes are atomic: data is written to a temporary file and then replaced.
|
|
117
|
+
|
|
118
|
+
## CLI
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
krishto encrypt "hello"
|
|
122
|
+
krishto encrypt --file secrets.env --output secrets.env.krs
|
|
123
|
+
krishto decrypt --file secrets.env.krs --output secrets.env
|
|
124
|
+
krishto vault secrets.krs set api_key abc123
|
|
125
|
+
krishto vault secrets.krs get api_key
|
|
126
|
+
krishto vault secrets.krs list
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Passwords can be supplied with `--password`, but interactive prompting is safer for shells and logs.
|
|
130
|
+
|
|
131
|
+
## Compatibility
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
from krishto import Encryption_methods
|
|
135
|
+
|
|
136
|
+
k = Encryption_methods("password", backend="stdlib")
|
|
137
|
+
token = k.E2D_1("legacy text")
|
|
138
|
+
assert k.D2E_2(token) == "legacy text"
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
Also retained: `crypto`, `crypto_V2`, `crypto_V3`, and `E2D_1`/`D2E_2`.
|
|
142
|
+
|
|
143
|
+
## Encrypted Python Modules
|
|
144
|
+
|
|
145
|
+
```python
|
|
146
|
+
from krishto import codec
|
|
147
|
+
|
|
148
|
+
blob = codec.compile_encrypted("def greet(name): return f'Hello, {name}'", "password")
|
|
149
|
+
namespace = codec.load_encrypted(blob, "password")
|
|
150
|
+
print(namespace["greet"]("world"))
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
Encryption is not sandboxing. `load_encrypted` executes Python code and must only receive trusted,
|
|
154
|
+
authenticated blobs.
|
|
155
|
+
|
|
156
|
+
## Security Notes
|
|
157
|
+
|
|
158
|
+
- Use a strong, unique password or integrate Krishto with an application-specific key manager.
|
|
159
|
+
- Use AAD for values that identify the data, such as a user ID, tenant ID, or filename.
|
|
160
|
+
- Treat authentication failures as untrusted or corrupt input.
|
|
161
|
+
- The stdlib backend uses HMAC-SHA256 for both keystream generation and the final MAC; AES-GCM or
|
|
162
|
+
ChaCha20-Poly1305 are preferred when `cryptography` is available.
|
krishto-1.0.0/README.md
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
# krishto 1.0
|
|
2
|
+
|
|
3
|
+
Modern, versioned, authenticated encryption for Python.
|
|
4
|
+
|
|
5
|
+
Krishto 1.0 replaces the original 0.2 implementation with a clean cryptographic API,
|
|
6
|
+
backward-compatible names, secure defaults, an encrypted vault, file helpers, and a CLI.
|
|
7
|
+
It does not preserve or reproduce the 0.2 cipher format.
|
|
8
|
+
|
|
9
|
+
## Highlights
|
|
10
|
+
|
|
11
|
+
- AES-256-GCM and ChaCha20-Poly1305 through `cryptography`
|
|
12
|
+
- Zero-dependency HMAC-SHA256 Encrypt-then-MAC stdlib backend
|
|
13
|
+
- scrypt key derivation
|
|
14
|
+
- Versioned `KRSH` envelopes
|
|
15
|
+
- Authenticated associated data (AAD) for binding ciphertext to identity or context
|
|
16
|
+
- Atomic encrypted vault storage
|
|
17
|
+
- File encryption with `.krs` output
|
|
18
|
+
- Legacy 0.2 method names
|
|
19
|
+
- Type annotations and PEP 561 marker
|
|
20
|
+
- CLI for text, files, and vaults
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pip install krishto
|
|
26
|
+
pip install "krishto[fast]"
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
The stdlib backend works without dependencies. `fast` enables AES-GCM and ChaCha20-Poly1305.
|
|
30
|
+
|
|
31
|
+
## Python API
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from krishto import Krishto
|
|
35
|
+
|
|
36
|
+
k = Krishto("use-a-strong-unique-password")
|
|
37
|
+
token = k.encrypt("hello", aad="user:42")
|
|
38
|
+
assert k.decrypt(token, aad="user:42") == "hello"
|
|
39
|
+
|
|
40
|
+
k.encrypt_file("secrets.env")
|
|
41
|
+
k.decrypt_file("secrets.env.krs")
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Encryption creates a fresh random salt and nonce each time, so encrypting identical
|
|
45
|
+
text twice produces different tokens. Keep the password safe: Krishto cannot recover
|
|
46
|
+
data if you lose it.
|
|
47
|
+
|
|
48
|
+
Choose an explicit backend:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
Krishto("password", backend="stdlib")
|
|
52
|
+
Krishto("password", backend="aesgcm")
|
|
53
|
+
Krishto("password", backend="chacha20")
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Usage Examples
|
|
57
|
+
|
|
58
|
+
The [`examples/`](./examples/) folder contains five complete scripts covering text,
|
|
59
|
+
files, vault storage, encrypted Python code, and the legacy API. Install Krishto and
|
|
60
|
+
run an example from the project root:
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
python -m pip install -e ".[fast]"
|
|
64
|
+
python examples/encrypt_text.py
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Each script prompts for a password instead of storing one in source code. You can
|
|
68
|
+
also set `KRISHTO_PASSWORD` in your environment for local automation; avoid putting
|
|
69
|
+
passwords directly in shell history or committed files.
|
|
70
|
+
|
|
71
|
+
| Script | Demonstrates |
|
|
72
|
+
|---|---|
|
|
73
|
+
| [`encrypt_text.py`](./examples/encrypt_text.py) | Text encryption, decryption, and AAD context binding |
|
|
74
|
+
| [`encrypt_file.py`](./examples/encrypt_file.py) | File encryption and decryption |
|
|
75
|
+
| [`vault_usage.py`](./examples/vault_usage.py) | Encrypted JSON-like key-value storage |
|
|
76
|
+
| [`encrypted_module.py`](./examples/encrypted_module.py) | Compile and load a trusted encrypted Python module |
|
|
77
|
+
| [`legacy_api.py`](./examples/legacy_api.py) | Compatibility with the 0.2 API names |
|
|
78
|
+
|
|
79
|
+
For example, encrypt a file with:
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
python examples/encrypt_file.py path/to/private.txt
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Encrypted Vault
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
from krishto import Vault
|
|
89
|
+
|
|
90
|
+
vault = Vault("secrets.krs", "a strong password")
|
|
91
|
+
vault.set("api_key", "abc123")
|
|
92
|
+
vault.set("config", {"region": "eu"})
|
|
93
|
+
|
|
94
|
+
assert Vault("secrets.krs", "a strong password").get("api_key") == "abc123"
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Vault writes are atomic: data is written to a temporary file and then replaced.
|
|
98
|
+
|
|
99
|
+
## CLI
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
krishto encrypt "hello"
|
|
103
|
+
krishto encrypt --file secrets.env --output secrets.env.krs
|
|
104
|
+
krishto decrypt --file secrets.env.krs --output secrets.env
|
|
105
|
+
krishto vault secrets.krs set api_key abc123
|
|
106
|
+
krishto vault secrets.krs get api_key
|
|
107
|
+
krishto vault secrets.krs list
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Passwords can be supplied with `--password`, but interactive prompting is safer for shells and logs.
|
|
111
|
+
|
|
112
|
+
## Compatibility
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
from krishto import Encryption_methods
|
|
116
|
+
|
|
117
|
+
k = Encryption_methods("password", backend="stdlib")
|
|
118
|
+
token = k.E2D_1("legacy text")
|
|
119
|
+
assert k.D2E_2(token) == "legacy text"
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Also retained: `crypto`, `crypto_V2`, `crypto_V3`, and `E2D_1`/`D2E_2`.
|
|
123
|
+
|
|
124
|
+
## Encrypted Python Modules
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
from krishto import codec
|
|
128
|
+
|
|
129
|
+
blob = codec.compile_encrypted("def greet(name): return f'Hello, {name}'", "password")
|
|
130
|
+
namespace = codec.load_encrypted(blob, "password")
|
|
131
|
+
print(namespace["greet"]("world"))
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Encryption is not sandboxing. `load_encrypted` executes Python code and must only receive trusted,
|
|
135
|
+
authenticated blobs.
|
|
136
|
+
|
|
137
|
+
## Security Notes
|
|
138
|
+
|
|
139
|
+
- Use a strong, unique password or integrate Krishto with an application-specific key manager.
|
|
140
|
+
- Use AAD for values that identify the data, such as a user ID, tenant ID, or filename.
|
|
141
|
+
- Treat authentication failures as untrusted or corrupt input.
|
|
142
|
+
- The stdlib backend uses HMAC-SHA256 for both keystream generation and the final MAC; AES-GCM or
|
|
143
|
+
ChaCha20-Poly1305 are preferred when `cryptography` is available.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Krishto: modern, versioned, authenticated encryption for Python."""
|
|
2
|
+
|
|
3
|
+
from .core import Krishto
|
|
4
|
+
from .exceptions import (
|
|
5
|
+
DecryptionError,
|
|
6
|
+
InvalidKeyError,
|
|
7
|
+
KrishtoError,
|
|
8
|
+
MissingDependencyError,
|
|
9
|
+
)
|
|
10
|
+
from .vault import Vault
|
|
11
|
+
from .codec import compile_encrypted, load_encrypted
|
|
12
|
+
|
|
13
|
+
__version__ = "1.0.0"
|
|
14
|
+
|
|
15
|
+
# Compatibility names retained for the 0.2 API.
|
|
16
|
+
Encryption_methods = Krishto
|
|
17
|
+
crypto = Krishto
|
|
18
|
+
crypto_V2 = Krishto
|
|
19
|
+
crypto_V3 = Krishto
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"Krishto",
|
|
23
|
+
"Vault",
|
|
24
|
+
"compile_encrypted",
|
|
25
|
+
"load_encrypted",
|
|
26
|
+
"DecryptionError",
|
|
27
|
+
"InvalidKeyError",
|
|
28
|
+
"KrishtoError",
|
|
29
|
+
"MissingDependencyError",
|
|
30
|
+
"Encryption_methods",
|
|
31
|
+
"crypto",
|
|
32
|
+
"crypto_V2",
|
|
33
|
+
"crypto_V3",
|
|
34
|
+
"__version__",
|
|
35
|
+
]
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import hmac
|
|
3
|
+
import secrets
|
|
4
|
+
from typing import Literal
|
|
5
|
+
|
|
6
|
+
from .exceptions import DecryptionError, MissingDependencyError
|
|
7
|
+
from .kdf import derive_key
|
|
8
|
+
|
|
9
|
+
MAGIC = b"KRSH"
|
|
10
|
+
FORMAT_VERSION = 1
|
|
11
|
+
STDLIB = 1
|
|
12
|
+
AES_GCM = 2
|
|
13
|
+
CHACHA20_POLY1305 = 3
|
|
14
|
+
SALT_SIZE = 16
|
|
15
|
+
|
|
16
|
+
BackendName = Literal["auto", "stdlib", "aesgcm", "chacha20"]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _keystream(key: bytes, nonce: bytes, length: int) -> bytes:
|
|
20
|
+
output = bytearray()
|
|
21
|
+
counter = 0
|
|
22
|
+
while len(output) < length:
|
|
23
|
+
output.extend(hmac.new(
|
|
24
|
+
key,
|
|
25
|
+
nonce + counter.to_bytes(8, "big"),
|
|
26
|
+
hashlib.sha256,
|
|
27
|
+
).digest())
|
|
28
|
+
counter += 1
|
|
29
|
+
return bytes(output[:length])
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _stdlib_encrypt(plaintext: bytes, password: str, aad: bytes) -> bytes:
|
|
33
|
+
salt = secrets.token_bytes(SALT_SIZE)
|
|
34
|
+
nonce = secrets.token_bytes(16)
|
|
35
|
+
master = derive_key(password, salt, 64)
|
|
36
|
+
enc_key, mac_key = master[:32], master[32:]
|
|
37
|
+
ciphertext = bytes(a ^ b for a, b in zip(plaintext, _keystream(enc_key, nonce, len(plaintext))))
|
|
38
|
+
header = MAGIC + bytes([FORMAT_VERSION, STDLIB]) + salt + nonce + len(aad).to_bytes(4, "big") + aad
|
|
39
|
+
tag = hmac.new(mac_key, header + ciphertext, hashlib.sha256).digest()
|
|
40
|
+
return header + ciphertext + tag
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _stdlib_decrypt(blob: bytes, password: str, aad: bytes) -> bytes:
|
|
44
|
+
minimum = 4 + 1 + 1 + 16 + 16 + 4 + 32
|
|
45
|
+
if len(blob) < minimum:
|
|
46
|
+
raise DecryptionError("Blob is truncated")
|
|
47
|
+
pos = 4
|
|
48
|
+
version = blob[pos]
|
|
49
|
+
pos += 1
|
|
50
|
+
algorithm = blob[pos]
|
|
51
|
+
pos += 1
|
|
52
|
+
if version != FORMAT_VERSION:
|
|
53
|
+
raise DecryptionError(f"Unsupported Krishto format version: {version}")
|
|
54
|
+
if algorithm != STDLIB:
|
|
55
|
+
raise DecryptionError("This blob does not use the stdlib backend")
|
|
56
|
+
salt = blob[pos:pos + 16]
|
|
57
|
+
pos += 16
|
|
58
|
+
nonce = blob[pos:pos + 16]
|
|
59
|
+
pos += 16
|
|
60
|
+
aad_size = int.from_bytes(blob[pos:pos + 4], "big")
|
|
61
|
+
pos += 4
|
|
62
|
+
if aad_size > len(blob) - pos - 32:
|
|
63
|
+
raise DecryptionError("AAD length is invalid")
|
|
64
|
+
embedded_aad = blob[pos:pos + aad_size]
|
|
65
|
+
pos += aad_size
|
|
66
|
+
if not hmac.compare_digest(embedded_aad, aad):
|
|
67
|
+
raise DecryptionError("AAD mismatch")
|
|
68
|
+
ciphertext = blob[pos:-32]
|
|
69
|
+
tag = blob[-32:]
|
|
70
|
+
master = derive_key(password, salt, 64)
|
|
71
|
+
enc_key, mac_key = master[:32], master[32:]
|
|
72
|
+
expected = hmac.new(mac_key, blob[:pos] + ciphertext, hashlib.sha256).digest()
|
|
73
|
+
if not hmac.compare_digest(tag, expected):
|
|
74
|
+
raise DecryptionError("Authentication failed: wrong password or tampered data")
|
|
75
|
+
return bytes(a ^ b for a, b in zip(ciphertext, _keystream(enc_key, nonce, len(ciphertext))))
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _load_crypto_classes():
|
|
79
|
+
try:
|
|
80
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM, ChaCha20Poly1305
|
|
81
|
+
return AESGCM, ChaCha20Poly1305
|
|
82
|
+
except ImportError as exc:
|
|
83
|
+
raise MissingDependencyError(
|
|
84
|
+
"Cryptography backend unavailable. Install 'krishto[fast]' or use backend='stdlib'."
|
|
85
|
+
) from exc
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _crypto_encrypt(plaintext: bytes, password: str, aad: bytes, algorithm: int) -> bytes:
|
|
89
|
+
AESGCM, ChaCha20Poly1305 = _load_crypto_classes()
|
|
90
|
+
salt = secrets.token_bytes(SALT_SIZE)
|
|
91
|
+
nonce = secrets.token_bytes(12)
|
|
92
|
+
key = derive_key(password, salt, 32)
|
|
93
|
+
header = MAGIC + bytes([FORMAT_VERSION, algorithm]) + salt + nonce + len(aad).to_bytes(4, "big") + aad
|
|
94
|
+
cipher = AESGCM(key) if algorithm == AES_GCM else ChaCha20Poly1305(key)
|
|
95
|
+
return header + cipher.encrypt(nonce, plaintext, header)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _crypto_decrypt(blob: bytes, password: str, aad: bytes) -> bytes:
|
|
99
|
+
AESGCM, ChaCha20Poly1305 = _load_crypto_classes()
|
|
100
|
+
if len(blob) < 4 + 1 + 1 + 16 + 12 + 4:
|
|
101
|
+
raise DecryptionError("Blob is truncated")
|
|
102
|
+
pos = 4
|
|
103
|
+
version = blob[pos]
|
|
104
|
+
pos += 1
|
|
105
|
+
algorithm = blob[pos]
|
|
106
|
+
pos += 1
|
|
107
|
+
if version != FORMAT_VERSION:
|
|
108
|
+
raise DecryptionError(f"Unsupported Krishto format version: {version}")
|
|
109
|
+
if algorithm not in (AES_GCM, CHACHA20_POLY1305):
|
|
110
|
+
raise DecryptionError(f"Unsupported algorithm: {algorithm}")
|
|
111
|
+
salt = blob[pos:pos + 16]
|
|
112
|
+
pos += 16
|
|
113
|
+
nonce = blob[pos:pos + 12]
|
|
114
|
+
pos += 12
|
|
115
|
+
aad_size = int.from_bytes(blob[pos:pos + 4], "big")
|
|
116
|
+
pos += 4
|
|
117
|
+
if aad_size > len(blob) - pos:
|
|
118
|
+
raise DecryptionError("AAD length is invalid")
|
|
119
|
+
embedded_aad = blob[pos:pos + aad_size]
|
|
120
|
+
pos += aad_size
|
|
121
|
+
if not hmac.compare_digest(embedded_aad, aad):
|
|
122
|
+
raise DecryptionError("AAD mismatch")
|
|
123
|
+
ciphertext = blob[pos:]
|
|
124
|
+
key = derive_key(password, salt, 32)
|
|
125
|
+
cipher = AESGCM(key) if algorithm == AES_GCM else ChaCha20Poly1305(key)
|
|
126
|
+
try:
|
|
127
|
+
return cipher.decrypt(nonce, ciphertext, blob[:pos])
|
|
128
|
+
except Exception as exc:
|
|
129
|
+
raise DecryptionError("Authentication failed: wrong password or tampered data") from exc
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def crypto_available() -> bool:
|
|
133
|
+
try:
|
|
134
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM # noqa: F401
|
|
135
|
+
return True
|
|
136
|
+
except ImportError:
|
|
137
|
+
return False
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def encrypt_bytes(
|
|
141
|
+
plaintext: bytes,
|
|
142
|
+
password: str,
|
|
143
|
+
aad: bytes = b"",
|
|
144
|
+
backend: BackendName = "auto",
|
|
145
|
+
) -> bytes:
|
|
146
|
+
if backend == "stdlib":
|
|
147
|
+
return _stdlib_encrypt(plaintext, password, aad)
|
|
148
|
+
if backend in ("aesgcm", "chacha20"):
|
|
149
|
+
algorithm = AES_GCM if backend == "aesgcm" else CHACHA20_POLY1305
|
|
150
|
+
return _crypto_encrypt(plaintext, password, aad, algorithm)
|
|
151
|
+
if backend == "auto":
|
|
152
|
+
if crypto_available():
|
|
153
|
+
return _crypto_encrypt(plaintext, password, aad, AES_GCM)
|
|
154
|
+
return _stdlib_encrypt(plaintext, password, aad)
|
|
155
|
+
raise ValueError(f"Unknown backend: {backend!r}")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def decrypt_bytes(
|
|
159
|
+
blob: bytes,
|
|
160
|
+
password: str,
|
|
161
|
+
aad: bytes = b"",
|
|
162
|
+
backend: BackendName = "auto",
|
|
163
|
+
) -> bytes:
|
|
164
|
+
if len(blob) < 6 or blob[:4] != MAGIC:
|
|
165
|
+
raise DecryptionError("Not a Krishto envelope")
|
|
166
|
+
algorithm = blob[5]
|
|
167
|
+
if algorithm == STDLIB:
|
|
168
|
+
return _stdlib_decrypt(blob, password, aad)
|
|
169
|
+
if algorithm in (AES_GCM, CHACHA20_POLY1305):
|
|
170
|
+
return _crypto_decrypt(blob, password, aad)
|
|
171
|
+
raise DecryptionError(f"Unsupported Krishto algorithm: {algorithm}")
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import getpass
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
from .core import Krishto
|
|
6
|
+
from .exceptions import KrishtoError
|
|
7
|
+
from .vault import Vault
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _password(args: argparse.Namespace) -> str:
|
|
11
|
+
if args.password:
|
|
12
|
+
return args.password
|
|
13
|
+
return getpass.getpass("Password: ")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def main(argv=None) -> int:
|
|
17
|
+
parser = argparse.ArgumentParser(prog="krishto", description="Modern authenticated encryption")
|
|
18
|
+
parser.add_argument("--password", help="Password (prompted when omitted)")
|
|
19
|
+
parser.add_argument("--backend", choices=["auto", "stdlib", "aesgcm", "chacha20"], default="auto")
|
|
20
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
21
|
+
|
|
22
|
+
encrypt = sub.add_parser("encrypt")
|
|
23
|
+
encrypt.add_argument("input", nargs="?")
|
|
24
|
+
encrypt.add_argument("--file")
|
|
25
|
+
encrypt.add_argument("--output")
|
|
26
|
+
encrypt.add_argument("--aad", default="")
|
|
27
|
+
|
|
28
|
+
decrypt = sub.add_parser("decrypt")
|
|
29
|
+
decrypt.add_argument("input", nargs="?")
|
|
30
|
+
decrypt.add_argument("--file")
|
|
31
|
+
decrypt.add_argument("--output")
|
|
32
|
+
decrypt.add_argument("--aad", default="")
|
|
33
|
+
|
|
34
|
+
vault = sub.add_parser("vault")
|
|
35
|
+
vault.add_argument("path")
|
|
36
|
+
vault.add_argument("action", choices=["set", "get", "list", "delete"])
|
|
37
|
+
vault.add_argument("key", nargs="?")
|
|
38
|
+
vault.add_argument("value", nargs="?")
|
|
39
|
+
|
|
40
|
+
args = parser.parse_args(argv)
|
|
41
|
+
password = _password(args)
|
|
42
|
+
try:
|
|
43
|
+
k = Krishto(password, backend=args.backend)
|
|
44
|
+
if args.command == "encrypt":
|
|
45
|
+
if args.file:
|
|
46
|
+
print(k.encrypt_file(args.file, args.output))
|
|
47
|
+
else:
|
|
48
|
+
print(k.encrypt(args.input or "", aad=args.aad))
|
|
49
|
+
elif args.command == "decrypt":
|
|
50
|
+
if args.file:
|
|
51
|
+
print(k.decrypt_file(args.file, args.output))
|
|
52
|
+
else:
|
|
53
|
+
print(k.decrypt(args.input or "", aad=args.aad))
|
|
54
|
+
elif args.command == "vault":
|
|
55
|
+
v = Vault(args.path, password, backend=args.backend)
|
|
56
|
+
if args.action == "set" and args.key is not None:
|
|
57
|
+
v.set(args.key, args.value)
|
|
58
|
+
print(f"set {args.key}")
|
|
59
|
+
elif args.action == "get" and args.key:
|
|
60
|
+
print(v.get(args.key))
|
|
61
|
+
elif args.action == "delete" and args.key:
|
|
62
|
+
print("deleted" if v.delete(args.key) else "not found")
|
|
63
|
+
else:
|
|
64
|
+
print("\n".join(v.keys()))
|
|
65
|
+
return 0
|
|
66
|
+
except (KrishtoError, ValueError, OSError) as exc:
|
|
67
|
+
print(f"krishto: {exc}", file=sys.stderr)
|
|
68
|
+
return 1
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
if __name__ == "__main__":
|
|
72
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import marshal
|
|
2
|
+
from typing import Optional
|
|
3
|
+
|
|
4
|
+
from .core import Krishto
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def compile_encrypted(source: str, password: str, filename: str = "<encrypted>", backend: str = "auto") -> bytes:
|
|
8
|
+
code = compile(source, filename, "exec")
|
|
9
|
+
return Krishto(password, backend=backend).encrypt_bytes(marshal.dumps(code))
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def load_encrypted(
|
|
13
|
+
blob: bytes,
|
|
14
|
+
password: str,
|
|
15
|
+
namespace: Optional[dict] = None,
|
|
16
|
+
backend: str = "auto",
|
|
17
|
+
) -> dict:
|
|
18
|
+
marshalled = Krishto(password, backend=backend).decrypt_bytes(blob)
|
|
19
|
+
code = marshal.loads(marshalled)
|
|
20
|
+
namespace = {} if namespace is None else namespace
|
|
21
|
+
exec(code, namespace)
|
|
22
|
+
return namespace
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Optional, Union
|
|
4
|
+
|
|
5
|
+
from . import backends
|
|
6
|
+
from .exceptions import InvalidKeyError
|
|
7
|
+
|
|
8
|
+
PathLike = Union[str, Path]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Krishto:
|
|
12
|
+
def __init__(self, password: Optional[str] = None, backend: str = "auto"):
|
|
13
|
+
if backend not in ("auto", "stdlib", "aesgcm", "chacha20", "cryptography"):
|
|
14
|
+
raise ValueError(f"Unknown backend: {backend!r}")
|
|
15
|
+
self._password = password
|
|
16
|
+
self.backend = "aesgcm" if backend == "cryptography" else backend
|
|
17
|
+
|
|
18
|
+
def _password_or(self, password: Optional[str]) -> str:
|
|
19
|
+
value = password if password is not None else self._password
|
|
20
|
+
if not value:
|
|
21
|
+
raise InvalidKeyError("No password supplied")
|
|
22
|
+
return value
|
|
23
|
+
|
|
24
|
+
def encrypt(self, text: str, password: Optional[str] = None, aad: str = "") -> str:
|
|
25
|
+
blob = self.encrypt_bytes(
|
|
26
|
+
text.encode("utf-8"),
|
|
27
|
+
password=password,
|
|
28
|
+
aad=aad.encode("utf-8"),
|
|
29
|
+
)
|
|
30
|
+
return base64.urlsafe_b64encode(blob).decode("ascii")
|
|
31
|
+
|
|
32
|
+
def decrypt(self, token: str, password: Optional[str] = None, aad: str = "") -> str:
|
|
33
|
+
try:
|
|
34
|
+
blob = base64.urlsafe_b64decode(token.encode("ascii"))
|
|
35
|
+
except Exception as exc:
|
|
36
|
+
raise InvalidKeyError("Token is not valid base64url") from exc
|
|
37
|
+
return self.decrypt_bytes(
|
|
38
|
+
blob,
|
|
39
|
+
password=password,
|
|
40
|
+
aad=aad.encode("utf-8"),
|
|
41
|
+
).decode("utf-8")
|
|
42
|
+
|
|
43
|
+
def encrypt_bytes(self, data: bytes, password: Optional[str] = None, aad: bytes = b"") -> bytes:
|
|
44
|
+
return backends.encrypt_bytes(data, self._password_or(password), aad, self.backend)
|
|
45
|
+
|
|
46
|
+
def decrypt_bytes(self, data: bytes, password: Optional[str] = None, aad: bytes = b"") -> bytes:
|
|
47
|
+
return backends.decrypt_bytes(data, self._password_or(password), aad, self.backend)
|
|
48
|
+
|
|
49
|
+
def encrypt_file(self, src: PathLike, dst: Optional[PathLike] = None, password: Optional[str] = None) -> Path:
|
|
50
|
+
src = Path(src)
|
|
51
|
+
dst = Path(dst) if dst is not None else src.with_name(src.name + ".krs")
|
|
52
|
+
dst.write_bytes(self.encrypt_bytes(src.read_bytes(), password=password))
|
|
53
|
+
return dst
|
|
54
|
+
|
|
55
|
+
def decrypt_file(self, src: PathLike, dst: Optional[PathLike] = None, password: Optional[str] = None) -> Path:
|
|
56
|
+
src = Path(src)
|
|
57
|
+
if dst is None:
|
|
58
|
+
dst = src.with_suffix("") if src.suffix == ".krs" else src.with_name(src.name + ".dec")
|
|
59
|
+
dst = Path(dst)
|
|
60
|
+
dst.write_bytes(self.decrypt_bytes(src.read_bytes(), password=password))
|
|
61
|
+
return dst
|
|
62
|
+
|
|
63
|
+
# Original 0.2 names
|
|
64
|
+
def E2D_1(self, text: str, password: Optional[str] = None) -> str:
|
|
65
|
+
return self.encrypt(text, password=password)
|
|
66
|
+
|
|
67
|
+
def D2E_2(self, token: str, password: Optional[str] = None) -> str:
|
|
68
|
+
return self.decrypt(token, password=password)
|