• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

kimci86 / bkcrack / 45245172729

23 Nov 2026 07:04PM UTC coverage: 93.045% (-0.06%) from 93.103%
45245172729

push

github

kimci86
Configure CI to test and package emscripten build

1873 of 2013 relevant lines covered (93.05%)

3090432.68 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

85.65
/src/cli/main.cpp
1
#include "Arguments.hpp"
2
#include "ConsoleProgress.hpp"
3
#include "SigintHandler.hpp"
4

5
#include <bkcrack/Attack.hpp>
6
#include <bkcrack/Data.hpp>
7
#include <bkcrack/Zip.hpp>
8
#include <bkcrack/Zreduction.hpp>
9
#include <bkcrack/file.hpp>
10
#include <bkcrack/log.hpp>
11
#include <bkcrack/password.hpp>
12
#include <bkcrack/version.hpp>
13

14
#include <cassert>
15
#include <iomanip>
16
#include <limits>
17

18
namespace
19
{
20

21
const char* const usage = R"_(usage: bkcrack [options]
22
Crack legacy zip encryption with Biham and Kocher's known plaintext attack.
23

24
Options to get the internal password representation:
25
 -c, --cipher-file <file>    Zip entry or file on disk containing ciphertext
26
     --cipher-index <index>  Index of the zip entry containing ciphertext
27
 -C, --cipher-zip <archive>  Zip archive containing the ciphertext entry
28

29
 -p, --plain-file <file>     Zip entry or file on disk containing plaintext
30
     --plain-index <index>   Index of the zip entry containing plaintext
31
 -P, --plain-zip <archive>   Zip archive containing the plaintext entry
32
 -t, --truncate <size>       Maximum number of bytes of plaintext to load
33
 -o, --offset <offset>       Known plaintext offset relative to ciphertext
34
                              without encryption header (may be negative)
35
 -x, --extra <offset> <data> Additional plaintext in hexadecimal starting
36
                              at the given offset (may be negative)
37
     --ignore-check-byte     Do not automatically use ciphertext's check byte
38
                              as known plaintext
39

40
     --continue-attack <checkpoint>
41
        Starting point of the attack. Useful to continue a previous
42
        non-exhaustive or interrupted attack.
43

44
     --password <password>
45
        Password from which to derive the internal password representation.
46
        Useful for testing purposes and advanced scenarios such as reverting
47
        the effect of the --change-password command.
48

49
Options to use the internal password representation:
50
 -k, --keys <X> <Y> <Z>      Internal password representation as three 32-bits
51
                              integers in hexadecimal (requires -d, -D, -U,
52
                              --change-keys, --bruteforce or --mask)
53

54
 -d, --decipher <file>       File to write the deciphered data (requires -c)
55
     --keep-header           Write the encryption header at the beginning of
56
                              deciphered data instead of discarding it
57

58
 -D, --decrypt <archive>
59
        Create a copy of the encrypted zip archive with deciphered entries,
60
        removing the password protection (requires -C)
61

62
 -U, --change-password <archive> <password>
63
        Create a copy of the encrypted zip archive with the password set to the
64
        given new password (requires -C)
65

66
     --change-keys <archive> <X> <Y> <Z>
67
        Create a copy of the encrypted zip archive using the given new internal
68
        password representation (requires -C)
69

70
 -b, --bruteforce <charset>
71
        Try to recover the password or an equivalent one by generating and
72
        testing password candidates using characters in the given charset.
73
        The charset is a sequence of characters or shortcuts for predefined
74
        charsets listed below. Example: ?l?d-.@
75

76
          ?l lowercase letters              abcdefghijklmnopqrstuvwxyz
77
          ?u uppercase letters              ABCDEFGHIJKLMNOPQRSTUVWXYZ
78
          ?d decimal digits                 0123456789
79
          ?s special characters              !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
80
          ?a alpha-numerical characters     (same as ?l?u?d)
81
          ?p printable ASCII characters     (same as ?l?u?d?s)
82
          ?b all bytes                      (0x00 - 0xff)
83

84
 -l, --length [ <min>..<max> | <min>.. | ..<max> | <length> ]
85
        Length interval or exact length of password candidates to generate and
86
        test during password recovery (requires --bruteforce)
87

88
 -r, --recover-password [ <min>..<max> | <min>.. | ..<max> | <max> ] <charset>
89
        Shortcut for --length and --bruteforce options
90

91
 -m, --mask <mask>
92
        Try to recover the password or an equivalent one by generating and
93
        testing password candidates following the given mask.
94
        The mask is a sequence of fixed characters or character sets (either
95
        predefined or custom charsets). Example: -m ?u?l?l?l?l-?d?d?d?d
96

97
 -s, --charset <identifier> <charset>
98
        Define a custom character set. Example: -s h ?dabcdef
99

100
     --continue-recovery <checkpoint>
101
        Starting point of the password recovery. Useful to continue a previous
102
        non-exhaustive or interrupted password recovery.
103

104
Other options:
105
 -j, --jobs <count>          Number of threads to use for parallel operations
106
 -e, --exhaustive            Exhaustively look for all solutions (keys or
107
                              passwords) instead of stopping after the first
108
                              solution is found
109
 -L, --list <archive>        List entries in a zip archive and exit
110
     --version               Show version information and exit
111
 -h, --help                  Show this help and exit)_";
