summaryrefslogtreecommitdiffstats
path: root/src/corelib/tools/qcryptographichash.cpp
blob: 7ccafaeb36e9a3b46593b1082ab0acc1ae4b5e5a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
// Copyright (C) 2016 The Qt Company Ltd.
// Copyright (C) 2013 Richard J. Moore <rich@kde.org>.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include <qcryptographichash.h>
#include <qiodevice.h>

#include <array>

#include "../../3rdparty/sha1/sha1.cpp"

#if defined(QT_BOOTSTRAPPED) && !defined(QT_CRYPTOGRAPHICHASH_ONLY_SHA1)
#  error "Are you sure you need the other hashing algorithms besides SHA-1?"
#endif

#ifndef QT_CRYPTOGRAPHICHASH_ONLY_SHA1
#if !QT_CONFIG(opensslv30) || !QT_CONFIG(openssl_linked)
// qdoc and qmake only need SHA-1
#include "../../3rdparty/md5/md5.h"
#include "../../3rdparty/md5/md5.cpp"
#include "../../3rdparty/md4/md4.h"
#include "../../3rdparty/md4/md4.cpp"

typedef unsigned char BitSequence;
typedef unsigned long long DataLength;
typedef enum { SUCCESS = 0, FAIL = 1, BAD_HASHLEN = 2 } HashReturn;

#ifdef Q_OS_RTEMS
#  undef ALIGN
#endif

#include "../../3rdparty/sha3/KeccakSponge.c"
typedef spongeState hashState;

#include "../../3rdparty/sha3/KeccakNISTInterface.c"

/*
  This lets us choose between SHA3 implementations at build time.
 */
typedef spongeState SHA3Context;
typedef HashReturn (SHA3Init)(hashState *state, int hashbitlen);
typedef HashReturn (SHA3Update)(hashState *state, const BitSequence *data, DataLength databitlen);
typedef HashReturn (SHA3Final)(hashState *state, BitSequence *hashval);

#if Q_PROCESSOR_WORDSIZE == 8 // 64 bit version

#include "../../3rdparty/sha3/KeccakF-1600-opt64.c"

Q_CONSTINIT static SHA3Init * const sha3Init = Init;
Q_CONSTINIT static SHA3Update * const sha3Update = Update;
Q_CONSTINIT static SHA3Final * const sha3Final = Final;

#else // 32 bit optimised fallback

#include "../../3rdparty/sha3/KeccakF-1600-opt32.c"

Q_CONSTINIT static SHA3Init * const sha3Init = Init;
Q_CONSTINIT static SHA3Update * const sha3Update = Update;
Q_CONSTINIT static SHA3Final * const sha3Final = Final;

#endif

// Header from rfc6234
#include "../../3rdparty/rfc6234/sha.h"

/*
    These 2 functions replace macros of the same name in sha224-256.c and
    sha384-512.c. Originally, these macros relied on a global static 'addTemp'
    variable. We do not want this for 2 reasons:

    1. since we are including the sources directly, the declaration of the 2 conflict

    2. static variables are not thread-safe, we do not want multiple threads
    computing a hash to corrupt one another
*/
static int SHA224_256AddLength(SHA256Context *context, unsigned int length);
static int SHA384_512AddLength(SHA512Context *context, unsigned int length);

// Sources from rfc6234, with 4 modifications:
// sha224-256.c - commented out 'static uint32_t addTemp;' on line 68
// sha224-256.c - appended 'M' to the SHA224_256AddLength macro on line 70
#include "../../3rdparty/rfc6234/sha224-256.c"
// sha384-512.c - commented out 'static uint64_t addTemp;' on line 302
// sha384-512.c - appended 'M' to the SHA224_256AddLength macro on line 304
#include "../../3rdparty/rfc6234/sha384-512.c"

static inline int SHA224_256AddLength(SHA256Context *context, unsigned int length)
{
  uint32_t addTemp;
  return SHA224_256AddLengthM(context, length);
}
static inline int SHA384_512AddLength(SHA512Context *context, unsigned int length)
{
  uint64_t addTemp;
  return SHA384_512AddLengthM(context, length);
}
#endif // !QT_CONFIG(opensslv30)

