krishto 1.0.0__py3-none-any.whl
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/__init__.py +35 -0
- krishto/backends.py +171 -0
- krishto/cli.py +72 -0
- krishto/codec.py +22 -0
- krishto/core.py +68 -0
- krishto/exceptions.py +14 -0
- krishto/kdf.py +18 -0
- krishto/py.typed +0 -0
- krishto/vault.py +46 -0
- krishto-1.0.0.dist-info/METADATA +162 -0
- krishto-1.0.0.dist-info/RECORD +15 -0
- krishto-1.0.0.dist-info/WHEEL +5 -0
- krishto-1.0.0.dist-info/entry_points.txt +2 -0
- krishto-1.0.0.dist-info/licenses/LICENCE +21 -0
- krishto-1.0.0.dist-info/top_level.txt +1 -0
krishto/__init__.py
ADDED
|
@@ -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
|
+
]
|
krishto/backends.py
ADDED
|
@@ -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}")
|
krishto/cli.py
ADDED
|
@@ -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())
|
krishto/codec.py
ADDED
|
@@ -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
|
krishto/core.py
ADDED
|
@@ -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)
|
krishto/exceptions.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
class KrishtoError(Exception):
|
|
2
|
+
"""Base exception for Krishto errors."""
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class DecryptionError(KrishtoError):
|
|
6
|
+
"""The blob is corrupt, unsupported, or has the wrong password/context."""
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class InvalidKeyError(KrishtoError):
|
|
10
|
+
"""A password or key is missing or invalid."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class MissingDependencyError(KrishtoError):
|
|
14
|
+
"""An optional cryptography backend is unavailable."""
|
krishto/kdf.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
|
|
3
|
+
SCRYPT_N = 1 << 14
|
|
4
|
+
SCRYPT_R = 8
|
|
5
|
+
SCRYPT_P = 1
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def derive_key(password: str, salt: bytes, length: int = 32) -> bytes:
|
|
9
|
+
if not isinstance(password, str) or not password:
|
|
10
|
+
raise ValueError("Password must be a non-empty string")
|
|
11
|
+
return hashlib.scrypt(
|
|
12
|
+
password.encode("utf-8"),
|
|
13
|
+
salt=salt,
|
|
14
|
+
n=SCRYPT_N,
|
|
15
|
+
r=SCRYPT_R,
|
|
16
|
+
p=SCRYPT_P,
|
|
17
|
+
dklen=length,
|
|
18
|
+
)
|
krishto/py.typed
ADDED
|
File without changes
|
krishto/vault.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Any, Optional
|
|
5
|
+
|
|
6
|
+
from .core import Krishto
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Vault:
|
|
10
|
+
def __init__(self, path: str, password: str, backend: str = "auto"):
|
|
11
|
+
self.path = Path(path)
|
|
12
|
+
self._k = Krishto(password, backend=backend)
|
|
13
|
+
self._data: dict[str, Any] = {}
|
|
14
|
+
if self.path.exists():
|
|
15
|
+
self.load()
|
|
16
|
+
|
|
17
|
+
def load(self) -> None:
|
|
18
|
+
plaintext = self._k.decrypt_bytes(self.path.read_bytes())
|
|
19
|
+
data = json.loads(plaintext.decode("utf-8"))
|
|
20
|
+
if not isinstance(data, dict):
|
|
21
|
+
raise ValueError("Vault contents must be a JSON object")
|
|
22
|
+
self._data = data
|
|
23
|
+
|
|
24
|
+
def save(self) -> None:
|
|
25
|
+
plaintext = json.dumps(self._data, ensure_ascii=False, sort_keys=True).encode("utf-8")
|
|
26
|
+
blob = self._k.encrypt_bytes(plaintext)
|
|
27
|
+
temporary = self.path.with_name(self.path.name + ".tmp")
|
|
28
|
+
temporary.write_bytes(blob)
|
|
29
|
+
os.replace(temporary, self.path)
|
|
30
|
+
|
|
31
|
+
def set(self, key: str, value: Any) -> None:
|
|
32
|
+
self._data[key] = value
|
|
33
|
+
self.save()
|
|
34
|
+
|
|
35
|
+
def get(self, key: str, default: Optional[Any] = None) -> Any:
|
|
36
|
+
return self._data.get(key, default)
|
|
37
|
+
|
|
38
|
+
def delete(self, key: str) -> bool:
|
|
39
|
+
if key not in self._data:
|
|
40
|
+
return False
|
|
41
|
+
del self._data[key]
|
|
42
|
+
self.save()
|
|
43
|
+
return True
|
|
44
|
+
|
|
45
|
+
def keys(self) -> list[str]:
|
|
46
|
+
return sorted(self._data)
|
|
@@ -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.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
krishto/__init__.py,sha256=lBiSL3e9tfvVqCqRIt-7jSlBhGcmB1JRacRvEKl1YKo,729
|
|
2
|
+
krishto/backends.py,sha256=SMyI6IkIjETGEUzo2m_b0KIRqORpgPIvO6IGGAS2hkU,6089
|
|
3
|
+
krishto/cli.py,sha256=cID_TuwFfv87zaYRBjmtRJwLnetsKke21vrkbILl7zU,2557
|
|
4
|
+
krishto/codec.py,sha256=jtY4aVrCetyYxb9Eivr7WVskanRne_36Nrio9S_eDFc,657
|
|
5
|
+
krishto/core.py,sha256=DQHRjYnaRM18FCKuYNHMnK95YXwGgQf8oiq-VV2bKu8,2845
|
|
6
|
+
krishto/exceptions.py,sha256=YYVWMpJaFYp7Q-9FTYZxHvSSaXOMi00R5nqxCLFXg94,389
|
|
7
|
+
krishto/kdf.py,sha256=nPcli77qbVw7PfZbhf4zGFJG9yl6tJiWJQG8XSTkwZE,420
|
|
8
|
+
krishto/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
krishto/vault.py,sha256=0ijYZT0AAPdT4E-GnVaxxEunWNSeJEu-tHA1z15i6Wc,1420
|
|
10
|
+
krishto-1.0.0.dist-info/licenses/LICENCE,sha256=O8KuuoP83dQekK6x_SC_e76tpdzUS2eukYCgvbzk6OU,1072
|
|
11
|
+
krishto-1.0.0.dist-info/METADATA,sha256=Z74aJAcE05bMt6IGzzwrpRIgiNjm7sUHvoUa4pNsTTI,4994
|
|
12
|
+
krishto-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
13
|
+
krishto-1.0.0.dist-info/entry_points.txt,sha256=qc9gUUYeLOqelAEmqiqLYFJ1KlebM96JV32uCGqSkWs,45
|
|
14
|
+
krishto-1.0.0.dist-info/top_level.txt,sha256=7-PTB_3r5TXyjL3ryKEV82y1pvXI1iG_bgZtM7CWh90,8
|
|
15
|
+
krishto-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 K.A.ISHAN OSHADA
|
|
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 @@
|
|
|
1
|
+
krishto
|