openbyd 0.0.1__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,200 @@
1
+ # This file is automatically @generated by Cargo.
2
+ # It is not intended for manual editing.
3
+ version = 4
4
+
5
+ [[package]]
6
+ name = "heck"
7
+ version = "0.5.0"
8
+ source = "registry+https://github.com/rust-lang/crates.io-index"
9
+ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
10
+
11
+ [[package]]
12
+ name = "itoa"
13
+ version = "1.0.19"
14
+ source = "registry+https://github.com/rust-lang/crates.io-index"
15
+ checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
16
+
17
+ [[package]]
18
+ name = "libc"
19
+ version = "0.2.191"
20
+ source = "registry+https://github.com/rust-lang/crates.io-index"
21
+ checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
22
+
23
+ [[package]]
24
+ name = "memchr"
25
+ version = "2.8.3"
26
+ source = "registry+https://github.com/rust-lang/crates.io-index"
27
+ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
28
+
29
+ [[package]]
30
+ name = "once_cell"
31
+ version = "1.21.4"
32
+ source = "registry+https://github.com/rust-lang/crates.io-index"
33
+ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
34
+
35
+ [[package]]
36
+ name = "openbyd-crypto"
37
+ version = "0.0.1"
38
+ dependencies = [
39
+ "serde_json",
40
+ ]
41
+
42
+ [[package]]
43
+ name = "openbyd-py"
44
+ version = "0.0.1"
45
+ dependencies = [
46
+ "openbyd-crypto",
47
+ "pyo3",
48
+ ]
49
+
50
+ [[package]]
51
+ name = "portable-atomic"
52
+ version = "1.15.0"
53
+ source = "registry+https://github.com/rust-lang/crates.io-index"
54
+ checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
55
+
56
+ [[package]]
57
+ name = "proc-macro2"
58
+ version = "1.0.107"
59
+ source = "registry+https://github.com/rust-lang/crates.io-index"
60
+ checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
61
+ dependencies = [
62
+ "unicode-ident",
63
+ ]
64
+
65
+ [[package]]
66
+ name = "pyo3"
67
+ version = "0.30.1"
68
+ source = "registry+https://github.com/rust-lang/crates.io-index"
69
+ checksum = "229ca13b8a15bb0d1487b81ab975bfcd97513416499a8312011b6036e42e0de4"
70
+ dependencies = [
71
+ "libc",
72
+ "once_cell",
73
+ "portable-atomic",
74
+ "pyo3-build-config",
75
+ "pyo3-ffi",
76
+ "pyo3-macros",
77
+ ]
78
+
79
+ [[package]]
80
+ name = "pyo3-build-config"
81
+ version = "0.30.1"
82
+ source = "registry+https://github.com/rust-lang/crates.io-index"
83
+ checksum = "70130e2b6dd1ee589a8788026a429561ca5c40fa7a2fa7914c2282eddae24700"
84
+ dependencies = [
85
+ "target-lexicon",
86
+ ]
87
+
88
+ [[package]]
89
+ name = "pyo3-ffi"
90
+ version = "0.30.1"
91
+ source = "registry+https://github.com/rust-lang/crates.io-index"
92
+ checksum = "5e7ff73c555c286d212d4ce7e5fbda845a973c4f61bd5f160f5f2c3c2a04d1c4"
93
+ dependencies = [
94
+ "libc",
95
+ "pyo3-build-config",
96
+ ]
97
+
98
+ [[package]]
99
+ name = "pyo3-macros"
100
+ version = "0.30.1"
101
+ source = "registry+https://github.com/rust-lang/crates.io-index"
102
+ checksum = "c46d2e5862c7bb8207e3b639f713dda3c499933444784154c11d013c5a691b60"
103
+ dependencies = [
104
+ "proc-macro2",
105
+ "pyo3-macros-backend",
106
+ "quote",
107
+ "syn",
108
+ ]
109
+
110
+ [[package]]
111
+ name = "pyo3-macros-backend"
112
+ version = "0.30.1"
113
+ source = "registry+https://github.com/rust-lang/crates.io-index"
114
+ checksum = "38b89f066f2ae72a2aef52d1537ca2fcd104440ebfadee06e97aa90738a25b9b"
115
+ dependencies = [
116
+ "heck",
117
+ "proc-macro2",
118
+ "quote",
119
+ "syn",
120
+ ]
121
+
122
+ [[package]]
123
+ name = "quote"
124
+ version = "1.0.47"
125
+ source = "registry+https://github.com/rust-lang/crates.io-index"
126
+ checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
127
+ dependencies = [
128
+ "proc-macro2",
129
+ ]
130
+
131
+ [[package]]
132
+ name = "serde"
133
+ version = "1.0.229"
134
+ source = "registry+https://github.com/rust-lang/crates.io-index"
135
+ checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
136
+ dependencies = [
137
+ "serde_core",
138
+ ]
139
+
140
+ [[package]]
141
+ name = "serde_core"
142
+ version = "1.0.229"
143
+ source = "registry+https://github.com/rust-lang/crates.io-index"
144
+ checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
145
+ dependencies = [
146
+ "serde_derive",
147
+ ]
148
+
149
+ [[package]]
150
+ name = "serde_derive"
151
+ version = "1.0.229"
152
+ source = "registry+https://github.com/rust-lang/crates.io-index"
153
+ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
154
+ dependencies = [
155
+ "proc-macro2",
156
+ "quote",
157
+ "syn",
158
+ ]
159
+
160
+ [[package]]
161
+ name = "serde_json"
162
+ version = "1.0.154"
163
+ source = "registry+https://github.com/rust-lang/crates.io-index"
164
+ checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
165
+ dependencies = [
166
+ "itoa",
167
+ "memchr",
168
+ "serde",
169
+ "serde_core",
170
+ "zmij",
171
+ ]
172
+
173
+ [[package]]
174
+ name = "syn"
175
+ version = "3.0.10"
176
+ source = "registry+https://github.com/rust-lang/crates.io-index"
177
+ checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
178
+ dependencies = [
179
+ "proc-macro2",
180
+ "quote",
181
+ "unicode-ident",
182
+ ]
183
+
184
+ [[package]]
185
+ name = "target-lexicon"
186
+ version = "0.13.6"
187
+ source = "registry+https://github.com/rust-lang/crates.io-index"
188
+ checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da"
189
+
190
+ [[package]]
191
+ name = "unicode-ident"
192
+ version = "1.0.27"
193
+ source = "registry+https://github.com/rust-lang/crates.io-index"
194
+ checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
195
+
196
+ [[package]]
197
+ name = "zmij"
198
+ version = "1.0.23"
199
+ source = "registry+https://github.com/rust-lang/crates.io-index"
200
+ checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
@@ -0,0 +1,21 @@
1
+ [workspace]
2
+ resolver = "3"
3
+ members = ["crates/openbyd-crypto", "crates/openbyd-py"]
4
+
5
+ [workspace.package]
6
+ version = "0.0.1"
7
+ edition = "2024"
8
+ license = "MIT"
9
+ repository = "https://github.com/Pho3niX90/openbyd"
10
+
11
+ [workspace.lints.rust]
12
+ unsafe_code = "forbid"
13
+ missing_docs = "warn"
14
+
15
+ [workspace.lints.clippy]
16
+ all = { level = "warn", priority = -1 }
17
+
18
+ [profile.release]
19
+ lto = "thin"
20
+ codegen-units = 1
21
+ strip = "symbols"
openbyd-0.0.1/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Joel Kåberg
4
+ Copyright (c) 2026 openbyd contributors
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
openbyd-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,106 @@
1
+ Metadata-Version: 2.4
2
+ Name: openbyd
3
+ Version: 0.0.1
4
+ Classifier: Development Status :: 2 - Pre-Alpha
5
+ Classifier: Intended Audience :: Developers
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: Programming Language :: Python :: 3.11
8
+ Classifier: Programming Language :: Python :: 3.12
9
+ Classifier: Programming Language :: Python :: 3.13
10
+ Classifier: Programming Language :: Rust
11
+ Classifier: Typing :: Typed
12
+ Requires-Dist: pytest>=8 ; extra == 'dev'
13
+ Provides-Extra: dev
14
+ License-File: LICENSE
15
+ Summary: Unofficial client for the BYD overseas app API, with a Rust core
16
+ Keywords: byd,ev,vehicle,telemetry
17
+ License-Expression: MIT
18
+ Requires-Python: >=3.11
19
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
20
+ Project-URL: Repository, https://github.com/Pho3niX90/openbyd
21
+ Project-URL: Upstream, https://github.com/jkaberg/pyBYD
22
+
23
+ # openbyd
24
+
25
+ An unofficial client for the BYD overseas app API, written in Rust, with Python bindings.
26
+
27
+ openbyd is a port of [pyBYD](https://github.com/jkaberg/pyBYD). pyBYD stays the reference: every piece ported here is tested against it, and the pyBYD commit openbyd currently matches is recorded in `parity/UPSTREAM_COMMIT`.
28
+
29
+ This project is not affiliated with, endorsed by or supported by BYD.
30
+
31
+ ## Status
32
+
33
+ Early. What exists today:
34
+
35
+ | Part | State |
36
+ |---|---|
37
+ | Envelope cipher (`openbyd-crypto`) | Done, matches pyBYD byte for byte |
38
+ | Python package (`openbyd`) | Cipher only |
39
+ | Drop-in speed-up for pyBYD | Done, see below |
40
+ | Signing, models, HTTP client, MQTT, commands | Not started |
41
+
42
+ ## Speed up pyBYD today
43
+
44
+ pyBYD encrypts every request and decrypts every reply with a table-driven cipher written in Python. A 2 KB request and reply cost it about 130 ms of CPU, during which the event loop is blocked. openbyd does the same work in under half a millisecond and releases the GIL while it runs.
45
+
46
+ ```python
47
+ from openbyd import pybyd_accel
48
+
49
+ pybyd_accel.install() # call once, before creating a BydClient
50
+ ```
51
+
52
+ `install()` returns `True` when pyBYD is using the Rust cipher. It first checks that pyBYD's tables are the ones built into openbyd and that both ciphers give the same answer on a self-test. If either check fails it changes nothing and returns `False`. A client given its own table file keeps using pyBYD's code.
53
+
54
+ ## Use the cipher directly
55
+
56
+ Python:
57
+
58
+ ```python
59
+ import openbyd
60
+
61
+ envelope = openbyd.encode_envelope('{"hello":"world"}')
62
+ plaintext = openbyd.decode_envelope(envelope)
63
+ ```
64
+
65
+ Rust:
66
+
67
+ ```rust
68
+ let envelope = openbyd_crypto::encode_envelope(br#"{"hello":"world"}"#);
69
+ let plaintext = openbyd_crypto::decode_envelope(&envelope)?;
70
+ ```
71
+
72
+ ## Build from source
73
+
74
+ You need a Rust toolchain and Python 3.11 or newer.
75
+
76
+ ```sh
77
+ python -m venv .venv
78
+ .venv/bin/pip install maturin pytest
79
+ .venv/bin/maturin develop --release
80
+ ```
81
+
82
+ ## Tests
83
+
84
+ ```sh
85
+ cargo test -p openbyd-crypto # Rust, against vectors recorded from pyBYD
86
+ pytest # Python bindings, same vectors
87
+ ```
88
+
89
+ With pyBYD installed, `pytest` also compares openbyd against it on random inputs, and checks that the recorded vectors are still what pyBYD produces:
90
+
91
+ ```sh
92
+ pip install "pybyd @ git+https://github.com/jkaberg/pyBYD@$(cat parity/UPSTREAM_COMMIT)"
93
+ pytest
94
+ ```
95
+
96
+ To follow upstream, change `parity/UPSTREAM_COMMIT`, reinstall pyBYD, and run `python parity/gen_bangcle_vectors.py`. Any test that then fails marks behaviour that changed upstream.
97
+
98
+ ## Credits
99
+
100
+ - [pyBYD](https://github.com/jkaberg/pyBYD) by Joel Kåberg and contributors, which this project ports.
101
+ - [Niek/BYD-re](https://github.com/Niek/BYD-re), the reverse-engineering work pyBYD builds on.
102
+
103
+ ## Licence
104
+
105
+ MIT. See [LICENSE](LICENSE).
106
+
@@ -0,0 +1,83 @@
1
+ # openbyd
2
+
3
+ An unofficial client for the BYD overseas app API, written in Rust, with Python bindings.
4
+
5
+ openbyd is a port of [pyBYD](https://github.com/jkaberg/pyBYD). pyBYD stays the reference: every piece ported here is tested against it, and the pyBYD commit openbyd currently matches is recorded in `parity/UPSTREAM_COMMIT`.
6
+
7
+ This project is not affiliated with, endorsed by or supported by BYD.
8
+
9
+ ## Status
10
+
11
+ Early. What exists today:
12
+
13
+ | Part | State |
14
+ |---|---|
15
+ | Envelope cipher (`openbyd-crypto`) | Done, matches pyBYD byte for byte |
16
+ | Python package (`openbyd`) | Cipher only |
17
+ | Drop-in speed-up for pyBYD | Done, see below |
18
+ | Signing, models, HTTP client, MQTT, commands | Not started |
19
+
20
+ ## Speed up pyBYD today
21
+
22
+ pyBYD encrypts every request and decrypts every reply with a table-driven cipher written in Python. A 2 KB request and reply cost it about 130 ms of CPU, during which the event loop is blocked. openbyd does the same work in under half a millisecond and releases the GIL while it runs.
23
+
24
+ ```python
25
+ from openbyd import pybyd_accel
26
+
27
+ pybyd_accel.install() # call once, before creating a BydClient
28
+ ```
29
+
30
+ `install()` returns `True` when pyBYD is using the Rust cipher. It first checks that pyBYD's tables are the ones built into openbyd and that both ciphers give the same answer on a self-test. If either check fails it changes nothing and returns `False`. A client given its own table file keeps using pyBYD's code.
31
+
32
+ ## Use the cipher directly
33
+
34
+ Python:
35
+
36
+ ```python
37
+ import openbyd
38
+
39
+ envelope = openbyd.encode_envelope('{"hello":"world"}')
40
+ plaintext = openbyd.decode_envelope(envelope)
41
+ ```
42
+
43
+ Rust:
44
+
45
+ ```rust
46
+ let envelope = openbyd_crypto::encode_envelope(br#"{"hello":"world"}"#);
47
+ let plaintext = openbyd_crypto::decode_envelope(&envelope)?;
48
+ ```
49
+
50
+ ## Build from source
51
+
52
+ You need a Rust toolchain and Python 3.11 or newer.
53
+
54
+ ```sh
55
+ python -m venv .venv
56
+ .venv/bin/pip install maturin pytest
57
+ .venv/bin/maturin develop --release
58
+ ```
59
+
60
+ ## Tests
61
+
62
+ ```sh
63
+ cargo test -p openbyd-crypto # Rust, against vectors recorded from pyBYD
64
+ pytest # Python bindings, same vectors
65
+ ```
66
+
67
+ With pyBYD installed, `pytest` also compares openbyd against it on random inputs, and checks that the recorded vectors are still what pyBYD produces:
68
+
69
+ ```sh
70
+ pip install "pybyd @ git+https://github.com/jkaberg/pyBYD@$(cat parity/UPSTREAM_COMMIT)"
71
+ pytest
72
+ ```
73
+
74
+ To follow upstream, change `parity/UPSTREAM_COMMIT`, reinstall pyBYD, and run `python parity/gen_bangcle_vectors.py`. Any test that then fails marks behaviour that changed upstream.
75
+
76
+ ## Credits
77
+
78
+ - [pyBYD](https://github.com/jkaberg/pyBYD) by Joel Kåberg and contributors, which this project ports.
79
+ - [Niek/BYD-re](https://github.com/Niek/BYD-re), the reverse-engineering work pyBYD builds on.
80
+
81
+ ## Licence
82
+
83
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,17 @@
1
+ [package]
2
+ name = "openbyd-crypto"
3
+ description = "Cipher and envelope primitives for the BYD overseas app API"
4
+ version.workspace = true
5
+ edition.workspace = true
6
+ license.workspace = true
7
+ repository.workspace = true
8
+ readme = "README.md"
9
+ include = ["src/**", "data/bangcle_tables.bin", "tests/**", "Cargo.toml"]
10
+
11
+ [dependencies]
12
+
13
+ [dev-dependencies]
14
+ serde_json = "1"
15
+
16
+ [lints]
17
+ workspace = true
@@ -0,0 +1,83 @@
1
+ # openbyd
2
+
3
+ An unofficial client for the BYD overseas app API, written in Rust, with Python bindings.
4
+
5
+ openbyd is a port of [pyBYD](https://github.com/jkaberg/pyBYD). pyBYD stays the reference: every piece ported here is tested against it, and the pyBYD commit openbyd currently matches is recorded in `parity/UPSTREAM_COMMIT`.
6
+
7
+ This project is not affiliated with, endorsed by or supported by BYD.
8
+
9
+ ## Status
10
+
11
+ Early. What exists today:
12
+
13
+ | Part | State |
14
+ |---|---|
15
+ | Envelope cipher (`openbyd-crypto`) | Done, matches pyBYD byte for byte |
16
+ | Python package (`openbyd`) | Cipher only |
17
+ | Drop-in speed-up for pyBYD | Done, see below |
18
+ | Signing, models, HTTP client, MQTT, commands | Not started |
19
+
20
+ ## Speed up pyBYD today
21
+
22
+ pyBYD encrypts every request and decrypts every reply with a table-driven cipher written in Python. A 2 KB request and reply cost it about 130 ms of CPU, during which the event loop is blocked. openbyd does the same work in under half a millisecond and releases the GIL while it runs.
23
+
24
+ ```python
25
+ from openbyd import pybyd_accel
26
+
27
+ pybyd_accel.install() # call once, before creating a BydClient
28
+ ```
29
+
30
+ `install()` returns `True` when pyBYD is using the Rust cipher. It first checks that pyBYD's tables are the ones built into openbyd and that both ciphers give the same answer on a self-test. If either check fails it changes nothing and returns `False`. A client given its own table file keeps using pyBYD's code.
31
+
32
+ ## Use the cipher directly
33
+
34
+ Python:
35
+
36
+ ```python
37
+ import openbyd
38
+
39
+ envelope = openbyd.encode_envelope('{"hello":"world"}')
40
+ plaintext = openbyd.decode_envelope(envelope)
41
+ ```
42
+
43
+ Rust:
44
+
45
+ ```rust
46
+ let envelope = openbyd_crypto::encode_envelope(br#"{"hello":"world"}"#);
47
+ let plaintext = openbyd_crypto::decode_envelope(&envelope)?;
48
+ ```
49
+
50
+ ## Build from source
51
+
52
+ You need a Rust toolchain and Python 3.11 or newer.
53
+
54
+ ```sh
55
+ python -m venv .venv
56
+ .venv/bin/pip install maturin pytest
57
+ .venv/bin/maturin develop --release
58
+ ```
59
+
60
+ ## Tests
61
+
62
+ ```sh
63
+ cargo test -p openbyd-crypto # Rust, against vectors recorded from pyBYD
64
+ pytest # Python bindings, same vectors
65
+ ```
66
+
67
+ With pyBYD installed, `pytest` also compares openbyd against it on random inputs, and checks that the recorded vectors are still what pyBYD produces:
68
+
69
+ ```sh
70
+ pip install "pybyd @ git+https://github.com/jkaberg/pyBYD@$(cat parity/UPSTREAM_COMMIT)"
71
+ pytest
72
+ ```
73
+
74
+ To follow upstream, change `parity/UPSTREAM_COMMIT`, reinstall pyBYD, and run `python parity/gen_bangcle_vectors.py`. Any test that then fails marks behaviour that changed upstream.
75
+
76
+ ## Credits
77
+
78
+ - [pyBYD](https://github.com/jkaberg/pyBYD) by Joel Kåberg and contributors, which this project ports.
79
+ - [Niek/BYD-re](https://github.com/Niek/BYD-re), the reverse-engineering work pyBYD builds on.
80
+
81
+ ## Licence
82
+
83
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,127 @@
1
+ //! Base64 with the same leniency as Python's `base64.b64decode`.
2
+ //!
3
+ //! pyBYD decodes envelopes with Python's default, non-validating decoder.
4
+ //! It skips characters outside the alphabet and stops at the first complete
5
+ //! padding, so this decoder does the same and accepts exactly what pyBYD
6
+ //! accepts.
7
+
8
+ const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
9
+ const PAD: u8 = b'=';
10
+
11
+ pub(crate) fn encode(data: &[u8]) -> String {
12
+ let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
13
+ for chunk in data.chunks(3) {
14
+ let bytes = [
15
+ chunk[0],
16
+ *chunk.get(1).unwrap_or(&0),
17
+ *chunk.get(2).unwrap_or(&0),
18
+ ];
19
+ let sextets = [
20
+ bytes[0] >> 2,
21
+ (bytes[0] & 0x03) << 4 | bytes[1] >> 4,
22
+ (bytes[1] & 0x0F) << 2 | bytes[2] >> 6,
23
+ bytes[2] & 0x3F,
24
+ ];
25
+ for (i, sextet) in sextets.iter().enumerate() {
26
+ if i <= chunk.len() {
27
+ out.push(char::from(ALPHABET[usize::from(*sextet)]));
28
+ } else {
29
+ out.push(char::from(PAD));
30
+ }
31
+ }
32
+ }
33
+ out
34
+ }
35
+
36
+ fn sextet(ch: u8) -> Option<u8> {
37
+ match ch {
38
+ b'A'..=b'Z' => Some(ch - b'A'),
39
+ b'a'..=b'z' => Some(ch - b'a' + 26),
40
+ b'0'..=b'9' => Some(ch - b'0' + 52),
41
+ b'+' => Some(62),
42
+ b'/' => Some(63),
43
+ _ => None,
44
+ }
45
+ }
46
+
47
+ pub(crate) fn decode_lenient(text: &[u8]) -> Result<Vec<u8>, &'static str> {
48
+ let mut out = Vec::with_capacity(text.len() / 4 * 3 + 3);
49
+ let mut position = 0u8;
50
+ let mut carry = 0u8;
51
+ let mut pads = 0u8;
52
+
53
+ for &ch in text {
54
+ if ch == PAD {
55
+ if position >= 2 {
56
+ pads += 1;
57
+ if position + pads >= 4 {
58
+ return Ok(out);
59
+ }
60
+ }
61
+ continue;
62
+ }
63
+ let Some(value) = sextet(ch) else { continue };
64
+ pads = 0;
65
+ match position {
66
+ 0 => carry = value,
67
+ 1 => {
68
+ out.push(carry << 2 | value >> 4);
69
+ carry = value & 0x0F;
70
+ }
71
+ 2 => {
72
+ out.push(carry << 4 | value >> 2);
73
+ carry = value & 0x03;
74
+ }
75
+ _ => out.push(carry << 6 | value),
76
+ }
77
+ position = (position + 1) & 3;
78
+ }
79
+
80
+ match position {
81
+ 0 => Ok(out),
82
+ 1 => Err("number of data characters cannot be 1 more than a multiple of 4"),
83
+ _ => Err("incorrect padding"),
84
+ }
85
+ }
86
+
87
+ #[cfg(test)]
88
+ mod tests {
89
+ use super::*;
90
+
91
+ #[test]
92
+ fn encodes_the_rfc_4648_examples() {
93
+ let cases = [
94
+ ("", ""),
95
+ ("f", "Zg=="),
96
+ ("fo", "Zm8="),
97
+ ("foo", "Zm9v"),
98
+ ("foob", "Zm9vYg=="),
99
+ ("fooba", "Zm9vYmE="),
100
+ ("foobar", "Zm9vYmFy"),
101
+ ];
102
+ for (plain, encoded) in cases {
103
+ assert_eq!(encode(plain.as_bytes()), encoded);
104
+ assert_eq!(
105
+ decode_lenient(encoded.as_bytes()).unwrap(),
106
+ plain.as_bytes()
107
+ );
108
+ }
109
+ }
110
+
111
+ #[test]
112
+ fn skips_characters_outside_the_alphabet() {
113
+ assert_eq!(decode_lenient(b"Zm9v!Ym*Fy").unwrap(), b"foobar");
114
+ }
115
+
116
+ #[test]
117
+ fn stops_at_complete_padding() {
118
+ assert_eq!(decode_lenient(b"Zg==Zm9v").unwrap(), b"f");
119
+ }
120
+
121
+ #[test]
122
+ fn rejects_incomplete_groups() {
123
+ assert!(decode_lenient(b"Z").is_err());
124
+ assert!(decode_lenient(b"Zg").is_err());
125
+ assert!(decode_lenient(b"Zg=").is_err());
126
+ }
127
+ }