#include "qtcore-config_p.h"

#if QT_CONFIG(system_libb2)
#include <blake2.h>
#else
#include "../../3rdparty/blake2/src/blake2b-ref.c"
#include "../../3rdparty/blake2/src/blake2s-ref.c"
#endif
#endif // QT_CRYPTOGRAPHICHASH_ONLY_SHA1

#if !defined(QT_BOOTSTRAPPED) && QT_CONFIG(opensslv30) && QT_CONFIG(openssl_linked)
#define USING_OPENSSL30
#include <openssl/evp.h>
#include <openssl/provider.h>
#include <openssl/sha.h>
#endif

QT_BEGIN_NAMESPACE

static constexpr qsizetype MaxHashLength = 64;

static constexpr int hashLengthInternal(QCryptographicHash::Algorithm method) noexcept
{
    switch (method) {
#define CASE(Enum, Size) \
    case QCryptographicHash:: Enum : \
        /* if this triggers, then increase MaxHashLength accordingly */ \
        static_assert(MaxHashLength >= qsizetype(Size) ); \
        return Size \
    /*end*/
    CASE(Sha1, 20);
#ifndef QT_CRYPTOGRAPHICHASH_ONLY_SHA1
    CASE(Md4, 16);
    CASE(Md5, 16);
#ifdef USING_OPENSSL30
    CASE(Sha224, SHA224_DIGEST_LENGTH);
    CASE(Sha256, SHA256_DIGEST_LENGTH);
    CASE(Sha384, SHA384_DIGEST_LENGTH);
    CASE(Sha512, SHA512_DIGEST_LENGTH);
#else
    CASE(Sha224, SHA224HashSize);
    CASE(Sha256, SHA256HashSize);
    CASE(Sha384, SHA384HashSize);
    CASE(Sha512, SHA512HashSize);
#endif
    CASE(Blake2s_128, 128 / 8);
    case QCryptographicHash::Blake2b_160:
    case QCryptographicHash::Blake2s_160:
        static_assert(160 / 8 <= MaxHashLength);
        return 160 / 8;
    case QCryptographicHash::RealSha3_224:
    case QCryptographicHash::Keccak_224:
    case QCryptographicHash::Blake2s_224:
        static_assert(224 / 8 <= MaxHashLength);
        return 224 / 8;
    case QCryptographicHash::RealSha3_256:
    case QCryptographicHash::Keccak_256:
    case QCryptographicHash::Blake2b_256:
    case QCryptographicHash::Blake2s_256:
        static_assert(256 / 8 <= MaxHashLength);
        return 256 / 8;
    case QCryptographicHash::RealSha3_384:
    case QCryptographicHash::Keccak_384:
    case QCryptographicHash::Blake2b_384:
        static_assert(384 / 8 <= MaxHashLength);
        return 384 / 8;
    case QCryptographicHash::RealSha3_512:
    case QCryptographicHash::Keccak_512:
    case QCryptographicHash::Blake2b_512:
        static_assert(512 / 8 <= MaxHashLength);
        return 512 / 8;
#endif
#undef CASE
    }
    return 0;
}

#ifdef USING_OPENSSL30
static constexpr const char * methodToName(QCryptographicHash::Algorithm method) noexcept
{
    switch (method) {
#define CASE(Enum, Name) \
    case QCryptographicHash:: Enum : \
        return Name \
    /*end*/
    CASE(Sha1, "SHA1");
    CASE(Md4, "MD4");
    CASE(Md5, "MD5");
    CASE(Sha224, "SHA224");
    CASE(Sha256, "SHA256");
    CASE(Sha384, "SHA384");
    CASE(Sha512, "SHA512");
    CASE(RealSha3_224, "SHA3-224");
    CASE(RealSha3_256, "SHA3-256");
    CASE(RealSha3_384, "SHA3-384");
    CASE(RealSha3_512, "SHA3-512");
    CASE(Keccak_224, "SHA3-224");
    CASE(Keccak_256, "SHA3-256");
    CASE(Keccak_384, "SHA3-384");
    CASE(Keccak_512, "SHA3-512");
    CASE(Blake2b_512, "BLAKE2B512");
    CASE(Blake2s_256, "BLAKE2S256");
#undef CASE
    default: return nullptr;
    }
}
#endif

