kuricrypt 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.
@@ -0,0 +1,67 @@
1
+ name: Kuricrypt
2
+
3
+ on:
4
+ push:
5
+ pull_request:
6
+ workflow_dispatch: {}
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ tests:
13
+ name: Python ${{ matrix.python-version }} on ${{ matrix.os }}
14
+ runs-on: ${{ matrix.os }}
15
+ strategy:
16
+ fail-fast: false
17
+ matrix:
18
+ os: [ubuntu-latest, windows-latest, macos-latest]
19
+ python-version: ["3.10", "3.11", "3.12", "3.13", "3.14", "3.15"]
20
+ steps:
21
+ - uses: actions/checkout@v6
22
+
23
+ - uses: actions/setup-python@v6
24
+ with:
25
+ python-version: ${{ matrix.python-version }}
26
+
27
+ - uses: dtolnay/rust-toolchain@stable
28
+
29
+ - name: Install package
30
+ run: python -m pip install pytest .
31
+
32
+ - name: Run tests
33
+ run: python -m pytest
34
+
35
+ tgcrypto-compatibility:
36
+ name: TgCrypto compatibility
37
+ runs-on: ubuntu-latest
38
+ steps:
39
+ - uses: actions/checkout@v6
40
+
41
+ - uses: actions/setup-python@v6
42
+ with:
43
+ python-version: "3.13"
44
+
45
+ - uses: dtolnay/rust-toolchain@stable
46
+
47
+ - name: Install reference and candidate packages
48
+ run: python -m pip install pytest tgcrypto .
49
+
50
+ - name: Run compatibility tests
51
+ run: python -m pytest tests/test_compatibility.py
52
+
53
+ rust-lint:
54
+ name: Rust format and lint
55
+ runs-on: ubuntu-latest
56
+ steps:
57
+ - uses: actions/checkout@v6
58
+
59
+ - uses: dtolnay/rust-toolchain@stable
60
+ with:
61
+ components: rustfmt, clippy
62
+
63
+ - name: Check formatting
64
+ run: cargo fmt --all -- --check
65
+
66
+ - name: Run Clippy
67
+ run: cargo clippy --locked --all-targets -- -D warnings
@@ -0,0 +1,137 @@
1
+ name: Upload release to GitHub and PyPI
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - "v*"
7
+ workflow_dispatch: {}
8
+
9
+ permissions:
10
+ contents: read
11
+
12
+ jobs:
13
+ test:
14
+ name: Test release tag
15
+ runs-on: ubuntu-latest
16
+ steps:
17
+ - uses: actions/checkout@v6
18
+
19
+ - uses: actions/setup-python@v6
20
+ with:
21
+ python-version: "3.13"
22
+
23
+ - uses: dtolnay/rust-toolchain@stable
24
+ with:
25
+ components: rustfmt, clippy
26
+
27
+ - name: Install TgCrypto reference and kuricrypt
28
+ run: python -m pip install pytest tgcrypto .
29
+
30
+ - name: Run tests
31
+ run: python -m pytest
32
+
33
+ - name: Check Rust formatting and lint
34
+ run: |
35
+ cargo fmt --all -- --check
36
+ cargo clippy --locked --all-targets -- -D warnings
37
+
38
+ build-wheels:
39
+ name: Build Python ${{ matrix.python-version }} on ${{ matrix.os }}
40
+ needs: test
41
+ runs-on: ${{ matrix.os }}
42
+ strategy:
43
+ fail-fast: false
44
+ matrix:
45
+ os: [ubuntu-latest, windows-latest, macos-latest]
46
+ python-version: ["3.10", "3.11", "3.12", "3.13", "3.14", "3.15"]
47
+ steps:
48
+ - uses: actions/checkout@v6
49
+
50
+ - uses: actions/setup-python@v6
51
+ with:
52
+ python-version: ${{ matrix.python-version }}
53
+
54
+ - uses: dtolnay/rust-toolchain@stable
55
+
56
+ - name: Build Linux wheel
57
+ if: runner.os == 'Linux'
58
+ uses: PyO3/maturin-action@v1
59
+ with:
60
+ command: build
61
+ args: --release --out dist --interpreter python${{ matrix.python-version }}
62
+ manylinux: "2_28"
63
+
64
+ - name: Build macOS and Windows wheel
65
+ if: runner.os != 'Linux'
66
+ uses: PyO3/maturin-action@v1
67
+ with:
68
+ command: build
69
+ args: --release --out dist --interpreter python
70
+ manylinux: off
71
+
72
+ - uses: actions/upload-artifact@v4
73
+ with:
74
+ name: wheel-${{ matrix.os }}-py${{ matrix.python-version }}
75
+ path: dist/*.whl
76
+ if-no-files-found: error
77
+
78
+ build-sdist:
79
+ name: Build source distribution
80
+ needs: test
81
+ runs-on: ubuntu-latest
82
+ steps:
83
+ - uses: actions/checkout@v6
84
+
85
+ - uses: actions/setup-python@v6
86
+ with:
87
+ python-version: "3.13"
88
+
89
+ - name: Install Maturin
90
+ run: python -m pip install maturin
91
+
92
+ - name: Build sdist
93
+ run: maturin sdist --out dist
94
+
95
+ - uses: actions/upload-artifact@v4
96
+ with:
97
+ name: source-distribution
98
+ path: dist/*.tar.gz
99
+ if-no-files-found: error
100
+
101
+ github-release:
102
+ name: Publish GitHub release
103
+ needs: [build-wheels, build-sdist]
104
+ runs-on: ubuntu-latest
105
+ permissions:
106
+ contents: write
107
+ steps:
108
+ - uses: actions/download-artifact@v4
109
+ with:
110
+ path: dist
111
+ merge-multiple: true
112
+
113
+ - uses: softprops/action-gh-release@v2
114
+ with:
115
+ tag_name: ${{ github.ref_name }}
116
+ name: ${{ github.ref_name }}
117
+ generate_release_notes: true
118
+ make_latest: true
119
+ draft: false
120
+ prerelease: false
121
+ files: dist/*
122
+ fail_on_unmatched_files: true
123
+
124
+ pypi-release:
125
+ name: Publish to PyPI
126
+ needs: [build-wheels, build-sdist]
127
+ runs-on: ubuntu-latest
128
+ steps:
129
+ - uses: actions/download-artifact@v4
130
+ with:
131
+ path: dist
132
+ merge-multiple: true
133
+
134
+ - uses: pypa/gh-action-pypi-publish@release/v1
135
+ with:
136
+ user: __token__
137
+ password: ${{ secrets.PYPI_API_TOKEN }}
@@ -0,0 +1,5 @@
1
+ /target/
2
+ /.venv/
3
+ /.pytest_cache/
4
+ __pycache__/
5
+ *.py[cod]
@@ -0,0 +1,202 @@
1
+ # This file is automatically @generated by Cargo.
2
+ # It is not intended for manual editing.
3
+ version = 4
4
+
5
+ [[package]]
6
+ name = "aes"
7
+ version = "0.9.4"
8
+ source = "registry+https://github.com/rust-lang/crates.io-index"
9
+ checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1"
10
+ dependencies = [
11
+ "cipher",
12
+ "cpubits",
13
+ "cpufeatures",
14
+ ]
15
+
16
+ [[package]]
17
+ name = "cipher"
18
+ version = "0.5.2"
19
+ source = "registry+https://github.com/rust-lang/crates.io-index"
20
+ checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
21
+ dependencies = [
22
+ "crypto-common",
23
+ "inout",
24
+ ]
25
+
26
+ [[package]]
27
+ name = "cpubits"
28
+ version = "0.1.1"
29
+ source = "registry+https://github.com/rust-lang/crates.io-index"
30
+ checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
31
+
32
+ [[package]]
33
+ name = "cpufeatures"
34
+ version = "0.3.1"
35
+ source = "registry+https://github.com/rust-lang/crates.io-index"
36
+ checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
37
+ dependencies = [
38
+ "libc",
39
+ ]
40
+
41
+ [[package]]
42
+ name = "crypto-common"
43
+ version = "0.2.2"
44
+ source = "registry+https://github.com/rust-lang/crates.io-index"
45
+ checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
46
+ dependencies = [
47
+ "hybrid-array",
48
+ ]
49
+
50
+ [[package]]
51
+ name = "heck"
52
+ version = "0.5.0"
53
+ source = "registry+https://github.com/rust-lang/crates.io-index"
54
+ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
55
+
56
+ [[package]]
57
+ name = "hybrid-array"
58
+ version = "0.4.15"
59
+ source = "registry+https://github.com/rust-lang/crates.io-index"
60
+ checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
61
+ dependencies = [
62
+ "typenum",
63
+ ]
64
+
65
+ [[package]]
66
+ name = "inout"
67
+ version = "0.2.6"
68
+ source = "registry+https://github.com/rust-lang/crates.io-index"
69
+ checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9"
70
+ dependencies = [
71
+ "hybrid-array",
72
+ ]
73
+
74
+ [[package]]
75
+ name = "kuricrypt"
76
+ version = "0.1.0"
77
+ dependencies = [
78
+ "aes",
79
+ "pyo3",
80
+ ]
81
+
82
+ [[package]]
83
+ name = "libc"
84
+ version = "0.2.191"
85
+ source = "registry+https://github.com/rust-lang/crates.io-index"
86
+ checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
87
+
88
+ [[package]]
89
+ name = "once_cell"
90
+ version = "1.21.4"
91
+ source = "registry+https://github.com/rust-lang/crates.io-index"
92
+ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
93
+
94
+ [[package]]
95
+ name = "portable-atomic"
96
+ version = "1.15.0"
97
+ source = "registry+https://github.com/rust-lang/crates.io-index"
98
+ checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
99
+
100
+ [[package]]
101
+ name = "proc-macro2"
102
+ version = "1.0.107"
103
+ source = "registry+https://github.com/rust-lang/crates.io-index"
104
+ checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
105
+ dependencies = [
106
+ "unicode-ident",
107
+ ]
108
+
109
+ [[package]]
110
+ name = "pyo3"
111
+ version = "0.30.1"
112
+ source = "registry+https://github.com/rust-lang/crates.io-index"
113
+ checksum = "229ca13b8a15bb0d1487b81ab975bfcd97513416499a8312011b6036e42e0de4"
114
+ dependencies = [
115
+ "libc",
116
+ "once_cell",
117
+ "portable-atomic",
118
+ "pyo3-build-config",
119
+ "pyo3-ffi",
120
+ "pyo3-macros",
121
+ ]
122
+
123
+ [[package]]
124
+ name = "pyo3-build-config"
125
+ version = "0.30.1"
126
+ source = "registry+https://github.com/rust-lang/crates.io-index"
127
+ checksum = "70130e2b6dd1ee589a8788026a429561ca5c40fa7a2fa7914c2282eddae24700"
128
+ dependencies = [
129
+ "target-lexicon",
130
+ ]
131
+
132
+ [[package]]
133
+ name = "pyo3-ffi"
134
+ version = "0.30.1"
135
+ source = "registry+https://github.com/rust-lang/crates.io-index"
136
+ checksum = "5e7ff73c555c286d212d4ce7e5fbda845a973c4f61bd5f160f5f2c3c2a04d1c4"
137
+ dependencies = [
138
+ "libc",
139
+ "pyo3-build-config",
140
+ ]
141
+
142
+ [[package]]
143
+ name = "pyo3-macros"
144
+ version = "0.30.1"
145
+ source = "registry+https://github.com/rust-lang/crates.io-index"
146
+ checksum = "c46d2e5862c7bb8207e3b639f713dda3c499933444784154c11d013c5a691b60"
147
+ dependencies = [
148
+ "proc-macro2",
149
+ "pyo3-macros-backend",
150
+ "quote",
151
+ "syn",
152
+ ]
153
+
154
+ [[package]]
155
+ name = "pyo3-macros-backend"
156
+ version = "0.30.1"
157
+ source = "registry+https://github.com/rust-lang/crates.io-index"
158
+ checksum = "38b89f066f2ae72a2aef52d1537ca2fcd104440ebfadee06e97aa90738a25b9b"
159
+ dependencies = [
160
+ "heck",
161
+ "proc-macro2",
162
+ "quote",
163
+ "syn",
164
+ ]
165
+
166
+ [[package]]
167
+ name = "quote"
168
+ version = "1.0.47"
169
+ source = "registry+https://github.com/rust-lang/crates.io-index"
170
+ checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
171
+ dependencies = [
172
+ "proc-macro2",
173
+ ]
174
+
175
+ [[package]]
176
+ name = "syn"
177
+ version = "3.0.9"
178
+ source = "registry+https://github.com/rust-lang/crates.io-index"
179
+ checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
180
+ dependencies = [
181
+ "proc-macro2",
182
+ "quote",
183
+ "unicode-ident",
184
+ ]
185
+
186
+ [[package]]
187
+ name = "target-lexicon"
188
+ version = "0.13.5"
189
+ source = "registry+https://github.com/rust-lang/crates.io-index"
190
+ checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
191
+
192
+ [[package]]
193
+ name = "typenum"
194
+ version = "1.20.1"
195
+ source = "registry+https://github.com/rust-lang/crates.io-index"
196
+ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
197
+
198
+ [[package]]
199
+ name = "unicode-ident"
200
+ version = "1.0.27"
201
+ source = "registry+https://github.com/rust-lang/crates.io-index"
202
+ checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
@@ -0,0 +1,18 @@
1
+ [package]
2
+ name = "kuricrypt"
3
+ version = "0.1.0"
4
+ edition = "2021"
5
+ description = "Rust-based Telegram cryptography extension for Python"
6
+ readme = "README.md"
7
+
8
+ [lib]
9
+ name = "kuricrypt"
10
+ crate-type = ["cdylib"]
11
+
12
+ [dependencies]
13
+ aes = "0.9.2"
14
+ pyo3 = { version = "0.30", features = ["extension-module"] }
15
+
16
+ [profile.release]
17
+ lto = "fat"
18
+ codegen-units = 1
@@ -0,0 +1,5 @@
1
+ Metadata-Version: 2.4
2
+ Name: kuricrypt
3
+ Version: 0.1.0
4
+ Summary: Rust-based Telegram cryptography extension for Python
5
+ Requires-Python: >=3.10
@@ -0,0 +1,146 @@
1
+ # kuricrypt
2
+
3
+ > Fast cryptography extension library for Telegram clients
4
+
5
+ **kuricrypt** is a Rust-based Python extension that implements the AES algorithms used by Telegram:
6
+
7
+ - **`AES-256-IGE`** - used in MTProto 2.0.
8
+ - **`AES-256-CTR`** - used for CDN encrypted files.
9
+ - **`AES-256-CBC`** - used for encrypted passport credentials.
10
+
11
+ The Python API is compatible with the six public `tgcrypto` functions.
12
+
13
+ ## Requirements
14
+
15
+ - Python 3.10 or higher.
16
+ - A Rust toolchain is required when building from source.
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ pip3 install -U kuricrypt
22
+ ```
23
+
24
+ To build and install from a source checkout:
25
+
26
+ ```bash
27
+ python -m pip install .
28
+ ```
29
+
30
+ ## API
31
+
32
+ ```python
33
+ def ige256_encrypt(data: bytes, key: bytes, iv: bytes) -> bytes: ...
34
+ def ige256_decrypt(data: bytes, key: bytes, iv: bytes) -> bytes: ...
35
+
36
+ def ctr256_encrypt(data: bytes, key: bytes, iv: bytes, state: bytes) -> bytes: ...
37
+ def ctr256_decrypt(data: bytes, key: bytes, iv: bytes, state: bytes) -> bytes: ...
38
+
39
+ def cbc256_encrypt(data: bytes, key: bytes, iv: bytes) -> bytes: ...
40
+ def cbc256_decrypt(data: bytes, key: bytes, iv: bytes) -> bytes: ...
41
+ ```
42
+
43
+ All functions accept contiguous Python buffer-protocol objects. Writable CTR and CBC `iv` buffers are updated in place. CTR also updates a writable one-byte `state` buffer so a stream can continue across chunks. Immutable buffers are accepted but are not modified.
44
+
45
+ ## Usage
46
+
47
+ ### IGE Mode
48
+
49
+ **Note**: Data must be non-empty and padded to a multiple of the block size (16 bytes).
50
+
51
+ ```python
52
+ import os
53
+
54
+ import kuricrypt
55
+
56
+ data = os.urandom(10 * 1024 * 1024 + 7)
57
+ key = os.urandom(32)
58
+ iv = os.urandom(32)
59
+
60
+ data += bytes(-len(data) % 16)
61
+
62
+ ige_encrypted = kuricrypt.ige256_encrypt(data, key, iv)
63
+ ige_decrypted = kuricrypt.ige256_decrypt(ige_encrypted, key, iv)
64
+
65
+ assert data == ige_decrypted
66
+ ```
67
+
68
+ ### CTR Mode (single chunk)
69
+
70
+ ```python
71
+ import os
72
+
73
+ import kuricrypt
74
+
75
+ data = os.urandom(10 * 1024 * 1024)
76
+ key = os.urandom(32)
77
+
78
+ enc_iv = bytearray(os.urandom(16))
79
+ dec_iv = enc_iv.copy()
80
+ enc_state = bytearray(1)
81
+ dec_state = bytearray(1)
82
+
83
+ ctr_encrypted = kuricrypt.ctr256_encrypt(data, key, enc_iv, enc_state)
84
+ ctr_decrypted = kuricrypt.ctr256_decrypt(ctr_encrypted, key, dec_iv, dec_state)
85
+
86
+ assert data == ctr_decrypted
87
+ ```
88
+
89
+ ### CTR Mode (stream)
90
+
91
+ ```python
92
+ import os
93
+ from io import BytesIO
94
+
95
+ import kuricrypt
96
+
97
+ data = BytesIO(os.urandom(10 * 1024 * 1024))
98
+ key = os.urandom(32)
99
+
100
+ enc_iv = bytearray(os.urandom(16))
101
+ dec_iv = enc_iv.copy()
102
+ enc_state = bytearray(1)
103
+ dec_state = bytearray(1)
104
+
105
+ encrypted_data = BytesIO()
106
+ decrypted_data = BytesIO()
107
+
108
+ while chunk := data.read(1024):
109
+ encrypted_data.write(kuricrypt.ctr256_encrypt(chunk, key, enc_iv, enc_state))
110
+
111
+ encrypted_data.seek(0)
112
+ while chunk := encrypted_data.read(1024):
113
+ decrypted_data.write(kuricrypt.ctr256_decrypt(chunk, key, dec_iv, dec_state))
114
+
115
+ assert data.getvalue() == decrypted_data.getvalue()
116
+ ```
117
+
118
+ ### CBC Mode
119
+
120
+ **Note**: Data must be non-empty and padded to a multiple of the block size (16 bytes).
121
+
122
+ ```python
123
+ import os
124
+
125
+ import kuricrypt
126
+
127
+ data = os.urandom(10 * 1024 * 1024 + 7)
128
+ key = os.urandom(32)
129
+
130
+ enc_iv = bytearray(os.urandom(16))
131
+ dec_iv = enc_iv.copy()
132
+
133
+ data += bytes(-len(data) % 16)
134
+
135
+ cbc_encrypted = kuricrypt.cbc256_encrypt(data, key, enc_iv)
136
+ cbc_decrypted = kuricrypt.cbc256_decrypt(cbc_encrypted, key, dec_iv)
137
+
138
+ assert data == cbc_decrypted
139
+ ```
140
+
141
+ ## Testing
142
+
143
+ ```bash
144
+ python -m pip install pytest
145
+ python -m pytest
146
+ ```
@@ -0,0 +1,8 @@
1
+ from typing import Any
2
+
3
+ def ige256_encrypt(data: Any, key: Any, iv: Any, /) -> bytes: ...
4
+ def ige256_decrypt(data: Any, key: Any, iv: Any, /) -> bytes: ...
5
+ def ctr256_encrypt(data: Any, key: Any, iv: Any, state: Any, /) -> bytes: ...
6
+ def ctr256_decrypt(data: Any, key: Any, iv: Any, state: Any, /) -> bytes: ...
7
+ def cbc256_encrypt(data: Any, key: Any, iv: Any, /) -> bytes: ...
8
+ def cbc256_decrypt(data: Any, key: Any, iv: Any, /) -> bytes: ...
@@ -0,0 +1,14 @@
1
+ [build-system]
2
+ requires = ["maturin>=1.8,<2"]
3
+ build-backend = "maturin"
4
+
5
+ [project]
6
+ name = "kuricrypt"
7
+ version = "0.1.0"
8
+ description = "Rust-based Telegram cryptography extension for Python"
9
+ requires-python = ">=3.10"
10
+
11
+ [tool.maturin]
12
+ module-name = "kuricrypt"
13
+ bindings = "pyo3"
14
+ include = ["kuricrypt.pyi"]
@@ -0,0 +1,479 @@
1
+ use aes::cipher::typenum::Unsigned;
2
+ use aes::cipher::{
3
+ array::Array, consts::U16, BlockCipherDecBackend, BlockCipherDecClosure, BlockCipherDecrypt,
4
+ BlockCipherEncBackend, BlockCipherEncClosure, BlockCipherEncrypt, BlockSizeUser, KeyInit,
5
+ ParBlocks,
6
+ };
7
+ use aes::{Aes256Dec, Aes256Enc};
8
+ use pyo3::buffer::PyUntypedBuffer;
9
+ use pyo3::exceptions::{PyBufferError, PyTypeError, PyValueError};
10
+ use pyo3::prelude::*;
11
+ use pyo3::types::{PyBytes, PyModule, PyTuple};
12
+ use std::slice;
13
+
14
+ type AesBlock = Array<u8, U16>;
15
+
16
+ const GIL_RELEASE_MIN: usize = 2048;
17
+
18
+ fn maybe_detach<T: Send>(py: Python<'_>, len: usize, work: impl FnOnce() -> T + Send) -> T {
19
+ if len >= GIL_RELEASE_MIN {
20
+ py.detach(work)
21
+ } else {
22
+ work()
23
+ }
24
+ }
25
+
26
+ fn read_buffer(value: &Bound<'_, PyAny>) -> PyResult<Vec<u8>> {
27
+ let buffer = PyUntypedBuffer::get(value)?;
28
+ if !buffer.is_c_contiguous() {
29
+ return Err(PyBufferError::new_err("Buffer must be contiguous"));
30
+ }
31
+ let len = buffer.len_bytes();
32
+ if len == 0 {
33
+ return Ok(Vec::new());
34
+ }
35
+ let bytes = unsafe { slice::from_raw_parts(buffer.buf_ptr().cast::<u8>(), len) };
36
+ Ok(bytes.to_vec())
37
+ }
38
+
39
+ fn write_buffer(value: &Bound<'_, PyAny>, bytes: &[u8]) -> PyResult<()> {
40
+ let buffer = PyUntypedBuffer::get(value)?;
41
+ if !buffer.is_c_contiguous() {
42
+ return Err(PyBufferError::new_err("Buffer must be contiguous"));
43
+ }
44
+ if !buffer.readonly() && buffer.len_bytes() == bytes.len() {
45
+ unsafe {
46
+ std::ptr::copy_nonoverlapping(
47
+ bytes.as_ptr(),
48
+ buffer.buf_ptr().cast::<u8>(),
49
+ bytes.len(),
50
+ );
51
+ }
52
+ }
53
+ Ok(())
54
+ }
55
+
56
+ #[allow(clippy::manual_is_multiple_of)]
57
+ fn check_block_inputs(data: &[u8], key: &[u8], iv: &[u8], iv_size: usize) -> PyResult<()> {
58
+ if data.is_empty() {
59
+ return Err(PyValueError::new_err("Data must not be empty"));
60
+ }
61
+ if data.len() % 16 != 0 {
62
+ return Err(PyValueError::new_err(
63
+ "Data size must match a multiple of 16 bytes",
64
+ ));
65
+ }
66
+ if key.len() != 32 {
67
+ return Err(PyValueError::new_err("Key size must be exactly 32 bytes"));
68
+ }
69
+ if iv.len() != iv_size {
70
+ return Err(PyValueError::new_err(format!(
71
+ "IV size must be exactly {iv_size} bytes"
72
+ )));
73
+ }
74
+ Ok(())
75
+ }
76
+
77
+ fn check_arg_count(args: &Bound<'_, PyTuple>, expected: usize) -> PyResult<()> {
78
+ if args.len() != expected {
79
+ return Err(PyTypeError::new_err(format!(
80
+ "function takes exactly {expected} arguments ({} given)",
81
+ args.len()
82
+ )));
83
+ }
84
+ Ok(())
85
+ }
86
+
87
+ struct IgeEncrypt<'a> {
88
+ data: &'a mut [u8],
89
+ iv: &'a [u8],
90
+ }
91
+
92
+ impl BlockSizeUser for IgeEncrypt<'_> {
93
+ type BlockSize = U16;
94
+ }
95
+
96
+ impl BlockCipherEncClosure for IgeEncrypt<'_> {
97
+ fn call<B: BlockCipherEncBackend<BlockSize = U16>>(self, backend: &B) {
98
+ let mut previous_cipher = u128::from_ne_bytes(self.iv[..16].try_into().unwrap());
99
+ let mut previous_plain = u128::from_ne_bytes(self.iv[16..].try_into().unwrap());
100
+
101
+ for chunk in self.data.chunks_mut(16) {
102
+ let mut plain_bytes = [0u8; 16];
103
+ plain_bytes.copy_from_slice(chunk);
104
+ let plain = u128::from_ne_bytes(plain_bytes);
105
+ let mut block = AesBlock::from((plain ^ previous_cipher).to_ne_bytes());
106
+ backend.encrypt_block_inplace(&mut block);
107
+ let encrypted = u128::from_ne_bytes(block.into());
108
+ let output = encrypted ^ previous_plain;
109
+ chunk.copy_from_slice(&output.to_ne_bytes());
110
+ previous_cipher = output;
111
+ previous_plain = plain;
112
+ }
113
+ }
114
+ }
115
+
116
+ struct IgeDecrypt<'a> {
117
+ data: &'a mut [u8],
118
+ iv: &'a [u8],
119
+ }
120
+
121
+ impl BlockSizeUser for IgeDecrypt<'_> {
122
+ type BlockSize = U16;
123
+ }
124
+
125
+ impl BlockCipherDecClosure for IgeDecrypt<'_> {
126
+ fn call<B: BlockCipherDecBackend<BlockSize = U16>>(self, backend: &B) {
127
+ let mut previous_cipher = u128::from_ne_bytes(self.iv[16..].try_into().unwrap());
128
+ let mut previous_plain = u128::from_ne_bytes(self.iv[..16].try_into().unwrap());
129
+
130
+ for chunk in self.data.chunks_mut(16) {
131
+ let mut cipher_bytes = [0u8; 16];
132
+ cipher_bytes.copy_from_slice(chunk);
133
+ let cipher = u128::from_ne_bytes(cipher_bytes);
134
+ let mut block = AesBlock::from((cipher ^ previous_cipher).to_ne_bytes());
135
+ backend.decrypt_block_inplace(&mut block);
136
+ let decrypted = u128::from_ne_bytes(block.into()) ^ previous_plain;
137
+ chunk.copy_from_slice(&decrypted.to_ne_bytes());
138
+ previous_cipher = decrypted;
139
+ previous_plain = cipher;
140
+ }
141
+ }
142
+ }
143
+
144
+ fn ige(mut output: Vec<u8>, key: &[u8], iv: &[u8], encrypt: bool) -> Vec<u8> {
145
+ if encrypt {
146
+ let cipher = Aes256Enc::new_from_slice(key).expect("validated AES-256 key");
147
+ cipher.encrypt_with_backend(IgeEncrypt {
148
+ data: &mut output,
149
+ iv,
150
+ });
151
+ } else {
152
+ let cipher = Aes256Dec::new_from_slice(key).expect("validated AES-256 key");
153
+ cipher.decrypt_with_backend(IgeDecrypt {
154
+ data: &mut output,
155
+ iv,
156
+ });
157
+ }
158
+ output
159
+ }
160
+
161
+ fn increment_counter(counter: &mut [u8; 16]) {
162
+ *counter = u128::from_be_bytes(*counter).wrapping_add(1).to_be_bytes();
163
+ }
164
+
165
+ struct CtrProcess<'a> {
166
+ data: &'a mut [u8],
167
+ counter: &'a mut [u8; 16],
168
+ state: &'a mut u8,
169
+ }
170
+
171
+ impl BlockSizeUser for CtrProcess<'_> {
172
+ type BlockSize = U16;
173
+ }
174
+
175
+ impl BlockCipherEncClosure for CtrProcess<'_> {
176
+ fn call<B: BlockCipherEncBackend<BlockSize = U16>>(self, backend: &B) {
177
+ let data = self.data;
178
+ let counter = self.counter;
179
+ let state = self.state;
180
+ let mut offset = 0;
181
+
182
+ if *state != 0 {
183
+ let mut stream = AesBlock::from(*counter);
184
+ backend.encrypt_block_inplace(&mut stream);
185
+ let stream: [u8; 16] = stream.into();
186
+ let take = (16 - *state as usize).min(data.len());
187
+ for index in 0..take {
188
+ data[index] ^= stream[*state as usize + index];
189
+ }
190
+ offset += take;
191
+ *state += take as u8;
192
+ if *state == 16 {
193
+ *state = 0;
194
+ increment_counter(counter);
195
+ }
196
+ if offset == data.len() {
197
+ return;
198
+ }
199
+ }
200
+
201
+ let parallel_width = B::ParBlocksSize::USIZE;
202
+ let mut groups = data[offset..].chunks_exact_mut(parallel_width * 16);
203
+ for group in &mut groups {
204
+ let mut streams: ParBlocks<B> = Default::default();
205
+ for stream in streams.iter_mut() {
206
+ *stream = AesBlock::from(*counter);
207
+ increment_counter(counter);
208
+ }
209
+ backend.encrypt_par_blocks_inplace(&mut streams);
210
+ for (block_index, stream) in streams.iter().enumerate() {
211
+ let stream: [u8; 16] = (*stream).into();
212
+ let start = block_index * 16;
213
+ for index in 0..16 {
214
+ group[start + index] ^= stream[index];
215
+ }
216
+ }
217
+ }
218
+
219
+ let remainder = groups.into_remainder();
220
+ for block in remainder.chunks_mut(16) {
221
+ let block_len = block.len();
222
+ let mut stream = AesBlock::from(*counter);
223
+ backend.encrypt_block_inplace(&mut stream);
224
+ let stream: [u8; 16] = stream.into();
225
+ for index in 0..block_len {
226
+ block[index] ^= stream[index];
227
+ }
228
+ if block_len == 16 {
229
+ increment_counter(counter);
230
+ } else {
231
+ *state = block_len as u8;
232
+ }
233
+ }
234
+ }
235
+ }
236
+
237
+ fn ctr(mut output: Vec<u8>, key: &[u8], iv: &mut [u8], state: &mut u8) -> Vec<u8> {
238
+ let mut counter = [0u8; 16];
239
+ counter.copy_from_slice(iv);
240
+ let cipher = Aes256Enc::new_from_slice(key).expect("validated AES-256 key");
241
+ cipher.encrypt_with_backend(CtrProcess {
242
+ data: &mut output,
243
+ counter: &mut counter,
244
+ state,
245
+ });
246
+ iv.copy_from_slice(&counter);
247
+ output
248
+ }
249
+
250
+ struct CbcEncrypt<'a> {
251
+ data: &'a mut [u8],
252
+ chain: &'a mut [u8; 16],
253
+ }
254
+
255
+ impl BlockSizeUser for CbcEncrypt<'_> {
256
+ type BlockSize = U16;
257
+ }
258
+
259
+ impl BlockCipherEncClosure for CbcEncrypt<'_> {
260
+ fn call<B: BlockCipherEncBackend<BlockSize = U16>>(self, backend: &B) {
261
+ let mut chain = u128::from_ne_bytes(*self.chain);
262
+ for chunk in self.data.chunks_mut(16) {
263
+ let mut plain_bytes = [0u8; 16];
264
+ plain_bytes.copy_from_slice(chunk);
265
+ let plain = u128::from_ne_bytes(plain_bytes);
266
+ let mut block = AesBlock::from((plain ^ chain).to_ne_bytes());
267
+ backend.encrypt_block_inplace(&mut block);
268
+ chain = u128::from_ne_bytes(block.into());
269
+ chunk.copy_from_slice(&chain.to_ne_bytes());
270
+ }
271
+ *self.chain = chain.to_ne_bytes();
272
+ }
273
+ }
274
+
275
+ struct CbcDecrypt<'a> {
276
+ data: &'a mut [u8],
277
+ chain: &'a mut [u8; 16],
278
+ }
279
+
280
+ impl BlockSizeUser for CbcDecrypt<'_> {
281
+ type BlockSize = U16;
282
+ }
283
+
284
+ impl BlockCipherDecClosure for CbcDecrypt<'_> {
285
+ fn call<B: BlockCipherDecBackend<BlockSize = U16>>(self, backend: &B) {
286
+ let mut chain = u128::from_ne_bytes(*self.chain);
287
+ for chunk in self.data.chunks_mut(16) {
288
+ let mut cipher_bytes = [0u8; 16];
289
+ cipher_bytes.copy_from_slice(chunk);
290
+ let cipher = u128::from_ne_bytes(cipher_bytes);
291
+ let mut block = AesBlock::from(cipher.to_ne_bytes());
292
+ backend.decrypt_block_inplace(&mut block);
293
+ let plain = u128::from_ne_bytes(block.into()) ^ chain;
294
+ chunk.copy_from_slice(&plain.to_ne_bytes());
295
+ chain = cipher;
296
+ }
297
+ *self.chain = chain.to_ne_bytes();
298
+ }
299
+ }
300
+
301
+ fn cbc(mut output: Vec<u8>, key: &[u8], iv: &mut [u8], encrypt: bool) -> Vec<u8> {
302
+ let mut chain = [0u8; 16];
303
+ chain.copy_from_slice(iv);
304
+ if encrypt {
305
+ let cipher = Aes256Enc::new_from_slice(key).expect("validated AES-256 key");
306
+ cipher.encrypt_with_backend(CbcEncrypt {
307
+ data: &mut output,
308
+ chain: &mut chain,
309
+ });
310
+ } else {
311
+ let cipher = Aes256Dec::new_from_slice(key).expect("validated AES-256 key");
312
+ cipher.decrypt_with_backend(CbcDecrypt {
313
+ data: &mut output,
314
+ chain: &mut chain,
315
+ });
316
+ }
317
+ iv.copy_from_slice(&chain);
318
+ output
319
+ }
320
+
321
+ fn ige_call(
322
+ py: Python<'_>,
323
+ data: Bound<'_, PyAny>,
324
+ key: Bound<'_, PyAny>,
325
+ iv: Bound<'_, PyAny>,
326
+ encrypt: bool,
327
+ ) -> PyResult<Py<PyBytes>> {
328
+ let data = read_buffer(&data)?;
329
+ let key = read_buffer(&key)?;
330
+ let iv = read_buffer(&iv)?;
331
+ check_block_inputs(&data, &key, &iv, 32)?;
332
+ let data_len = data.len();
333
+ let output = maybe_detach(py, data_len, move || ige(data, &key, &iv, encrypt));
334
+ Ok(PyBytes::new(py, &output).unbind())
335
+ }
336
+
337
+ #[pyfunction(signature = (*args))]
338
+ fn ige256_encrypt(py: Python<'_>, args: Bound<'_, PyTuple>) -> PyResult<Py<PyBytes>> {
339
+ check_arg_count(&args, 3)?;
340
+ ige_call(
341
+ py,
342
+ args.get_item(0)?,
343
+ args.get_item(1)?,
344
+ args.get_item(2)?,
345
+ true,
346
+ )
347
+ }
348
+
349
+ #[pyfunction(signature = (*args))]
350
+ fn ige256_decrypt(py: Python<'_>, args: Bound<'_, PyTuple>) -> PyResult<Py<PyBytes>> {
351
+ check_arg_count(&args, 3)?;
352
+ ige_call(
353
+ py,
354
+ args.get_item(0)?,
355
+ args.get_item(1)?,
356
+ args.get_item(2)?,
357
+ false,
358
+ )
359
+ }
360
+
361
+ fn ctr_call(
362
+ py: Python<'_>,
363
+ data: Bound<'_, PyAny>,
364
+ key: Bound<'_, PyAny>,
365
+ iv: Bound<'_, PyAny>,
366
+ state: Bound<'_, PyAny>,
367
+ ) -> PyResult<Py<PyBytes>> {
368
+ let data_bytes = read_buffer(&data)?;
369
+ let key_bytes = read_buffer(&key)?;
370
+ let mut iv_bytes = read_buffer(&iv)?;
371
+ let state_bytes = read_buffer(&state)?;
372
+ if data_bytes.is_empty() {
373
+ return Err(PyValueError::new_err("Data must not be empty"));
374
+ }
375
+ if key_bytes.len() != 32 {
376
+ return Err(PyValueError::new_err("Key size must be exactly 32 bytes"));
377
+ }
378
+ if iv_bytes.len() != 16 {
379
+ return Err(PyValueError::new_err("IV size must be exactly 16 bytes"));
380
+ }
381
+ if state_bytes.len() != 1 {
382
+ return Err(PyValueError::new_err("State size must be exactly 1 byte"));
383
+ }
384
+ let mut state_byte = state_bytes[0];
385
+ if state_byte > 15 {
386
+ return Err(PyValueError::new_err(
387
+ "State value must be in the range [0, 15]",
388
+ ));
389
+ }
390
+
391
+ let data_len = data_bytes.len();
392
+ let (output, iv_bytes, state_byte) = maybe_detach(py, data_len, move || {
393
+ let output = ctr(data_bytes, &key_bytes, &mut iv_bytes, &mut state_byte);
394
+ (output, iv_bytes, state_byte)
395
+ });
396
+ write_buffer(&iv, &iv_bytes)?;
397
+ write_buffer(&state, &[state_byte])?;
398
+ Ok(PyBytes::new(py, &output).unbind())
399
+ }
400
+
401
+ #[pyfunction]
402
+ #[pyo3(signature = (*args))]
403
+ fn ctr256_encrypt(py: Python<'_>, args: Bound<'_, PyTuple>) -> PyResult<Py<PyBytes>> {
404
+ check_arg_count(&args, 4)?;
405
+ ctr_call(
406
+ py,
407
+ args.get_item(0)?,
408
+ args.get_item(1)?,
409
+ args.get_item(2)?,
410
+ args.get_item(3)?,
411
+ )
412
+ }
413
+
414
+ #[pyfunction(signature = (*args))]
415
+ fn ctr256_decrypt(py: Python<'_>, args: Bound<'_, PyTuple>) -> PyResult<Py<PyBytes>> {
416
+ check_arg_count(&args, 4)?;
417
+ ctr_call(
418
+ py,
419
+ args.get_item(0)?,
420
+ args.get_item(1)?,
421
+ args.get_item(2)?,
422
+ args.get_item(3)?,
423
+ )
424
+ }
425
+
426
+ fn cbc_call(
427
+ py: Python<'_>,
428
+ data: Bound<'_, PyAny>,
429
+ key: Bound<'_, PyAny>,
430
+ iv: Bound<'_, PyAny>,
431
+ encrypt: bool,
432
+ ) -> PyResult<Py<PyBytes>> {
433
+ let data_bytes = read_buffer(&data)?;
434
+ let key_bytes = read_buffer(&key)?;
435
+ let mut iv_bytes = read_buffer(&iv)?;
436
+ check_block_inputs(&data_bytes, &key_bytes, &iv_bytes, 16)?;
437
+ let data_len = data_bytes.len();
438
+ let (output, iv_bytes) = maybe_detach(py, data_len, move || {
439
+ let output = cbc(data_bytes, &key_bytes, &mut iv_bytes, encrypt);
440
+ (output, iv_bytes)
441
+ });
442
+ write_buffer(&iv, &iv_bytes)?;
443
+ Ok(PyBytes::new(py, &output).unbind())
444
+ }
445
+
446
+ #[pyfunction(signature = (*args))]
447
+ fn cbc256_encrypt(py: Python<'_>, args: Bound<'_, PyTuple>) -> PyResult<Py<PyBytes>> {
448
+ check_arg_count(&args, 3)?;
449
+ cbc_call(
450
+ py,
451
+ args.get_item(0)?,
452
+ args.get_item(1)?,
453
+ args.get_item(2)?,
454
+ true,
455
+ )
456
+ }
457
+
458
+ #[pyfunction(signature = (*args))]
459
+ fn cbc256_decrypt(py: Python<'_>, args: Bound<'_, PyTuple>) -> PyResult<Py<PyBytes>> {
460
+ check_arg_count(&args, 3)?;
461
+ cbc_call(
462
+ py,
463
+ args.get_item(0)?,
464
+ args.get_item(1)?,
465
+ args.get_item(2)?,
466
+ false,
467
+ )
468
+ }
469
+
470
+ #[pymodule]
471
+ fn kuricrypt(module: &Bound<'_, PyModule>) -> PyResult<()> {
472
+ module.add_function(wrap_pyfunction!(ige256_encrypt, module)?)?;
473
+ module.add_function(wrap_pyfunction!(ige256_decrypt, module)?)?;
474
+ module.add_function(wrap_pyfunction!(ctr256_encrypt, module)?)?;
475
+ module.add_function(wrap_pyfunction!(ctr256_decrypt, module)?)?;
476
+ module.add_function(wrap_pyfunction!(cbc256_encrypt, module)?)?;
477
+ module.add_function(wrap_pyfunction!(cbc256_decrypt, module)?)?;
478
+ Ok(())
479
+ }
@@ -0,0 +1,82 @@
1
+ from array import array
2
+ import unittest
3
+ from typing import Any, Callable
4
+
5
+ import kuricrypt
6
+
7
+ KEY = bytes.fromhex(
8
+ "603deb1015ca71be2b73aef0857d7781"
9
+ "1f352c073b6108d72d9810a30914dff4"
10
+ )
11
+
12
+
13
+ class TestKuricryptApi(unittest.TestCase):
14
+ def test_cbc_nist_vector_and_mutable_iv(self):
15
+ iv = bytearray.fromhex("000102030405060708090a0b0c0d0e0f")
16
+ plaintext = bytes.fromhex("6bc1bee22e409f96e93d7e117393172a")
17
+ ciphertext = bytes.fromhex("f58c4c04d6e5f1ba779eabfb5f7bfbd6")
18
+
19
+ self.assertEqual(kuricrypt.cbc256_encrypt(plaintext, KEY, iv), ciphertext)
20
+ self.assertEqual(iv, ciphertext)
21
+
22
+ decrypt_iv = bytearray.fromhex("000102030405060708090a0b0c0d0e0f")
23
+ self.assertEqual(kuricrypt.cbc256_decrypt(ciphertext, KEY, decrypt_iv), plaintext)
24
+ self.assertEqual(decrypt_iv, ciphertext)
25
+
26
+ def test_ctr_nist_vector_and_stream_state(self):
27
+ iv = bytearray.fromhex("f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff")
28
+ state = bytearray([0])
29
+ plaintext = bytes.fromhex("6bc1bee22e409f96e93d7e117393172a")
30
+ ciphertext = bytes.fromhex("601ec313775789a5b7a7f504bbf3d228")
31
+
32
+ self.assertEqual(kuricrypt.ctr256_encrypt(plaintext, KEY, iv, state), ciphertext)
33
+ self.assertEqual(iv, bytes.fromhex("f0f1f2f3f4f5f6f7f8f9fafbfcfdff00"))
34
+ self.assertEqual(state, bytearray([0]))
35
+
36
+ iv = bytearray.fromhex("f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff")
37
+ state = bytearray([0])
38
+ chunks = [plaintext[:5], plaintext[5:11], plaintext[11:]]
39
+ encrypted = b"".join(
40
+ kuricrypt.ctr256_encrypt(chunk, KEY, iv, state) for chunk in chunks
41
+ )
42
+
43
+ self.assertEqual(encrypted, ciphertext)
44
+ self.assertEqual(iv, bytes.fromhex("f0f1f2f3f4f5f6f7f8f9fafbfcfdff00"))
45
+ self.assertEqual(state, bytearray([0]))
46
+
47
+ def test_ige_round_trip(self):
48
+ data = bytes(range(64))
49
+ iv = bytes(range(32))
50
+ encrypted = kuricrypt.ige256_encrypt(data, KEY, iv)
51
+
52
+ self.assertNotEqual(encrypted, data)
53
+ self.assertEqual(kuricrypt.ige256_decrypt(encrypted, KEY, iv), data)
54
+
55
+ def test_typed_contiguous_buffers(self):
56
+ data = array("I", range(4))
57
+ key = array("I", range(8))
58
+ iv = array("I", range(8))
59
+
60
+ actual = kuricrypt.ige256_encrypt(memoryview(data), memoryview(key), memoryview(iv))
61
+ expected = kuricrypt.ige256_encrypt(data.tobytes(), key.tobytes(), iv.tobytes())
62
+ self.assertEqual(actual, expected)
63
+
64
+ def test_validation_errors(self):
65
+ cases: list[tuple[Callable[..., bytes], tuple[Any, ...], str]] = [
66
+ (kuricrypt.ige256_encrypt, (b"", KEY, bytes(32)), "Data must not be empty"),
67
+ (kuricrypt.ige256_encrypt, (bytes(15), KEY, bytes(32)), "multiple of 16 bytes"),
68
+ (
69
+ kuricrypt.cbc256_encrypt,
70
+ (bytes(16), bytes(31), bytes(16)),
71
+ "Key size must be exactly 32 bytes",
72
+ ),
73
+ (
74
+ kuricrypt.ctr256_encrypt,
75
+ (b"x", KEY, bytes(16), bytes([16])),
76
+ r"range \[0, 15\]",
77
+ ),
78
+ ]
79
+ for function, args, message in cases:
80
+ with self.subTest(message=message):
81
+ with self.assertRaisesRegex(ValueError, message):
82
+ function(*args)
@@ -0,0 +1,56 @@
1
+ from importlib import import_module
2
+ import unittest
3
+
4
+ import kuricrypt
5
+
6
+ try:
7
+ tgcrypto = import_module("tgcrypto")
8
+ except ImportError:
9
+ tgcrypto = None
10
+
11
+
12
+ KEY = bytes.fromhex(
13
+ "603deb1015ca71be2b73aef0857d7781"
14
+ "1f352c073b6108d72d9810a30914dff4"
15
+ )
16
+
17
+
18
+ class TestTgcryptoCompatibility(unittest.TestCase):
19
+ @unittest.skipIf(tgcrypto is None, "tgcrypto is not installed")
20
+ def test_all_cipher_functions_match_tgcrypto(self):
21
+ data = bytes(range(256)) * 16
22
+ block_iv = bytes(range(32))
23
+ stream_iv = bytes(range(16))
24
+
25
+ for function_name in ("ige256_encrypt", "ige256_decrypt"):
26
+ with self.subTest(function=function_name):
27
+ reference = getattr(tgcrypto, function_name)(data, KEY, block_iv)
28
+ actual = getattr(kuricrypt, function_name)(data, KEY, block_iv)
29
+ self.assertEqual(actual, reference)
30
+
31
+ for function_name in ("cbc256_encrypt", "cbc256_decrypt"):
32
+ with self.subTest(function=function_name):
33
+ reference_iv = bytearray(stream_iv)
34
+ actual_iv = bytearray(stream_iv)
35
+ reference = getattr(tgcrypto, function_name)(data, KEY, reference_iv)
36
+ actual = getattr(kuricrypt, function_name)(data, KEY, actual_iv)
37
+ self.assertEqual(actual, reference)
38
+ self.assertEqual(actual_iv, reference_iv)
39
+
40
+ stream_data = data[:-3]
41
+ initial_state = bytearray([7])
42
+ for function_name in ("ctr256_encrypt", "ctr256_decrypt"):
43
+ with self.subTest(function=function_name):
44
+ reference_iv = bytearray(stream_iv)
45
+ actual_iv = bytearray(stream_iv)
46
+ reference_state = bytearray(initial_state)
47
+ actual_state = bytearray(initial_state)
48
+ reference = getattr(tgcrypto, function_name)(
49
+ stream_data, KEY, reference_iv, reference_state
50
+ )
51
+ actual = getattr(kuricrypt, function_name)(
52
+ stream_data, KEY, actual_iv, actual_state
53
+ )
54
+ self.assertEqual(actual, reference)
55
+ self.assertEqual(actual_iv, reference_iv)
56
+ self.assertEqual(actual_state, reference_state)