Branch data Line data Source code
1 : : // SPDX-FileCopyrightText: 2025 KeePassXC Team <team@keepassxc.org>
2 : : // SPDX-FileCopyrightText: 2026 Anne Jan Brouwer
3 : : // SPDX-License-Identifier: GPL-3.0-or-later
4 : :
5 : : /**
6 : : * @file
7 : : * @brief Implements the Base32 codec: quantum-by-quantum decode and encode
8 : : * loops with the tail-shape table that fixes KeePassXC's mis-padded cases.
9 : : *
10 : : * Conforms to RFC 4648, see https://tools.ietf.org/html/rfc4648. Ported from
11 : : * KeePassXC `src/core/Base32.cpp`; the differences are documented at each
12 : : * site.
13 : : *
14 : : * @see base32.h
15 : : */
16 : :
17 : : #include "base32.h"
18 : :
19 : : #include <optional>
20 : : #include <string_view>
21 : :
22 : : namespace {
23 : :
24 : : /**
25 : : * @name Top-symbol masks
26 : : * Mask selecting the top 5 bits of an encode quantum of the given width; the
27 : : * encoder shifts it down 5 bits per output symbol. A full input group is 40
28 : : * bits; the short final group is widened to 10, 20, 25 or 35 bits.
29 : : * @{
30 : : */
31 : : constexpr quint64 MASK_40BIT = quint64{0xF8} << 32;
32 : : constexpr quint64 MASK_35BIT = quint64{0x7C0000000};
33 : : constexpr quint64 MASK_25BIT = quint64{0x1F00000};
34 : : constexpr quint64 MASK_20BIT = quint64{0xF8000};
35 : : constexpr quint64 MASK_10BIT = quint64{0x3E0};
36 : : /** @} */
37 : :
38 : : /** @brief The 32 RFC 4648 symbols, indexed by 5-bit value. */
39 : : constexpr std::string_view kAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
40 : : /** @brief Alphabet position of '2', the first digit symbol. */
41 : : constexpr quint8 ALPH_POS_2 = 26;
42 : :
43 : : /** @brief ASCII code of '2', the lowest digit symbol. */
44 : : constexpr quint8 ASCII_2 = static_cast<quint8>('2');
45 : : /** @brief ASCII code of '7', the highest digit symbol. */
46 : : constexpr quint8 ASCII_7 = static_cast<quint8>('7');
47 : : /** @brief ASCII code of 'A', the first letter symbol. */
48 : : constexpr quint8 ASCII_A = static_cast<quint8>('A');
49 : : /** @brief ASCII code of 'Z', the last upper-case letter symbol. */
50 : : constexpr quint8 ASCII_Z = static_cast<quint8>('Z');
51 : : /** @brief ASCII code of 'a'; lower case is folded onto upper case. */
52 : : constexpr quint8 ASCII_a = static_cast<quint8>('a');
53 : : /** @brief ASCII code of 'z', the last lower-case letter symbol. */
54 : : constexpr quint8 ASCII_z = static_cast<quint8>('z');
55 : : /** @brief ASCII code of '=', the padding character. */
56 : : constexpr quint8 ASCII_EQ = static_cast<quint8>('=');
57 : :
58 : : /**
59 : : * @brief Length of the trailing run of '=' characters.
60 : : *
61 : : * Stops at the first non-'=': counting every '=' in the last few positions
62 : : * would treat an interior one as padding, and removePadding() would then
63 : : * truncate real data.
64 : : * @param encodedData Base32 text.
65 : : * @return Number of trailing '=', at most 6.
66 : : */
67 : 495 : auto countPadding(const QByteArray &encodedData) -> int {
68 : : int nPads = 0;
69 : 495 : for (qsizetype i = encodedData.size() - 1;
70 [ + - + + ]: 897 : i >= 0 && i > encodedData.size() - 7; --i) {
71 [ + + ]: 870 : if (encodedData.at(i) != '=') {
72 : : break;
73 : : }
74 : 402 : ++nPads;
75 : : }
76 : 495 : return nPads;
77 : : }
78 : :
79 : : /**
80 : : * @brief What the padding says about the last quantum.
81 : : *
82 : : * A base32 encoder pads to a multiple of 8 with 0, 1, 3, 4 or 6 '='; any
83 : : * other count cannot come from one. KeePassXC fell through to "no special
84 : : * bytes" for 2, 5 and 7 and returned wrong-length data.
85 : : */
86 : : struct Tail {
87 : : int bytes = 0; ///< Bytes the final quantum carries; 0 for a full one.
88 : : int offset = 0; ///< Bits of the final quantum that are padding.
89 : : };
90 : :
91 : : /// The tail shape for @p nPads trailing '=', or nothing for a count no
92 : : /// encoder produces.
93 : 445 : auto tailShape(int nPads) -> std::optional<Tail> {
94 [ + + + + : 445 : switch (nPads) {
+ + ]
95 : 329 : case 0:
96 : 329 : return Tail{};
97 : 37 : case 1:
98 : 37 : return Tail{4, 3};
99 : 23 : case 3:
100 : 23 : return Tail{3, 1};
101 : 28 : case 4:
102 : 28 : return Tail{2, 4};
103 : 25 : case 6:
104 : 25 : return Tail{1, 2};
105 : 3 : default:
106 : 3 : return std::nullopt;
107 : : }
108 : : }
109 : :
110 : : /// The alphabet position of @p ch (upper or lower case, digits 2-7), or
111 : : /// nothing when it is not a base32 symbol.
112 : 17860 : auto symbolValue(quint8 ch) -> std::optional<quint8> {
113 [ + + ]: 17860 : if ((ASCII_A <= ch && ch <= ASCII_Z) || (ASCII_a <= ch && ch <= ASCII_z)) {
114 : : ch -= ASCII_A;
115 [ + + ]: 17013 : if (ch >= ALPH_POS_2) {
116 : : // Fold lower case onto the same alphabet positions as upper case.
117 : : ch -= ASCII_a - ASCII_A;
118 : : }
119 : 17013 : return ch;
120 : : }
121 [ + + ]: 847 : if (ASCII_2 <= ch && ch <= ASCII_7) {
122 : 846 : return static_cast<quint8>(ch - ASCII_2 + ALPH_POS_2);
123 : : }
124 : 1 : return std::nullopt;
125 : : }
126 : :
127 : : } // namespace
128 : :
129 : 564 : auto Base32::decode(const QByteArray &encodedData) -> QByteArray {
130 : : // Strict: a well-formed base32 string is always padded to a multiple of 8.
131 [ + + + + ]: 564 : if (encodedData.isEmpty() || encodedData.size() % 8 != 0) {
132 : 119 : return {};
133 : : }
134 : 445 : const int nPads = countPadding(encodedData);
135 : 445 : const std::optional<Tail> tail = tailShape(nPads);
136 [ + + ]: 445 : if (!tail) {
137 : 3 : return {};
138 : : }
139 : :
140 : 442 : const qsizetype nQuanta = encodedData.size() / 8;
141 : : const qsizetype nBytes =
142 [ + + ]: 442 : tail->bytes > 0 ? (nQuanta - 1) * 5 + tail->bytes : nQuanta * 5;
143 : :
144 : 442 : QByteArray data(nBytes, Qt::Uninitialized);
145 : : // Written through a raw pointer to avoid QByteArray's detach check on every
146 : : // subscript in the hot loop.
147 : : char *out = data.data();
148 : :
149 : : qsizetype i = 0;
150 : : qsizetype o = 0;
151 : : // Everything from the first '=' onward must be padding. Reuse the pad count
152 : : // computed above rather than scanning the tail a second time.
153 : 442 : const qsizetype firstPad = encodedData.size() - nPads;
154 : :
155 [ + + ]: 2719 : while (i < encodedData.size()) {
156 : : quint64 quantum = 0;
157 : : int nQuantumBytes = 5;
158 : :
159 [ + + ]: 20506 : for (int n = 0; n < 8; ++n) {
160 : 18229 : const auto ch = static_cast<quint8>(encodedData.at(i++));
161 [ + + ]: 18229 : if (ASCII_EQ == ch) {
162 [ + + ]: 369 : if (i - 1 < firstPad) {
163 : : // '=' before the trailing run is not padding, it is malformed input.
164 : 3 : return {};
165 : : }
166 [ + + ]: 367 : if (i == encodedData.size()) {
167 : : // Finished with the short final quantum.
168 : 112 : quantum >>= tail->offset;
169 : : nQuantumBytes = tail->bytes;
170 : : }
171 : 367 : continue;
172 : : }
173 : 17860 : const std::optional<quint8> value = symbolValue(ch);
174 [ + + ]: 17860 : if (!value) {
175 : 1 : return {};
176 : : }
177 : 17859 : quantum <<= 5;
178 : 17859 : quantum |= *value;
179 : : }
180 : :
181 : 2277 : const int offset = (nQuantumBytes - 1) * 8;
182 : 2277 : quint64 mask = quint64{0xFF} << offset;
183 [ + + ]: 13396 : for (int n = offset; n >= 0 && o < nBytes; n -= 8) {
184 : 11119 : out[o++] = static_cast<char>((quantum & mask) >> n);
185 : 11119 : mask >>= 8;
186 : : }
187 : : }
188 : :
189 : : return data;
190 : : }
191 : :
192 : 23 : auto Base32::encode(const QByteArray &data) -> QByteArray {
193 [ + + ]: 23 : if (data.isEmpty()) {
194 : 1 : return {};
195 : : }
196 : :
197 : 22 : const qsizetype nBits = data.size() * 8;
198 : 22 : const int rBits = static_cast<int>(nBits % 40); // in {0, 8, 16, 24, 32}
199 [ + + ]: 22 : const qsizetype nQuanta = nBits / 40 + (rBits > 0 ? 1 : 0);
200 : 22 : const qsizetype nBytes = nQuanta * 8;
201 : 22 : QByteArray encodedData(nBytes, Qt::Uninitialized);
202 : : // Raw pointer: see the note in decode().
203 : : char *out = encodedData.data();
204 : :
205 : : qsizetype i = 0;
206 : : qsizetype o = 0;
207 : : int n = 0;
208 : : quint64 mask = 0;
209 : : quint64 quantum = 0;
210 : :
211 : : // QByteArray elements are signed char: widening them directly (as KeePassXC
212 : : // does) sign-extends any byte >= 0x80 and the resulting high bits corrupt
213 : : // the neighbouring bytes of the quantum. Cast through quint8.
214 : : const auto byteAt = [&data](qsizetype index) -> quint64 {
215 : 221 : return static_cast<quint64>(static_cast<quint8>(data.at(index)));
216 : : };
217 : :
218 : : // 40 bits of input per input group.
219 [ + + ]: 58 : while (i + 5 <= data.size()) {
220 : : quantum = 0;
221 [ + + ]: 216 : for (n = 32; n >= 0; n -= 8) {
222 : 180 : quantum |= byteAt(i++) << n;
223 : : }
224 : :
225 : : mask = MASK_40BIT;
226 [ + + ]: 324 : for (n = 35; n >= 0; n -= 5) {
227 : 288 : out[o++] = kAlphabet[(quantum & mask) >> n];
228 : 288 : mask >>= 5;
229 : : }
230 : : }
231 : :
232 : : // Fewer than 40 bits of input in the final input group.
233 [ + + ]: 22 : if (i < data.size()) {
234 : : quantum = 0;
235 [ + + ]: 58 : for (n = rBits - 8; n >= 0; n -= 8) {
236 : 41 : quantum |= byteAt(i++) << n;
237 : : }
238 : :
239 [ + + + + ]: 17 : switch (rBits) {
240 : 5 : case 8: // expand to 10 bits
241 : 5 : quantum <<= 2;
242 : : mask = MASK_10BIT;
243 : : n = 5;
244 : 5 : break;
245 : 4 : case 16: // expand to 20 bits
246 : 4 : quantum <<= 4;
247 : : mask = MASK_20BIT;
248 : : n = 15;
249 : 4 : break;
250 : 4 : case 24: // expand to 25 bits
251 : 4 : quantum <<= 1;
252 : : mask = MASK_25BIT;
253 : : n = 20;
254 : 4 : break;
255 : 4 : default: // expand to 35 bits
256 : 4 : quantum <<= 3;
257 : : mask = MASK_35BIT;
258 : : n = 30;
259 : : }
260 : :
261 [ + + ]: 91 : while (n >= 0) {
262 : 74 : out[o++] = kAlphabet[(quantum & mask) >> n];
263 : 74 : mask >>= 5;
264 : 74 : n -= 5;
265 : : }
266 : :
267 : : // Add the pad characters.
268 [ + + ]: 79 : while (o < encodedData.size()) {
269 : 62 : out[o++] = '=';
270 : : }
271 : : }
272 : :
273 : : return encodedData;
274 : : }
275 : :
276 : 493 : auto Base32::addPadding(const QByteArray &encodedData) -> QByteArray {
277 [ + + + + ]: 493 : if (encodedData.isEmpty() || encodedData.size() % 8 == 0) {
278 : : return encodedData;
279 : : }
280 : :
281 : 168 : const int rBytes = static_cast<int>(encodedData.size() % 8);
282 : : // rBytes must be a member of {2, 4, 5, 7}.
283 [ + + ]: 168 : if (1 == rBytes || 3 == rBytes || 6 == rBytes) {
284 : : return encodedData;
285 : : }
286 : :
287 : : QByteArray newEncodedData(encodedData);
288 [ + + ]: 437 : for (int nPads = 8 - rBytes; nPads > 0; --nPads) {
289 : 335 : newEncodedData.append('=');
290 : : }
291 : :
292 : : return newEncodedData;
293 : : }
294 : :
295 : 51 : auto Base32::removePadding(const QByteArray &encodedData) -> QByteArray {
296 [ + - + + ]: 51 : if (encodedData.isEmpty() || encodedData.size() % 8 != 0) {
297 : : return encodedData; // return the same bad input
298 : : }
299 : :
300 : : QByteArray newEncodedData(encodedData);
301 : 50 : newEncodedData.resize(encodedData.size() - countPadding(encodedData));
302 : :
303 : : return newEncodedData;
304 : : }
305 : :
306 : 529 : auto Base32::sanitizeInput(const QByteArray &encodedData) -> QByteArray {
307 [ + + ]: 529 : if (encodedData.isEmpty()) {
308 : : return encodedData;
309 : : }
310 : :
311 : 479 : QByteArray newEncodedData(encodedData.size(), Qt::Uninitialized);
312 : : // Raw pointer: see the note in decode().
313 : : char *out = newEncodedData.data();
314 : : qsizetype i = 0;
315 [ + + ]: 18640 : for (auto ch : encodedData) {
316 [ + + + + ]: 18161 : switch (ch) {
317 : 1 : case '0':
318 : 1 : out[i++] = 'O';
319 : 1 : break;
320 : 14 : case '1':
321 : 14 : out[i++] = 'L';
322 : 14 : break;
323 : 16 : case '8':
324 : 16 : out[i++] = 'B';
325 : 16 : break;
326 : 18130 : default:
327 [ + + ]: 18130 : if (('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z') ||
328 [ + + ]: 1035 : ('2' <= ch && ch <= '7')) {
329 : 17943 : out[i++] = ch;
330 : : }
331 : : }
332 : : }
333 : 479 : newEncodedData.resize(i);
334 : :
335 : 479 : return addPadding(newEncodedData);
336 : : }
|