class QCryptographicHashPrivate
{
public:
    explicit QCryptographicHashPrivate(QCryptographicHash::Algorithm method) noexcept
        : method(method)
    {
        reset();
    }

    void reset() noexcept;
    void addData(QByteArrayView bytes) noexcept;
    void finalize() noexcept;
    QByteArrayView resultView() const noexcept { return result.toByteArrayView(); }

    const QCryptographicHash::Algorithm method;

#ifdef USING_OPENSSL30
    struct EVP_MD_CTX_deleter {
        void operator()(EVP_MD_CTX *ctx) const noexcept {
            EVP_MD_CTX_free(ctx);
        }
    };
    struct EVP_MD_deleter {
        void operator()(EVP_MD *md) const noexcept {
            EVP_MD_free(md);
        }
    };
    using EVP_MD_CTX_ptr = std::unique_ptr<EVP_MD_CTX, EVP_MD_CTX_deleter>;
    using EVP_MD_ptr = std::unique_ptr<EVP_MD, EVP_MD_deleter>;
    EVP_MD_ptr algorithm;
    EVP_MD_CTX_ptr context;
    bool initializationFailed = false;
#endif

    union {
        Sha1State sha1Context;
#ifndef QT_CRYPTOGRAPHICHASH_ONLY_SHA1
#ifndef USING_OPENSSL30
        MD5Context md5Context;
        md4_context md4Context;
        SHA224Context sha224Context;
        SHA256Context sha256Context;
        SHA384Context sha384Context;
        SHA512Context sha512Context;
        SHA3Context sha3Context;
#endif
        blake2b_state blake2bContext;
        blake2s_state blake2sContext;
#endif
    };
#ifndef QT_CRYPTOGRAPHICHASH_ONLY_SHA1
#ifndef USING_OPENSSL30
    enum class Sha3Variant
    {
        Sha3,
        Keccak
    };
    void sha3Finish(int bitCount, Sha3Variant sha3Variant);
#endif
#endif
    class SmallByteArray {
        std::array<char, MaxHashLength> m_data;
        static_assert(MaxHashLength <= std::numeric_limits<std::uint8_t>::max());
        std::uint8_t m_size;
    public:
        char *data() noexcept { return m_data.data(); }
        const char *data() const noexcept { return m_data.data(); }
        qsizetype size() const noexcept { return qsizetype{m_size}; }
        bool isEmpty() const noexcept { return size() == 0; }
        void clear() noexcept { m_size = 0; }
        void resizeForOverwrite(qsizetype s) {
            Q_ASSERT(s >= 0);
            Q_ASSERT(s <= MaxHashLength);
            m_size = std::uint8_t(s);
        }
        QByteArrayView toByteArrayView() const noexcept
        { return QByteArrayView{data(), size()}; }
    };
    SmallByteArray result;
};

#ifndef QT_CRYPTOGRAPHICHASH_ONLY_SHA1
#ifndef USING_OPENSSL30
void QCryptographicHashPrivate::sha3Finish(int bitCount, Sha3Variant sha3Variant)
{
    /*
        FIPS 202 §6.1 defines SHA-3 in terms of calculating the Keccak function
        over the original message with the two-bit suffix "01" appended to it.
        This variable stores that suffix (and it's fed into the calculations
        when the hash is returned to users).

        Only 2 bits of this variable are actually used (see the call to sha3Update
        below). The Keccak implementation we're using will actually use the
        *leftmost* 2 bits, and interpret them right-to-left. In other words, the
        bits must appear in order of *increasing* significance; and as the two most
        significant bits of the byte -- the rightmost 6 are ignored. (Yes, this
        seems self-contradictory, but it's the way it is...)

        Overall, this means:
        * the leftmost two bits must be "10" (not "01"!);
        * we don't care what the other six bits are set to (they can be set to
        any value), but we arbitrarily set them to 0;

        and for an unsigned char this gives us 0b10'00'00'00, or 0x80.
    */
    static const unsigned char sha3FinalSuffix = 0x80;

    result.resizeForOverwrite(bitCount / 8);

    SHA3Context copy = sha3Context;

    switch (sha3Variant) {
    case Sha3Variant::Sha3:
        sha3Update(&copy, reinterpret_cast<const BitSequence *>(&sha3FinalSuffix), 2);
        break;
    case Sha3Variant::Keccak:
        break;
    }

    sha3Final(&copy, reinterpret_cast<BitSequence *>(result.data()));
}
#endif // !QT_CONFIG(opensslv30)
#endif

