QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
base32.cpp
Go to the documentation of this file.
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
16
17#include "base32.h"
18
19#include <optional>
20#include <string_view>
21
22namespace {
23
31constexpr quint64 MASK_40BIT = quint64{0xF8} << 32;
32constexpr quint64 MASK_35BIT = quint64{0x7C0000000};
33constexpr quint64 MASK_25BIT = quint64{0x1F00000};
34constexpr quint64 MASK_20BIT = quint64{0xF8000};
35constexpr quint64 MASK_10BIT = quint64{0x3E0};
37
39constexpr std::string_view kAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
41constexpr quint8 ALPH_POS_2 = 26;
42
44constexpr quint8 ASCII_2 = static_cast<quint8>('2');
46constexpr quint8 ASCII_7 = static_cast<quint8>('7');
48constexpr quint8 ASCII_A = static_cast<quint8>('A');
50constexpr quint8 ASCII_Z = static_cast<quint8>('Z');
52constexpr quint8 ASCII_a = static_cast<quint8>('a');
54constexpr quint8 ASCII_z = static_cast<quint8>('z');
56constexpr quint8 ASCII_EQ = static_cast<quint8>('=');
57
67auto countPadding(const QByteArray &encodedData) -> int {
68 int nPads = 0;
69 for (qsizetype i = encodedData.size() - 1;
70 i >= 0 && i > encodedData.size() - 7; --i) {
71 if (encodedData.at(i) != '=') {
72 break;
73 }
74 ++nPads;
75 }
76 return nPads;
77}
78
86struct Tail {
87 int bytes = 0;
88 int offset = 0;
89};
90
93auto tailShape(int nPads) -> std::optional<Tail> {
94 switch (nPads) {
95 case 0:
96 return Tail{};
97 case 1:
98 return Tail{4, 3};
99 case 3:
100 return Tail{3, 1};
101 case 4:
102 return Tail{2, 4};
103 case 6:
104 return Tail{1, 2};
105 default:
106 return std::nullopt;
107 }
108}
109
112auto symbolValue(quint8 ch) -> std::optional<quint8> {
113 if ((ASCII_A <= ch && ch <= ASCII_Z) || (ASCII_a <= ch && ch <= ASCII_z)) {
114 ch -= ASCII_A;
115 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 return ch;
120 }
121 if (ASCII_2 <= ch && ch <= ASCII_7) {
122 return static_cast<quint8>(ch - ASCII_2 + ALPH_POS_2);
123 }
124 return std::nullopt;
125}
126
127} // namespace
128
129auto Base32::decode(const QByteArray &encodedData) -> QByteArray {
130 // Strict: a well-formed base32 string is always padded to a multiple of 8.
131 if (encodedData.isEmpty() || encodedData.size() % 8 != 0) {
132 return {};
133 }
134 const int nPads = countPadding(encodedData);
135 const std::optional<Tail> tail = tailShape(nPads);
136 if (!tail) {
137 return {};
138 }
139
140 const qsizetype nQuanta = encodedData.size() / 8;
141 const qsizetype nBytes =
142 tail->bytes > 0 ? (nQuanta - 1) * 5 + tail->bytes : nQuanta * 5;
143
144 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 const qsizetype firstPad = encodedData.size() - nPads;
154
155 while (i < encodedData.size()) {
156 quint64 quantum = 0;
157 int nQuantumBytes = 5;
158
159 for (int n = 0; n < 8; ++n) {
160 const auto ch = static_cast<quint8>(encodedData.at(i++));
161 if (ASCII_EQ == ch) {
162 if (i - 1 < firstPad) {
163 // '=' before the trailing run is not padding, it is malformed input.
164 return {};
165 }
166 if (i == encodedData.size()) {
167 // Finished with the short final quantum.
168 quantum >>= tail->offset;
169 nQuantumBytes = tail->bytes;
170 }
171 continue;
172 }
173 const std::optional<quint8> value = symbolValue(ch);
174 if (!value) {
175 return {};
176 }
177 quantum <<= 5;
178 quantum |= *value;
179 }
180
181 const int offset = (nQuantumBytes - 1) * 8;
182 quint64 mask = quint64{0xFF} << offset;
183 for (int n = offset; n >= 0 && o < nBytes; n -= 8) {
184 out[o++] = static_cast<char>((quantum & mask) >> n);
185 mask >>= 8;
186 }
187 }
188
189 return data;
190}
191
192auto Base32::encode(const QByteArray &data) -> QByteArray {
193 if (data.isEmpty()) {
194 return {};
195 }
196
197 const qsizetype nBits = data.size() * 8;
198 const int rBits = static_cast<int>(nBits % 40); // in {0, 8, 16, 24, 32}
199 const qsizetype nQuanta = nBits / 40 + (rBits > 0 ? 1 : 0);
200 const qsizetype nBytes = nQuanta * 8;
201 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 return static_cast<quint64>(static_cast<quint8>(data.at(index)));
216 };
217
218 // 40 bits of input per input group.
219 while (i + 5 <= data.size()) {
220 quantum = 0;
221 for (n = 32; n >= 0; n -= 8) {
222 quantum |= byteAt(i++) << n;
223 }
224
225 mask = MASK_40BIT;
226 for (n = 35; n >= 0; n -= 5) {
227 out[o++] = kAlphabet[(quantum & mask) >> n];
228 mask >>= 5;
229 }
230 }
231
232 // Fewer than 40 bits of input in the final input group.
233 if (i < data.size()) {
234 quantum = 0;
235 for (n = rBits - 8; n >= 0; n -= 8) {
236 quantum |= byteAt(i++) << n;
237 }
238
239 switch (rBits) {
240 case 8: // expand to 10 bits
241 quantum <<= 2;
242 mask = MASK_10BIT;
243 n = 5;
244 break;
245 case 16: // expand to 20 bits
246 quantum <<= 4;
247 mask = MASK_20BIT;
248 n = 15;
249 break;
250 case 24: // expand to 25 bits
251 quantum <<= 1;
252 mask = MASK_25BIT;
253 n = 20;
254 break;
255 default: // expand to 35 bits
256 quantum <<= 3;
257 mask = MASK_35BIT;
258 n = 30;
259 }
260
261 while (n >= 0) {
262 out[o++] = kAlphabet[(quantum & mask) >> n];
263 mask >>= 5;
264 n -= 5;
265 }
266
267 // Add the pad characters.
268 while (o < encodedData.size()) {
269 out[o++] = '=';
270 }
271 }
272
273 return encodedData;
274}
275
276auto Base32::addPadding(const QByteArray &encodedData) -> QByteArray {
277 if (encodedData.isEmpty() || encodedData.size() % 8 == 0) {
278 return encodedData;
279 }
280
281 const int rBytes = static_cast<int>(encodedData.size() % 8);
282 // rBytes must be a member of {2, 4, 5, 7}.
283 if (1 == rBytes || 3 == rBytes || 6 == rBytes) {
284 return encodedData;
285 }
286
287 QByteArray newEncodedData(encodedData);
288 for (int nPads = 8 - rBytes; nPads > 0; --nPads) {
289 newEncodedData.append('=');
290 }
291
292 return newEncodedData;
293}
294
295auto Base32::removePadding(const QByteArray &encodedData) -> QByteArray {
296 if (encodedData.isEmpty() || encodedData.size() % 8 != 0) {
297 return encodedData; // return the same bad input
298 }
299
300 QByteArray newEncodedData(encodedData);
301 newEncodedData.resize(encodedData.size() - countPadding(encodedData));
302
303 return newEncodedData;
304}
305
306auto Base32::sanitizeInput(const QByteArray &encodedData) -> QByteArray {
307 if (encodedData.isEmpty()) {
308 return encodedData;
309 }
310
311 QByteArray newEncodedData(encodedData.size(), Qt::Uninitialized);
312 // Raw pointer: see the note in decode().
313 char *out = newEncodedData.data();
314 qsizetype i = 0;
315 for (auto ch : encodedData) {
316 switch (ch) {
317 case '0':
318 out[i++] = 'O';
319 break;
320 case '1':
321 out[i++] = 'L';
322 break;
323 case '8':
324 out[i++] = 'B';
325 break;
326 default:
327 if (('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z') ||
328 ('2' <= ch && ch <= '7')) {
329 out[i++] = ch;
330 }
331 }
332 }
333 newEncodedData.resize(i);
334
335 return addPadding(newEncodedData);
336}
Strict RFC 4648 base32 codec plus the input sanitizer that makes human-typed TOTP secrets decodable.
static auto sanitizeInput(const QByteArray &encodedData) -> QByteArray
Make human-entered base32 text decodable.
Definition base32.cpp:306
static auto addPadding(const QByteArray &encodedData) -> QByteArray
Append '=' padding up to a multiple of 8 characters.
Definition base32.cpp:276
static auto decode(const QByteArray &encodedData) -> QByteArray
Decode strict RFC 4648 base32 data.
Definition base32.cpp:129
static auto encode(const QByteArray &data) -> QByteArray
Encode raw bytes as padded RFC 4648 base32.
Definition base32.cpp:192
static auto removePadding(const QByteArray &encodedData) -> QByteArray
Strip trailing '=' padding.
Definition base32.cpp:295