File indexing completed on 2024-04-28 04:43:40

0001 /*
0002  * qca_basic.h - Qt Cryptographic Architecture
0003  * Copyright (C) 2003-2007  Justin Karneges <justin@affinix.com>
0004  * Copyright (C) 2004-2007  Brad Hards <bradh@frogmouth.net>
0005  * Copyright (C) 2013-2016  Ivan Romanov <drizt@land.ru>
0006  *
0007  * This library is free software; you can redistribute it and/or
0008  * modify it under the terms of the GNU Lesser General Public
0009  * License as published by the Free Software Foundation; either
0010  * version 2.1 of the License, or (at your option) any later version.
0011  *
0012  * This library is distributed in the hope that it will be useful,
0013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
0014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
0015  * Lesser General Public License for more details.
0016  *
0017  * You should have received a copy of the GNU Lesser General Public
0018  * License along with this library; if not, write to the Free Software
0019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
0020  * 02110-1301  USA
0021  *
0022  */
0023 
0024 /**
0025    \file qca_basic.h
0026 
0027    Header file for classes for cryptographic primitives (basic operations).
0028 
0029    \note You should not use this header directly from an
0030    application. You should just use <tt> \#include \<QtCrypto>
0031    </tt> instead.
0032 */
0033 
0034 #ifndef QCA_BASIC_H
0035 #define QCA_BASIC_H
0036 
0037 #include "qca_core.h"
0038 
0039 #include <QIODevice>
0040 
0041 namespace QCA {
0042 
0043 /**
0044    \defgroup UserAPI QCA user API
0045 
0046    This is the main set of QCA classes, intended for use
0047    in standard applications.
0048 */
0049 
0050 /**
0051    \class Random qca_basic.h QtCrypto
0052 
0053    Source of random numbers.
0054 
0055    QCA provides a built in source of random numbers, which
0056    can be accessed through this class. You can also use
0057    an alternative random number source, by implementing
0058    another provider.
0059 
0060    The normal use of this class is expected to be through the
0061    static members - randomChar(), randomInt() and randomArray().
0062 
0063    \ingroup UserAPI
0064  */
0065 class QCA_EXPORT Random : public Algorithm
0066 {
0067 public:
0068     /**
0069        Standard Constructor
0070 
0071        \param provider the name of the provider library for the random
0072            number generation
0073     */
0074     Random(const QString &provider = QString());
0075 
0076     /**
0077        Copy constructor
0078 
0079        \param from the %Random object to copy from
0080         */
0081     Random(const Random &from);
0082 
0083     ~Random() override;
0084 
0085     /**
0086    Assignment operator
0087 
0088    \param from the %Random object to copy state from
0089     */
0090     Random &operator=(const Random &from);
0091 
0092     /**
0093        Provide a random byte.
0094 
0095        This method isn't normally required - you should use
0096        the static randomChar() method instead.
0097 
0098        \sa randomChar
0099     */
0100     uchar nextByte();
0101 
0102     /**
0103        Provide a specified number of random bytes.
0104 
0105        This method isn't normally required - you should use
0106        the static randomArray() method instead.
0107 
0108        \param size the number of bytes to provide
0109 
0110        \sa randomArray
0111     */
0112     SecureArray nextBytes(int size);
0113 
0114     /**
0115        Provide a random character (byte)
0116 
0117        This is the normal way of obtaining a single random char
0118        (i.e. 8 bit byte), as shown below:
0119        \code
0120 myRandomChar = QCA::Random::randomChar();
0121        \endcode
0122 
0123        If you need a number of bytes, perhaps randomArray() may be of use.
0124     */
0125     static uchar randomChar();
0126 
0127     /**
0128        Provide a random integer.
0129 
0130        This is the normal way of obtaining a single random integer,
0131        as shown below:
0132        \code
0133 myRandomInt = QCA::Random::randomInt();
0134        \endcode
0135     */
0136     static int randomInt();
0137 
0138     /**
0139        Provide a specified number of random bytes.
0140 
0141        \code
0142 // build a 30 byte secure array.
0143 SecureArray arry = QCA::Random::randomArray(30);
0144        \endcode
0145 
0146        \param size the number of bytes to provide
0147     */
0148     static SecureArray randomArray(int size);
0149 
0150 private:
0151     class Private;
0152     Private *d;
0153 };
0154 
0155 /**
0156    \class Hash qca_basic.h QtCrypto
0157 
0158    General class for hashing algorithms.
0159 
0160    Hash is the class for the various hashing algorithms
0161    within %QCA. SHA256, SHA1 or RIPEMD160 are recommended for
0162    new applications, although MD2, MD4, MD5 or SHA0 may be
0163    applicable (for interoperability reasons) for some
0164    applications.
0165 
0166    To perform a hash, you create a Hash object, call update()
0167    with the data that needs to be hashed, and then call
0168    final(), which returns a QByteArray of the hash result. An
0169    example (using the SHA1 hash, with 1000 updates of a 1000
0170    byte string) is shown below:
0171 
0172    \code
0173 if(!QCA::isSupported("sha1"))
0174     printf("SHA1 not supported!\n");
0175 else
0176 {
0177     QByteArray fillerString;
0178     fillerString.fill('a', 1000);
0179 
0180     QCA::Hash shaHash("sha1");
0181     for (int i=0; i<1000; i++)
0182         shaHash.update(fillerString);
0183     QByteArray hashResult = shaHash.final();
0184     if ( "34aa973cd4c4daa4f61eeb2bdbad27316534016f" == QCA::arrayToHex(hashResult) )
0185     {
0186         printf("big SHA1 is OK\n");
0187     }
0188     else
0189     {
0190         printf("big SHA1 failed\n");
0191     }
0192 }
0193    \endcode
0194 
0195    If you only have a simple hash requirement - a single
0196    string that is fully available in memory at one time - then
0197    you may be better off with one of the convenience
0198    methods. So, for example, instead of creating a QCA::Hash
0199    object, then doing a single update() and the final() call;
0200    you could simply call QCA::Hash("algoName").hash() with the
0201    data that you would otherwise have provided to the update()
0202    call.
0203 
0204    For more information on hashing algorithms, see \ref hashing.
0205 
0206    \ingroup UserAPI
0207 */
0208 class QCA_EXPORT Hash : public Algorithm, public BufferedComputation
0209 {
0210 public:
0211     /**
0212        Constructor
0213 
0214        \param type label for the type of hash to be
0215        created (for example, "sha1" or "md2")
0216        \param provider the name of the provider plugin
0217        for the subclass (eg "qca-ossl")
0218     */
0219     explicit Hash(const QString &type, const QString &provider = QString());
0220 
0221     /**
0222        Copy constructor
0223 
0224        \param from the Hash object to copy from
0225         */
0226     Hash(const Hash &from);
0227 
0228     ~Hash() override;
0229 
0230     /**
0231        Assignment operator
0232 
0233        \param from the Hash object to copy state from
0234         */
0235     Hash &operator=(const Hash &from);
0236 
0237     /**
0238        Returns a list of all of the hash types available
0239 
0240        \param provider the name of the provider to get a list from, if one
0241        provider is required. If not specified, available hash types from all
0242        providers will be returned.
0243     */
0244     static QStringList supportedTypes(const QString &provider = QString());
0245 
0246     /**
0247        Return the hash type
0248     */
0249     QString type() const;
0250 
0251     /**
0252        Reset a hash, dumping all previous parts of the
0253        message.
0254 
0255        This method clears (or resets) the hash algorithm,
0256        effectively undoing any previous update()
0257        calls. You should use this call if you are re-using
0258        a Hash sub-class object to calculate additional
0259        hashes.
0260     */
0261     void clear() override;
0262 
0263     /**
0264        Update a hash, adding more of the message contents
0265        to the digest. The whole message needs to be added
0266        using this method before you call final().
0267 
0268        If you find yourself only calling update() once,
0269        you may be better off using a convenience method
0270        such as hash() or hashToString() instead.
0271 
0272        \param a the byte array to add to the hash
0273     */
0274     void update(const MemoryRegion &a) override;
0275 
0276     /**
0277        \overload
0278 
0279        \param a the QByteArray to add to the hash
0280     */
0281     void update(const QByteArray &a);
0282 
0283     /**
0284        \overload
0285 
0286        This method is provided to assist with code that
0287        already exists, and is being ported to %QCA. You are
0288        better off passing a SecureArray (as shown above)
0289        if you are writing new code.
0290 
0291        \param data pointer to a char array
0292        \param len the length of the array. If not specified
0293        (or specified as a negative number), the length will be
0294        determined with strlen(), which may not be what you want
0295        if the array contains a null (0x00) character.
0296     */
0297     void update(const char *data, int len = -1);
0298 
0299     /**
0300        \overload
0301 
0302        This allows you to read from a file or other
0303        I/O device. Note that the device must be already
0304        open for reading
0305 
0306        \param file an I/O device
0307 
0308        If you are trying to calculate the hash of
0309        a whole file (and it isn't already open), you
0310        might want to use code like this:
0311        \code
0312 QFile f( "file.dat" );
0313 if ( f.open( QIODevice::ReadOnly ) )
0314 {
0315     QCA::Hash hashObj("sha1");
0316     hashObj.update( &f );
0317     QByteArray output = hashObj.final().toByteArray();
0318 }
0319        \endcode
0320     */
0321     void update(QIODevice *file);
0322 
0323     /**
0324        Finalises input and returns the hash result
0325 
0326        After calling update() with the required data, the
0327        hash results are finalised and produced.
0328 
0329        Note that it is not possible to add further data (with
0330        update()) after calling final(), because of the way
0331        the hashing works - null bytes are inserted to pad
0332        the results up to a fixed size. If you want to
0333        reuse the Hash object, you should call clear() and
0334        start to update() again.
0335     */
0336     MemoryRegion final() override;
0337 
0338     /**
0339        %Hash a byte array, returning it as another
0340        byte array
0341 
0342        This is a convenience method that returns the
0343        hash of a SecureArray.
0344 
0345        \code
0346 SecureArray sampleArray(3);
0347 sampleArray.fill('a');
0348 SecureArray outputArray = QCA::Hash("md2")::hash(sampleArray);
0349        \endcode
0350 
0351        \param array the QByteArray to hash
0352 
0353        If you need more flexibility (e.g. you are constructing
0354        a large byte array object just to pass it to hash(), then
0355        consider creating an Hash object, and then calling
0356        update() and final().
0357     */
0358     MemoryRegion hash(const MemoryRegion &array);
0359 
0360     /**
0361        %Hash a byte array, returning it as a printable
0362        string
0363 
0364        This is a convenience method that returns the
0365        hash of a SecureArray as a hexadecimal
0366        representation encoded in a QString.
0367 
0368        \param array the QByteArray to hash
0369 
0370        If you need more flexibility, you can create a Hash
0371        object, call Hash::update() as required, then call
0372        Hash::final(), before using the static arrayToHex() method.
0373     */
0374     QString hashToString(const MemoryRegion &array);
0375 
0376 private:
0377     class Private;
0378     Private *d;
0379 };
0380 
0381 /**
0382    \page hashing Hashing Algorithms
0383 
0384    There are a range of hashing algorithms available in
0385    %QCA. Hashing algorithms are used with the Hash and
0386    MessageAuthenticationCode classes.
0387 
0388    The MD2 algorithm takes an arbitrary data stream, known as the
0389    message and outputs a condensed 128 bit (16 byte)
0390    representation of that data stream, known as the message
0391    digest. This algorithm is considered slightly more secure than MD5,
0392    but is more expensive to compute. Unless backward
0393    compatibility or interoperability are considerations, you
0394    are better off using the SHA1 or RIPEMD160 hashing algorithms.
0395    For more information on %MD2, see B. Kalinski RFC1319 "The %MD2
0396    Message-Digest Algorithm". The label for MD2 is "md2".
0397 
0398    The MD4 algorithm takes an arbitrary data stream, known as the
0399    message and outputs a condensed 128 bit (16 byte)
0400    representation of that data stream, known as the message
0401    digest. MD4 is not considered to be secure, based on
0402    known attacks. It should only be used for applications where
0403    collision attacks are not a consideration (for example, as
0404    used in the rsync algorithm for fingerprinting blocks of
0405    data). If a secure hash is required, you are better off using
0406    the SHA1 or RIPEMD160 hashing algorithms. MD2 and MD5 are both
0407    stronger 128 bit hashes.  For more information on MD4, see
0408    R. Rivest RFC1320 "The %MD4 Message-Digest Algorithm". The
0409    label for MD4 is "md4".
0410 
0411    The MD5 takes an arbitrary data stream, known as the message
0412    and outputs a condensed 128 bit (16 byte) representation of
0413    that data stream, known as the message digest. MD5 is not
0414    considered to be secure, based on known attacks. It should
0415    only be used for applications where collision attacks are not
0416    a consideration. If a secure hash is required, you are better
0417    off using the SHA1 or RIPEMD160 hashing algorithms.  For more
0418    information on MD5, see R. Rivest RFC1321 "The %MD5
0419    Message-Digest Algorithm". The label for MD5 is "md5".
0420 
0421    The RIPEMD160 algorithm takes an arbitrary data stream, known
0422    as the message (up to \f$2^{64}\f$ bits in length) and outputs
0423    a condensed 160 bit (20 byte) representation of that data
0424    stream, known as the message digest. The RIPEMD160 algorithm
0425    is considered secure in that it is considered computationally
0426    infeasible to find the message that produced the message
0427    digest. The label for RIPEMD160 is "ripemd160".
0428 
0429    The SHA-0 algorithm is a 160 bit hashing function, no longer
0430    recommended for new applications because of known (partial)
0431    attacks against it. The label for SHA-0 is "sha0".
0432 
0433    The SHA-1 algorithm takes an arbitrary data stream, known as
0434    the message (up to \f$2^{64}\f$ bits in length) and outputs a
0435    condensed 160 bit (20 byte) representation of that data
0436    stream, known as the message digest. SHA-1 is considered
0437    secure in that it is considered computationally infeasible to
0438    find the message that produced the message digest. For more
0439    information on the SHA-1 algorithm,, see Federal Information
0440    Processing Standard Publication 180-2 "Specifications for the
0441    Secure %Hash Standard", available from
0442    http://csrc.nist.gov/publications/. The label for SHA-1 is
0443    "sha1".
0444 
0445    The SHA-224 algorithm takes an arbitrary data stream, known as
0446    the message (up to \f$2^{64}\f$ bits in length) and outputs a
0447    condensed 224 bit (28 byte) representation of that data
0448    stream, known as the message digest. SHA-224 is a "cut down"
0449    version of SHA-256, and you may be better off using SHA-256 in
0450    new designs. The SHA-224 algorithm is considered secure in
0451    that it is considered computationally infeasible to find the
0452    message that produced the message digest. For more information
0453    on SHA-224, see Federal Information Processing Standard
0454    Publication 180-2 "Specifications for the Secure %Hash
0455    Standard", with change notice 1, available from
0456    http://csrc.nist.gov/publications/. The label for SHA-224 is
0457    "sha224".
0458 
0459    The SHA-256 algorithm takes an arbitrary data stream, known as
0460    the message (up to \f$2^{64}\f$ bits in length) and outputs a
0461    condensed 256 bit (32 byte) representation of that data
0462    stream, known as the message digest. The SHA-256 algorithm is
0463    considered secure in that it is considered computationally
0464    infeasible to find the message that produced the message
0465    digest. For more information on SHA-256, see Federal
0466    Information Processing Standard Publication 180-2
0467    "Specifications for the Secure %Hash Standard", available from
0468    http://csrc.nist.gov/publications/. The label for SHA-256 is
0469    "sha256".
0470 
0471    The SHA-384 algorithm takes an arbitrary data stream, known as
0472    the message (up to \f$2^{128}\f$ bits in length) and outputs a
0473    condensed 384 bit (48 byte) representation of that data
0474    stream, known as the message digest. The SHA-384 algorithm is
0475    a "cut down" version of SHA-512, and you may be better off
0476    using SHA-512 in new designs. The SHA-384 algorithm is
0477    considered secure in that it is considered computationally
0478    infeasible to find the message that produced the message
0479    digest. For more information on SHA-384, see Federal
0480    Information Processing Standard Publication 180-2
0481    "Specifications for the Secure %Hash Standard", available from
0482    http://csrc.nist.gov/publications/. The label for SHA-384 is
0483    "sha384".
0484 
0485    The SHA-512 algorithm takes an arbitrary data stream, known as
0486    the message (up to \f$2^{128}\f$ bits in length) and outputs a
0487    condensed 512 bit (64 byte) representation of that data
0488    stream, known as the message digest. The SHA-512 algorithm is
0489    considered secure in that it is considered computationally
0490    infeasible to find the message that produced the message
0491    digest. For more information on SHA-512, see Federal
0492    Information Processing Standard Publication 180-2
0493    "Specifications for the Secure %Hash Standard", available from
0494    http://csrc.nist.gov/publications/. The label for SHA-512 is
0495    "sha512".
0496 
0497    The Whirlpool algorithm takes an arbitrary data stream, known as
0498    the message (up to \f$2^{256}\f$ bits in length) and outputs a
0499    condensed 512 bit (64 byte) representation of that data
0500    stream, known as the message digest. The Whirlpool algorithm is
0501    considered secure in that it is considered computationally
0502    infeasible to find the message that produced the message
0503    digest. For more information on Whirlpool, see
0504    http://paginas.terra.com.br/informatica/paulobarreto/WhirlpoolPage.html
0505    or ISO/IEC 10118-3:2004. The label for Whirlpool is
0506    "whirlpool".
0507 */
0508 
0509 /**
0510    \page paddingDescription Padding
0511 
0512    For those Cipher sub-classes that are block based, there are modes
0513    that require a full block on encryption and decryption - %Cipher Block
0514    Chaining mode and Electronic Code Book modes are good examples.
0515 
0516    Since real world messages are not always a convenient multiple of a
0517    block size, we have to adding <i>padding</i>. There are a number of
0518    padding modes that %QCA supports, including not doing any padding
0519    at all.
0520 
0521    If you are not going to use padding, then you can pass
0522    QCA::Cipher::NoPadding as the pad argument to the Cipher sub-class,
0523    however it is then your responsibility to pass in appropriate data for
0524    the mode that you are using.
0525 
0526    The most common padding scheme is known as PKCS#7 (also PKCS#1), and
0527    it specifies that the pad bytes are all equal to the length of the
0528    padding ( for example, if you need three pad bytes to complete the block,
0529    then the padding is 0x03 0x03 0x03 ). PKCS#5 padding is a subset of
0530    PKCS#7 padding for 8 byte block sizes. For explanation, see
0531    http://crypto.stackexchange.com/questions/9043/what-is-the-difference-between-pkcs5-padding-and-pkcs7-padding/9044#9044.
0532 
0533    On encryption, for algorithm / mode combinations that require
0534    padding, you will get a block of ciphertext when the input plain
0535    text block is complete. When you call final(), you will get out the
0536    ciphertext that corresponds to the last part of the plain text,
0537    plus any padding. If you had provided plaintext that matched up
0538    with a block size, then the cipher text block is generated from
0539    pure padding - you always get at least some padding, to ensure that
0540    the padding can be safely removed on decryption.
0541 
0542    On decryption, for algorithm / mode combinations that use padding,
0543    you will get back a block of plaintext when the input ciphertext block
0544    is complete. When you call final(), you will get a block that has been
0545    stripped of ciphertext.
0546 */
0547 
0548 /**
0549    \class Cipher qca_basic.h QtCrypto
0550 
0551    General class for cipher (encryption / decryption) algorithms.
0552 
0553    Cipher is the class for the various algorithms that perform
0554    low level encryption and decryption within %QCA.
0555 
0556    AES128, AES192 and AES256 are recommended for new applications.
0557 
0558    Standard names for ciphers are:
0559    - Blowfish - "blowfish"
0560    - TripleDES - "tripledes"
0561    - DES - "des"
0562    - AES128 - "aes128"
0563    - AES192 - "aes192"
0564    - AES256 - "aes256"
0565    - CAST5 (CAST-128) - "cast5"
0566 
0567    When checking for the availability of a particular kind
0568    of cipher operation (e.g. AES128 in CBC mode with PKCS7
0569    padding), you append the mode and padding type (in that
0570    example "aes128-cbc-pkcs7"). CFB and OFB modes don't use
0571    padding, so they are always just the cipher name followed
0572    by the mode (e.g. "blowfish-cfb" or "aes192-ofb"). If
0573    you are not using padding with CBC mode (i.e. you are
0574    ensuring block size operations yourself), just use
0575    the cipher name followed by "-cbc" (e.g. "blowfish-cbc"
0576    or "aes256-cbc").
0577 
0578    \ingroup UserAPI
0579 */
0580 
0581 class QCA_EXPORT Cipher : public Algorithm, public Filter
0582 {
0583 public:
0584     /**
0585        Mode settings for cipher algorithms.
0586 
0587        \note ECB is almost never what you want, unless you
0588        are trying to implement a %Cipher variation that is not
0589        supported by %QCA.
0590     */
0591     enum Mode
0592     {
0593         CBC, ///< operate in %Cipher Block Chaining mode
0594         CFB, ///< operate in %Cipher FeedBack mode
0595         ECB, ///< operate in Electronic Code Book mode
0596         OFB, ///< operate in Output FeedBack Mode
0597         CTR, ///< operate in CounTer Mode
0598         GCM, ///< operate in Galois Counter Mode
0599         CCM  ///< operate in Counter with CBC-MAC
0600     };
0601 
0602     /**
0603        Padding variations for cipher algorithms.
0604 
0605        See the \ref paddingDescription description for more details on
0606        padding schemes.
0607     */
0608     enum Padding
0609     {
0610         DefaultPadding, ///< Default for cipher-mode
0611         NoPadding,      ///< Do not use padding
0612         PKCS7           ///< Pad using the scheme in PKCS#7
0613     };
0614 
0615     /**
0616        Standard constructor
0617 
0618        \param type the name of the cipher specialisation to use (e.g.
0619        "aes128")
0620        \param mode the operating Mode to use (e.g. QCA::Cipher::CBC)
0621        \param pad the type of Padding to use
0622        \param dir the Direction that this Cipher should use (Encode for
0623        encryption, Decode for decryption)
0624        \param key the SymmetricKey array that is the key
0625        \param iv the InitializationVector to use (not used for ECB mode)
0626        \param provider the name of the Provider to use
0627 
0628        \note Padding only applies to CBC and ECB modes.  CFB and OFB
0629        ciphertext is always the length of the plaintext.
0630     */
0631     Cipher(const QString              &type,
0632            Mode                        mode,
0633            Padding                     pad      = DefaultPadding,
0634            Direction                   dir      = Encode,
0635            const SymmetricKey         &key      = SymmetricKey(),
0636            const InitializationVector &iv       = InitializationVector(),
0637            const QString              &provider = QString());
0638 
0639     /**
0640        Standard constructor
0641 
0642        \param type the name of the cipher specialisation to use (e.g.
0643        "aes128")
0644        \param mode the operating Mode to use (e.g. QCA::Cipher::CBC)
0645        \param pad the type of Padding to use
0646        \param dir the Direction that this Cipher should use (Encode for
0647        encryption, Decode for decryption)
0648        \param key the SymmetricKey array that is the key
0649        \param iv the InitializationVector to use (not used for ECB mode)
0650        \param tag the AuthTag to use (only for GCM and CCM modes)
0651        \param provider the name of the Provider to use
0652 
0653        \note Padding only applies to CBC and ECB modes.  CFB and OFB
0654        ciphertext is always the length of the plaintext.
0655     */
0656     Cipher(const QString              &type,
0657            Mode                        mode,
0658            Padding                     pad,
0659            Direction                   dir,
0660            const SymmetricKey         &key,
0661            const InitializationVector &iv,
0662            const AuthTag              &tag,
0663            const QString              &provider = QString());
0664 
0665     /**
0666        Standard copy constructor
0667 
0668        \param from the Cipher to copy state from
0669     */
0670     Cipher(const Cipher &from);
0671 
0672     ~Cipher() override;
0673 
0674     /**
0675        Assignment operator
0676 
0677        \param from the Cipher to copy state from
0678     */
0679     Cipher &operator=(const Cipher &from);
0680 
0681     /**
0682        Returns a list of all of the cipher types available
0683 
0684        \param provider the name of the provider to get a list from, if one
0685        provider is required. If not specified, available cipher types from all
0686        providers will be returned.
0687     */
0688     static QStringList supportedTypes(const QString &provider = QString());
0689 
0690     /**
0691        Return the cipher type
0692     */
0693     QString type() const;
0694 
0695     /**
0696        Return the cipher mode
0697     */
0698     Mode mode() const;
0699 
0700     /**
0701        Return the cipher padding type
0702     */
0703     Padding padding() const;
0704 
0705     /**
0706        Return the cipher direction
0707     */
0708     Direction direction() const;
0709 
0710     /**
0711        Return acceptable key lengths
0712     */
0713     KeyLength keyLength() const;
0714 
0715     /**
0716        Test if a key length is valid for the cipher algorithm
0717 
0718        \param n the key length in bytes
0719        \return true if the key would be valid for the current algorithm
0720     */
0721     bool validKeyLength(int n) const;
0722 
0723     /**
0724        return the block size for the cipher object
0725     */
0726     int blockSize() const;
0727 
0728     /**
0729        return the authentication tag for the cipher object
0730     */
0731     AuthTag tag() const;
0732 
0733     /**
0734        reset the cipher object, to allow re-use
0735     */
0736     void clear() override;
0737 
0738     /**
0739        pass in a byte array of data, which will be encrypted or decrypted
0740        (according to the Direction that was set in the constructor or in
0741        setup() ) and returned.
0742 
0743        \param a the array of data to encrypt / decrypt
0744     */
0745     MemoryRegion update(const MemoryRegion &a) override;
0746 
0747     /**
0748        complete the block of data, padding as required, and returning
0749        the completed block
0750     */
0751     MemoryRegion final() override;
0752 
0753     /**
0754        Test if an update() or final() call succeeded.
0755 
0756        \return true if the previous call succeeded
0757     */
0758     bool ok() const override;
0759 
0760     /**
0761        Reset / reconfigure the Cipher
0762 
0763        You can use this to re-use an existing Cipher, rather than creating
0764        a new object with a slightly different configuration.
0765 
0766        \param dir the Direction that this Cipher should use (Encode for
0767        encryption, Decode for decryption)
0768        \param key the SymmetricKey array that is the key
0769        \param iv the InitializationVector to use (not used for ECB Mode)
0770 
0771        \note You should not leave iv empty for any Mode except ECB.
0772     */
0773     void setup(Direction dir, const SymmetricKey &key, const InitializationVector &iv = InitializationVector());
0774 
0775     /**
0776        Reset / reconfigure the Cipher
0777 
0778        You can use this to re-use an existing Cipher, rather than creating
0779        a new object with a slightly different configuration.
0780 
0781        \param dir the Direction that this Cipher should use (Encode for
0782        encryption, Decode for decryption)
0783        \param key the SymmetricKey array that is the key
0784        \param iv the InitializationVector to use (not used for ECB Mode)
0785        \param tag the AuthTag to use (only for GCM and CCM modes)
0786 
0787        \note You should not leave iv empty for any Mode except ECB.
0788     */
0789     void setup(Direction dir, const SymmetricKey &key, const InitializationVector &iv, const AuthTag &tag);
0790 
0791     /**
0792        Construct a Cipher type string
0793 
0794        \param cipherType the name of the algorithm (eg AES128, DES)
0795        \param modeType the mode to operate the cipher in (eg QCA::CBC,
0796        QCA::CFB)
0797        \param paddingType the padding required (eg QCA::NoPadding,
0798        QCA::PCKS7)
0799     */
0800     static QString withAlgorithms(const QString &cipherType, Mode modeType, Padding paddingType);
0801 
0802 private:
0803     class Private;
0804     Private *d;
0805 };
0806 
0807 /**
0808    \class MessageAuthenticationCode  qca_basic.h QtCrypto
0809 
0810    General class for message authentication code (MAC) algorithms.
0811 
0812    MessageAuthenticationCode is a class for accessing the various
0813    message authentication code algorithms within %QCA.
0814    HMAC using SHA1 ("hmac(sha1)") or HMAC using SHA256 ("hmac(sha256)")
0815    is recommended for new applications.
0816 
0817    Note that if your application is potentially susceptable to "replay
0818    attacks" where the message is sent more than once, you should include a
0819    counter in the message that is covered by the MAC, and check that the
0820    counter is always incremented every time you receive a message and MAC.
0821 
0822    For more information on HMAC, see H. Krawczyk et al. RFC2104
0823    "HMAC: Keyed-Hashing for Message Authentication"
0824 
0825    \ingroup UserAPI
0826 */
0827 class QCA_EXPORT MessageAuthenticationCode : public Algorithm, public BufferedComputation
0828 {
0829 public:
0830     /**
0831        Standard constructor
0832 
0833        \param type the name of the MAC (and algorithm, if applicable) to
0834        use
0835        \param key the shared key
0836        \param provider the provider to use, if a particular provider is
0837        required
0838     */
0839     MessageAuthenticationCode(const QString &type, const SymmetricKey &key, const QString &provider = QString());
0840 
0841     /**
0842        Standard copy constructor
0843 
0844        Copies the state (including key) from one MessageAuthenticationCode
0845        to another
0846 
0847        \param from the MessageAuthenticationCode to copy state from
0848     */
0849     MessageAuthenticationCode(const MessageAuthenticationCode &from);
0850 
0851     ~MessageAuthenticationCode() override;
0852 
0853     /**
0854        Assignment operator.
0855 
0856        Copies the state (including key) from one MessageAuthenticationCode
0857        to another
0858 
0859        \param from the MessageAuthenticationCode to assign from.
0860     */
0861     MessageAuthenticationCode &operator=(const MessageAuthenticationCode &from);
0862 
0863     /**
0864        Returns a list of all of the message authentication code types
0865        available
0866 
0867        \param provider the name of the provider to get a list from, if one
0868        provider is required. If not specified, available message authentication
0869        codes types from all providers will be returned.
0870     */
0871     static QStringList supportedTypes(const QString &provider = QString());
0872 
0873     /**
0874        Return the MAC type
0875     */
0876     QString type() const;
0877 
0878     /**
0879        Return acceptable key lengths
0880     */
0881     KeyLength keyLength() const;
0882 
0883     /**
0884        Test if a key length is valid for the MAC algorithm
0885 
0886        \param n the key length in bytes
0887        \return true if the key would be valid for the current algorithm
0888     */
0889     bool validKeyLength(int n) const;
0890 
0891     /**
0892        Reset a MessageAuthenticationCode, dumping all
0893        previous parts of the message.
0894 
0895        This method clears (or resets) the algorithm,
0896        effectively undoing any previous update()
0897        calls. You should use this call if you are re-using
0898        a %MessageAuthenticationCode sub-class object
0899        to calculate additional MACs. Note that if the key
0900        doesn't need to be changed, you don't need to call
0901        setup() again, since the key can just be reused.
0902     */
0903     void clear() override;
0904 
0905     /**
0906        Update the MAC, adding more of the message contents
0907        to the digest. The whole message needs to be added
0908        using this method before you call final().
0909 
0910        \param array the message contents
0911     */
0912     void update(const MemoryRegion &array) override;
0913 
0914     /**
0915        Finalises input and returns the MAC result
0916 
0917        After calling update() with the required data, the
0918        hash results are finalised and produced.
0919 
0920        Note that it is not possible to add further data (with
0921        update()) after calling final(). If you want to
0922        reuse the %MessageAuthenticationCode object, you
0923        should call clear() and start to update() again.
0924     */
0925     MemoryRegion final() override;
0926 
0927     /**
0928        Initialise the MAC algorithm
0929 
0930        \param key the key to use for the algorithm
0931     */
0932     void setup(const SymmetricKey &key);
0933 
0934 private:
0935     class Private;
0936     Private *d;
0937 };
0938 
0939 /**
0940    \class KeyDerivationFunction  qca_basic.h QtCrypto
0941 
0942    General superclass for key derivation algorithms.
0943 
0944    %KeyDerivationFunction is a superclass for the various
0945    key derivation function algorithms within %QCA. You should
0946    not need to use it directly unless you are
0947    adding another key derivation capability to %QCA - you should be
0948    using a sub-class. PBKDF2 using SHA1 is recommended for new applications.
0949 
0950    \ingroup UserAPI
0951 
0952 */
0953 class QCA_EXPORT KeyDerivationFunction : public Algorithm
0954 {
0955 public:
0956     /**
0957        Standard copy constructor
0958 
0959        \param from the KeyDerivationFunction to copy from
0960     */
0961     KeyDerivationFunction(const KeyDerivationFunction &from);
0962 
0963     ~KeyDerivationFunction() override;
0964 
0965     /**
0966        Assignment operator
0967 
0968        Copies the state (including key) from one KeyDerivationFunction
0969        to another
0970 
0971        \param from the KeyDerivationFunction to assign from
0972     */
0973     KeyDerivationFunction &operator=(const KeyDerivationFunction &from);
0974 
0975     /**
0976        Generate the key from a specified secret and salt value
0977 
0978        \note key length is ignored for some functions
0979 
0980        \param secret the secret (password or passphrase)
0981        \param salt the salt to use
0982        \param keyLength the length of key to return
0983        \param iterationCount the number of iterations to perform
0984 
0985        \return the derived key
0986     */
0987     SymmetricKey makeKey(const SecureArray          &secret,
0988                          const InitializationVector &salt,
0989                          unsigned int                keyLength,
0990                          unsigned int                iterationCount);
0991 
0992     /**
0993        Generate the key from a specified secret and salt value
0994 
0995        \note key length is ignored for some functions
0996 
0997        \param secret the secret (password or passphrase)
0998        \param salt the salt to use
0999        \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     */
1005     SymmetricKey makeKey(const SecureArray          &secret,
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 
1025 protected:
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 
1034 private:
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 */
1049 class QCA_EXPORT PBKDF1 : public KeyDerivationFunction
1050 {
1051 public:
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 */
1074 class QCA_EXPORT PBKDF2 : public KeyDerivationFunction
1075 {
1076 public:
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 */
1100 class QCA_EXPORT HKDF : public Algorithm
1101 {
1102 public:
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     */
1142     SymmetricKey makeKey(const SecureArray          &secret,
1143                          const InitializationVector &salt,
1144                          const InitializationVector &info,
1145                          unsigned int                keyLength);
1146 };
1147 
1148 }
1149 
1150 #endif