/*!
  \class QCryptographicHash
  \inmodule QtCore

  \brief The QCryptographicHash class provides a way to generate cryptographic hashes.

  \since 4.3

  \ingroup tools
  \reentrant

  QCryptographicHash can be used to generate cryptographic hashes of binary or text data.

  Refer to the documentation of the \l QCryptographicHash::Algorithm enum for a
  list of the supported algorithms.
*/

/*!
  \enum QCryptographicHash::Algorithm

  \note In Qt versions before 5.9, when asked to generate a SHA3 hash sum,
  QCryptographicHash actually calculated Keccak. If you need compatibility with
  SHA-3 hashes produced by those versions of Qt, use the \c{Keccak_}
  enumerators. Alternatively, if source compatibility is required, define the
  macro \c QT_SHA3_KECCAK_COMPAT.

  \value Md4 Generate an MD4 hash sum
  \value Md5 Generate an MD5 hash sum
  \value Sha1 Generate an SHA-1 hash sum
  \value Sha224 Generate an SHA-224 hash sum (SHA-2). Introduced in Qt 5.0
  \value Sha256 Generate an SHA-256 hash sum (SHA-2). Introduced in Qt 5.0
  \value Sha384 Generate an SHA-384 hash sum (SHA-2). Introduced in Qt 5.0
  \value Sha512 Generate an SHA-512 hash sum (SHA-2). Introduced in Qt 5.0
  \value Sha3_224 Generate an SHA3-224 hash sum. Introduced in Qt 5.1
  \value Sha3_256 Generate an SHA3-256 hash sum. Introduced in Qt 5.1
  \value Sha3_384 Generate an SHA3-384 hash sum. Introduced in Qt 5.1
  \value Sha3_512 Generate an SHA3-512 hash sum. Introduced in Qt 5.1
  \value Keccak_224 Generate a Keccak-224 hash sum. Introduced in Qt 5.9.2
  \value Keccak_256 Generate a Keccak-256 hash sum. Introduced in Qt 5.9.2
  \value Keccak_384 Generate a Keccak-384 hash sum. Introduced in Qt 5.9.2
  \value Keccak_512 Generate a Keccak-512 hash sum. Introduced in Qt 5.9.2
  \value Blake2b_160 Generate a BLAKE2b-160 hash sum. Introduced in Qt 6.0
  \value Blake2b_256 Generate a BLAKE2b-256 hash sum. Introduced in Qt 6.0
  \value Blake2b_384 Generate a BLAKE2b-384 hash sum. Introduced in Qt 6.0
  \value Blake2b_512 Generate a BLAKE2b-512 hash sum. Introduced in Qt 6.0
  \value Blake2s_128 Generate a BLAKE2s-128 hash sum. Introduced in Qt 6.0
  \value Blake2s_160 Generate a BLAKE2s-160 hash sum. Introduced in Qt 6.0
  \value Blake2s_224 Generate a BLAKE2s-224 hash sum. Introduced in Qt 6.0
  \value Blake2s_256 Generate a BLAKE2s-256 hash sum. Introduced in Qt 6.0
  \omitvalue RealSha3_224
  \omitvalue RealSha3_256
  \omitvalue RealSha3_384
  \omitvalue RealSha3_512
*/

/*!
  Constructs an object that can be used to create a cryptographic hash from data using \a method.
*/
QCryptographicHash::QCryptographicHash(Algorithm method)
    : d(new QCryptographicHashPrivate{method})
{
}