112

113
auto getCompressionDescription(Zip::Compression compression) -> std::string;
114
void listEntries(const std::string& archiveFilename);
115

116
} // namespace
117

118
auto main(int argc, const char* argv[]) -> int
31 ✔
119
try
120
{
121
    // version information
122
    std::cout << "bkcrack " << bkcrackVersion << " - " << bkcrackVersionDate << std::endl;
31 ✔
123

124
    const auto args = Arguments{argc, argv};
31 ✔
125
    if (args.help)
29 ✔
126
    {
127
        std::cout << usage << std::endl;
1 ✔
128
        return 0;
1 ✔
129
    }
130

131
    if (args.version)
28 ✔
132
    {
133
        // version information was already printed, nothing else to do
134
        return 0;
1 ✔
135
    }
136

137
    if (args.infoArchive)
27 ✔
138
    {
139
        listEntries(*args.infoArchive);
1 ✔
140
        return 0;
1 ✔
141
    }
142

143
    auto keysvec = std::vector<Keys>{};
26 ✔
144
    if (args.keys)
26 ✔
145
        keysvec.push_back(*args.keys);
20 ✔
146
    else if (args.password)
6 ✔
147
    {
148
        keysvec.emplace_back(*args.password);
5 ✔
149
        std::cout << "Internal representation for password \"" << *args.password << "\": " << keysvec.back()
5 ✔
150
                  << std::endl;
5 ✔
151
    }
152
    else
153
    // find keys from known plaintext
154
    {
155
        const auto data = args.loadData();
1 ✔
156

157
        // generate and reduce Zi[10,32) values
158
        auto zr = Zreduction{data.keystream};
1 ✔
159
        if (data.keystream.size() > Attack::contiguousSize)
1 ✔
160
        {
161
            std::cout << "[" << put_time << "] Z reduction using " << (data.keystream.size() - Attack::contiguousSize)
1 ✔
162
                      << " bytes of known plaintext" << std::endl;
1 ✔
163

164
            auto progress = ConsoleProgress{std::cout};
1 ✔
165
            zr.reduce(progress);
1 ✔
166
        }
1 ✔
167

168
        // generate Zi[2,32) values
169
        zr.generate();
1 ✔
170

171
        // carry out the attack on the remaining Zi[2,32) values
172
        std::cout << "[" << put_time << "] Attack on " << zr.getCandidates().size() << " Z values at index "
1 ✔
173
                  << (static_cast<int>(data.offset + zr.getIndex()) - static_cast<int>(Data::encryptionHeaderSize))
1 ✔
174
                  << std::endl;
1 ✔
175

176
        const auto [state, restart] = [&]() -> std::pair<Progress::State, int>
1 ✔
177
        {
178
            auto       start         = args.attackStart;
1 ✔
179
            auto       progress      = ConsoleProgress{std::cout};
1 ✔
180
            const auto sigintHandler = SigintHandler{progress.state};
1 ✔
181
            keysvec = attack(data, zr.getCandidates(), start, zr.getIndex(), args.jobs, args.exhaustive, progress);
1 ✔
182
            return {progress.state, start};
2 ✔
183
        }();
2 ✔
184

185
        if (state != Progress::State::Normal)
1 ✔
186
        {
187
            if (state == Progress::State::Canceled)
1 ✔
188
                std::cout << "Operation interrupted by user." << std::endl;
×
189
            else if (state == Progress::State::EarlyExit)
1 ✔
190
                std::cout << "Found a solution. Stopping." << std::endl;
1 ✔
191

192
            if (restart < static_cast<int>(zr.getCandidates().size()))
1 ✔
193
                std::cout << "You may resume the attack with the option: --continue-attack " << restart << std::endl;
1 ✔
194
        }
195

196
        // print the keys
197
        std::cout << "[" << put_time << "] ";
1 ✔
198
        if (keysvec.empty())
1 ✔
199
        {
200
            std::cout << "Could not find the keys." << std::endl;
×
201
            return 1;
×
202
        }
203
        else
204
        {
205
            std::cout << "Keys" << std::endl;
1 ✔
206
            for (const auto& keys : keysvec)
3 ✔
207
                std::cout << keys << std::endl;
1 ✔
208
        }
209
    }
1 ✔
210

211
    // From there, keysvec is not empty.
212

213
    const auto keys = keysvec.front();
26 ✔
214
    if ((args.decipheredFile || args.changePassword || args.changeKeys || args.bruteforce) && keysvec.size() > 1)
26 ✔
215
        std::cout << "Continuing with keys " << keys << "\n"
×
216
                  << "Use the command line option -k to provide other keys." << std::endl;
×
217

218
    // decipher
219
    if (args.decipheredFile)
26 ✔
220
    {
221
        std::cout << "[" << put_time << "] Writing deciphered data " << *args.decipheredFile;
1 ✔
222
        if (args.keepHeader)
1 ✔
223
            std::cout << " with encryption header";
×
224
        std::cout << std::endl;
1 ✔
225

226
        auto compression = std::optional<Zip::Compression>{};
1 ✔
227

228
        {
229
            auto cipherstream = openInput(args.cipherArchive ? *args.cipherArchive : *args.cipherFile);
1 ✔
230
            auto ciphersize   = std::numeric_limits<std::size_t>::max();
1 ✔
231

232
            if (args.cipherArchive)
1 ✔
233
            {
234
                const auto archive = Zip{cipherstream};
1 ✔
235
                const auto entry   = args.cipherFile ? archive[*args.cipherFile] : archive[*args.cipherIndex];
1 ✔
236
                Zip::checkEncryption(entry, Zip::Encryption::Traditional);
1 ✔
237
                compression = entry.compression;
1 ✔
238

239
                archive.seek(entry);
1 ✔
240
                ciphersize = entry.packedSize;
1 ✔
241
            }
1 ✔
242

243
            auto decipheredstream = openOutput(*args.decipheredFile);
1 ✔
244

245
            decipher(cipherstream, ciphersize,
1 ✔
246
                     args.keepHeader ? 0 : static_cast<std::size_t>(Data::encryptionHeaderSize), decipheredstream,
1 ✔
247
                     keys);
248
        }
1 ✔
249

250
        std::cout << "Wrote deciphered data";
1 ✔
251
        if (compression)
1 ✔
252
        {
253
            if (compression == Zip::Compression::Store)
1 ✔
254
                std::cout << " (not compressed)";
×
255
            else
256
                std::cout << " (compressed with " << getCompressionDescription(*compression) << " method)";
1 ✔
257
        }
258
        std::cout << "." << std::endl;
1 ✔
259
    }
260

261
    // decrypt
262
    if (args.decryptedArchive)
26 ✔
263
    {
264
        std::cout << "[" << put_time << "] Writing decrypted archive " << *args.decryptedArchive << std::endl;
1 ✔
265

266
        auto stream    = openInput(*args.cipherArchive);
1 ✔
267
        auto encrypted = Zip{stream};
1 ✔
268
        auto decrypted = openOutput(*args.decryptedArchive);
1 ✔
269

270
        auto progress = ConsoleProgress{std::cout};
1 ✔
271
        encrypted.decrypt(decrypted, keys, progress);
1 ✔
272
    }
1 ✔
273

274
    // unlock
275
    if (args.changePassword)
26 ✔
276
    {
277
        const auto& [unlockedArchive, newPassword] = *args.changePassword;
1 ✔
278

279
        std::cout << "[" << put_time << "] Writing unlocked archive " << unlockedArchive << " with password \""
1 ✔
280
                  << newPassword << "\"" << std::endl;
1 ✔
281

282
        {
283
            auto       stream   = openInput(*args.cipherArchive);
1 ✔
284
            const auto archive  = Zip{stream};
1 ✔
285
            auto       unlocked = openOutput(unlockedArchive);
1 ✔
286

287
            auto progress = ConsoleProgress{std::cout};
1 ✔
288
            archive.changeKeys(unlocked, keys, Keys{newPassword}, progress);
1 ✔
289
        }
1 ✔
290

291
        std::cout << "Wrote unlocked archive." << std::endl;
1 ✔
292
    }
293

294
    if (args.changeKeys)
26 ✔
295
    {
296
        const auto& [unlockedArchive, newKeys] = *args.changeKeys;
1 ✔
297

298
        std::cout << "[" << put_time << "] Writing unlocked archive " << unlockedArchive << " with keys " << newKeys
1 ✔
299
                  << std::endl;
1 ✔
300

301
        {
302
            auto       stream   = openInput(*args.cipherArchive);
1 ✔
303
            const auto archive  = Zip{stream};
1 ✔
304
            auto       unlocked = openOutput(unlockedArchive);
1 ✔
305

306
            auto progress = ConsoleProgress{std::cout};
1 ✔
307
            archive.changeKeys(unlocked, keys, newKeys, progress);
1 ✔
308
        }
1 ✔
309

310
        std::cout << "Wrote unlocked archive." << std::endl;
1 ✔
311
    }
312

313
    // recover password
314
    if (args.bruteforce || args.mask)
26 ✔
315
    {
316
        std::cout << "[" << put_time << "] Recovering password" << std::endl;
20 ✔
317

318
        auto passwords = std::vector<std::string>{};
20 ✔
319

320
        const auto [state, restart] = [&]() -> std::pair<Progress::State, std::string>
20 ✔
321
        {
322
            auto       start         = args.recoveryStart;
20 ✔
323
            auto       progress      = ConsoleProgress{std::cout};
20 ✔
324
            const auto sigintHandler = SigintHandler{progress.state};
20 ✔
325

326
            if (args.bruteforce)
20 ✔
327
            {
328
                const auto& charset                = *args.bruteforce;
10 ✔
329
                const auto& [minLength, maxLength] = args.length.value_or(Arguments::LengthInterval{});
10 ✔
330
                passwords = recoverPassword(keysvec.front(), charset, minLength, maxLength, start, args.jobs,
20 ✔
331
                                            args.exhaustive, progress);
20 ✔
332
            }
333
            else
334
                passwords = recoverPassword(keysvec.front(), *args.mask, start, args.jobs, args.exhaustive, progress);
10 ✔
335

336
            return {progress.state, start};
40 ✔
337
        }();
40 ✔
338

339
        if (state != Progress::State::Normal)
20 ✔
340
        {
341
            if (state == Progress::State::Canceled)
20 ✔
342
                std::cout << "Operation interrupted by user." << std::endl;
×
343
            else if (state == Progress::State::EarlyExit)
20 ✔
344
                std::cout << "Found a solution. Stopping." << std::endl;
20 ✔
345

346
            if (!restart.empty())
20 ✔
347
            {
348
                const auto flagsBefore = std::cout.setf(std::ios::hex, std::ios::basefield);
4 ✔
349
                const auto fillBefore  = std::cout.fill('0');
4 ✔
350

351
                std::cout << "You may resume the password recovery with the option: --continue-recovery ";
4 ✔
352
                for (const auto c : restart)
45 ✔
353
                    std::cout << std::setw(2) << int{static_cast<std::uint8_t>(c)};
37 ✔
354
                std::cout << std::endl;
4 ✔
355

356
                std::cout.fill(fillBefore);
4 ✔
357
                std::cout.flags(flagsBefore);
4 ✔
358
            }
359
        }
360

361
        std::cout << "[" << put_time << "] ";
20 ✔
362
        if (passwords.empty())
20 ✔
363
        {
364
            std::cout << "Could not recover password" << std::endl;
×
365
            return 1;
×
366
        }
367
        else
368
        {
369
            std::cout << "Password" << std::endl;
20 ✔
370

371
            const auto flagsBefore = std::cout.setf(std::ios::hex, std::ios::basefield);
20 ✔
372
            const auto fillBefore  = std::cout.fill('0');
20 ✔
373

374
            for (const auto& password : passwords)
60 ✔
375
            {
376
                std::cout << "as bytes:";
20 ✔
377
                for (const auto c : password)
259 ✔
378
                    std::cout << ' ' << std::setw(2) << int{static_cast<std::uint8_t>(c)};
219 ✔
379
                std::cout << std::endl;
20 ✔
380
                std::cout << "as text: " << password << std::endl;
20 ✔
381
            }
382

383
            std::cout.fill(fillBefore);
20 ✔
384
            std::cout.flags(flagsBefore);
20 ✔
385
        }
386
    }
40 ✔
387

388
    return 0;
26 ✔
389
}
29 ✔
390
catch (const Arguments::Error& e)
2 ✔
391
{
392
    std::cout << e.what() << std::endl;
2 ✔
393
    std::cout << "Run 'bkcrack -h' for help." << std::endl;
2 ✔
394
    return 1;
2 ✔
395
}
2 ✔
396
catch (const BaseError& e)
×
397
{
398
    std::cout << e.what() << std::endl;
×
399
    return 1;
×
400
}
×
401

