vorn 0.1.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.
vorn/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .core import VornError, __version__, decrypt, encrypt
2
+
3
+ __all__ = ["encrypt", "decrypt", "VornError", "__version__"]
vorn/core.py ADDED
@@ -0,0 +1,241 @@
1
+ import hashlib
2
+ import hmac
3
+ import secrets
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["encrypt", "decrypt", "VornError"]
7
+
8
+
9
+ class VornError(Exception):
10
+ pass
11
+
12
+
13
+ def _generate_primes(limit: int = 120) -> tuple[int, ...]:
14
+ primes: list[int] = []
15
+ num = 2
16
+ while len(primes) < limit:
17
+ if all(num % p != 0 for p in primes if p * p <= num):
18
+ primes.append(num)
19
+ num += 1
20
+ return tuple(primes)
21
+
22
+
23
+ _PRIMES = _generate_primes(120)
24
+
25
+
26
+ def _ct_lookup(table, target_idx: int) -> int:
27
+ result = 0
28
+ for i, val in enumerate(table):
29
+ mask = -int(i == target_idx)
30
+ result |= val & mask
31
+ return result
32
+
33
+
34
+ def _ct_prime_index(prime_val: int) -> int:
35
+ result = -1
36
+ for i in range(100):
37
+ mask = -int(_PRIMES[i] == prime_val)
38
+ result = (result & ~mask) | (i & mask)
39
+ if result == -1:
40
+ raise VornError("Invalid state encountered during decryption.")
41
+ return result
42
+
43
+
44
+ def _derive_keys(password: str, nonce: bytes, scrypt_n: int = 16384):
45
+ if not password:
46
+ raise VornError("Password must not be empty.")
47
+
48
+ master_key = hashlib.scrypt(
49
+ password.encode("utf-8"),
50
+ salt=nonce,
51
+ n=scrypt_n,
52
+ r=8,
53
+ p=1,
54
+ dklen=64,
55
+ )
56
+
57
+ enc_seed = master_key[:24]
58
+ pbox_seed = master_key[24:32]
59
+ mac_key = master_key[32:]
60
+
61
+ a = ((enc_seed[0] % 6) + 2) * 8
62
+
63
+ valid_b = (3, 5, 7, 9, 11, 13, 15, 17, 19)
64
+ filtered_b = [val for val in valid_b if a % val != 0]
65
+ b = filtered_b[enc_seed[1] % len(filtered_b)]
66
+
67
+ x = (1, 2, 4, 8)[enc_seed[2] % 4]
68
+ c = a // x
69
+ d = enc_seed[3] % 2
70
+
71
+ s0_forward = (int.from_bytes(enc_seed[4:6], "big") % 900) + 100
72
+ s0_backward = (int.from_bytes(enc_seed[6:8], "big") % 900) + 100
73
+
74
+ sbox = list(range(16))
75
+ for i in range(15, 0, -1):
76
+ j = enc_seed[8 + (15 - i)] % (i + 1)
77
+ sbox[i], sbox[j] = sbox[j], sbox[i]
78
+
79
+ inv_sbox = [0] * 16
80
+ for idx, val in enumerate(sbox):
81
+ inv_sbox[val] = idx
82
+
83
+ return a, b, c, d, s0_forward, s0_backward, sbox, inv_sbox, pbox_seed, mac_key
84
+
85
+
86
+ def _permute_bits(data: bytes, pbox_seed: bytes, inverse: bool = False) -> bytes:
87
+ total_bits = len(data) * 8
88
+ if total_bits == 0:
89
+ return data
90
+
91
+ perm = list(range(total_bits))
92
+ stream = bytearray()
93
+ counter = 0
94
+ needed_bytes = total_bits * 4
95
+ while len(stream) < needed_bytes:
96
+ stream.extend(
97
+ hashlib.blake2b(pbox_seed + counter.to_bytes(4, "big"), digest_size=64).digest()
98
+ )
99
+ counter += 1
100
+
101
+ for i in range(total_bits - 1, 0, -1):
102
+ offset = (total_bits - 1 - i) * 4
103
+ rand_val = int.from_bytes(stream[offset : offset + 4], "big")
104
+ j = rand_val % (i + 1)
105
+ perm[i], perm[j] = perm[j], perm[i]
106
+
107
+ bits = [(data[idx // 8] >> (7 - (idx % 8))) & 1 for idx in range(total_bits)]
108
+ out_bits = [0] * total_bits
109
+
110
+ if not inverse:
111
+ for dst, src in enumerate(perm):
112
+ out_bits[dst] = bits[src]
113
+ else:
114
+ for dst, src in enumerate(perm):
115
+ out_bits[src] = bits[dst]
116
+
117
+ out_bytes = bytearray(len(data))
118
+ for i, bit in enumerate(out_bits):
119
+ if bit:
120
+ out_bytes[i // 8] |= 1 << (7 - (i % 8))
121
+
122
+ return bytes(out_bytes)
123
+
124
+
125
+ def _sign(i: int, c: int, d: int) -> int:
126
+ block_parity = (i // c) % 2
127
+ if d == 0:
128
+ return -1 if block_parity == 0 else 1
129
+ return 1 if block_parity == 0 else -1
130
+
131
+
132
+ def _prime_pass_encrypt(symbols, a: int, b: int, c: int, d: int, s0: int) -> list[int]:
133
+ prev = s0
134
+ out = []
135
+ for i, sym in enumerate(symbols):
136
+ jump = a + (prev % 16)
137
+ jumped_prime = _ct_lookup(_PRIMES, sym + jump)
138
+ offset = (a % b) + (prev % b)
139
+ cipher_val = jumped_prime + _sign(i, c, d) * offset
140
+ out.append(cipher_val)
141
+ prev = cipher_val
142
+ return out
143
+
144
+
145
+ def _prime_pass_decrypt(cipher_vals, a: int, b: int, c: int, d: int, s0: int) -> list[int]:
146
+ prev = s0
147
+ out = []
148
+ for i, c_val in enumerate(cipher_vals):
149
+ offset = (a % b) + (prev % b)
150
+ jumped_prime = c_val - _sign(i, c, d) * offset
151
+ jumped_idx = _ct_prime_index(jumped_prime)
152
+ jump = a + (prev % 16)
153
+ out.append(jumped_idx - jump)
154
+ prev = c_val
155
+ return out
156
+
157
+
158
+ def encrypt(data: bytes | str, password: str, *, _scrypt_n: int = 16384) -> str:
159
+ if isinstance(data, str):
160
+ data = data.encode("utf-8")
161
+
162
+ nonce = secrets.token_bytes(16)
163
+ a, b, c, d, s0_f, s0_b, sbox, _, pbox_seed, mac_key = _derive_keys(password, nonce, _scrypt_n)
164
+
165
+ nibbles = []
166
+ for byte in data:
167
+ nibbles.append(_ct_lookup(sbox, (byte >> 4) & 0x0F))
168
+ nibbles.append(_ct_lookup(sbox, byte & 0x0F))
169
+
170
+ pass1 = _prime_pass_encrypt(nibbles, a, b, c, d, s0_f)
171
+
172
+ pass1_bytes = b"".join(val.to_bytes(2, "big") for val in pass1)
173
+ permuted_bytes = _permute_bits(pass1_bytes, pbox_seed, inverse=False)
174
+
175
+ mid_nibbles = []
176
+ for byte in reversed(permuted_bytes):
177
+ mid_nibbles.append((byte >> 4) & 0x0F)
178
+ mid_nibbles.append(byte & 0x0F)
179
+
180
+ pass2 = _prime_pass_encrypt(mid_nibbles, a, b, c, d, s0_b)
181
+
182
+ nonce_str = "".join(f"{byte:03d}" for byte in nonce)
183
+ cipher_str = "".join(f"{val:03d}" for val in pass2)
184
+ payload = nonce_str + cipher_str
185
+
186
+ mac_digest = hmac.new(mac_key, payload.encode("ascii"), hashlib.sha256).digest()
187
+ mac_str = "".join(f"{byte:03d}" for byte in mac_digest)
188
+
189
+ return payload + mac_str
190
+
191
+
192
+ def decrypt(ciphertext: str, password: str, *, _scrypt_n: int = 16384) -> bytes:
193
+ if (
194
+ not isinstance(ciphertext, str)
195
+ or len(ciphertext) < 144
196
+ or len(ciphertext) % 3 != 0
197
+ or not (ciphertext.isascii() and ciphertext.isdigit())
198
+ ):
199
+ raise VornError("Malformed ciphertext packet.")
200
+
201
+ nonce_str = ciphertext[:48]
202
+ mac_str = ciphertext[-96:]
203
+ cipher_str = ciphertext[48:-96]
204
+
205
+ try:
206
+ nonce = bytes(int(nonce_str[i : i + 3]) for i in range(0, 48, 3))
207
+ except ValueError as exc:
208
+ raise VornError("Corrupted nonce block.") from exc
209
+
210
+ a, b, c, d, s0_f, s0_b, _, inv_sbox, pbox_seed, mac_key = _derive_keys(
211
+ password, nonce, _scrypt_n
212
+ )
213
+
214
+ expected_mac = hmac.new(mac_key, (nonce_str + cipher_str).encode("ascii"), hashlib.sha256).digest()
215
+ expected_mac_str = "".join(f"{byte:03d}" for byte in expected_mac)
216
+ if not hmac.compare_digest(mac_str, expected_mac_str):
217
+ raise VornError("Authentication failed: invalid password or tampered payload.")
218
+
219
+ pass2 = [int(cipher_str[i : i + 3]) for i in range(0, len(cipher_str), 3)]
220
+ if len(pass2) % 8 != 0:
221
+ raise VornError("Malformed ciphertext packet.")
222
+
223
+ mid_nibbles = _prime_pass_decrypt(pass2, a, b, c, d, s0_b)
224
+
225
+ reversed_permuted = bytearray()
226
+ for i in range(0, len(mid_nibbles), 2):
227
+ reversed_permuted.append((mid_nibbles[i] << 4) | mid_nibbles[i + 1])
228
+
229
+ permuted_bytes = bytes(reversed(reversed_permuted))
230
+ pass1_bytes = _permute_bits(permuted_bytes, pbox_seed, inverse=True)
231
+
232
+ pass1 = [int.from_bytes(pass1_bytes[i : i + 2], "big") for i in range(0, len(pass1_bytes), 2)]
233
+
234
+ mapped_nibbles = _prime_pass_decrypt(pass1, a, b, c, d, s0_f)
235
+ raw_nibbles = [_ct_lookup(inv_sbox, n) for n in mapped_nibbles]
236
+
237
+ result = bytearray()
238
+ for i in range(0, len(raw_nibbles), 2):
239
+ result.append((raw_nibbles[i] << 4) | raw_nibbles[i + 1])
240
+
241
+ return bytes(result)
@@ -0,0 +1,130 @@
1
+ Metadata-Version: 2.4
2
+ Name: vorn
3
+ Version: 0.1.0
4
+ Summary: Experimental authenticated symmetric cipher based on prime-index hopping and bit diffusion. Educational use only.
5
+ Author: LowLeery
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/LowLeery/vorn
8
+ Project-URL: Repository, https://github.com/LowLeery/vorn
9
+ Keywords: cryptography,encryption,cipher,prime,experimental
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Education
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Security :: Cryptography
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Dynamic: license-file
23
+
24
+ # Vorn
25
+
26
+ > **Warning: experimental / educational.** Vorn is a custom cipher design. It has **not** been
27
+ > reviewed by cryptographers and must **not** be used to protect real secrets. For production use
28
+ > a vetted AEAD such as AES-GCM or ChaCha20-Poly1305 (e.g. via the `cryptography` package).
29
+
30
+ **Vorn** is a zero-dependency Python library that experiments with a symmetric cipher built from
31
+ dynamic prime-index hopping, alternating modular offsets, a keyed bit permutation, and
32
+ HMAC-SHA256 authentication (Encrypt-then-MAC).
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ pip install vorn
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ ```python
43
+ from vorn import encrypt, decrypt, VornError
44
+
45
+ password = "correct-horse-battery-staple"
46
+ ciphertext = encrypt("Payload 257-ALPHA", password)
47
+
48
+ try:
49
+ plaintext = decrypt(ciphertext, password).decode("utf-8")
50
+ print(plaintext)
51
+ except VornError as e:
52
+ print(f"Decryption error: {e}")
53
+ ```
54
+
55
+ ### Files
56
+
57
+ ```python
58
+ from vorn import encrypt, decrypt
59
+
60
+ with open("archive.bin", "rb") as src:
61
+ encoded = encrypt(src.read(), "file-encryption-key")
62
+
63
+ with open("archive.vorn", "w", encoding="ascii") as dst:
64
+ dst.write(encoded)
65
+
66
+ with open("archive.vorn", "r", encoding="ascii") as src:
67
+ restored = decrypt(src.read(), "file-encryption-key")
68
+ ```
69
+
70
+ Note: the pure-Python implementation is slow and memory hungry, and ciphertext is about
71
+ 24 characters per plaintext byte. It is meant for small payloads.
72
+
73
+ ## Specification
74
+
75
+ ### 1. Key derivation
76
+ A UTF-8 passphrase `P` and a random 128-bit nonce `N` are fed to **scrypt** (n=16384, r=8, p=1)
77
+ to produce 64 bytes: `K_enc (32 bytes, 24 used) || K_pbox (8 bytes) || K_mac (32 bytes)`.
78
+
79
+ From `K_enc` the following parameters are derived:
80
+ - `a`: one of 16, 24, 32, 40, 48, 56 (a multiple of 8).
81
+ - `b`: a modular base (3..19) that does not divide `a`.
82
+ - `c`: block period `a / x` with `x` in {1, 2, 4, 8}.
83
+ - `d`: polarity bit selecting the initial offset sign.
84
+ - `S0_fwd`, `S0_bwd`: initial chaining states (100..999) for the two passes.
85
+ - A keyed 16-element S-Box over nibbles.
86
+
87
+ ### 2. Round function
88
+ Input bytes are split into nibbles and passed through the S-Box. For symbol `s_i` with previous
89
+ state `C_{i-1}` (`C_{-1} = S0`):
90
+
91
+ ```
92
+ J_i = a + (C_{i-1} mod 16)
93
+ p_i = Prime[s_i + J_i]
94
+ R_i = (a mod b) + (C_{i-1} mod b)
95
+ sigma_i = (-1)^(floor(i / c) + d)
96
+ C_i = p_i + sigma_i * R_i
97
+ ```
98
+
99
+ ### 3. Diffusion
100
+ 1. Forward pass over all nibbles using `S0_fwd`.
101
+ 2. States are serialized to bytes, then a keyed Fisher-Yates **bit permutation** (seeded via
102
+ BLAKE2b of `K_pbox`) is applied and the byte stream is reversed.
103
+ 3. Backward-direction pass over the resulting nibbles using `S0_bwd`.
104
+
105
+ ### 4. Wire format
106
+ Everything is serialized as zero-padded 3-digit decimal blocks (`000`-`999`):
107
+
108
+ ```
109
+ | nonce: 16 bytes (48 chars) | state stream: 24 * L chars | HMAC-SHA256: 32 bytes (96 chars) |
110
+ ```
111
+
112
+ The MAC covers `nonce || state stream` and is verified before any decryption work.
113
+ Any altered digit raises `VornError`.
114
+
115
+ ## Limitations
116
+
117
+ - No formal security analysis; the construction is non-standard.
118
+ - Python offers no real constant-time guarantees.
119
+ - Not suitable for large files.
120
+
121
+ ## Tests
122
+
123
+ ```bash
124
+ pip install pytest
125
+ python -m pytest
126
+ ```
127
+
128
+ ## License
129
+
130
+ MIT
@@ -0,0 +1,7 @@
1
+ vorn/__init__.py,sha256=0rwYtJWBGvteGZyjrraQfMrWK_98X23sUct0keCLmFU,121
2
+ vorn/core.py,sha256=2yEuLmag0WGNoqcmj2Vydea-lMyNcBHvmJVHQCuA5zM,7364
3
+ vorn-0.1.0.dist-info/licenses/LICENSE,sha256=GQUTLHdooU-ogdmV5NjyZOJ3tXEzmtlfGexRipNN544,1065
4
+ vorn-0.1.0.dist-info/METADATA,sha256=fFut9GIjT_xUmu9JRZPzMrRLjksvWyDQ_H7AQW1zizI,4119
5
+ vorn-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ vorn-0.1.0.dist-info/top_level.txt,sha256=7iNBWqr5jUB0Yw-KZ1bkV4TyzZEQMIrlLEPMciaYWt8,5
7
+ vorn-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 LowLeery
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
+ vorn