/*!
    \fn QCryptographicHash::QCryptographicHash(QCryptographicHash &&other)

    Move-constructs a new QCryptographicHash from \a other.

    \note The moved-from object \a other is placed in a
    partially-formed state, in which the only valid operations are
    destruction and assignment of a new value.

    \since 6.5
*/

/*!
  Destroys the object.
*/
QCryptographicHash::~QCryptographicHash()
{
    delete d;
}

/*!
    \fn QCryptographicHash &QCryptographicHash::operator=(QCryptographicHash &&other)

    Move-assigns \a other to this QCryptographicHash instance.

    \note The moved-from object \a other is placed in a
    partially-formed state, in which the only valid operations are
    destruction and assignment of a new value.

    \since 6.5
*/

/*!
    \fn void QCryptographicHash::swap(QCryptographicHash &other)

    Swaps cryptographic hash \a other with this cryptographic hash. This
    operation is very fast and never fails.

    \since 6.5
*/

/*!
  Resets the object.
*/
void QCryptographicHash::reset() noexcept
{
    d->reset();
}

/*!
    Returns the algorithm used to generate the cryptographic hash.

    \since 6.5
*/
QCryptographicHash::Algorithm QCryptographicHash::algorithm() const noexcept
{
    return d->method;
}

void QCryptographicHashPrivate::reset() noexcept
{
#ifdef USING_OPENSSL30
    if (method == QCryptographicHash::Blake2b_160 ||
        method == QCryptographicHash::Blake2b_256 ||
        method == QCryptographicHash::Blake2b_384) {
        new (&blake2bContext) blake2b_state;
        blake2b_init(&blake2bContext, hashLengthInternal(method));
        return;
    } else if (method == QCryptographicHash::Blake2s_128 ||
               method == QCryptographicHash::Blake2s_160 ||
               method == QCryptographicHash::Blake2s_224) {
        new (&blake2sContext) blake2s_state;
        blake2s_init(&blake2sContext, hashLengthInternal(method));
        return;
    }

    initializationFailed = true;

    if (method == QCryptographicHash::Md4) {
        /*
         * We need to load the legacy provider in order to have the MD4
         * algorithm available.
         */
        if (!OSSL_PROVIDER_load(nullptr, "legacy"))
            return;
        if (!OSSL_PROVIDER_load(nullptr, "default"))
            return;
    }

    context = EVP_MD_CTX_ptr(EVP_MD_CTX_new());

    if (!context) {
        return;
    }

    /*
     * Using the "-fips" option will disable the global "fips=yes" for
     * this one lookup and the algorithm can be fetched from any provider
     * that implements the algorithm (including the FIPS provider).
     */
    algorithm = EVP_MD_ptr(EVP_MD_fetch(nullptr, methodToName(method), "-fips"));
    if (!algorithm) {
        return;
    }

    initializationFailed = !EVP_DigestInit_ex(context.get(), algorithm.get(), nullptr);
#else
    switch (method) {
    case QCryptographicHash::Sha1:
        new (&sha1Context) Sha1State;
        sha1InitState(&sha1Context);
        break;
#ifdef QT_CRYPTOGRAPHICHASH_ONLY_SHA1
    default:
        Q_ASSERT_X(false, "QCryptographicHash", "Method not compiled in");
        Q_UNREACHABLE();
        break;
#else
    case QCryptographicHash::Md4:
        new (&md4Context) md4_context;
        md4_init(&md4Context);
        break;
    case QCryptographicHash::Md5:
        new (&md5Context) MD5Context;
        MD5Init(&md5Context);
        break;
    case QCryptographicHash::Sha224:
        new (&sha224Context) SHA224Context;
        SHA224Reset(&sha224Context);
        break;
    case QCryptographicHash::Sha256:
        new (&sha256Context) SHA256Context;
        SHA256Reset(&sha256Context);
        break;
    case QCryptographicHash::Sha384:
        new (&sha384Context) SHA384Context;
        SHA384Reset(&sha384Context);
        break;
    case QCryptographicHash::Sha512:
        new (&sha512Context) SHA512Context;
        SHA512Reset(&sha512Context);
        break;
    case QCryptographicHash::RealSha3_224:
    case QCryptographicHash::Keccak_224:
    case QCryptographicHash::RealSha3_256:
    case QCryptographicHash::Keccak_256:
    case QCryptographicHash::RealSha3_384:
    case QCryptographicHash::Keccak_384:
    case QCryptographicHash::RealSha3_512:
    case QCryptographicHash::Keccak_512:
        new (&sha3Context) SHA3Context;
        sha3Init(&sha3Context, hashLengthInternal(method) * 8);
        break;
    case QCryptographicHash::Blake2b_160:
    case QCryptographicHash::Blake2b_256:
    case QCryptographicHash::Blake2b_384:
    case QCryptographicHash::Blake2b_512:
        new (&blake2bContext) blake2b_state;
        blake2b_init(&blake2bContext, hashLengthInternal(method));
        break;
    case QCryptographicHash::Blake2s_128:
    case QCryptographicHash::Blake2s_160:
    case QCryptographicHash::Blake2s_224:
    case QCryptographicHash::Blake2s_256:
        new (&blake2sContext) blake2s_state;
        blake2s_init(&blake2sContext, hashLengthInternal(method));
        break;
#endif
    }
    result.clear();
#endif // !QT_CONFIG(opensslv30)
}