402
namespace
403
{
404

405
auto getEncryptionDescription(Zip::Encryption encryption) -> std::string
2 ✔
406
{
407
    switch (encryption)
2 ✔
408
    {
409
    case Zip::Encryption::None:
×
410
        return "None";
×
411
    case Zip::Encryption::Traditional:
2 ✔
412
        return "ZipCrypto";
4 ✔
413
    case Zip::Encryption::Unsupported:
×
414
        return "Other";
×
415
    }
416
    assert(false);
×
417

418
    return "";
419
}
420

421
auto getCompressionDescription(Zip::Compression compression) -> std::string
3 ✔
422
{
423
    switch (compression)
3 ✔
424
    {
425
#define CASE(c)                                                                                                        \
426
    case Zip::Compression::c:                                                                                          \
427
        return #c
428
        CASE(Store);
3 ✔
429
        CASE(Shrink);
×
430
        CASE(Implode);
×
431
        CASE(Deflate);
6 ✔
432
        CASE(Deflate64);
×
433
        CASE(BZip2);
×
434
        CASE(LZMA);
×
435
        CASE(Zstandard);
×
436
        CASE(MP3);
×
437
        CASE(XZ);
×
438
        CASE(JPEG);
×
439
        CASE(WavPack);
×
440
        CASE(PPMd);
×
441
#undef CASE
442
    }
443

444
    return "Other (" + std::to_string(static_cast<int>(compression)) + ")";
×
445
}
446

447
void listEntries(const std::string& archiveFilename)
1 ✔
448
{
449
    auto       stream  = openInput(archiveFilename);
1 ✔
450
    const auto archive = Zip{stream};
1 ✔
451

452
    std::cout << "Archive: " << archiveFilename << "\n"
453
              << "Index Encryption Compression CRC32    Uncompressed  Packed size Name\n"
454
                 "----- ---------- ----------- -------- ------------ ------------ ----------------\n";
1 ✔
455

456
    const auto flagsBefore =
457
        std::cout.setf(std::ios::right | std::ios::dec, std::ios::adjustfield | std::ios::basefield);
1 ✔
458
    const auto fillBefore = std::cout.fill(' ');
1 ✔
459

460
    auto index = std::size_t{};
1 ✔
461
    for (const auto& entry : archive)
3 ✔
462
    {
463
        // clang-format off
464
        std::cout << std::setw(5) << index++ << ' '
2 ✔
465

466
                  << std::left
2 ✔
467
                  << std::setw(10) << getEncryptionDescription(entry.encryption) << ' '
4 ✔
468
                  << std::setw(11) << getCompressionDescription(entry.compression) << ' '
6 ✔
469
                  << std::right
2 ✔
470

471
                  << std::setfill('0') << std::hex
2 ✔
472
                  << std::setw(8) << entry.crc32 << ' '
2 ✔
473
                  << std::setfill(' ') << std::dec
2 ✔
474

475
                  << std::setw(12) << entry.uncompressedSize << ' '
2 ✔
476
                  << std::setw(12) << entry.packedSize << ' '
2 ✔
477
                  << entry.name << '\n';
2 ✔
478
        // clang-format on
479
    }
1 ✔
480

481
    std::cout.fill(fillBefore);
1 ✔
482
    std::cout.flags(flagsBefore);
1 ✔
483
}
1 ✔
484

485
} // namespace
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc