QCA

qca_basic.h
Go to the documentation of this file.
1/*
2 * qca_basic.h - Qt Cryptographic Architecture
3 * Copyright (C) 2003-2007 Justin Karneges <justin@affinix.com>
4 * Copyright (C) 2004-2007 Brad Hards <bradh@frogmouth.net>
5 * Copyright (C) 2013-2016 Ivan Romanov <drizt@land.ru>
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20 * 02110-1301 USA
21 *
22 */
23
24/**
25 \file qca_basic.h
26
27 Header file for classes for cryptographic primitives (basic operations).
28
29 \note You should not use this header directly from an
30 application. You should just use <tt> \#include <QtCrypto>
31 </tt> instead.
32*/
33
34#ifndef QCA_BASIC_H
35#define QCA_BASIC_H
36
37#include "qca_core.h"
38
39#include <QIODevice>
40
41namespace QCA {
42
43/**
44 \defgroup UserAPI QCA user API
45
46 This is the main set of QCA classes, intended for use
47 in standard applications.
48*/
49
50/**
51 \class Random qca_basic.h QtCrypto
52
53 Source of random numbers.
54
55 QCA provides a built in source of random numbers, which
56 can be accessed through this class. You can also use
57 an alternative random number source, by implementing
58 another provider.
59
60 The normal use of this class is expected to be through the
61 static members - randomChar(), randomInt() and randomArray().
62
63 \ingroup UserAPI
64 */
65class QCA_EXPORT Random : public Algorithm
66{
67public:
68 /**
69 Standard Constructor
70
71 \param provider the name of the provider library for the random
72 number generation
73 */
74 Random(const QString &provider = QString());
75
76 /**
77 Copy constructor
78
79 \param from the %Random object to copy from
80 */
81 Random(const Random &from);
82
83 ~Random() override;
84
85 /**
86 Assignment operator
87
88 \param from the %Random object to copy state from
89 */
90 Random &operator=(const Random &from);
91
92 /**
93 Provide a random byte.
94
95 This method isn't normally required - you should use
96 the static randomChar() method instead.
97
98 \sa randomChar
99 */
100 uchar nextByte();
101
102 /**
103 Provide a specified number of random bytes.
104
105 This method isn't normally required - you should use
106 the static randomArray() method instead.
107
108 \param size the number of bytes to provide
109
110 \sa randomArray
111 */
113
114 /**
115 Provide a random character (byte)
116
117 This is the normal way of obtaining a single random char
118 (i.e. 8 bit byte), as shown below:
119 \code
120myRandomChar = QCA::Random::randomChar();
121 \endcode
122
123 If you need a number of bytes, perhaps randomArray() may be of use.
124 */
125 static uchar randomChar();
126
127 /**
128 Provide a random integer.
129
130 This is the normal way of obtaining a single random integer,
131 as shown below:
132 \code
133myRandomInt = QCA::Random::randomInt();
134 \endcode
135 */
136 static int randomInt();
137
138 /**
139 Provide a specified number of random bytes.
140
141 \code
142// build a 30 byte secure array.
143SecureArray arry = QCA::Random::randomArray(30);
144 \endcode
145
146 \param size the number of bytes to provide
147 */
148 static SecureArray randomArray(int size);
149
150private:
151 class Private;
152 Private *d;
153};
154
155/**
156 \class Hash qca_basic.h QtCrypto
157
158 General class for hashing algorithms.
159
160 Hash is the class for the various hashing algorithms
161 within %QCA. SHA256, SHA1 or RIPEMD160 are recommended for
162 new applications, although MD2, MD4, MD5 or SHA0 may be
163 applicable (for interoperability reasons) for some
164 applications.
165
166 To perform a hash, you create a Hash object, call update()
167 with the data that needs to be hashed, and then call
168 final(), which returns a QByteArray of the hash result. An
169 example (using the SHA1 hash, with 1000 updates of a 1000
170 byte string) is shown below:
171
172 \code
173if(!QCA::isSupported("sha1"))
174 printf("SHA1 not supported!\n");
175else
176{
177 QByteArray fillerString;
178 fillerString.fill('a', 1000);
179
180 QCA::Hash shaHash("sha1");
181 for (int i=0; i<1000; i++)
182 shaHash.update(fillerString);
183 QByteArray hashResult = shaHash.final();
184 if ( "34aa973cd4c4daa4f61eeb2bdbad27316534016f" == QCA::arrayToHex(hashResult) )
185 {
186 printf("big SHA1 is OK\n");
187 }
188 else
189 {
190 printf("big SHA1 failed\n");
191 }
192}
193 \endcode
194
195 If you only have a simple hash requirement - a single
196 string that is fully available in memory at one time - then
197 you may be better off with one of the convenience
198 methods. So, for example, instead of creating a QCA::Hash
199 object, then doing a single update() and the final() call;
200 you could simply call QCA::Hash("algoName").hash() with the
201 data that you would otherwise have provided to the update()
202 call.
203
204 For more information on hashing algorithms, see \ref hashing.
205
206 \ingroup UserAPI
207*/
208class QCA_EXPORT Hash : public Algorithm, public BufferedComputation
209{
210public:
211 /**
212 Constructor
213
214 \param type label for the type of hash to be
215 created (for example, "sha1" or "md2")
216 \param provider the name of the provider plugin
217 for the subclass (eg "qca-ossl")
218 */
219 explicit Hash(const QString &type, const QString &provider = QString());
220
221 /**
222 Copy constructor
223
224 \param from the Hash object to copy from
225 */
226 Hash(const Hash &from);
227
228 ~Hash() override;
229
230 /**
231 Assignment operator
232
233 \param from the Hash object to copy state from
234 */
235 Hash &operator=(const Hash &from);
236
237 /**
238 Returns a list of all of the hash types available
239
240 \param provider the name of the provider to get a list from, if one
241 provider is required. If not specified, available hash types from all
242 providers will be returned.
243 */
244 static QStringList supportedTypes(const QString &provider = QString());
245
246 /**
247 Return the hash type
248 */
249 QString type() const;
250
251 /**
252 Reset a hash, dumping all previous parts of the
253 message.
254
255 This method clears (or resets) the hash algorithm,
256 effectively undoing any previous update()
257 calls. You should use this call if you are re-using
258 a Hash sub-class object to calculate additional
259 hashes.
260 */
261 void clear() override;
262
263 /**
264 Update a hash, adding more of the message contents
265 to the digest. The whole message needs to be added
266 using this method before you call final().
267
268 If you find yourself only calling update() once,
269 you may be better off using a convenience method
270 such as hash() or hashToString() instead.
271
272 \param a the byte array to add to the hash
273 */
274 void update(const MemoryRegion &a) override;
275
276 /**
277 \overload
278
279 \param a the QByteArray to add to the hash
280 */
281 void update(const QByteArray &a);
282
283 /**
284 \overload
285
286 This method is provided to assist with code that
287 already exists, and is being ported to %QCA. You are
288 better off passing a SecureArray (as shown above)
289 if you are writing new code.
290
291 \param data pointer to a char array
292 \param len the length of the array. If not specified
293 (or specified as a negative number), the length will be
294 determined with strlen(), which may not be what you want
295 if the array contains a null (0x00) character.
296 */
297 void update(const char *data, int len = -1);
298
299 /**
300 \overload
301
302 This allows you to read from a file or other
303 I/O device. Note that the device must be already
304 open for reading
305
306 \param file an I/O device
307
308 If you are trying to calculate the hash of
309 a whole file (and it isn't already open), you
310 might want to use code like this:
311 \code
312QFile f( "file.dat" );
313if ( f.open( QIODevice::ReadOnly ) )
314{
315 QCA::Hash hashObj("sha1");
316 hashObj.update( &f );
317 QByteArray output = hashObj.final().toByteArray();
318}
319 \endcode
320 */
321 void update(QIODevice *file);
322
323 /**
324 Finalises input and returns the hash result
325
326 After calling update() with the required data, the
327 hash results are finalised and produced.
328
329 Note that it is not possible to add further data (with
330 update()) after calling final(), because of the way
331 the hashing works - null bytes are inserted to pad
332 the results up to a fixed size. If you want to
333 reuse the Hash object, you should call clear() and
334 start to update() again.
335 */
336 MemoryRegion final() override;
337
338 /**
339 %Hash a byte array, returning it as another
340 byte array
341
342 This is a convenience method that returns the
343 hash of a SecureArray.
344
345 \code
346SecureArray sampleArray(3);
347sampleArray.fill('a');
348SecureArray outputArray = QCA::Hash("md2")::hash(sampleArray);
349 \endcode
350
351 \param array the QByteArray to hash
352
353 If you need more flexibility (e.g. you are constructing
354 a large byte array object just to pass it to hash(), then
355 consider creating an Hash object, and then calling
356 update() and final().
357 */
359
360 /**
361 %Hash a byte array, returning it as a printable
362 string
363
364 This is a convenience method that returns the
365 hash of a SecureArray as a hexadecimal
366 representation encoded in a QString.
367
368 \param array the QByteArray to hash
369
370 If you need more flexibility, you can create a Hash
371 object, call Hash::update() as required, then call
372 Hash::final(), before using the static arrayToHex() method.
373 */
375
376private:
377 class Private;
378 Private *d;
379};
380
381/**
382 \page hashing Hashing Algorithms
383
384 There are a range of hashing algorithms available in
385 %QCA. Hashing algorithms are used with the Hash and
386 MessageAuthenticationCode classes.
387
388 The MD2 algorithm takes an arbitrary data stream, known as the
389 message and outputs a condensed 128 bit (16 byte)
390 representation of that data stream, known as the message
391 digest. This algorithm is considered slightly more secure than MD5,
392 but is more expensive to compute. Unless backward
393 compatibility or interoperability are considerations, you
394 are better off using the SHA1 or RIPEMD160 hashing algorithms.
395 For more information on %MD2, see B. Kalinski RFC1319 "The %MD2
396 Message-Digest Algorithm". The label for MD2 is "md2".
397
398 The MD4 algorithm takes an arbitrary data stream, known as the
399 message and outputs a condensed 128 bit (16 byte)
400 representation of that data stream, known as the message
401 digest. MD4 is not considered to be secure, based on
402 known attacks. It should only be used for applications where
403 collision attacks are not a consideration (for example, as
404 used in the rsync algorithm for fingerprinting blocks of
405 data). If a secure hash is required, you are better off using
406 the SHA1 or RIPEMD160 hashing algorithms. MD2 and MD5 are both
407 stronger 128 bit hashes. For more information on MD4, see
408 R. Rivest RFC1320 "The %MD4 Message-Digest Algorithm". The
409 label for MD4 is "md4".
410
411 The MD5 takes an arbitrary data stream, known as the message
412 and outputs a condensed 128 bit (16 byte) representation of
413 that data stream, known as the message digest. MD5 is not
414 considered to be secure, based on known attacks. It should
415 only be used for applications where collision attacks are not
416 a consideration. If a secure hash is required, you are better
417 off using the SHA1 or RIPEMD160 hashing algorithms. For more
418 information on MD5, see R. Rivest RFC1321 "The %MD5
419 Message-Digest Algorithm". The label for MD5 is "md5".
420
421 The RIPEMD160 algorithm takes an arbitrary data stream, known
422 as the message (up to \f$2^{64}\f$ bits in length) and outputs
423 a condensed 160 bit (20 byte) representation of that data
424 stream, known as the message digest. The RIPEMD160 algorithm
425 is considered secure in that it is considered computationally
426 infeasible to find the message that produced the message
427 digest. The label for RIPEMD160 is "ripemd160".
428
429 The SHA-0 algorithm is a 160 bit hashing function, no longer
430 recommended for new applications because of known (partial)
431 attacks against it. The label for SHA-0 is "sha0".
432
433 The SHA-1 algorithm takes an arbitrary data stream, known as
434 the message (up to \f$2^{64}\f$ bits in length) and outputs a
435 condensed 160 bit (20 byte) representation of that data
436 stream, known as the message digest. SHA-1 is considered
437 secure in that it is considered computationally infeasible to
438 find the message that produced the message digest. For more
439 information on the SHA-1 algorithm,, see Federal Information
440 Processing Standard Publication 180-2 "Specifications for the
441 Secure %Hash Standard", available from
442 http://csrc.nist.gov/publications/. The label for SHA-1 is
443 "sha1".
444
445 The SHA-224 algorithm takes an arbitrary data stream, known as
446 the message (up to \f$2^{64}\f$ bits in length) and outputs a
447 condensed 224 bit (28 byte) representation of that data
448 stream, known as the message digest. SHA-224 is a "cut down"
449 version of SHA-256, and you may be better off using SHA-256 in
450 new designs. The SHA-224 algorithm is considered secure in
451 that it is considered computationally infeasible to find the
452 message that produced the message digest. For more information
453 on SHA-224, see Federal Information Processing Standard
454 Publication 180-2 "Specifications for the Secure %Hash
455 Standard", with change notice 1, available from
456 http://csrc.nist.gov/publications/. The label for SHA-224 is
457 "sha224".
458
459 The SHA-256 algorithm takes an arbitrary data stream, known as
460 the message (up to \f$2^{64}\f$ bits in length) and outputs a
461 condensed 256 bit (32 byte) representation of that data
462 stream, known as the message digest. The SHA-256 algorithm is
463 considered secure in that it is considered computationally
464 infeasible to find the message that produced the message
465 digest. For more information on SHA-256, see Federal
466 Information Processing Standard Publication 180-2
467 "Specifications for the Secure %Hash Standard", available from
468 http://csrc.nist.gov/publications/. The label for SHA-256 is
469 "sha256".
470
471 The SHA-384 algorithm takes an arbitrary data stream, known as
472 the message (up to \f$2^{128}\f$ bits in length) and outputs a
473 condensed 384 bit (48 byte) representation of that data
474 stream, known as the message digest. The SHA-384 algorithm is
475 a "cut down" version of SHA-512, and you may be better off
476 using SHA-512 in new designs. The SHA-384 algorithm is
477 considered secure in that it is considered computationally
478 infeasible to find the message that produced the message
479 digest. For more information on SHA-384, see Federal
480 Information Processing Standard Publication 180-2
481 "Specifications for the Secure %Hash Standard", available from
482 http://csrc.nist.gov/publications/. The label for SHA-384 is
483 "sha384".
484
485 The SHA-512 algorithm takes an arbitrary data stream, known as
486 the message (up to \f$2^{128}\f$ bits in length) and outputs a
487 condensed 512 bit (64 byte) representation of that data
488 stream, known as the message digest. The SHA-512 algorithm is
489 considered secure in that it is considered computationally
490 infeasible to find the message that produced the message
491 digest. For more information on SHA-512, see Federal
492 Information Processing Standard Publication 180-2
493 "Specifications for the Secure %Hash Standard", available from
494 http://csrc.nist.gov/publications/. The label for SHA-512 is
495 "sha512".
496
497 The Whirlpool algorithm takes an arbitrary data stream, known as
498 the message (up to \f$2^{256}\f$ bits in length) and outputs a
499 condensed 512 bit (64 byte) representation of that data
500 stream, known as the message digest. The Whirlpool algorithm is
501 considered secure in that it is considered computationally
502 infeasible to find the message that produced the message
503 digest. For more information on Whirlpool, see
504 http://paginas.terra.com.br/informatica/paulobarreto/WhirlpoolPage.html
505 or ISO/IEC 10118-3:2004. The label for Whirlpool is
506 "whirlpool".
507*/
508
509/**
510 \page paddingDescription Padding
511
512 For those Cipher sub-classes that are block based, there are modes
513 that require a full block on encryption and decryption - %Cipher Block
514 Chaining mode and Electronic Code Book modes are good examples.
515
516 Since real world messages are not always a convenient multiple of a
517 block size, we have to adding <i>padding</i>. There are a number of
518 padding modes that %QCA supports, including not doing any padding
519 at all.
520
521 If you are not going to use padding, then you can pass
522 QCA::Cipher::NoPadding as the pad argument to the Cipher sub-class,
523 however it is then your responsibility to pass in appropriate data for
524 the mode that you are using.
525
526 The most common padding scheme is known as PKCS#7 (also PKCS#1), and
527 it specifies that the pad bytes are all equal to the length of the
528 padding ( for example, if you need three pad bytes to complete the block,
529 then the padding is 0x03 0x03 0x03 ). PKCS#5 padding is a subset of
530 PKCS#7 padding for 8 byte block sizes. For explanation, see
531 http://crypto.stackexchange.com/questions/9043/what-is-the-difference-between-pkcs5-padding-and-pkcs7-padding/9044#9044.
532
533 On encryption, for algorithm / mode combinations that require
534 padding, you will get a block of ciphertext when the input plain
535 text block is complete. When you call final(), you will get out the
536 ciphertext that corresponds to the last part of the plain text,
537 plus any padding. If you had provided plaintext that matched up
538 with a block size, then the cipher text block is generated from
539 pure padding - you always get at least some padding, to ensure that
540 the padding can be safely removed on decryption.
541
542 On decryption, for algorithm / mode combinations that use padding,
543 you will get back a block of plaintext when the input ciphertext block
544 is complete. When you call final(), you will get a block that has been
545 stripped of ciphertext.
546*/
547
548/**
549 \class Cipher qca_basic.h QtCrypto
550
551 General class for cipher (encryption / decryption) algorithms.
552
553 Cipher is the class for the various algorithms that perform
554 low level encryption and decryption within %QCA.
555
556 AES128, AES192 and AES256 are recommended for new applications.
557
558 Standard names for ciphers are:
559 - Blowfish - "blowfish"
560 - TripleDES - "tripledes"
561 - DES - "des"
562 - AES128 - "aes128"
563 - AES192 - "aes192"
564 - AES256 - "aes256"
565 - CAST5 (CAST-128) - "cast5"
566
567 When checking for the availability of a particular kind
568 of cipher operation (e.g. AES128 in CBC mode with PKCS7
569 padding), you append the mode and padding type (in that
570 example "aes128-cbc-pkcs7"). CFB and OFB modes don't use
571 padding, so they are always just the cipher name followed
572 by the mode (e.g. "blowfish-cfb" or "aes192-ofb"). If
573 you are not using padding with CBC mode (i.e. you are
574 ensuring block size operations yourself), just use
575 the cipher name followed by "-cbc" (e.g. "blowfish-cbc"
576 or "aes256-cbc").
577
578 \ingroup UserAPI
579*/
580
581class QCA_EXPORT Cipher : public Algorithm, public Filter
582{
583public:
584 /**
585 Mode settings for cipher algorithms.
586
587 \note ECB is almost never what you want, unless you
588 are trying to implement a %Cipher variation that is not
589 supported by %QCA.
590 */
591 enum Mode
592 {
593 CBC, ///< operate in %Cipher Block Chaining mode
594 CFB, ///< operate in %Cipher FeedBack mode
595 ECB, ///< operate in Electronic Code Book mode
596 OFB, ///< operate in Output FeedBack Mode
597 CTR, ///< operate in CounTer Mode
598 GCM, ///< operate in Galois Counter Mode
599 CCM ///< operate in Counter with CBC-MAC
600 };
601
602 /**
603 Padding variations for cipher algorithms.
604
605 See the \ref paddingDescription description for more details on
606 padding schemes.
607 */
609 {
610 DefaultPadding, ///< Default for cipher-mode
611 NoPadding, ///< Do not use padding
612 PKCS7 ///< Pad using the scheme in PKCS#7
613 };
614
615 /**
616 Standard constructor
617
618 \param type the name of the cipher specialisation to use (e.g.
619 "aes128")
620 \param mode the operating Mode to use (e.g. QCA::Cipher::CBC)
621 \param pad the type of Padding to use
622 \param dir the Direction that this Cipher should use (Encode for
623 encryption, Decode for decryption)
624 \param key the SymmetricKey array that is the key
625 \param iv the InitializationVector to use (not used for ECB mode)
626 \param provider the name of the Provider to use
627
628 \note Padding only applies to CBC and ECB modes. CFB and OFB
629 ciphertext is always the length of the plaintext.
630 */
631 Cipher(const QString &type,
632 Mode mode,
633 Padding pad = DefaultPadding,
634 Direction dir = Encode,
635 const SymmetricKey &key = SymmetricKey(),
637 const QString &provider = QString());
638
639 /**
640 Standard constructor
641
642 \param type the name of the cipher specialisation to use (e.g.
643 "aes128")
644 \param mode the operating Mode to use (e.g. QCA::Cipher::CBC)
645 \param pad the type of Padding to use
646 \param dir the Direction that this Cipher should use (Encode for
647 encryption, Decode for decryption)
648 \param key the SymmetricKey array that is the key
649 \param iv the InitializationVector to use (not used for ECB mode)
650 \param tag the AuthTag to use (only for GCM and CCM modes)
651 \param provider the name of the Provider to use
652
653 \note Padding only applies to CBC and ECB modes. CFB and OFB
654 ciphertext is always the length of the plaintext.
655 */
656 Cipher(const QString &type,
657 Mode mode,
658 Padding pad,
659 Direction dir,
660 const SymmetricKey &key,
661 const InitializationVector &iv,
662 const AuthTag &tag,
663 const QString &provider = QString());
664
665 /**
666 Standard copy constructor
667
668 \param from the Cipher to copy state from
669 */
670 Cipher(const Cipher &from);
671
672 ~Cipher() override;
673
674 /**
675 Assignment operator
676
677 \param from the Cipher to copy state from
678 */
679 Cipher &operator=(const Cipher &from);
680
681 /**
682 Returns a list of all of the cipher types available
683
684 \param provider the name of the provider to get a list from, if one
685 provider is required. If not specified, available cipher types from all
686 providers will be returned.
687 */
688 static QStringList supportedTypes(const QString &provider = QString());
689
690 /**
691 Return the cipher type
692 */
693 QString type() const;
694
695 /**
696 Return the cipher mode
697 */
698 Mode mode() const;
699
700 /**
701 Return the cipher padding type
702 */
704
705 /**
706 Return the cipher direction
707 */
709
710 /**
711 Return acceptable key lengths
712 */
714
715 /**
716 Test if a key length is valid for the cipher algorithm
717
718 \param n the key length in bytes
719 \return true if the key would be valid for the current algorithm
720 */
721 bool validKeyLength(int n) const;
722
723 /**
724 return the block size for the cipher object
725 */
726 int blockSize() const;
727
728 /**
729 return the authentication tag for the cipher object
730 */
731 AuthTag tag() const;
732
733 /**
734 reset the cipher object, to allow re-use
735 */
736 void clear() override;
737
738 /**
739 pass in a byte array of data, which will be encrypted or decrypted
740 (according to the Direction that was set in the constructor or in
741 setup() ) and returned.
742
743 \param a the array of data to encrypt / decrypt
744 */
745 MemoryRegion update(const MemoryRegion &a) override;
746
747 /**
748 complete the block of data, padding as required, and returning
749 the completed block
750 */
751 MemoryRegion final() override;
752
753 /**
754 Test if an update() or final() call succeeded.
755
756 \return true if the previous call succeeded
757 */
758 bool ok() const override;
759
760 /**
761 Reset / reconfigure the Cipher
762
763 You can use this to re-use an existing Cipher, rather than creating
764 a new object with a slightly different configuration.
765
766 \param dir the Direction that this Cipher should use (Encode for
767 encryption, Decode for decryption)
768 \param key the SymmetricKey array that is the key
769 \param iv the InitializationVector to use (not used for ECB Mode)
770
771 \note You should not leave iv empty for any Mode except ECB.
772 */
774
775 /**
776 Reset / reconfigure the Cipher
777
778 You can use this to re-use an existing Cipher, rather than creating
779 a new object with a slightly different configuration.
780
781 \param dir the Direction that this Cipher should use (Encode for
782 encryption, Decode for decryption)
783 \param key the SymmetricKey array that is the key
784 \param iv the InitializationVector to use (not used for ECB Mode)
785 \param tag the AuthTag to use (only for GCM and CCM modes)
786
787 \note You should not leave iv empty for any Mode except ECB.
788 */
789 void setup(Direction dir, const SymmetricKey &key, const InitializationVector &iv, const AuthTag &tag);
790
791 /**
792 Construct a Cipher type string
793
794 \param cipherType the name of the algorithm (eg AES128, DES)
795 \param modeType the mode to operate the cipher in (eg QCA::CBC,
796 QCA::CFB)
797 \param paddingType the padding required (eg QCA::NoPadding,
798 QCA::PCKS7)
799 */
800 static QString withAlgorithms(const QString &cipherType, Mode modeType, Padding paddingType);
801
802private:
803 class Private;
804 Private *d;
805};
806
807/**
808 \class MessageAuthenticationCode qca_basic.h QtCrypto
809
810 General class for message authentication code (MAC) algorithms.
811
812 MessageAuthenticationCode is a class for accessing the various
813 message authentication code algorithms within %QCA.
814 HMAC using SHA1 ("hmac(sha1)") or HMAC using SHA256 ("hmac(sha256)")
815 is recommended for new applications.
816
817 Note that if your application is potentially susceptable to "replay
818 attacks" where the message is sent more than once, you should include a
819 counter in the message that is covered by the MAC, and check that the
820 counter is always incremented every time you receive a message and MAC.
821
822 For more information on HMAC, see H. Krawczyk et al. RFC2104
823 "HMAC: Keyed-Hashing for Message Authentication"
824
825 \ingroup UserAPI
826*/
828{
829public:
830 /**
831 Standard constructor
832
833 \param type the name of the MAC (and algorithm, if applicable) to
834 use
835 \param key the shared key
836 \param provider the provider to use, if a particular provider is
837 required
838 */
839 MessageAuthenticationCode(const QString &type, const SymmetricKey &key, const QString &provider = QString());
840
841 /**
842 Standard copy constructor
843
844 Copies the state (including key) from one MessageAuthenticationCode
845 to another
846
847 \param from the MessageAuthenticationCode to copy state from
848 */
850
852
853 /**
854 Assignment operator.
855
856 Copies the state (including key) from one MessageAuthenticationCode
857 to another
858
859 \param from the MessageAuthenticationCode to assign from.
860 */
862
863 /**
864 Returns a list of all of the message authentication code types
865 available
866
867 \param provider the name of the provider to get a list from, if one
868 provider is required. If not specified, available message authentication
869 codes types from all providers will be returned.
870 */
871 static QStringList supportedTypes(const QString &provider = QString());
872
873 /**
874 Return the MAC type
875 */
876 QString type() const;
877
878 /**
879 Return acceptable key lengths
880 */
882
883 /**
884 Test if a key length is valid for the MAC algorithm
885
886 \param n the key length in bytes
887 \return true if the key would be valid for the current algorithm
888 */
889 bool validKeyLength(int n) const;
890
891 /**
892 Reset a MessageAuthenticationCode, dumping all
893 previous parts of the message.
894
895 This method clears (or resets) the algorithm,
896 effectively undoing any previous update()
897 calls. You should use this call if you are re-using
898 a %MessageAuthenticationCode sub-class object
899 to calculate additional MACs. Note that if the key
900 doesn't need to be changed, you don't need to call
901 setup() again, since the key can just be reused.
902 */
903 void clear() override;
904
905 /**
906 Update the MAC, adding more of the message contents
907 to the digest. The whole message needs to be added
908 using this method before you call final().
909
910 \param array the message contents
911 */
912 void update(const MemoryRegion &array) override;
913
914 /**
915 Finalises input and returns the MAC result
916
917 After calling update() with the required data, the
918 hash results are finalised and produced.
919
920 Note that it is not possible to add further data (with
921 update()) after calling final(). If you want to
922 reuse the %MessageAuthenticationCode object, you
923 should call clear() and start to update() again.
924 */
925 MemoryRegion final() override;
926
927 /**
928 Initialise the MAC algorithm
929
930 \param key the key to use for the algorithm
931 */
932 void setup(const SymmetricKey &key);
933
934private:
935 class Private;
936 Private *d;
937};
938
939/**
940 \class KeyDerivationFunction qca_basic.h QtCrypto
941
942 General superclass for key derivation algorithms.
943
944 %KeyDerivationFunction is a superclass for the various
945 key derivation function algorithms within %QCA. You should
946 not need to use it directly unless you are
947 adding another key derivation capability to %QCA - you should be
948 using a sub-class. PBKDF2 using SHA1 is recommended for new applications.
949
950 \ingroup UserAPI
951
952*/
953class QCA_EXPORT KeyDerivationFunction : public Algorithm
954{
955public:
956 /**
957 Standard copy constructor
958
959 \param from the KeyDerivationFunction to copy from
960 */
962
963 ~KeyDerivationFunction() override;
964
965 /**
966 Assignment operator
967
968 Copies the state (including key) from one KeyDerivationFunction
969 to another
970
971 \param from the KeyDerivationFunction to assign from
972 */
974
975 /**
976 Generate the key from a specified secret and salt value
977
978 \note key length is ignored for some functions
979
980 \param secret the secret (password or passphrase)
981 \param salt the salt to use
982 \param keyLength the length of key to return
983 \param iterationCount the number of iterations to perform
984
985 \return the derived key
986 */
988 const InitializationVector &salt,
989 unsigned int keyLength,
990 unsigned int iterationCount);
991
992 /**
993 Generate the key from a specified secret and salt value
994
995 \note key length is ignored for some functions
996
997 \param secret the secret (password or passphrase)
998 \param salt the salt to use
999 \param keyLength the length of key to return
1000 \param msecInterval the maximum time to compute the key, in milliseconds
1001 \param iterationCount a pointer to store the number of iteration done for the specified time
1002
1003 \return the derived key
1004 */
1006 const InitializationVector &salt,
1007 unsigned int keyLength,
1008 int msecInterval,
1009 unsigned int *iterationCount);
1010
1011 /**
1012 Construct the name of the algorithm
1013
1014 You can use this to build a standard name string.
1015 You probably only need this method if you are
1016 creating a new subclass.
1017
1018 \param kdfType the type of key derivation function
1019 \param algType the name of the algorithm to use with the key derivation function
1020
1021 \return the name of the KDF/algorithm pair
1022 */
1023 static QString withAlgorithm(const QString &kdfType, const QString &algType);
1024
1025protected:
1026 /**
1027 Special constructor for subclass initialisation
1028
1029 \param type the algorithm to create
1030 \param provider the name of the provider to create the key derivation function in.
1031 */
1032 KeyDerivationFunction(const QString &type, const QString &provider);
1033
1034private:
1035 class Private;
1036 Private *d;
1037};
1038
1039/**
1040 \class PBKDF1 qca_basic.h QtCrypto
1041
1042 Password based key derivation function version 1
1043
1044 This class implements Password Based Key Derivation Function version 1,
1045 as specified in RFC2898, and also in PKCS#5.
1046
1047 \ingroup UserAPI
1048*/
1049class QCA_EXPORT PBKDF1 : public KeyDerivationFunction
1050{
1051public:
1052 /**
1053 Standard constructor
1054
1055 \param algorithm the name of the hashing algorithm to use
1056 \param provider the name of the provider to use, if available
1057 */
1058 explicit PBKDF1(const QString &algorithm = QStringLiteral("sha1"), const QString &provider = QString())
1059 : KeyDerivationFunction(withAlgorithm(QStringLiteral("pbkdf1"), algorithm), provider)
1060 {
1061 }
1062};
1063
1064/**
1065 \class PBKDF2 qca_basic.h QtCrypto
1066
1067 Password based key derivation function version 2
1068
1069 This class implements Password Based Key Derivation Function version 2,
1070 as specified in RFC2898, and also in PKCS#5.
1071
1072 \ingroup UserAPI
1073*/
1074class QCA_EXPORT PBKDF2 : public KeyDerivationFunction
1075{
1076public:
1077 /**
1078 Standard constructor
1079
1080 \param algorithm the name of the hashing algorithm to use
1081 \param provider the name of the provider to use, if available
1082 */
1083 explicit PBKDF2(const QString &algorithm = QStringLiteral("sha1"), const QString &provider = QString())
1084 : KeyDerivationFunction(withAlgorithm(QStringLiteral("pbkdf2"), algorithm), provider)
1085 {
1086 }
1087};
1088
1089/**
1090 \class HKDF qca_basic.h QtCrypto
1091 \since 2.3
1092
1093 HMAC-based extract-and-expand key derivation function
1094
1095 This class implements HMAC-based Extract-and-Expand Key Derivation Function,
1096 as specified in RFC5869.
1097
1098 \ingroup UserAPI
1099*/
1100class QCA_EXPORT HKDF : public Algorithm
1101{
1102public:
1103 /**
1104 Standard constructor
1105
1106 \param algorithm the name of the hashing algorithm to use
1107 \param provider the name of the provider to use, if available
1108 */
1109 explicit HKDF(const QString &algorithm = QStringLiteral("sha256"), const QString &provider = QString());
1110
1111 /**
1112 Standard copy constructor
1113
1114 \param from the KeyDerivationFunction to copy from
1115 */
1116 HKDF(const HKDF &from);
1117
1118 ~HKDF() override;
1119
1120 /**
1121 Assignment operator
1122
1123 Copies the state (including key) from one HKDF
1124 to another
1125
1126 \param from the HKDF to assign from
1127 */
1128 HKDF &operator=(const HKDF &from);
1129
1130 /**
1131 Generate the key from a specified secret, salt value, and an additional info
1132
1133 \note key length is ignored for some functions
1134
1135 \param secret the secret (password or passphrase)
1136 \param salt the salt to use
1137 \param info the info to use
1138 \param keyLength the length of key to return
1139
1140 \return the derived key
1141 */
1143 const InitializationVector &salt,
1144 const InitializationVector &info,
1145 unsigned int keyLength);
1146};
1147
1148}
1149
1150#endif
General superclass for an algorithm.
Definition qca_core.h:1164
Container for authentication tag.
Definition qca_core.h:1347
General superclass for buffered computation algorithms.
Definition qca_core.h:1052
General class for cipher (encryption / decryption) algorithms.
Definition qca_basic.h:582
bool validKeyLength(int n) const
Test if a key length is valid for the cipher algorithm.
Cipher(const QString &type, Mode mode, Padding pad, Direction dir, const SymmetricKey &key, const InitializationVector &iv, const AuthTag &tag, const QString &provider=QString())
Standard constructor.
Direction direction() const
Return the cipher direction.
Cipher & operator=(const Cipher &from)
Assignment operator.
static QStringList supportedTypes(const QString &provider=QString())
Returns a list of all of the cipher types available.
Padding padding() const
Return the cipher padding type.
Mode
Mode settings for cipher algorithms.
Definition qca_basic.h:592
@ ECB
operate in Electronic Code Book mode
Definition qca_basic.h:595
@ OFB
operate in Output FeedBack Mode
Definition qca_basic.h:596
@ CFB
operate in Cipher FeedBack mode
Definition qca_basic.h:594
@ GCM
operate in Galois Counter Mode
Definition qca_basic.h:598
@ CTR
operate in CounTer Mode
Definition qca_basic.h:597
@ CBC
operate in Cipher Block Chaining mode
Definition qca_basic.h:593
void setup(Direction dir, const SymmetricKey &key, const InitializationVector &iv=InitializationVector())
Reset / reconfigure the Cipher.
QString type() const
Return the cipher type.
static QString withAlgorithms(const QString &cipherType, Mode modeType, Padding paddingType)
Construct a Cipher type string.
Cipher(const QString &type, Mode mode, Padding pad=DefaultPadding, Direction dir=Encode, const SymmetricKey &key=SymmetricKey(), const InitializationVector &iv=InitializationVector(), const QString &provider=QString())
Standard constructor.
AuthTag tag() const
return the authentication tag for the cipher object
MemoryRegion update(const MemoryRegion &a) override
pass in a byte array of data, which will be encrypted or decrypted (according to the Direction that w...
void setup(Direction dir, const SymmetricKey &key, const InitializationVector &iv, const AuthTag &tag)
Reset / reconfigure the Cipher.
bool ok() const override
Test if an update() or final() call succeeded.
void clear() override
reset the cipher object, to allow re-use
Cipher(const Cipher &from)
Standard copy constructor.
Mode mode() const
Return the cipher mode.
KeyLength keyLength() const
Return acceptable key lengths.
@ NoPadding
Do not use padding.
Definition qca_basic.h:611
@ DefaultPadding
Default for cipher-mode.
Definition qca_basic.h:610
int blockSize() const
return the block size for the cipher object
General superclass for filtering transformation algorithms.
Definition qca_core.h:1108
HKDF & operator=(const HKDF &from)
Assignment operator.
HKDF(const QString &algorithm=QStringLiteral("sha256"), const QString &provider=QString())
Standard constructor.
HKDF(const HKDF &from)
Standard copy constructor.
SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt, const InitializationVector &info, unsigned int keyLength)
Generate the key from a specified secret, salt value, and an additional info.
General class for hashing algorithms.
Definition qca_basic.h:209
static QStringList supportedTypes(const QString &provider=QString())
Returns a list of all of the hash types available.
void update(QIODevice *file)
This is an overloaded member function, provided for convenience. It differs from the above function o...
void update(const MemoryRegion &a) override
Update a hash, adding more of the message contents to the digest.
MemoryRegion hash(const MemoryRegion &array)
Hash a byte array, returning it as another byte array
QString type() const
Return the hash type.
void clear() override
Reset a hash, dumping all previous parts of the message.
void update(const QByteArray &a)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Hash & operator=(const Hash &from)
Assignment operator.
Hash(const Hash &from)
Copy constructor.
QString hashToString(const MemoryRegion &array)
Hash a byte array, returning it as a printable string
Hash(const QString &type, const QString &provider=QString())
Constructor.
void update(const char *data, int len=-1)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Container for initialisation vectors and nonces.
Definition qca_core.h:1310
General superclass for key derivation algorithms.
Definition qca_basic.h:954
KeyDerivationFunction(const KeyDerivationFunction &from)
Standard copy constructor.
static QString withAlgorithm(const QString &kdfType, const QString &algType)
Construct the name of the algorithm.
KeyDerivationFunction & operator=(const KeyDerivationFunction &from)
Assignment operator.
SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt, unsigned int keyLength, int msecInterval, unsigned int *iterationCount)
Generate the key from a specified secret and salt value.
SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt, unsigned int keyLength, unsigned int iterationCount)
Generate the key from a specified secret and salt value.
KeyDerivationFunction(const QString &type, const QString &provider)
Special constructor for subclass initialisation.
Simple container for acceptable key lengths.
Definition qca_core.h:701
Array of bytes that may be optionally secured.
Definition qca_tools.h:91
General class for message authentication code (MAC) algorithms.
Definition qca_basic.h:828
bool validKeyLength(int n) const
Test if a key length is valid for the MAC algorithm.
MessageAuthenticationCode(const QString &type, const SymmetricKey &key, const QString &provider=QString())
Standard constructor.
static QStringList supportedTypes(const QString &provider=QString())
Returns a list of all of the message authentication code types available.
void setup(const SymmetricKey &key)
Initialise the MAC algorithm.
MessageAuthenticationCode & operator=(const MessageAuthenticationCode &from)
Assignment operator.
QString type() const
Return the MAC type.
void update(const MemoryRegion &array) override
Update the MAC, adding more of the message contents to the digest.
MessageAuthenticationCode(const MessageAuthenticationCode &from)
Standard copy constructor.
KeyLength keyLength() const
Return acceptable key lengths.
void clear() override
Reset a MessageAuthenticationCode, dumping all previous parts of the message.
Password based key derivation function version 1.
Definition qca_basic.h:1050
PBKDF1(const QString &algorithm=QStringLiteral("sha1"), const QString &provider=QString())
Standard constructor.
Definition qca_basic.h:1058
Password based key derivation function version 2.
Definition qca_basic.h:1075
PBKDF2(const QString &algorithm=QStringLiteral("sha1"), const QString &provider=QString())
Standard constructor.
Definition qca_basic.h:1083
Source of random numbers.
Definition qca_basic.h:66
uchar nextByte()
Provide a random byte.
Random & operator=(const Random &from)
Assignment operator.
Random(const Random &from)
Copy constructor.
static SecureArray randomArray(int size)
Provide a specified number of random bytes.
static int randomInt()
Provide a random integer.
Random(const QString &provider=QString())
Standard Constructor.
static uchar randomChar()
Provide a random character (byte)
SecureArray nextBytes(int size)
Provide a specified number of random bytes.
Secure array of bytes.
Definition qca_tools.h:317
Container for keys for symmetric encryption algorithms.
Definition qca_core.h:1264
QCA - the Qt Cryptographic Architecture.
Definition qca_basic.h:41
Direction
Direction settings for symmetric algorithms.
Definition qca_core.h:141
Header file for core QCA infrastructure.
This file is part of the KDE documentation.
Documentation copyright © 1996-2024 The KDE developers.
Generated on Mon Nov 18 2024 12:15:56 by doxygen 1.12.0 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.