#if QT_DEPRECATED_SINCE(6, 4)
/*!
    Adds the first \a length chars of \a data to the cryptographic
    hash.

    \obsolete
    Use the QByteArrayView overload instead.
*/
void QCryptographicHash::addData(const char *data, qsizetype length)
{
    Q_ASSERT(length >= 0);
    addData(QByteArrayView{data, length});
}
#endif

/*!
    Adds the characters in \a bytes to the cryptographic hash.

    \note In Qt versions prior to 6.3, this function took QByteArray,
    not QByteArrayView.
*/
void QCryptographicHash::addData(QByteArrayView bytes) noexcept
{
    d->addData(bytes);
}

void QCryptographicHashPrivate::addData(QByteArrayView bytes) noexcept
{
    const char *data = bytes.data();
    auto length = bytes.size();

#if QT_POINTER_SIZE == 8
    // feed the data UINT_MAX bytes at a time, as some of the methods below
    // take a uint (of course, feeding more than 4G of data into the hashing
    // functions will be pretty slow anyway)
    for (auto remaining = length; remaining; remaining -= length, data += length) {
        length = qMin(qsizetype(std::numeric_limits<uint>::max()), remaining);
#else
    {
#endif

#ifdef USING_OPENSSL30
        if (method == QCryptographicHash::Blake2b_160 ||
            method == QCryptographicHash::Blake2b_256 ||
            method == QCryptographicHash::Blake2b_384) {
            blake2b_update(&blake2bContext, reinterpret_cast<const uint8_t *>(data), length);
        } else if (method == QCryptographicHash::Blake2s_128 ||
                method == QCryptographicHash::Blake2s_160 ||
                method == QCryptographicHash::Blake2s_224) {
            blake2s_update(&blake2sContext, reinterpret_cast<const uint8_t *>(data), length);
        } else if (!initializationFailed) {
            result.resizeForOverwrite(EVP_MD_get_size(algorithm.get()));
            const int ret = EVP_DigestUpdate(context.get(), (const unsigned char *)data, length);
            Q_UNUSED(ret);
        }
#else
        switch (method) {
        case QCryptographicHash::Sha1:
            sha1Update(&sha1Context, (const unsigned char *)data, length);
            break;
#ifdef QT_CRYPTOGRAPHICHASH_ONLY_SHA1
        default:
            Q_ASSERT_X(false, "QCryptographicHash", "Method not compiled in");
            Q_UNREACHABLE();
            break;
#else
        case QCryptographicHash::Md4:
            md4_update(&md4Context, (const unsigned char *)data, length);
            break;
        case QCryptographicHash::Md5:
            MD5Update(&md5Context, (const unsigned char *)data, length);
            break;
        case QCryptographicHash::Sha224:
            SHA224Input(&sha224Context, reinterpret_cast<const unsigned char *>(data), length);
            break;
        case QCryptographicHash::Sha256:
            SHA256Input(&sha256Context, reinterpret_cast<const unsigned char *>(data), length);
            break;
        case QCryptographicHash::Sha384:
            SHA384Input(&sha384Context, reinterpret_cast<const unsigned char *>(data), length);
            break;
        case QCryptographicHash::Sha512:
            SHA512Input(&sha512Context, reinterpret_cast<const unsigned char *>(data), length);
            break;
        case QCryptographicHash::RealSha3_224:
        case QCryptographicHash::Keccak_224:
        case QCryptographicHash::RealSha3_256:
        case QCryptographicHash::Keccak_256:
        case QCryptographicHash::RealSha3_384:
        case QCryptographicHash::Keccak_384:
        case QCryptographicHash::RealSha3_512:
        case QCryptographicHash::Keccak_512:
            sha3Update(&sha3Context, reinterpret_cast<const BitSequence *>(data), uint64_t(length) * 8);
            break;
        case QCryptographicHash::Blake2b_160:
        case QCryptographicHash::Blake2b_256:
        case QCryptographicHash::Blake2b_384:
        case QCryptographicHash::Blake2b_512:
            blake2b_update(&blake2bContext, reinterpret_cast<const uint8_t *>(data), length);
            break;
        case QCryptographicHash::Blake2s_128:
        case QCryptographicHash::Blake2s_160:
        case QCryptographicHash::Blake2s_224:
        case QCryptographicHash::Blake2s_256:
            blake2s_update(&blake2sContext, reinterpret_cast<const uint8_t *>(data), length);
            break;
#endif
        }
#endif // !QT_CONFIG(opensslv30)
    }
    result.clear();
}

/*!
  Reads the data from the open QIODevice \a device until it ends
  and hashes it. Returns \c true if reading was successful.
  \since 5.0
 */
bool QCryptographicHash::addData(QIODevice *device)
{
    if (!device->isReadable())
        return false;

    if (!device->isOpen())
        return false;

    char buffer[1024];
    int length;

    while ((length = device->read(buffer, sizeof(buffer))) > 0)
        d->addData({buffer, length});

    return device->atEnd();
}


/*!
  Returns the final hash value.

  \sa resultView(), QByteArray::toHex()
*/
QByteArray QCryptographicHash::result() const
{
    return resultView().toByteArray();
}

/*!
  \since 6.3

  Returns the final hash value.

  Note that the returned view remains valid only as long as the QCryptographicHash object is
  not modified by other means.

  \sa result()
*/
QByteArrayView QCryptographicHash::resultView() const noexcept
{
    d->finalize();
    return d->resultView();
}

void QCryptographicHashPrivate::finalize() noexcept
{
    if (!result.isEmpty())
        return;

#ifdef USING_OPENSSL30
    if (method == QCryptographicHash::Blake2b_160 ||
        method == QCryptographicHash::Blake2b_256 ||
        method == QCryptographicHash::Blake2b_384) {
        const auto length = hashLengthInternal(method);
        blake2b_state copy = blake2bContext;
        result.resizeForOverwrite(length);
        blake2b_final(&copy, reinterpret_cast<uint8_t *>(result.data()), length);
    } else if (method == QCryptographicHash::Blake2s_128 ||
               method == QCryptographicHash::Blake2s_160 ||
               method == QCryptographicHash::Blake2s_224) {
        const auto length = hashLengthInternal(method);
        blake2s_state copy = blake2sContext;
        result.resizeForOverwrite(length);
        blake2s_final(&copy, reinterpret_cast<uint8_t *>(result.data()), length);
    } else if (!initializationFailed) {
        result.resizeForOverwrite(EVP_MD_get_size(algorithm.get()));
        const int ret = EVP_DigestFinal_ex(context.get(), (unsigned char *)result.data(), nullptr);
        Q_UNUSED(ret);
    }
#else
    switch (method) {
    case QCryptographicHash::Sha1: {
        Sha1State copy = sha1Context;
        result.resizeForOverwrite(20);
        sha1FinalizeState(&copy);
        sha1ToHash(&copy, (unsigned char *)result.data());
        break;
    }
#ifdef QT_CRYPTOGRAPHICHASH_ONLY_SHA1
    default:
        Q_ASSERT_X(false, "QCryptographicHash", "Method not compiled in");
        Q_UNREACHABLE();
        break;
#else
    case QCryptographicHash::Md4: {
        md4_context copy = md4Context;
        result.resizeForOverwrite(MD4_RESULTLEN);
        md4_final(&copy, (unsigned char *)result.data());
        break;
    }
    case QCryptographicHash::Md5: {
        MD5Context copy = md5Context;
        result.resizeForOverwrite(16);
        MD5Final(&copy, (unsigned char *)result.data());
        break;
    }
    case QCryptographicHash::Sha224: {
        SHA224Context copy = sha224Context;
        result.resizeForOverwrite(SHA224HashSize);
        SHA224Result(&copy, reinterpret_cast<unsigned char *>(result.data()));
        break;
    }
    case QCryptographicHash::Sha256: {
        SHA256Context copy = sha256Context;
        result.resizeForOverwrite(SHA256HashSize);
        SHA256Result(&copy, reinterpret_cast<unsigned char *>(result.data()));
        break;
    }
    case QCryptographicHash::Sha384: {
        SHA384Context copy = sha384Context;
        result.resizeForOverwrite(SHA384HashSize);
        SHA384Result(&copy, reinterpret_cast<unsigned char *>(result.data()));
        break;
    }
    case QCryptographicHash::Sha512: {
        SHA512Context copy = sha512Context;
        result.resizeForOverwrite(SHA512HashSize);
        SHA512Result(&copy, reinterpret_cast<unsigned char *>(result.data()));
        break;
    }
    case QCryptographicHash::RealSha3_224:
    case QCryptographicHash::RealSha3_256:
    case QCryptographicHash::RealSha3_384:
    case QCryptographicHash::RealSha3_512: {
        sha3Finish(8 * hashLengthInternal(method), Sha3Variant::Sha3);
        break;
    }
    case QCryptographicHash::Keccak_224:
    case QCryptographicHash::Keccak_256:
    case QCryptographicHash::Keccak_384:
    case QCryptographicHash::Keccak_512: {
        sha3Finish(8 * hashLengthInternal(method), Sha3Variant::Keccak);
        break;
    }
    case QCryptographicHash::Blake2b_160:
    case QCryptographicHash::Blake2b_256:
    case QCryptographicHash::Blake2b_384:
    case QCryptographicHash::Blake2b_512: {
        const auto length = hashLengthInternal(method);
        blake2b_state copy = blake2bContext;
        result.resizeForOverwrite(length);
        blake2b_final(&copy, reinterpret_cast<uint8_t *>(result.data()), length);
        break;
    }
    case QCryptographicHash::Blake2s_128:
    case QCryptographicHash::Blake2s_160:
    case QCryptographicHash::Blake2s_224:
    case QCryptographicHash::Blake2s_256: {
        const auto length = hashLengthInternal(method);
        blake2s_state copy = blake2sContext;
        result.resizeForOverwrite(length);
        blake2s_final(&copy, reinterpret_cast<uint8_t *>(result.data()), length);
        break;
    }
#endif
    }
#endif // !QT_CONFIG(opensslv30)
}

/*!
  Returns the hash of \a data using \a method.

  \note In Qt versions prior to 6.3, this function took QByteArray,
  not QByteArrayView.
*/
QByteArray QCryptographicHash::hash(QByteArrayView data, Algorithm method)
{
    QCryptographicHashPrivate hash(method);
    hash.addData(data);
    hash.finalize();
    return hash.resultView().toByteArray();
}

/*!
  Returns the size of the output of the selected hash \a method in bytes.

  \since 5.12
*/
int QCryptographicHash::hashLength(QCryptographicHash::Algorithm method)
{
    return hashLengthInternal(method);
}

QT_END_NAMESPACE

#ifndef QT_NO_QOBJECT
#include "moc_qcryptographichash.cpp"
#endif