diff --git a/include/QtCrypto/qca_core.h b/include/QtCrypto/qca_core.h index 4d015cd5..9c4ca3fb 100644 --- a/include/QtCrypto/qca_core.h +++ b/include/QtCrypto/qca_core.h @@ -1,6 +1,6 @@ /* * qca_core.h - Qt Cryptographic Architecture - * Copyright (C) 2003-2005 Justin Karneges <justin@affinix.com> + * Copyright (C) 2003-2007 Justin Karneges <justin@affinix.com> * Copyright (C) 2004,2005 Brad Hards <bradh@frogmouth.net> * * This library is free software; you can redistribute it and/or @@ -58,1439 +58,1437 @@ */ QCA_EXPORT int qcaVersion(); -/** - * QCA - the Qt Cryptographic Architecture - */ -namespace QCA +/** + QCA - the Qt Cryptographic Architecture +*/ +namespace QCA { + +class Provider; +class Random; +class CertificateCollection; +class Global; +class KeyStore; +class KeyStoreEntry; +class KeyStoreInfo; +class KeyStoreManager; +class Logger; + +/** + Convenience representation for the plugin providers + + You can get a list of providers using the providers() + function + + \sa ProviderListIterator + \sa providers() +*/ +typedef QList<Provider*> ProviderList; + +/** + Mode settings for memory allocation + + QCA can use secure memory, however most operating systems + restrict the amount of memory that can be pinned by user + applications, to prevent a denial-of-service attack. + + QCA supports two approaches to getting memory - the mlock + method, which generally requires root (administrator) level + privileges, and the mmap method which is not as secure, but + which should be able to be used by any process. + + \sa Initializer +*/ +enum MemoryMode { - class Provider; - class Random; - class CertificateCollection; - class Global; - class KeyStore; - class KeyStoreEntry; - class KeyStoreInfo; - class KeyStoreManager; - class Logger; + Practical, ///< mlock and drop root if available, else mmap + Locking, ///< mlock and drop root + LockingKeepPrivileges ///< mlock, retaining root privileges +}; - /** - * Convenience representation for the plugin providers - * - * You can get a list of providers using the providers() - * function - * - * \sa ProviderListIterator - * \sa providers() - */ - typedef QList<Provider*> ProviderList; +/** + Direction settings for symmetric algorithms - /** - * Mode settings for memory allocation - * - * QCA can use secure memory, however most operating systems - * restrict the amount of memory that can be pinned by user - * applications, to prevent a denial-of-service attack. - * - * QCA supports two approaches to getting memory - the mlock - * method, which generally requires root (administrator) level - * privileges, and the mmap method which is not as secure, but - * which should be able to be used by any process. - * - * \sa Initializer - */ - enum MemoryMode - { - Practical, ///< mlock and drop root if available, else mmap - Locking, ///< mlock and drop root - LockingKeepPrivileges ///< mlock, retaining root privileges - }; + For some algorithms, it makes sense to have a "direction", such + as Cipher algorithms which can be used to encrypt or decrypt. +*/ +enum Direction +{ + Encode, ///< Operate in the "forward" direction; for example, encrypting + Decode ///< Operate in the "reverse" direction; for example, decrypting +}; - /** - * Direction settings for symmetric algorithms - * - * For some algorithms, it makes sense to have a "direction", such - * as Cipher algorithms which can be used to encrypt or decrypt. - */ - enum Direction - { - Encode, ///< Operate in the "forward" direction; for example, encrypting - Decode ///< Operate in the "reverse" direction; for example, decrypting - }; +/** + Initialise %QCA. + This call is not normally required, because it is cleaner + to use an Initializer. +*/ +QCA_EXPORT void init(); - /** - * Initialise %QCA. - * This call is not normally required, because it is cleaner - * to use an Initializer. - */ - QCA_EXPORT void init(); +/** + \overload - /** - * \overload - * - * \param m the MemoryMode to use - * \param prealloc the amount of memory in kilobytes to allocate - * for secure storage - */ - QCA_EXPORT void init(MemoryMode m, int prealloc); + \param m the MemoryMode to use + \param prealloc the amount of memory in kilobytes to allocate + for secure storage +*/ +QCA_EXPORT void init(MemoryMode m, int prealloc); - /** - * Clean up routine - * - * This routine cleans up %QCA, including memory allocations - * This call is not normally required, because it is cleaner - * to use an Initializer - */ - QCA_EXPORT void deinit(); +/** + Clean up routine - /** - * Test if secure storage memory is available - * - * \return true if secure storage memory is available - */ - QCA_EXPORT bool haveSecureMemory(); + This routine cleans up %QCA, including memory allocations + This call is not normally required, because it is cleaner + to use an Initializer +*/ +QCA_EXPORT void deinit(); - /** - * Test if secure random is available - * - * Secure random is considered available if the global random - * provider is not the default provider. - * - * \return true if secure random is available - */ - QCA_EXPORT bool haveSecureRandom(); +/** + Test if secure storage memory is available - /** - * Test if a capability (algorithm) is available. - * - * Since capabilities are made available at runtime, you - * should always check before using a capability the first - * time, as shown below. - * \code - * QCA::init(); - * if(!QCA::isSupported("sha1")) - * printf("SHA1 not supported!\n"); - * else { - * QString result = QCA::SHA1::hashToString(myString); - * printf("sha1(\"%s\") = [%s]\n", myString.data(), qPrintable(result)); - * } - * \endcode - * - * \param features the name of the capability to test for - * \param provider if specified, only check for the capability in that - specific provider. If not provided, or provided as an empty - string, then check for capabilities in all available providers - * \return true if the capability is available, otherwise false - * - * Note that you can test for a combination of capabilities, - * using a comma delimited list: - * \code - * QCA::isSupported("sha1,md5"): - * \endcode - * which will return true if all of the capabilities listed - * are present. - * - */ - QCA_EXPORT bool isSupported(const char *features, const QString &provider = QString()); + \return true if secure storage memory is available +*/ +QCA_EXPORT bool haveSecureMemory(); +/** + Test if secure random is available + + Secure random is considered available if the global random + provider is not the default provider. + + \return true if secure random is available +*/ +QCA_EXPORT bool haveSecureRandom(); + +/** + Test if a capability (algorithm) is available. + + Since capabilities are made available at runtime, you + should always check before using a capability the first + time, as shown below. + \code +QCA::init(); +if(!QCA::isSupported("sha1")) + printf("SHA1 not supported!\n"); +else +{ + QString result = QCA::SHA1::hashToString(myString); + printf("sha1(\"%s\") = [%s]\n", myString.data(), qPrintable(result)); +} + \endcode + + \param features the name of the capability to test for + \param provider if specified, only check for the capability in that + specific provider. If not provided, or provided as an empty + string, then check for capabilities in all available providers + \return true if the capability is available, otherwise false + + Note that you can test for a combination of capabilities, + using a comma delimited list: + \code +QCA::isSupported("sha1,md5"): + \endcode + which will return true if all of the capabilities listed + are present. +*/ +QCA_EXPORT bool isSupported(const char *features, const QString &provider = QString()); + +/** + \overload + + \param features a list of features to test for + \param provider if specified, only check for the capability in that + specific provider. If not provided, or provided as an empty + string, then check for capabilities in all available providers +*/ +QCA_EXPORT bool isSupported(const QStringList &features, const QString &provider = QString()); + +/** + Generate a list of all the supported features in plugins, + and in built in capabilities + + \return a list containing the names of the features + + The following code writes a list of features to standard out + \code +QStringList capabilities; +capabilities = QCA::supportedFeatures(); +std::cout << "Supported:" << capabilities.join(",") << std::endl; + \endcode + \sa isSupported(const char *features) + \sa isSupported(const QStringList &features) + \sa defaultFeatures() +*/ +QCA_EXPORT QStringList supportedFeatures(); + +/** + Generate a list of the built in features. This differs from + supportedFeatures() in that it does not include features provided + by plugins. + + \return a list containing the names of the features + + The following code writes a list of features to standard out + \code +QStringList capabilities; +capabilities = QCA::defaultFeatures(); +std::cout << "Default:" << capabilities.join(",") << std::endl; + \endcode + + \sa isSupported + \sa supportedFeatures() +*/ +QCA_EXPORT QStringList defaultFeatures(); + +/** + Add a provider to the current list of providers + + This function allows you to add a provider to the + current plugin providers at a specified priority. If + a provider with the name already exists, this call fails. + + \param p a pointer to a Provider object, which must be + set up. + \param priority the priority level to set the provider to + \return true if the provider is added, and false if the + provider is not added (failure) + + \sa setProviderPriority for a description of the provider priority system +*/ +QCA_EXPORT bool insertProvider(Provider *p, int priority = 0); + +/** + Change the priority of a specified provider + + QCA supports a number of providers, and if a number of providers + support the same algorithm, it needs to choose between them. You + can do this at object instantiation time (by specifying the name + of the provider that should be used). Alternatively, you can provide a + relative priority level at an application level, using this call. + + Priority is used at object instantiation time. The provider is selected + according to the following logic: + - if a particular provider is nominated, and that provider supports + the required algorithm, then the nominated provider is used + - if no provider is nominated, or it doesn't support the required + algorithm, then the provider with the lowest priority number will be used, + if that provider supports the algorithm. + - if the provider with the lowest priority number doesn't support + the required algorithm, the provider with the next lowest priority number + will be tried,and so on through to the provider with the largest priority number + - if none of the plugin providers support the required algorithm, then + the default (built-in) provider will be tried. + + \param name the name of the provider + \param priority the new priority of the provider. As a special case, if + you pass in -1, then this provider gets the same priority as the + the last provider that was added or had its priority set using this + call. + + \sa providerPriority +*/ +QCA_EXPORT void setProviderPriority(const QString &name, int priority); + +/** + Return the priority of a specified provider + + The name of the provider (eg "qca-openssl") is used to look up the + current priority associated with that provider. If the provider + is not found (or something else went wrong), -1 is returned. + + \param name the name of the provider + + \return the current priority level + + \sa setProviderPriority for a description of the provider priority system +*/ +QCA_EXPORT int providerPriority(const QString &name); + +/** + Return a list of the current providers + + The current plugin providers are provided as a list, which you + can iterate over using ProviderListIterator. + + \sa ProviderList + \sa ProviderListIterator +*/ +QCA_EXPORT ProviderList providers(); + +/** + Return the named provider, or 0 if not found +*/ +QCA_EXPORT Provider *findProvider(const QString &name); + +/** + Return the default provider +*/ +QCA_EXPORT Provider *defaultProvider(); + +/** + Scan for new plugins +*/ +QCA_EXPORT void scanForPlugins(); + +/** + Unload the current plugins +*/ +QCA_EXPORT void unloadAllPlugins(); + +/** + Retrieve plugin diagnostic text +*/ +QCA_EXPORT QString pluginDiagnosticText(); + +/** + Clear plugin diagnostic text +*/ +QCA_EXPORT void clearPluginDiagnosticText(); + +/** + Add plugin diagnostic text + + This function should only be called by providers. +*/ +QCA_EXPORT void appendPluginDiagnosticText(const QString &text); + +/** + Set a global property +*/ +QCA_EXPORT void setProperty(const QString &name, const QVariant &value); + +/** + Retrieve a global property +*/ +QCA_EXPORT QVariant getProperty(const QString &name); + +/** + Set provider configuration + + Allowed value types: QString, int, bool +*/ +QCA_EXPORT void setProviderConfig(const QString &name, const QVariantMap &config); + +/** + Retrieve provider configuration +*/ +QCA_EXPORT QVariantMap getProviderConfig(const QString &name); + +/** + Save provider configuration to persistent storage +*/ +QCA_EXPORT void saveProviderConfig(const QString &name); + +/** + Return the name of the global random number provider +*/ +QCA_EXPORT QString globalRandomProvider(); + +/** + Change the global random number provider + + The Random capabilities of %QCA are provided as part of the + built in capabilities, however the generator can be changed + if required. +*/ +QCA_EXPORT void setGlobalRandomProvider(const QString &provider); + +/** + Return a reference to the %QCA Logger, which is used for diagnostics + and error recording. + + The system Logger is automatically created for you on start. +*/ +QCA_EXPORT Logger *logger(); + +/** + Log a text message. This is an efficient function + to avoid overhead of argument executions when log level + blocks the message. + + \param message the text to log + \param severity the type of information to log + + \note This is a macro, so arguments may or may not be evaluated. +*/ +#define QCA_logTextMessage(message, severity) \ + do { \ + register QCA::Logger::Severity s = severity; \ + register QCA::Logger *l = QCA::logger (); \ + if (s <= l->level ()) { \ + l->logTextMessage (message, s); \ + } \ + } while (false) + +/** + Log a binary message. This is an efficient function + to avoid overhead of argument executions when log level + blocks the message. + + \param blob the blob to log + \param severity the type of information to log + + \note This is a macro, so arguments may or may not be evaluated. +*/ +#define QCA_logBinaryMessage(blob, severity) \ + do { \ + register QCA::Logger::Severity s = severity; \ + register QCA::Logger *l = QCA::logger (); \ + if (s <= l->level ()) { \ + l->logBinaryMessage (blob, s); \ + } \ + } while (false) + +/** + Test if QCA can access the root CA certificates + + If root certificates are available, this function returns true, + otherwise it returns false. + + \sa systemStore +*/ +QCA_EXPORT bool haveSystemStore(); + +/** + Get system-wide root CA certificates + + \sa haveSystemStore +*/ +QCA_EXPORT CertificateCollection systemStore(); + +/** + Get the application name that will be used by SASL server mode + + The application name is used by SASL in server mode, as some systems might + have different security policies depending on the app. + The default application name is 'qca' +*/ +QCA_EXPORT QString appName(); + +/** + Set the application name that will be used by SASL server mode + + The application name is used by SASL in server mode, as some systems might + have different security policies depending on the app. This should be set + before using SASL objects, and it cannot be changed later. + + \param name the name string to use for SASL server mode +*/ +QCA_EXPORT void setAppName(const QString &name); + +/** + Convert a byte array to printable hexadecimal + representation. + + This is a convenience function to convert an arbitrary + SecureArray to a printable representation. + + \code +SecureArray test(10); +test.fill('a'); +// 0x61 is 'a' in ASCII +if (QString("61616161616161616161") == QCA::arrayToHex(test) ) +{ + printf ("arrayToHex passed\n"); +} + \endcode + + \param array the array to be converted + \return a printable representation +*/ +QCA_EXPORT QString arrayToHex(const SecureArray &array); + +/** + Convert a QString containing a hexadecimal representation + of a byte array into a QByteArray + + This is a convenience function to convert a printable + representation into a QByteArray - effectively the inverse + of QCA::arrayToHex. + + \code +QCA::init(); +QByteArray test(10); + +test.fill('b'); // 0x62 in hexadecimal +test[7] = 0x00; // can handle strings with nulls + +if (QCA::hexToArray(QString("62626262626262006262") ) == test ) +{ + printf ("hexToArray passed\n"); +} + \endcode + + \param hexString the string containing a printable + representation to be converted + \return the equivalent QByteArray +*/ +QCA_EXPORT QByteArray hexToArray(const QString &hexString); + +/** + \class Initializer qca_core.h QtCrypto + + Convenience method for initialising and cleaning up %QCA + + To ensure that QCA is properly initialised and cleaned up, + it is convenient to create an Initializer object, and let it + go out of scope at the end of %QCA usage. +*/ +class QCA_EXPORT Initializer +{ +public: /** - \overload - - \param features a list of features to test for - \param provider if specified, only check for the capability in that - specific provider. If not provided, or provided as an empty - string, then check for capabilities in all available providers + Standard constructor + + \param m the MemoryMode to use for secure memory + \param prealloc the amount of secure memory to pre-allocate, + in units of 1024 bytes (1K). */ - QCA_EXPORT bool isSupported(const QStringList &features, const QString &provider = QString()); + explicit Initializer(MemoryMode m = Practical, int prealloc = 64); + ~Initializer(); +}; +/** + \class KeyLength qca_core.h QtCrypto + + Simple container for acceptable key lengths + + The KeyLength specifies the minimum and maximum byte sizes + allowed for a key, as well as a "multiple" which the key + size must evenly divide into. + + As an example, if the key can be 4, 8 or 12 bytes, you can + express this as + \code +KeyLength keyLen( 4, 12, 4 ); + \endcode + + If you want to express a KeyLength that takes any number + of bytes (including zero), you may want to use + \code +#include<limits> +KeyLength( 0, std::numeric_limits<int>::max(), 1 ); + \endcode +*/ +class QCA_EXPORT KeyLength +{ +public: /** - * Generate a list of all the supported features in plugins, - * and in built in capabilities - * - * \return a list containing the names of the features - * - * The following code writes a list of features to standard out - * \code - * QStringList capabilities; - * capabilities = QCA::supportedFeatures(); - * std::cout << "Supported:" << capabilities.join(",") << std::endl; - * \endcode - * - * \sa isSupported(const char *features) - * \sa isSupported(const QStringList &features) - * \sa defaultFeatures() - */ - QCA_EXPORT QStringList supportedFeatures(); + Construct a %KeyLength object - /** - * Generate a list of the built in features. This differs from - * supportedFeatures() in that it does not include features provided - * by plugins. - * - * \return a list containing the names of the features - * - * The following code writes a list of features to standard out - * \code - * QStringList capabilities; - * capabilities = QCA::defaultFeatures(); - * std::cout << "Default:" << capabilities.join(",") << std::endl; - * \endcode - * - * \sa isSupported(const char *features) - * \sa isSupported(const QStringList &features) - * \sa supportedFeatures() - */ - QCA_EXPORT QStringList defaultFeatures(); - - /** - * Add a provider to the current list of providers - * - * This function allows you to add a provider to the - * current plugin providers at a specified priority. If - * a provider with the name already exists, this call fails. - * - * \param p a pointer to a Provider object, which must be - * set up. - * \param priority the priority level to set the provider to - * - * \return true if the provider is added, and false if the - * provider is not added (failure) - * - * \sa setProviderPriority for a description of the provider priority system - */ - QCA_EXPORT bool insertProvider(Provider *p, int priority = 0); - - /** - * Change the priority of a specified provider - * - * QCA supports a number of providers, and if a number of providers - * support the same algorithm, it needs to choose between them. You - * can do this at object instantiation time (by specifying the name - * of the provider that should be used). Alternatively, you can provide a - * relative priority level at an application level, using this call. - * - * Priority is used at object instantiation time. The provider is selected - * according to the following logic: - * - if a particular provider is nominated, and that provider supports - * the required algorithm, then the nominated provider is used - * - if no provider is nominated, or it doesn't support the required - * algorithm, then the provider with the lowest priority number will be used, - * if that provider supports the algorithm. - * - if the provider with the lowest priority number doesn't support - * the required algorithm, the provider with the next lowest priority number - * will be tried,and so on through to the provider with the largest priority number - * - if none of the plugin providers support the required algorithm, then - * the default (built-in) provider will be tried. - * - * \param name the name of the provider - * \param priority the new priority of the provider. As a special case, if - * you pass in -1, then this provider gets the same priority as the - * the last provider that was added or had its priority set using this - * call. - * - * \sa providerPriority - */ - QCA_EXPORT void setProviderPriority(const QString &name, int priority); - - /** - * Return the priority of a specified provider - * - * The name of the provider (eg "qca-openssl") is used to look up the - * current priority associated with that provider. If the provider - * is not found (or something else went wrong), -1 is returned. - * - * \param name the name of the provider - * - * \return the current priority level - * - * \sa setProviderPriority for a description of the provider priority system - */ - QCA_EXPORT int providerPriority(const QString &name); - - /** - * Return a list of the current providers - * - * The current plugin providers are provided as a list, which you - * can iterate over using ProviderListIterator. - * - * \sa ProviderList - * \sa ProviderListIterator - */ - QCA_EXPORT ProviderList providers(); - - /** - * Return the named provider, or 0 if not found - */ - QCA_EXPORT Provider *findProvider(const QString &name); - - /** - * Return the default provider - */ - QCA_EXPORT Provider *defaultProvider(); - - /** - * Scan for new plugins - */ - QCA_EXPORT void scanForPlugins(); - - /** - * Unload the current plugins - */ - QCA_EXPORT void unloadAllPlugins(); - - /** - * Retrieve plugin diagnostic text - */ - QCA_EXPORT QString pluginDiagnosticText(); - - /** - * Clear plugin diagnostic text - */ - QCA_EXPORT void clearPluginDiagnosticText(); - - /** - * Add plugin diagnostic text - * - * This function should only be called by providers. - */ - QCA_EXPORT void appendPluginDiagnosticText(const QString &text); - - /** - * Set a global property - */ - QCA_EXPORT void setProperty(const QString &name, const QVariant &value); - - /** - * Retrieve a global property - */ - QCA_EXPORT QVariant getProperty(const QString &name); - - /** - * Set provider configuration - * - * Allowed value types: QString, int, bool - */ - QCA_EXPORT void setProviderConfig(const QString &name, const QVariantMap &config); - - /** - * Retrieve provider configuration - */ - QCA_EXPORT QVariantMap getProviderConfig(const QString &name); - - /** - * Save provider configuration to persistent storage - */ - QCA_EXPORT void saveProviderConfig(const QString &name); - - /** - * Return the name of the global random number provider - */ - QCA_EXPORT QString globalRandomProvider(); - - /** - * Change the global random number provider - * - * The Random capabilities of %QCA are provided as part of the - * built in capabilities, however the generator can be changed - * if required. - */ - QCA_EXPORT void setGlobalRandomProvider(const QString &provider); - - /** - Return a reference to the %QCA Logger, which is used for diagnostics - and error recording. - - The system Logger is automatically created for you on start. + \param min the minimum length of the key, in bytes + \param max the maximum length of the key, in bytes + \param multiple the number of bytes that the key must be a + multiple of. */ - QCA_EXPORT Logger *logger(); + KeyLength(int min, int max, int multiple) + : _min( min ), _max(max), _multiple( multiple ) + { } /** - Log a text message. This is an efficient function - to avoid overhead of argument executions when log level - blocks the message. - - \param message the text to log - \param severity the type of information to log - - \note This is a macro, so arguments may or may not be evaluated. + Obtain the minimum length for the key, in bytes */ -# define QCA_logTextMessage(message, severity) \ - do { \ - register QCA::Logger::Severity s = severity; \ - register QCA::Logger *l = QCA::logger (); \ - if (s <= l->level ()) { \ - l->logTextMessage (message, s); \ - } \ - } while (false) + int minimum() const { return _min; } /** - Log a binary message. This is an efficient function - to avoid overhead of argument executions when log level - blocks the message. - - \param blob the blob to log - \param severity the type of information to log - - \note This is a macro, so arguments may or may not be evaluated. + Obtain the maximum length for the key, in bytes */ -# define QCA_logBinaryMessage(blob, severity) \ - do { \ - register QCA::Logger::Severity s = severity; \ - register QCA::Logger *l = QCA::logger (); \ - if (s <= l->level ()) { \ - l->logBinaryMessage (blob, s); \ - } \ - } while (false) + int maximum() const { return _max; } /** - Test if QCA can access the root CA certificates + Return the number of bytes that the key must be a multiple of - If root certificates are available, this function returns true, - otherwise it returns false. - - \sa systemStore + If this is one, then anything between minimum and maximum (inclusive) + is acceptable. */ - QCA_EXPORT bool haveSystemStore(); + int multiple() const { return _multiple; } + +private: + const int _min, _max, _multiple; +}; + +/** + \class Provider qca_core.h QtCrypto + + Algorithm provider + + Provider represents a plugin provider (or as a special case, the + built-in provider). This is the class you need to inherit + from to create your own plugin. You don't normally need to + worry about this class if you are just using existing + QCA capabilities and plugins, however there is nothing stopping + you from using it to obtain information about specific plugins, + as shown in the example below. +*/ +class QCA_EXPORT Provider +{ +public: + virtual ~Provider(); + + class Context; /** - Get system-wide root CA certificates + Initialisation routine. - \sa haveSystemStore + This routine will be called when your plugin + is loaded, so this is a good place to do any + one-off initialisation tasks. If you don't need + any initialisation, just implement it as an empty + routine. */ - QCA_EXPORT CertificateCollection systemStore(); + virtual void init(); /** - * Get the application name that will be used by SASL server mode - * - * The application name is used by SASL in server mode, as some systems might - * have different security policies depending on the app. - * The default application name is 'qca' - */ - QCA_EXPORT QString appName(); + Target QCA version for the provider. + + This is used to verify compatibility between the + provider and QCA. For a provider to be used, it + must have major and minor version numbers that are + less-than or equal to the QCA version (the patch + version number is ignored). This means an older + provider may be used with a newer QCA, but a newer + provider cannot be used with an older QCA. + */ + virtual int version() const = 0; /** - * Set the application name that will be used by SASL server mode - * - * The application name is used by SASL in server mode, as some systems might - * have different security policies depending on the app. This should be set - * before using SASL objects, and it cannot be changed later. - * - * \param name the name string to use for SASL server mode - */ - QCA_EXPORT void setAppName(const QString &name); + The name of the provider. - /** - * Convert a byte array to printable hexadecimal - * representation. - * - * This is a convenience function to convert an arbitrary - * SecureArray to a printable representation. - * - * \code - * SecureArray test(10); - * test.fill('a'); - * // 0x61 is 'a' in ASCII - * if (QString("61616161616161616161") == QCA::arrayToHex(test) ) { - * printf ("arrayToHex passed\n"); - * } - * \endcode - * - * \param array the array to be converted - * \return a printable representation - */ - QCA_EXPORT QString arrayToHex(const SecureArray &array); + Typically you just return a string containing a + convenient name. - /** - * Convert a QString containing a hexadecimal representation - * of a byte array into a QByteArray - * - * This is a convenience function to convert a printable - * representation into a QByteArray - effectively the inverse - * of QCA::arrayToHex. - * - * \code - * QCA::init(); - * QByteArray test(10); - * - * test.fill('b'); // 0x62 in hexadecimal - * test[7] = 0x00; // can handle strings with nulls - * - * if (QCA::hexToArray(QString("62626262626262006262") ) == test ) { - * printf ("hexToArray passed\n"); - * } - * \endcode - * - * \param hexString the string containing a printable - * representation to be converted - * \return the equivalent QByteArray - * - */ - QCA_EXPORT QByteArray hexToArray(const QString &hexString); - - /** - \class Initializer qca_core.h QtCrypto - - Convenience method for initialising and cleaning up %QCA - - To ensure that QCA is properly initialised and cleaned up, - it is convenient to create an Initializer object, and let it - go out of scope at the end of %QCA usage. - */ - class QCA_EXPORT Initializer - { - public: - /** - * Standard constructor - * - * \param m the MemoryMode to use for secure memory - * \param prealloc the amount of secure memory to pre-allocate, - * in units of 1024 bytes (1K). - */ - explicit Initializer(MemoryMode m = Practical, int prealloc = 64); - ~Initializer(); - }; - - /** - \class KeyLength qca_core.h QtCrypto - - Simple container for acceptable key lengths - - The KeyLength specifies the minimum and maximum byte sizes - allowed for a key, as well as a "multiple" which the key - size must evenly divide into. - - As an example, if the key can be 4, 8 or 12 bytes, you can - express this as \code - KeyLength keyLen( 4, 12, 4 ); +QString name() const +{ + return "qca-myplugin"; +} \endcode - If you want to express a KeyLength that takes any number - of bytes (including zero), you may want to use + \note The name is used to tell if a provider is + already loaded, so you need to make sure it is + unique amongst the various plugins. + */ + virtual QString name() const = 0; + + /** + The capabilities (algorithms) of the provider. + + Typically you just return a fixed QStringList: \code - #include<limits> - KeyLength( 0, std::numeric_limits<int>::max(), 1 ); +QStringList features() const +{ + QStringList list; + list += "sha1"; + list += "sha256"; + list += "hmac(md5)"; + return list; +} \endcode - */ - class QCA_EXPORT KeyLength - { - public: - /** - * Construct a %KeyLength object - * - * \param min the minimum length of the key, in bytes - * \param max the maximum length of the key, in bytes - * \param multiple the number of bytes that the key must be a - * multiple of. - */ - KeyLength(int min, int max, int multiple) - : _min( min ), _max(max), _multiple( multiple ) - { } - - /** - * Obtain the minimum length for the key, in bytes - */ - int minimum() const { return _min; } - - /** - * Obtain the maximum length for the key, in bytes - */ - int maximum() const { return _max; } - - /** - * Return the number of bytes that the key must be a multiple of - * - * If this is one, then anything between minimum and maximum (inclusive) - * is acceptable. - */ - int multiple() const { return _multiple; } - - private: - const int _min, _max, _multiple; - }; + */ + virtual QStringList features() const = 0; /** - \class Provider qca_core.h QtCrypto + Optional credit text for the provider. - Algorithm provider - - Provider represents a plugin provider (or as a special case, the - built-in provider). This is the class you need to inherit - from to create your own plugin. You don't normally need to - worry about this class if you are just using existing - QCA capabilities and plugins, however there is nothing stopping - you from using it to obtain information about specific plugins, - as shown in the example below. - */ - class QCA_EXPORT Provider - { - public: - virtual ~Provider(); - - class Context; - - /** - * Initialisation routine. - * - * This routine will be called when your plugin - * is loaded, so this is a good place to do any - * one-off initialisation tasks. If you don't need - * any initialisation, just implement it as an empty - * routine. - */ - virtual void init(); - - /** - * Target QCA version for the provider. - * - * This is used to verify compatibility between the - * provider and QCA. For a provider to be used, it - * must have major and minor version numbers that are - * less-than or equal to the QCA version (the patch - * version number is ignored). This means an older - * provider may be used with a newer QCA, but a newer - * provider cannot be used with an older QCA. - */ - virtual int version() const = 0; - - /** - * The name of the provider. - * - * Typically you just return a string containing a - * convenient name. - * - * \code - * QString name() const - * { - * return "qca-myplugin"; - * } - * \endcode - * - * \note The name is used to tell if a provider is - * already loaded, so you need to make sure it is - * unique amongst the various plugins. - */ - virtual QString name() const = 0; - - /** - * The capabilities (algorithms) of the provider. - * - * Typically you just return a fixed QStringList: - * \code - * QStringList features() const - * { - * QStringList list; - * list += "sha1"; - * list += "sha256"; - * list += "hmac(md5)"; - * return list; - * } - * \endcode - */ - virtual QStringList features() const = 0; - - /** - * Optional credit text for the provider. - * - * You might display this information in a credits or - * "About" dialog. Returns an empty string if the - * provider has no credit text. - */ - virtual QString credit() const; - - /** - * Routine to create a plugin context - * - * You need to return a pointer to an algorithm - * Context that corresponds with the algorithm - * name specified. - * - * \param type the name of the algorithm required - * - * \code - * Context *createContext(const QString &type) - * { - * if ( type == "sha1" ) - * return new SHA1Context( this ); - * else if ( type == "sha256" ) - * return new SHA0256Context( this ); - * else if ( type == "hmac(sha1)" ) - * return new HMACSHA1Context( this ); - * else - * return 0; - * } - * \endcode - * - * Naturally you also need to implement - * the specified Context subclasses as well. - */ - virtual Context *createContext(const QString &type) = 0; - - virtual QVariantMap defaultConfig() const; - virtual void configChanged(const QVariantMap &config); - }; + You might display this information in a credits or + "About" dialog. Returns an empty string if the + provider has no credit text. + */ + virtual QString credit() const; /** - \class Context qca_core.h QtCrypto + Routine to create a plugin context - Internal context class used for the plugin + You need to return a pointer to an algorithm + Context that corresponds with the algorithm + name specified. + \param type the name of the algorithm required + + \code +Context *createContext(const QString &type) +{ + if ( type == "sha1" ) + return new SHA1Context( this ); + else if ( type == "sha256" ) + return new SHA0256Context( this ); + else if ( type == "hmac(sha1)" ) + return new HMACSHA1Context( this ); + else + return 0; +} + \endcode + + Naturally you also need to implement + the specified Context subclasses as well. + */ + virtual Context *createContext(const QString &type) = 0; + + virtual QVariantMap defaultConfig() const; + virtual void configChanged(const QVariantMap &config); +}; + +/** + \class Context qca_core.h QtCrypto + + Internal context class used for the plugin + + \internal +*/ +class QCA_EXPORT Provider::Context : public QObject +{ + Q_OBJECT +public: + virtual ~Context(); + + /** + The Provider associated with this Context + */ + Provider *provider() const; + + /** + The type of context, as passed to the constructor + */ + QString type() const; + + /** + Create a duplicate of this Context + */ + virtual Context *clone() const = 0; + + /** + Test if two Contexts have the same Provider + + \param c pointer to the Context to compare to + + \return true if the argument and this Context + have the same provider. + */ + bool sameProvider(const Context *c) const; + +protected: + /** + Standard constructor + + \param parent the parent provider for this + context + \param type the name of the provider context type + */ + Context(Provider *parent, const QString &type); + + // copy constructor + Context(const Context &from); + +private: + // disable assignment + Context & operator=(const Context &from); + + Provider *_provider; + QString _type; +}; + +class QCA_EXPORT BasicContext : public Provider::Context +{ + Q_OBJECT +public: + ~BasicContext(); + +protected: + BasicContext(Provider *parent, const QString &type); + BasicContext(const BasicContext &from); + +private: + // disable assignment + BasicContext & operator=(const BasicContext &from); +}; + +/** + \class BufferedComputation qca_core.h QtCrypto + + General superclass for buffered computation algorithms + + A buffered computation is characterised by having the + algorithm take data in an incremental way, then having + the results delivered at the end. Conceptually, the + algorithm has some internal state that is modified + when you call update() and returned when you call + final(). +*/ +class QCA_EXPORT BufferedComputation +{ +public: + virtual ~BufferedComputation(); + + /** + Reset the internal state + */ + virtual void clear() = 0; + + /** + Update the internal state with a byte array + + \param a the byte array of data that is to + be used to update the internal state. + */ + virtual void update(const SecureArray &a) = 0; + + /** + Complete the algorithm and return the internal state + */ + virtual SecureArray final() = 0; + + /** + Perform an "all in one" update, returning + the result. This is appropriate if you + have all the data in one array - just + call process on that array, and you will + get back the results of the computation. + + \note This will invalidate any previous + computation using this object. + */ + SecureArray process(const SecureArray &a); +}; + +/** + \class Filter qca_core.h QtCrypto + + General superclass for filtering transformation algorithms + + A filtering computation is characterised by having the + algorithm take input data in an incremental way, with results + delivered for each input, or block of input. Some internal + state may be managed, with the transformation completed + when final() is called. + + If this seems a big vague, then you might try deriving + your class from a subclass with stronger semantics, or if your + update() function is always returning null results, and + everything comes out at final(), try BufferedComputation. +*/ +class QCA_EXPORT Filter +{ +public: + virtual ~Filter(); + + /** + Reset the internal state + */ + virtual void clear() = 0; + + /** + Process more data, returning the corresponding + filtered version of the data. + + \param a the array containing data to process + */ + virtual SecureArray update(const SecureArray &a) = 0; + + /** + Complete the algorithm, returning any + additional results. + */ + virtual SecureArray final() = 0; + + /** + Test if an update() or final() call succeeded. + + \return true if the previous call succeeded + */ + virtual bool ok() const = 0; + + /** + Perform an "all in one" update, returning + the result. This is appropriate if you + have all the data in one array - just + call process on that array, and you will + get back the results of the computation. + + \note This will invalidate any previous + computation using this object. + */ + SecureArray process(const SecureArray &a); +}; + +/** + \class Algorithm qca_core.h QtCrypto + + General superclass for an algorithm. + + This is a fairly abstract class, mainly used for + implementing the backend "provider" interface. +*/ +class QCA_EXPORT Algorithm +{ +public: + /** + Standard copy constructor + + \param from the Algorithm to copy from + */ + Algorithm(const Algorithm &from); + + virtual ~Algorithm(); + + /** + Assignment operator + + \param from the Algorithm to copy state from + */ + Algorithm & operator=(const Algorithm &from); + + /** + The name of the algorithm type. + */ + QString type() const; + + /** + The name of the provider + + Each algorithm is implemented by a provider. This + allows you to figure out which provider is associated + */ + Provider *provider() const; + + // Note: The next five functions are not public! + + /** \internal + + The context associated with this algorithm */ - class QCA_EXPORT Provider::Context : public QObject + Provider::Context *context(); + + /** + \internal + + The context associated with this algorithm + */ + const Provider::Context *context() const; + + /** + \internal + + Set the Provider for this algorithm + + \param c the context for the Provider to use + */ + void change(Provider::Context *c); + + /** + \internal + + \overload + + \param type the name of the algorithm to use + \param provider the name of the preferred provider + */ + void change(const QString &type, const QString &provider); + + /** + \internal + + Take the Provider from this algorithm + */ + Provider::Context *takeContext(); + +protected: + /** + Constructor for empty algorithm + */ + Algorithm(); + + /** + Constructor of a particular algorithm. + + \param type the algorithm to construct + \param provider the name of a particular Provider + */ + Algorithm(const QString &type, const QString &provider); + +private: + class Private; + QSharedDataPointer<Private> d; +}; + +/** + \class SymmetricKey qca_core.h QtCrypto + + Container for keys for symmetric encryption algorithms. +*/ +class QCA_EXPORT SymmetricKey : public SecureArray +{ +public: + /** + Construct an empty (zero length) key + */ + SymmetricKey(); + + /** + Construct an key of specified size, with random contents + + This is intended to be used as a random session key. + + \param size the number of bytes for the key + */ + SymmetricKey(int size); + + /** + Construct a key from a provided byte array + + \param a the byte array to copy + */ + SymmetricKey(const SecureArray &a); + + /** + Construct a key from a provided byte array + + \param a the byte array to copy + */ + SymmetricKey(const QByteArray &a); + + /** + Test for weak DES keys + + \return true if the key is a weak key for DES + */ + bool isWeakDESKey(); +}; + +/** + \class InitializationVector qca_core.h QtCrypto + + Container for initialisation vectors and nonces +*/ +class QCA_EXPORT InitializationVector : public SecureArray +{ +public: + /** + Construct an empty (zero length) initisation vector + */ + InitializationVector(); + + /** + Construct an initialisation vector of the specified size + + \param size the length of the initialisation vector, in bytes + */ + InitializationVector(int size); + + /** + Construct an initialisation vector from a provided byte array + + \param a the byte array to copy + */ + InitializationVector(const SecureArray &a); + + /** + Construct an initialisation vector from a provided byte array + + \param a the byte array to copy + */ + InitializationVector(const QByteArray &a); +}; + +/** + An asynchronous event + + Events are produced in response to the library's need for some user + intervention, such as entering a pin or password, or inserting a cryptographic + token. + + Event is an abstraction, so you can handle this need in a way that makes sense + for your application. +*/ +class QCA_EXPORT Event +{ +public: + /** + %Type of event + + \sa type() + */ + enum Type { - Q_OBJECT - public: - virtual ~Context(); - - /** - The Provider associated with this Context - */ - Provider *provider() const; - - /** - The type of context, as passed to the constructor - */ - QString type() const; - - /** - Create a duplicate of this Context - */ - virtual Context *clone() const = 0; - - /** - Test if two Contexts have the same Provider - - \param c pointer to the Context to compare to - - \return true if the argument and this Context - have the same provider. - */ - bool sameProvider(const Context *c) const; - - protected: - /** - Standard constructor - - \param parent the parent provider for this - context - \param type the name of the provider context type - */ - Context(Provider *parent, const QString &type); - - // copy constructor - Context(const Context &from); - - private: - // disable assignment - Context & operator=(const Context &from); - - Provider *_provider; - QString _type; - }; - - class QCA_EXPORT BasicContext : public Provider::Context - { - Q_OBJECT - public: - ~BasicContext(); - - protected: - BasicContext(Provider *parent, const QString &type); - BasicContext(const BasicContext &from); - - private: - // disable assignment - BasicContext & operator=(const BasicContext &from); + Password, ///< Asking for a password, PIN or passphrase. + Token ///< Asking for a token }; /** - \class BufferedComputation qca_core.h QtCrypto + %Source of the event - General superclass for buffered computation algorithms + Events are associated with access to a KeyStore, or access to + a file (or bytearray/stream or equivalent). This tells you the + type of source that caused the Event. - A buffered computation is characterised by having the - algorithm take data in an incremental way, then having - the results delivered at the end. Conceptually, the - algorithm has some internal state that is modified - when you call update() and returned when you call - final(). + \sa source() + \sa fileName() for the name, if source is Event::Data + \sa keyStoreInfo() and keyStoreEntry() for the keystore and entry, if + the source is Event::KeyStore */ - class QCA_EXPORT BufferedComputation + enum Source { - public: - virtual ~BufferedComputation(); - - /** - Reset the internal state - */ - virtual void clear() = 0; - - /** - Update the internal state with a byte array - - \param a the byte array of data that is to - be used to update the internal state. - */ - virtual void update(const SecureArray &a) = 0; - - /** - Complete the algorithm and return the internal state - */ - virtual SecureArray final() = 0; - - /** - Perform an "all in one" update, returning - the result. This is appropriate if you - have all the data in one array - just - call process on that array, and you will - get back the results of the computation. - - \note This will invalidate any previous - computation using this object. - */ - SecureArray process(const SecureArray &a); + KeyStore, ///< KeyStore generated the event + Data ///< File or bytearray generated the event }; /** - \class Filter qca_core.h QtCrypto + password variation - General superclass for filtering transformation algorithms + If the Type of Event is Password, PasswordStyle tells you whether + it is a PIN, passphrase or password. - A filtering computation is characterised by having the - algorithm take input data in an incremental way, with results - delivered for each input, or block of input. Some internal - state may be managed, with the transformation completed - when final() is called. - - If this seems a big vague, then you might try deriving - your class from a subclass with stronger semantics, or if your - update() function is always returning null results, and - everything comes out at final(), try BufferedComputation. + \sa passwordStyle() */ - class QCA_EXPORT Filter + enum PasswordStyle { - public: - virtual ~Filter(); - - /** - Reset the internal state - */ - virtual void clear() = 0; - - /** - Process more data, returning the corresponding - filtered version of the data. - - \param a the array containing data to process - */ - virtual SecureArray update(const SecureArray &a) = 0; - - /** - Complete the algorithm, returning any - additional results. - */ - virtual SecureArray final() = 0; - - /** - Test if an update() or final() call succeeded. - - \return true if the previous call succeeded - */ - virtual bool ok() const = 0; - - /** - Perform an "all in one" update, returning - the result. This is appropriate if you - have all the data in one array - just - call process on that array, and you will - get back the results of the computation. - - \note This will invalidate any previous - computation using this object. - */ - SecureArray process(const SecureArray &a); + StylePassword, ///< User should be prompted for a "Password" + StylePassphrase, ///< User should be prompted for a "Passphrase" + StylePIN ///< User should be prompted for a "PIN" }; /** - \class Algorithm qca_core.h QtCrypto - - General superclass for an algorithm. - - This is a fairly abstract class, mainly used for - implementing the backend "provider" interface. + Constructor */ - class QCA_EXPORT Algorithm - { - public: - /** - Standard copy constructor - - \param from the Algorithm to copy from - */ - Algorithm(const Algorithm &from); - - virtual ~Algorithm(); - - /** - Assignment operator - - \param from the Algorithm to copy state from - */ - Algorithm & operator=(const Algorithm &from); - - /** - The name of the algorithm type. - */ - QString type() const; - - /** - The name of the provider - - Each algorithm is implemented by a provider. This - allows you to figure out which provider is associated - */ - Provider *provider() const; - - // Note: The next five functions are not public! - - /** - \internal - - The context associated with this algorithm - */ - Provider::Context *context(); - - /** - \internal - - The context associated with this algorithm - */ - const Provider::Context *context() const; - - /** - \internal - - Set the Provider for this algorithm - - \param c the context for the Provider to use - */ - void change(Provider::Context *c); - - /** - \internal - - \overload - - \param type the name of the algorithm to use - \param provider the name of the preferred provider - */ - void change(const QString &type, const QString &provider); - - /** - \internal - - Take the Provider from this algorithm - */ - Provider::Context *takeContext(); - - protected: - /** - Constructor for empty algorithm - */ - Algorithm(); - - /** - Constructor of a particular algorithm. - - \param type the algorithm to construct - \param provider the name of a particular Provider - */ - Algorithm(const QString &type, const QString &provider); - - private: - class Private; - QSharedDataPointer<Private> d; - }; + Event(); /** - \class SymmetricKey qca_core.h QtCrypto + Copy constructor - Container for keys for symmetric encryption algorithms. - */ - class QCA_EXPORT SymmetricKey : public SecureArray - { - public: - /** - * Construct an empty (zero length) key - */ - SymmetricKey(); - - /** - * Construct an key of specified size, with random contents - * - * This is intended to be used as a random session key. - * - * \param size the number of bytes for the key - * - */ - SymmetricKey(int size); - - /** - * Construct a key from a provided byte array - * - * \param a the byte array to copy - */ - SymmetricKey(const SecureArray &a); - - /** - * Construct a key from a provided byte array - * - * \param a the byte array to copy - */ - SymmetricKey(const QByteArray &a); - - /** - * Test for weak DES keys - * - * \return true if the key is a weak key for DES - */ - bool isWeakDESKey(); - }; + \param from the Event to copy from + */ + Event(const Event &from); /** - \class InitializationVector qca_core.h QtCrypto - - Container for initialisation vectors and nonces - */ - class QCA_EXPORT InitializationVector : public SecureArray - { - public: - /** - Construct an empty (zero length) initisation vector - */ - InitializationVector(); - - /** - Construct an initialisation vector of the specified size - - \param size the length of the initialisation vector, in bytes - */ - InitializationVector(int size); - - /** - Construct an initialisation vector from a provided byte array - - \param a the byte array to copy - */ - InitializationVector(const SecureArray &a); - - /** - Construct an initialisation vector from a provided byte array - - \param a the byte array to copy - */ - InitializationVector(const QByteArray &a); - }; + Destructor + */ + ~Event(); /** - An asynchronous event + Assignment operator - Events are produced in response to the library's need for some user - intervention, such as entering a pin or password, or inserting a cryptographic - token. - - Event is an abstraction, so you can handle this need in a way that makes sense - for your application. + \param from the Event to copy from */ - class QCA_EXPORT Event - { - public: - /** - %Type of event - - \sa type() - */ - enum Type - { - Password, ///< Asking for a password, PIN or passphrase. - Token ///< Asking for a token - }; - - /** - %Source of the event - - Events are associated with access to a KeyStore, or access to - a file (or bytearray/stream or equivalent). This tells you the - type of source that caused the Event. - - \sa source() - \sa fileName() for the name, if source is Event::Data - \sa keyStoreInfo() and keyStoreEntry() for the keystore and entry, if - the source is Event::KeyStore - */ - enum Source - { - KeyStore, ///< KeyStore generated the event - Data ///< File or bytearray generated the event - }; - - /** - password variation - - If the Type of Event is Password, PasswordStyle tells you whether - it is a PIN, passphrase or password. - - \sa passwordStyle() - */ - enum PasswordStyle - { - StylePassword, ///< User should be prompted for a "Password" - StylePassphrase, ///< User should be prompted for a "Passphrase" - StylePIN ///< User should be prompted for a "PIN" - }; - - /** - Constructor - */ - Event(); - - /** - Copy constructor - - \param from the Event to copy from - */ - Event(const Event &from); - - /** - Destructor - */ - ~Event(); - - /** - Assignment operator - - \param from the Event to copy from - */ - Event & operator=(const Event &from); - - /** - test if this event has been setup correctly - */ - bool isNull() const; - - /** - the Type of this event - */ - Type type() const; - - /** - the Source of this event - */ - Source source() const; - - /** - the style of password required. - - This is not meaningful unless the Type is Event::Password. - - \sa PasswordStyle - */ - PasswordStyle passwordStyle() const; - - /** - The info of the KeyStore associated with this event - - This is not meaningful unless the Source is KeyStore. - */ - KeyStoreInfo keyStoreInfo() const; - - /** - The KeyStoreEntry associated with this event - - This is not meaningful unless the Source is KeyStore. - */ - KeyStoreEntry keyStoreEntry() const; - - /** - Name or other identifier for the file or byte array - associated with this event. - - This is not meaningful unless the Source is Data. - */ - QString fileName() const; - - /** - opaque data - */ - void *ptr() const; - - /** - Set the values for this Event - - This creates a Password type event, for a keystore. - - \param pstyle the style of information required (e.g. PIN, password or passphrase) - \param keyStoreInfo info about the keystore that the information is required for - \param keyStoreEntry the entry in the keystore that the information is required for - \param ptr opaque data - */ - void setPasswordKeyStore(PasswordStyle pstyle, const KeyStoreInfo &keyStoreInfo, const KeyStoreEntry &keyStoreEntry, void *ptr); - - /** - Set the values for this Event - - This creates a Password type event, for a file. - - \param pstyle the style of information required (e.g. PIN, password or passphrase) - \param fileName the name of the file (or other identifier) that the information is required for - \param ptr opaque data - */ - void setPasswordData(PasswordStyle pstyle, const QString &fileName, void *ptr); - - /** - Set the values for this Event - - This creates a Token type event. - - \param keyStoreInfo info about the keystore that the token is required for - \param keyStoreEntry the entry in the keystore that the token is required for - \param ptr opaque data - */ - void setToken(const KeyStoreInfo &keyStoreInfo, const KeyStoreEntry &keyStoreEntry, void *ptr); - - private: - class Private; - QSharedDataPointer<Private> d; - }; + Event & operator=(const Event &from); /** - Interface class for password / passphrase / PIN and token handlers - - This class is used on client side applications to handle - the provision of passwords, passphrases and PINs by users, and - to indicate that tokens have been correctly inserted. - - The concept behind this class is that the library can raise - events (typically using PasswordAsker or TokenAsker), which - may (or may not) be handled by the application using a - handler object (that has-a EventHandler, or possibly is-a - EventHandler) that is connected to the eventReady() signal. + test if this event has been setup correctly */ - class QCA_EXPORT EventHandler : public QObject - { - Q_OBJECT - public: - /** - Constructor + bool isNull() const; - \param parent the parent object for this object - */ - EventHandler(QObject *parent = 0); - ~EventHandler(); - - /** - mandatory function to call after connecting the - signal to a slot in your application specific password - / passphrase / PIN or token handler - */ - void start(); - - /** - function to call to return the user provided - password, passphrase or PIN. - - \param id the id corresponding to the password request - \param password the user-provided password, passphrase or PIN. - - \note the id parameter is the same as that provided in the - eventReady() signal. - */ - void submitPassword(int id, const SecureArray &password); - - /** - function to call to indicate that the token has been inserted - by the user. - - \param id the id corresponding to the password request - - \note the id parameter is the same as that provided in the - eventReady() signal. - */ - void tokenOkay(int id); - - /** - function to call to indicate that the user declined to - provide a password, passphrase, PIN or token. - - \param id the id corresponding to the password request - - \note the id parameter is the same as that provided in the - eventReady() signal. - */ - void reject(int id); - - Q_SIGNALS: - /** - signal emitted when an Event requires attention. - - You typically need to connect this signal to - a compatible slot in your callback handler - */ - void eventReady(int id, const QCA::Event &context); - - private: - Q_DISABLE_COPY(EventHandler) - - class Private; - friend class Private; - Private *d; - }; - - /** - User password / passphrase / PIN handler - - This class is used to obtain a password from a user. + /** + the Type of this event */ - class QCA_EXPORT PasswordAsker : public QObject - { - Q_OBJECT - public: - /** - Construct a new asker + Type type() const; - \param parent the parent object for this QObject - */ - PasswordAsker(QObject *parent = 0); - ~PasswordAsker(); - - /** - queue a password / passphrase request associated with a key store - - \param pstyle the type of information required (e.g. PIN, passphrase or password) - \param keyStoreInfo info of the key store that the information is required for - \param keyStoreEntry the item in the key store that the information is required for (if applicable) - \param ptr opaque data - */ - void ask(Event::PasswordStyle pstyle, const KeyStoreInfo &keyStoreInfo, const KeyStoreEntry &keyStoreEntry, void *ptr); - - /** - queue a password / passphrase request associated with a file - - \param pstyle the type of information required (e.g. PIN, passphrase or password) - \param fileName the name of the file that the information is required for - \param ptr opaque data - */ - void ask(Event::PasswordStyle pstyle, const QString &fileName, void *ptr); - - /** - Cancel the pending password / passphrase request - */ - void cancel(); - - /** - Block until the password / passphrase request is - completed - - You can use the responseReady signal instead of - blocking, if appropriate. - */ - void waitForResponse(); - - /** - Determine whether the password / passphrase was accepted or not - - In this context, returning true is indicative of the user clicking "Ok" - or equivalent; and returning false indicates that either the user - clicked "Cancel" or equivalent, or that the cancel() function was - called, or that the request is still pending. - */ - bool accepted() const; - - /** - The password / passphrase / PIN provided by the user in response to - the asker request. This may be empty. - */ - SecureArray password() const; - - Q_SIGNALS: - /** - Emitted when the asker process has been completed. - - You should check whether the user accepted() the response - prior to relying on the password(). - */ - void responseReady(); - - private: - Q_DISABLE_COPY(PasswordAsker) - - class Private; - friend class Private; - Private *d; - }; - - /** - User token handler - - This class is used to request the user to insert a token. + /** + the Source of this event */ - class QCA_EXPORT TokenAsker : public QObject - { - Q_OBJECT - public: - /** - Construct a new asker + Source source() const; - \param parent the parent object for this QObject - */ - TokenAsker(QObject *parent = 0); - ~TokenAsker(); + /** + the style of password required. - /** - queue a token request associated with a key store - - \param keyStoreInfo info of the key store that the information is required for - \param keyStoreEntry the item in the key store that the information is required for (if applicable) - \param ptr opaque data - */ - void ask(const KeyStoreInfo &keyStoreInfo, const KeyStoreEntry &keyStoreEntry, void *ptr); + This is not meaningful unless the Type is Event::Password. - /** - Cancel the pending password / passphrase request - */ - void cancel(); + \sa PasswordStyle + */ + PasswordStyle passwordStyle() const; - /** - Block until the token request is completed + /** + The info of the KeyStore associated with this event - You can use the responseReady signal instead of - blocking, if appropriate. - */ - void waitForResponse(); + This is not meaningful unless the Source is KeyStore. + */ + KeyStoreInfo keyStoreInfo() const; - /** - Test if the token request was accepted or not. + /** + The KeyStoreEntry associated with this event - \return true if the token request was accepted - */ - bool accepted() const; + This is not meaningful unless the Source is KeyStore. + */ + KeyStoreEntry keyStoreEntry() const; - Q_SIGNALS: - /** - Emitted when the asker process has been completed. + /** + Name or other identifier for the file or byte array + associated with this event. - You should check whether the user accepted() the response - prior to relying on token being present. - */ - void responseReady(); + This is not meaningful unless the Source is Data. + */ + QString fileName() const; - private: - Q_DISABLE_COPY(TokenAsker) + /** + opaque data + */ + void *ptr() const; + + /** + Set the values for this Event + + This creates a Password type event, for a keystore. + + \param pstyle the style of information required (e.g. PIN, password or passphrase) + \param keyStoreInfo info about the keystore that the information is required for + \param keyStoreEntry the entry in the keystore that the information is required for + \param ptr opaque data + */ + void setPasswordKeyStore(PasswordStyle pstyle, const KeyStoreInfo &keyStoreInfo, const KeyStoreEntry &keyStoreEntry, void *ptr); + + /** + Set the values for this Event + + This creates a Password type event, for a file. + + \param pstyle the style of information required (e.g. PIN, password or passphrase) + \param fileName the name of the file (or other identifier) that the information is required for + \param ptr opaque data + */ + void setPasswordData(PasswordStyle pstyle, const QString &fileName, void *ptr); + + /** + Set the values for this Event + + This creates a Token type event. + + \param keyStoreInfo info about the keystore that the token is required for + \param keyStoreEntry the entry in the keystore that the token is required for + \param ptr opaque data + */ + void setToken(const KeyStoreInfo &keyStoreInfo, const KeyStoreEntry &keyStoreEntry, void *ptr); + +private: + class Private; + QSharedDataPointer<Private> d; +}; + +/** + Interface class for password / passphrase / PIN and token handlers + + This class is used on client side applications to handle + the provision of passwords, passphrases and PINs by users, and + to indicate that tokens have been correctly inserted. + + The concept behind this class is that the library can raise + events (typically using PasswordAsker or TokenAsker), which + may (or may not) be handled by the application using a + handler object (that has-a EventHandler, or possibly is-a + EventHandler) that is connected to the eventReady() signal. +*/ +class QCA_EXPORT EventHandler : public QObject +{ + Q_OBJECT +public: + /** + Constructor + + \param parent the parent object for this object + */ + EventHandler(QObject *parent = 0); + ~EventHandler(); + + /** + mandatory function to call after connecting the + signal to a slot in your application specific password + / passphrase / PIN or token handler + */ + void start(); + + /** + function to call to return the user provided + password, passphrase or PIN. + + \param id the id corresponding to the password request + \param password the user-provided password, passphrase or PIN. + + \note the id parameter is the same as that provided in the + eventReady() signal. + */ + void submitPassword(int id, const SecureArray &password); + + /** + function to call to indicate that the token has been inserted + by the user. + + \param id the id corresponding to the password request + + \note the id parameter is the same as that provided in the + eventReady() signal. + */ + void tokenOkay(int id); + + /** + function to call to indicate that the user declined to + provide a password, passphrase, PIN or token. + + \param id the id corresponding to the password request + + \note the id parameter is the same as that provided in the + eventReady() signal. + */ + void reject(int id); + +Q_SIGNALS: + /** + signal emitted when an Event requires attention. + + You typically need to connect this signal to + a compatible slot in your callback handler + */ + void eventReady(int id, const QCA::Event &context); + +private: + Q_DISABLE_COPY(EventHandler) + + class Private; + friend class Private; + Private *d; +}; + +/** + User password / passphrase / PIN handler + + This class is used to obtain a password from a user. +*/ +class QCA_EXPORT PasswordAsker : public QObject +{ + Q_OBJECT +public: + /** + Construct a new asker + + \param parent the parent object for this QObject + */ + PasswordAsker(QObject *parent = 0); + ~PasswordAsker(); + + /** + queue a password / passphrase request associated with a key store + + \param pstyle the type of information required (e.g. PIN, passphrase or password) + \param keyStoreInfo info of the key store that the information is required for + \param keyStoreEntry the item in the key store that the information is required for (if applicable) + \param ptr opaque data + */ + void ask(Event::PasswordStyle pstyle, const KeyStoreInfo &keyStoreInfo, const KeyStoreEntry &keyStoreEntry, void *ptr); + + /** + queue a password / passphrase request associated with a file + + \param pstyle the type of information required (e.g. PIN, passphrase or password) + \param fileName the name of the file that the information is required for + \param ptr opaque data + */ + void ask(Event::PasswordStyle pstyle, const QString &fileName, void *ptr); + + /** + Cancel the pending password / passphrase request + */ + void cancel(); + + /** + Block until the password / passphrase request is + completed + + You can use the responseReady signal instead of + blocking, if appropriate. + */ + void waitForResponse(); + + /** + Determine whether the password / passphrase was accepted or not + + In this context, returning true is indicative of the user clicking "Ok" + or equivalent; and returning false indicates that either the user + clicked "Cancel" or equivalent, or that the cancel() function was + called, or that the request is still pending. + */ + bool accepted() const; + + /** + The password / passphrase / PIN provided by the user in response to + the asker request. This may be empty. + */ + SecureArray password() const; + +Q_SIGNALS: + /** + Emitted when the asker process has been completed. + + You should check whether the user accepted() the response + prior to relying on the password(). + */ + void responseReady(); + +private: + Q_DISABLE_COPY(PasswordAsker) + + class Private; + friend class Private; + Private *d; +}; + +/** + User token handler + + This class is used to request the user to insert a token. +*/ +class QCA_EXPORT TokenAsker : public QObject +{ + Q_OBJECT +public: + /** + Construct a new asker + + \param parent the parent object for this QObject + */ + TokenAsker(QObject *parent = 0); + ~TokenAsker(); + + /** + queue a token request associated with a key store + + \param keyStoreInfo info of the key store that the information is required for + \param keyStoreEntry the item in the key store that the information is required for (if applicable) + \param ptr opaque data + */ + void ask(const KeyStoreInfo &keyStoreInfo, const KeyStoreEntry &keyStoreEntry, void *ptr); + + /** + Cancel the pending password / passphrase request + */ + void cancel(); + + /** + Block until the token request is completed + + You can use the responseReady signal instead of + blocking, if appropriate. + */ + void waitForResponse(); + + /** + Test if the token request was accepted or not. + + \return true if the token request was accepted + */ + bool accepted() const; + +Q_SIGNALS: + /** + Emitted when the asker process has been completed. + + You should check whether the user accepted() the response + prior to relying on token being present. + */ + void responseReady(); + +private: + Q_DISABLE_COPY(TokenAsker) + + class Private; + friend class Private; + Private *d; +}; - class Private; - friend class Private; - Private *d; - }; } #endif diff --git a/include/QtCrypto/qca_support.h b/include/QtCrypto/qca_support.h index f74952ae..7fa6caeb 100644 --- a/include/QtCrypto/qca_support.h +++ b/include/QtCrypto/qca_support.h @@ -47,448 +47,447 @@ #include "qca_export.h" #include "qca_tools.h" -namespace QCA +namespace QCA { + +QCA_EXPORT QByteArray methodReturnType(const QMetaObject *obj, const QByteArray &method, const QList<QByteArray> argTypes); +QCA_EXPORT bool invokeMethodWithVariants(QObject *obj, const QByteArray &method, const QVariantList &args, QVariant *ret, Qt::ConnectionType type = Qt::AutoConnection); + +class QCA_EXPORT SyncThread : public QThread { - QCA_EXPORT QByteArray methodReturnType(const QMetaObject *obj, const QByteArray &method, const QList<QByteArray> argTypes); - QCA_EXPORT bool invokeMethodWithVariants(QObject *obj, const QByteArray &method, const QVariantList &args, QVariant *ret, Qt::ConnectionType type = Qt::AutoConnection); + Q_OBJECT +public: + SyncThread(QObject *parent = 0); + ~SyncThread(); - class QCA_EXPORT SyncThread : public QThread + void start(); + void stop(); + QVariant call(QObject *obj, const QByteArray &method, const QVariantList &args = QVariantList(), bool *ok = 0); + +protected: + virtual void atStart() = 0; + virtual void atEnd() = 0; + + // reimplemented + virtual void run(); + +private: + Q_DISABLE_COPY(SyncThread) + + class Private; + friend class Private; + Private *d; +}; + +class QCA_EXPORT Synchronizer : public QObject +{ + Q_OBJECT +public: + Synchronizer(QObject *parent); + ~Synchronizer(); + + bool waitForCondition(int msecs = -1); + void conditionMet(); + +private: + Q_DISABLE_COPY(Synchronizer) + + class Private; + Private *d; +}; + +class QCA_EXPORT DirWatch : public QObject +{ + Q_OBJECT +public: + explicit DirWatch(const QString &dir = QString(), QObject *parent = 0); + ~DirWatch(); + + QString dirName() const; + void setDirName(const QString &dir); + +Q_SIGNALS: + void changed(); + +private: + Q_DISABLE_COPY(DirWatch) + + class Private; + friend class Private; + Private *d; +}; + +/** + Support class to monitor a file for activity + + %FileWatch monitors a specified file for any changes. When + the file changes, the changed() signal is emitted. +*/ +class QCA_EXPORT FileWatch : public QObject +{ + Q_OBJECT +public: + /** + Standard constructor + + \param file the name of the file to watch. If not + in this object, you can set it using setFileName() + \param parent the parent object for this object + */ + explicit FileWatch(const QString &file = QString(), QObject *parent = 0); + ~FileWatch(); + + /** + The name of the file that is being monitored + */ + QString fileName() const; + + /** + Change the file being monitored + + \param file the name of the file to monitor + */ + void setFileName(const QString &file); + +Q_SIGNALS: + /** + The changed signal is emitted when the file is + changed (e.g. modified, deleted) + */ + void changed(); + +private: + Q_DISABLE_COPY(FileWatch) + + class Private; + friend class Private; + Private *d; +}; + +class ConsolePrivate; +class ConsoleReferencePrivate; +class ConsoleReference; + +// QCA Console system +// +// QCA provides an API for asynchronous, event-based access to +// the console and stdin/stdout, as these facilities are +// otherwise not portable. The primary use of this system within +// QCA is for passphrase prompting in command-line applications, +// using the tty console type. +// +// How it works: Create a Console object for the type of console +// desired, and then use ConsoleReference to act on the console. +// Only one ConsoleReference may operate on a Console at a time. +// +// A Console object overtakes either the physical console (tty +// type) or stdin/stdout (stdio type). Only one of each type +// may be created at a time. +// +// Whenever code is written that needs a tty or stdio object, the +// code should first call one of the static methods (ttyInstance +// or stdioInstance) to see if a console object for the desired +// type exists already. If the object exists, use it. If it does +// not exist, the rule is that the relevant code should create the +// object, use the object, and then destroy the object when the +// operation is completed. +// +// By following the above rule, you can write code that utilizes +// a console without the application having to create some master +// console object for you. Of course, if the application has +// created a console then it will be used. +// +// Why make a master console object? The primary reason is that it +// is not guaranteed that all I/O will survive creation and +// destruction of a console object. If you are using the stdio +// type, then you probably want a long-lived console object. It +// is possible to capture unprocessed I/O by calling +// bytesLeftToRead or bytesLeftToWrite. However, it is not +// expected that general console-needing code will call these +// functions when utilizing a temporary console. Thus, an +// application developer would need to create his own console +// object, invoke the console-needing code, and then do his own +// extraction of the unprocessed I/O if necessary. Another reason +// to extract unprocessed I/O is if you need to switch from +// QCA::Console back to standard functions (e.g. fgets). +// +class QCA_EXPORT Console : public QObject +{ + Q_OBJECT +public: + enum Type { - Q_OBJECT - public: - SyncThread(QObject *parent = 0); - ~SyncThread(); - - void start(); - void stop(); - QVariant call(QObject *obj, const QByteArray &method, const QVariantList &args = QVariantList(), bool *ok = 0); - - protected: - virtual void atStart() = 0; - virtual void atEnd() = 0; - - // reimplemented - virtual void run(); - - private: - Q_DISABLE_COPY(SyncThread) - - class Private; - friend class Private; - Private *d; + Tty, // physical console + Stdio // stdin/stdout }; - class QCA_EXPORT Synchronizer : public QObject + enum ChannelMode { - Q_OBJECT - public: - Synchronizer(QObject *parent); - ~Synchronizer(); - - bool waitForCondition(int msecs = -1); - void conditionMet(); - - private: - Q_DISABLE_COPY(Synchronizer) - - class Private; - Private *d; + Read, // stdin + ReadWrite // stdin + stdout }; - class QCA_EXPORT DirWatch : public QObject + enum TerminalMode { - Q_OBJECT - public: - explicit DirWatch(const QString &dir = QString(), QObject *parent = 0); - ~DirWatch(); + Default, // use default terminal settings + Interactive // char-by-char input, no echo + }; - QString dirName() const; - void setDirName(const QString &dir); + Console(Type type, ChannelMode cmode, TerminalMode tmode, QObject *parent = 0); + ~Console(); - Q_SIGNALS: - void changed(); + static bool isStdinRedirected(); + static bool isStdoutRedirected(); - private: - Q_DISABLE_COPY(DirWatch) + static Console *ttyInstance(); + static Console *stdioInstance(); - class Private; - friend class Private; - Private *d; + // call release() to get access to unempty buffers + void release(); + QByteArray bytesLeftToRead(); + QByteArray bytesLeftToWrite(); + +private: + Q_DISABLE_COPY(Console) + + friend class ConsolePrivate; + ConsolePrivate *d; + + friend class ConsoleReference; +}; + +// note: only one ConsoleReference object can be active at a time +class QCA_EXPORT ConsoleReference : public QObject +{ + Q_OBJECT +public: + enum SecurityMode + { + SecurityDisabled, + SecurityEnabled + }; + + ConsoleReference(QObject *parent = 0); + ~ConsoleReference(); + + bool start(Console *console, SecurityMode mode = SecurityDisabled); + void stop(); + + // normal i/o + QByteArray read(int bytes = -1); + void write(const QByteArray &a); + + // secure i/o + SecureArray readSecure(int bytes = -1); + void writeSecure(const SecureArray &a); + + // close write channel (only if writing enabled) + void closeOutput(); + + int bytesAvailable() const; + int bytesToWrite() const; + +Q_SIGNALS: + void readyRead(); + void bytesWritten(int bytes); + void inputClosed(); + void outputClosed(); + +private: + Q_DISABLE_COPY(ConsoleReference) + + friend class ConsoleReferencePrivate; + ConsoleReferencePrivate *d; + + friend class Console; +}; + +class QCA_EXPORT ConsolePrompt : public QObject +{ + Q_OBJECT +public: + ConsolePrompt(QObject *parent = 0); + ~ConsolePrompt(); + + void getHidden(const QString &promptStr); + void getEnter(); + void waitForFinished(); + + SecureArray result() const; + +signals: + void finished(); + +private: + Q_DISABLE_COPY(ConsolePrompt) + + class Private; + friend class Private; + Private *d; +}; + +class AbstractLogDevice; + +/** + A simple logging system + + This class provides a simple but flexible approach to logging information that + may be used for debugging or system operation diagnostics. + + There is a single %Logger for each application that uses %QCA. You do not need + to create this %Logger yourself - %QCA automatically creates it on startup. You + can get access to the %Logger using the global QCA::logger() method. + + By default the Logger just accepts all messages (binary and text). If you want to + get access to those messages, you need to subclass AbstractLogDevice, and register + your subclass (using registerLogDevice()). You can then take whatever action is + appropriate (e.g. show to the user using the GUI, log to a file or send to standard + error). +*/ +class QCA_EXPORT Logger : public QObject +{ + Q_OBJECT +public: + /** + The severity of the message + + This information may be used by the log device to determine + what the appropriate action is. + */ + enum Severity + { + Quiet = 0, ///< Quiet: turn of logging + Emergency = 1, ///< Emergency: system is unusable + Alert = 2, ///< Alert: action must be taken immediately + Critical = 3, ///< Critical: critical conditions + Error = 4, ///< Error: error conditions + Warning = 5, ///< Warning: warning conditions + Notice = 6, ///< Notice: normal but significant condition + Information = 7, ///< Informational: informational messages + Debug = 8 ///< Debug: debug-level messages }; /** - Support class to monitor a file for activity + Get the current logging level - %FileWatch monitors a specified file for any changes. When - the file changes, the changed() signal is emitted. + \return Current level */ - class QCA_EXPORT FileWatch : public QObject - { - Q_OBJECT - public: - /** - Standard constructor + inline Logger::Severity level () const { return m_logLevel; } - \param file the name of the file to watch. If not - in this object, you can set it using setFileName() - \param parent the parent object for this object - */ - explicit FileWatch(const QString &file = QString(), QObject *parent = 0); - ~FileWatch(); + /** + Set the current logging level - /** - The name of the file that is being monitored - */ - QString fileName() const; + \param level new logging level - /** - Change the file being monitored + Only severities less or equal than the log level one will be logged + */ + void setLevel (Logger::Severity level); - \param file the name of the file to monitor - */ - void setFileName(const QString &file); + /** + Log a message to all available log devices - Q_SIGNALS: - /** - The changed signal is emitted when the file is - changed (e.g. modified, deleted) - */ - void changed(); + \param message the text to log + */ + void logTextMessage(const QString &message, Severity = Information); - private: - Q_DISABLE_COPY(FileWatch) + /** + Log a binary blob to all available log devices - class Private; - friend class Private; - Private *d; - }; + \param blob the information to log - class ConsolePrivate; - class ConsoleReferencePrivate; - class ConsoleReference; + \note how this is handled is quite logger specific. For + example, it might be logged as a binary, or it might be + encoded in some way + */ + void logBinaryMessage(const QByteArray &blob, Severity = Information); - // QCA Console system - // - // QCA provides an API for asynchronous, event-based access to - // the console and stdin/stdout, as these facilities are - // otherwise not portable. The primary use of this system within - // QCA is for passphrase prompting in command-line applications, - // using the tty console type. - // - // How it works: Create a Console object for the type of console - // desired, and then use ConsoleReference to act on the console. - // Only one ConsoleReference may operate on a Console at a time. - // - // A Console object overtakes either the physical console (tty - // type) or stdin/stdout (stdio type). Only one of each type - // may be created at a time. - // - // Whenever code is written that needs a tty or stdio object, the - // code should first call one of the static methods (ttyInstance - // or stdioInstance) to see if a console object for the desired - // type exists already. If the object exists, use it. If it does - // not exist, the rule is that the relevant code should create the - // object, use the object, and then destroy the object when the - // operation is completed. - // - // By following the above rule, you can write code that utilizes - // a console without the application having to create some master - // console object for you. Of course, if the application has - // created a console then it will be used. - // - // Why make a master console object? The primary reason is that it - // is not guaranteed that all I/O will survive creation and - // destruction of a console object. If you are using the stdio - // type, then you probably want a long-lived console object. It - // is possible to capture unprocessed I/O by calling - // bytesLeftToRead or bytesLeftToWrite. However, it is not - // expected that general console-needing code will call these - // functions when utilizing a temporary console. Thus, an - // application developer would need to create his own console - // object, invoke the console-needing code, and then do his own - // extraction of the unprocessed I/O if necessary. Another reason - // to extract unprocessed I/O is if you need to switch from - // QCA::Console back to standard functions (e.g. fgets). - // - class QCA_EXPORT Console : public QObject - { - Q_OBJECT - public: - enum Type - { - Tty, // physical console - Stdio // stdin/stdout - }; + /** + Add an AbstractLogDevice subclass to the existing list of loggers - enum ChannelMode - { - Read, // stdin - ReadWrite // stdin + stdout - }; + \param logger the LogDevice to add + */ + void registerLogDevice(AbstractLogDevice *logger); - enum TerminalMode - { - Default, // use default terminal settings - Interactive // char-by-char input, no echo - }; + /** + Remove an AbstractLogDevice subclass from the existing list of loggers - Console(Type type, ChannelMode cmode, TerminalMode tmode, QObject *parent = 0); - ~Console(); + \param loggerName the name of the LogDevice to remove - static bool isStdinRedirected(); - static bool isStdoutRedirected(); + \note If there are several log devices with the same name, all will be removed. + */ + void unregisterLogDevice(const QString &loggerName); - static Console *ttyInstance(); - static Console *stdioInstance(); + /** + Get a list of the names of all registered log devices + */ + QStringList currentLogDevices() const; - // call release() to get access to unempty buffers - void release(); - QByteArray bytesLeftToRead(); - QByteArray bytesLeftToWrite(); +private: + Q_DISABLE_COPY(Logger) - private: - Q_DISABLE_COPY(Console) + friend class Global; - friend class ConsolePrivate; - ConsolePrivate *d; + /** + Create a new message logger + */ + Logger(); - friend class ConsoleReference; - }; + ~Logger(); - // note: only one ConsoleReference object can be active at a time - class QCA_EXPORT ConsoleReference : public QObject - { - Q_OBJECT - public: - enum SecurityMode - { - SecurityDisabled, - SecurityEnabled - }; + QStringList m_loggerNames; + QList<AbstractLogDevice*> m_loggers; + Severity m_logLevel; +}; - ConsoleReference(QObject *parent = 0); - ~ConsoleReference(); +/** + An abstract log device +*/ +class QCA_EXPORT AbstractLogDevice : public QObject +{ + Q_OBJECT +public: + /** + The name of this log device + */ + QString name() const; - bool start(Console *console, SecurityMode mode = SecurityDisabled); - void stop(); + /** + Log a message - // normal i/o - QByteArray read(int bytes = -1); - void write(const QByteArray &a); + The default implementation does nothing - you should + override this method in your subclass to do whatever + logging is required + */ + virtual void logTextMessage( const QString &message, enum Logger::Severity severity ); - // secure i/o - SecureArray readSecure(int bytes = -1); - void writeSecure(const SecureArray &a); + /** + Log a binary blob - // close write channel (only if writing enabled) - void closeOutput(); + The default implementation does nothing - you should + override this method in your subclass to do whatever + logging is required + */ + virtual void logBinaryMessage( const QByteArray &blob, Logger::Severity severity ); - int bytesAvailable() const; - int bytesToWrite() const; +protected: + /** + Create a new message logger - Q_SIGNALS: - void readyRead(); - void bytesWritten(int bytes); - void inputClosed(); - void outputClosed(); + \param name the name of this log device + \param parent the parent for this logger + */ + explicit AbstractLogDevice(const QString &name, QObject *parent = 0); - private: - Q_DISABLE_COPY(ConsoleReference) + virtual ~AbstractLogDevice() = 0; - friend class ConsoleReferencePrivate; - ConsoleReferencePrivate *d; +private: + Q_DISABLE_COPY(AbstractLogDevice) - friend class Console; - }; + class Private; + Private *d; - class QCA_EXPORT ConsolePrompt : public QObject - { - Q_OBJECT - public: - ConsolePrompt(QObject *parent = 0); - ~ConsolePrompt(); + QString m_name; +}; - void getHidden(const QString &promptStr); - void getEnter(); - void waitForFinished(); - - SecureArray result() const; - - signals: - void finished(); - - private: - Q_DISABLE_COPY(ConsolePrompt) - - class Private; - friend class Private; - Private *d; - }; - - class AbstractLogDevice; - - /** - A simple logging system - - This class provides a simple but flexible approach to logging information that - may be used for debugging or system operation diagnostics. - - There is a single %Logger for each application that uses %QCA. You do not need - to create this %Logger yourself - %QCA automatically creates it on startup. You - can get access to the %Logger using the global QCA::logger() method. - - By default the Logger just accepts all messages (binary and text). If you want to - get access to those messages, you need to subclass AbstractLogDevice, and register - your subclass (using registerLogDevice()). You can then take whatever action is - appropriate (e.g. show to the user using the GUI, log to a file or send to standard - error). - */ - class QCA_EXPORT Logger : public QObject - { - Q_OBJECT - public: - /** - The severity of the message - - This information may be used by the log device to determine - what the appropriate action is. - */ - enum Severity - { - Quiet = 0, ///< Quiet: turn of logging - Emergency = 1, ///< Emergency: system is unusable - Alert = 2, ///< Alert: action must be taken immediately - Critical = 3, ///< Critical: critical conditions - Error = 4, ///< Error: error conditions - Warning = 5, ///< Warning: warning conditions - Notice = 6, ///< Notice: normal but significant condition - Information = 7, ///< Informational: informational messages - Debug = 8 ///< Debug: debug-level messages - }; - - /** - Get the current logging level - - \return Current level - */ - inline Logger::Severity level () const { - return m_logLevel; - } - - /** - Set the current logging level - - \param level new logging level - - Only severities less or equal than the log level one will be logged - */ - void setLevel (Logger::Severity level); - - /** - Log a message to all available log devices - - \param message the text to log - */ - void logTextMessage(const QString &message, Severity = Information); - - /** - Log a binary blob to all available log devices - - \param blob the information to log - - \note how this is handled is quite logger specific. For - example, it might be logged as a binary, or it might be - encoded in some way - */ - void logBinaryMessage(const QByteArray &blob, Severity = Information); - - /** - Add an AbstractLogDevice subclass to the existing list of loggers - - \param logger the LogDevice to add - */ - void registerLogDevice(AbstractLogDevice *logger); - - /** - Remove an AbstractLogDevice subclass from the existing list of loggers - - \param loggerName the name of the LogDevice to remove - - \note If there are several log devices with the same name, all will be removed. - */ - void unregisterLogDevice(const QString &loggerName); - - /** - Get a list of the names of all registered log devices - */ - QStringList currentLogDevices() const; - - private: - Q_DISABLE_COPY(Logger) - - friend class Global; - - /** - Create a new message logger - */ - Logger(); - - ~Logger(); - - QStringList m_loggerNames; - QList<AbstractLogDevice*> m_loggers; - Severity m_logLevel; - }; - - /** - An abstract log device - */ - class QCA_EXPORT AbstractLogDevice : public QObject - { - Q_OBJECT - public: - /** - The name of this log device - */ - QString name() const; - - /** - Log a message - - The default implementation does nothing - you should - override this method in your subclass to do whatever - logging is required - */ - virtual void logTextMessage( const QString &message, enum Logger::Severity severity ); - - /** - Log a binary blob - - The default implementation does nothing - you should - override this method in your subclass to do whatever - logging is required - */ - virtual void logBinaryMessage( const QByteArray &blob, Logger::Severity severity ); - - protected: - /** - Create a new message logger - - \param name the name of this log device - \param parent the parent for this logger - */ - explicit AbstractLogDevice(const QString &name, QObject *parent = 0); - - virtual ~AbstractLogDevice() = 0; - - private: - Q_DISABLE_COPY(AbstractLogDevice) - - class Private; - Private *d; - - QString m_name; - }; } #endif diff --git a/include/QtCrypto/qca_textfilter.h b/include/QtCrypto/qca_textfilter.h index b4c90e47..5d4e90dc 100644 --- a/include/QtCrypto/qca_textfilter.h +++ b/include/QtCrypto/qca_textfilter.h @@ -34,260 +34,261 @@ #include "qca_core.h" -namespace QCA +namespace QCA { + +/** + \class TextFilter qca_textfilter.h QtCrypto + + Superclass for text based filtering algorithms + + This differs from Filter in that it has the concept + of an algorithm that works in two directions, and + supports operations on QString arguments. +*/ +class QCA_EXPORT TextFilter : public Filter { +public: /** - \class TextFilter qca_textfilter.h QtCrypto + Standard constructor - Superclass for text based filtering algorithms - - This differs from Filter in that it has the concept - of an algorithm that works in two directions, and - supports operations on QString arguments. + \param dir the Direction that this TextFilter + should use. */ - class QCA_EXPORT TextFilter : public Filter - { - public: - /** - Standard constructor - - \param dir the Direction that this TextFilter - should use. - */ - TextFilter(Direction dir); - - /** - Reset the TextFilter - - \param dir the Direction that this TextFilter - should use. - */ - void setup(Direction dir); - - /** - Process an array in the "forward" direction, - returning an array - - This method runs in the forward direction, so - for something like a Base64 encoding, it takes - the "native" array, and returns that array - encoded in base64. - - \param a the array to encode - */ - SecureArray encode(const SecureArray &a); - - /** - Process an array in the "reverse" direction, - returning an array - - This method runs in the reverse direction, so - for something like a Base64 encoding, it takes - a Base64 encoded array, and returns the "native" - representation.. - - \param a the array to decode - */ - SecureArray decode(const SecureArray &a); - - /** - Process an array in the "forward" direction, - returning a QString - - This is equivalent to encode(), except - that it returns a QString, rather than a - byte array. - - \param a the array to encode - */ - QString arrayToString(const SecureArray &a); - - /** - Process an string in the "reverse" direction, - returning a byte array - - This is equivalent to decode(), except - that it takes a QString, rather than a - byte array. - - \param s the array to decode - */ - SecureArray stringToArray(const QString &s); - - /** - Process a string in the "forward" direction, - returning a string - - This is equivalent to encode(), except - that it takes and returns a QString, rather than - byte arrays. - - \param s the string to encode - */ - QString encodeString(const QString &s); - - /** - Process a string in the "reverse" direction, - returning a string - - This is equivalent to decode(), except - that it takes and returns a QString, rather than - byte arrays. - - \param s the string to decode - */ - QString decodeString(const QString &s); - - protected: - /** - Internal state variable for the Direction - that the filter operates in - */ - Direction _dir; - }; + TextFilter(Direction dir); /** - \class Hex qca_textfilter.h QtCrypto + Reset the TextFilter - Hexadecimal encoding / decoding + \param dir the Direction that this TextFilter + should use. */ - class QCA_EXPORT Hex : public TextFilter - { - public: - /** - Standard constructor - - \param dir the Direction that should be used. - - \note The direction can be changed using - the setup() call. - */ - Hex(Direction dir = Encode); - - /** - Reset the internal state. - - This is useful to reuse an existing Hex object - */ - virtual void clear(); - - /** - Process more data, returning the corresponding - encoded or decoded (depending on the Direction - set in the constructor or setup() call) representation. - - If you find yourself with code that only calls - this method once, you might be better off using - encode() or decode(). Similarly, if the data is - really a string, you might be better off using - arrayToString(), encodeString(), stringToArray() - or decodeString(). - - \param a the array containing data to process - */ - virtual SecureArray update(const SecureArray &a); - - /** - Complete the algorithm - - \return any remaining output. Because of the way - hexadecimal encoding works, this will return a - zero length array - any output will have been returned - from the update() call. - */ - virtual SecureArray final(); - - /** - Test if an update() or final() call succeeded. - - \return true if the previous call succeeded - */ - virtual bool ok() const; - - private: - uchar val; - bool partial; - bool _ok; - }; + void setup(Direction dir); /** - \class Base64 qca_textfilter.h QtCrypto + Process an array in the "forward" direction, + returning an array - %Base64 encoding / decoding + This method runs in the forward direction, so + for something like a Base64 encoding, it takes + the "native" array, and returns that array + encoded in base64. + + \param a the array to encode */ - class QCA_EXPORT Base64 : public TextFilter - { - public: - /** - Standard constructor + SecureArray encode(const SecureArray &a); - \param dir the Direction that should be used. + /** + Process an array in the "reverse" direction, + returning an array - \note The direction can be changed using - the setup() call. - */ - Base64(Direction dir = Encode); + This method runs in the reverse direction, so + for something like a Base64 encoding, it takes + a Base64 encoded array, and returns the "native" + representation.. - /** - Sets line break mode. If enabled, linebreaks will be - added to encoded output or accepted in encoded input. - If disabled, linebreaks in encoded input will cause - a failure to decode. The default is disabled. - */ - void setLineBreaksEnabled(bool b); + \param a the array to decode + */ + SecureArray decode(const SecureArray &a); - /** - Sets the column that linebreaks should be inserted at - when encoding. - */ - void setLineBreaksColumn(int column); + /** + Process an array in the "forward" direction, + returning a QString - /** - Reset the internal state. This is useful to - reuse an existing Base64 object - */ - virtual void clear(); + This is equivalent to encode(), except + that it returns a QString, rather than a + byte array. - /** - Process more data, returning the corresponding - encoded or decoded (depending on the Direction - set in the constructor or setup() call) representation. + \param a the array to encode + */ + QString arrayToString(const SecureArray &a); - If you find yourself with code that only calls - this method once, you might be better off using - encode() or decode(). Similarly, if the data is - really a string, you might be better off using - arrayToString(), encodeString(), stringToArray() - or decodeString(). + /** + Process an string in the "reverse" direction, + returning a byte array - \param a the array containing data to process - */ - virtual SecureArray update(const SecureArray &a); + This is equivalent to decode(), except + that it takes a QString, rather than a + byte array. - /** - Complete the algorithm + \param s the array to decode + */ + SecureArray stringToArray(const QString &s); - \return any remaining output. Because of the way - Base64 encoding works, you will get either an - empty array, or an array containing one or two - "=" (equals, 0x3D) characters. - */ - virtual SecureArray final(); + /** + Process a string in the "forward" direction, + returning a string - /** - Test if an update() or final() call succeeded. - - \return true if the previous call succeeded - */ - virtual bool ok() const; + This is equivalent to encode(), except + that it takes and returns a QString, rather than + byte arrays. + + \param s the string to encode + */ + QString encodeString(const QString &s); + + /** + Process a string in the "reverse" direction, + returning a string + + This is equivalent to decode(), except + that it takes and returns a QString, rather than + byte arrays. + + \param s the string to decode + */ + QString decodeString(const QString &s); + +protected: + /** + Internal state variable for the Direction + that the filter operates in + */ + Direction _dir; +}; + +/** + \class Hex qca_textfilter.h QtCrypto + + Hexadecimal encoding / decoding +*/ +class QCA_EXPORT Hex : public TextFilter +{ +public: + /** + Standard constructor + + \param dir the Direction that should be used. + + \note The direction can be changed using + the setup() call. + */ + Hex(Direction dir = Encode); + + /** + Reset the internal state. + + This is useful to reuse an existing Hex object + */ + virtual void clear(); + + /** + Process more data, returning the corresponding + encoded or decoded (depending on the Direction + set in the constructor or setup() call) representation. + + If you find yourself with code that only calls + this method once, you might be better off using + encode() or decode(). Similarly, if the data is + really a string, you might be better off using + arrayToString(), encodeString(), stringToArray() + or decodeString(). + + \param a the array containing data to process + */ + virtual SecureArray update(const SecureArray &a); + + /** + Complete the algorithm + + \return any remaining output. Because of the way + hexadecimal encoding works, this will return a + zero length array - any output will have been returned + from the update() call. + */ + virtual SecureArray final(); + + /** + Test if an update() or final() call succeeded. + + \return true if the previous call succeeded + */ + virtual bool ok() const; + +private: + uchar val; + bool partial; + bool _ok; +}; + +/** + \class Base64 qca_textfilter.h QtCrypto + + %Base64 encoding / decoding +*/ +class QCA_EXPORT Base64 : public TextFilter +{ +public: + /** + Standard constructor + + \param dir the Direction that should be used. + + \note The direction can be changed using + the setup() call. + */ + Base64(Direction dir = Encode); + + /** + Sets line break mode. If enabled, linebreaks will be + added to encoded output or accepted in encoded input. + If disabled, linebreaks in encoded input will cause + a failure to decode. The default is disabled. + */ + void setLineBreaksEnabled(bool b); + + /** + Sets the column that linebreaks should be inserted at + when encoding. + */ + void setLineBreaksColumn(int column); + + /** + Reset the internal state. This is useful to + reuse an existing Base64 object + */ + virtual void clear(); + + /** + Process more data, returning the corresponding + encoded or decoded (depending on the Direction + set in the constructor or setup() call) representation. + + If you find yourself with code that only calls + this method once, you might be better off using + encode() or decode(). Similarly, if the data is + really a string, you might be better off using + arrayToString(), encodeString(), stringToArray() + or decodeString(). + + \param a the array containing data to process + */ + virtual SecureArray update(const SecureArray &a); + + /** + Complete the algorithm + + \return any remaining output. Because of the way + Base64 encoding works, you will get either an + empty array, or an array containing one or two + "=" (equals, 0x3D) characters. + */ + virtual SecureArray final(); + + /** + Test if an update() or final() call succeeded. + + \return true if the previous call succeeded + */ + virtual bool ok() const; + +private: + SecureArray partial; + bool _ok; + int col; + bool _lb_enabled; + int _lb_column; +}; - private: - SecureArray partial; - bool _ok; - int col; - bool _lb_enabled; - int _lb_column; - }; } #endif diff --git a/include/QtCrypto/qca_tools.h b/include/QtCrypto/qca_tools.h index c4ad5ddf..9adee277 100644 --- a/include/QtCrypto/qca_tools.h +++ b/include/QtCrypto/qca_tools.h @@ -75,212 +75,206 @@ QCA_EXPORT void *qca_secure_realloc(void *p, int bytes); namespace QCA { /** - \class SecureArray qca_tools.h QtCrypto + \class SecureArray qca_tools.h QtCrypto - Secure array of bytes + Secure array of bytes - The %SecureArray provides an array of memory from a pool that is, - at least partly, secure. In this sense, secure means that the contents - of the memory should not be made available to other applications. By - comparison, a QMemArray (or subclass such as QCString or QByteArray) may - be held in pages that might be swapped to disk or free'd without being - cleared first. - - Note that this class is implicitly shared (that is, copy on write). - **/ + The %SecureArray provides an array of memory from a pool that is, + at least partly, secure. In this sense, secure means that the contents + of the memory should not be made available to other applications. By + comparison, a QMemArray (or subclass such as QCString or QByteArray) may + be held in pages that might be swapped to disk or free'd without being + cleared first. + + Note that this class is implicitly shared (that is, copy on write). +*/ class QCA_EXPORT SecureArray { public: /** - * Construct a secure byte array, zero length - */ + Construct a secure byte array, zero length + */ SecureArray(); /** - * Construct a secure byte array of the specified length - * - * \param size the number of bytes in the array - * \param ch the value every byte should be set to - */ + Construct a secure byte array of the specified length + + \param size the number of bytes in the array + \param ch the value every byte should be set to + */ explicit SecureArray(int size, char ch = 0); /** - * Construct a secure byte array from a string - * - * Note that this copies, rather than references the source array - */ + Construct a secure byte array from a string + + Note that this copies, rather than references the source array + */ SecureArray(const char *str); /** - * Construct a secure byte array from a QByteArray - * - * Note that this copies, rather than references the source array - * - * \sa operator=() - */ + Construct a secure byte array from a QByteArray + + Note that this copies, rather than references the source array + + \sa operator=() + */ SecureArray(const QByteArray &a); /** - * Construct a (shallow) copy of another secure byte array - * - * \param from the source of the data and length. - */ + Construct a (shallow) copy of another secure byte array + + \param from the source of the data and length. + */ SecureArray(const SecureArray &from); ~SecureArray(); - /** - * Creates a reference, rather than a deep copy. - * if you want a deep copy then you should use copy() - * instead, or use operator=(), then call detach() when required. - */ + /** + Creates a reference, rather than a deep copy. + */ SecureArray & operator=(const SecureArray &from); /** - * Creates a copy, rather than references - * - * \param a the array to copy from - */ + Creates a copy, rather than references + + \param a the array to copy from + */ SecureArray & operator=(const QByteArray &a); /** - * Clears the contents of the array and makes it empty - */ + Clears the contents of the array and makes it empty + */ void clear(); /** - * Returns a reference to the byte at the index position - * - * \param index the zero-based offset to obtain - */ + Returns a reference to the byte at the index position + + \param index the zero-based offset to obtain + */ char & operator[](int index); /** - * Returns a reference to the byte at the index position - * - * \param index the zero-based offset to obtain - */ + Returns a reference to the byte at the index position + + \param index the zero-based offset to obtain + */ const char & operator[](int index) const; /** - * Pointer to the data in the secure array - * - * You can use this for memcpy and similar functions. If you are trying - * to obtain data at a particular offset, you might be better off using - * at() or operator[] - * - */ + Pointer to the data in the secure array + + You can use this for memcpy and similar functions. If you are trying + to obtain data at a particular offset, you might be better off using + at() or operator[] + */ char *data(); /** - * Pointer to the data in the secure array - * - * You can use this for memcpy and similar functions. If you are trying - * to obtain data at a particular offset, you might be better off using - * at() or operator[] - * - */ + Pointer to the data in the secure array + + You can use this for memcpy and similar functions. If you are trying + to obtain data at a particular offset, you might be better off using + at() or operator[] + */ const char *data() const; /** - * Pointer to the data in the secure array - * - * You can use this for memcpy and similar functions. If you are trying - * to obtain data at a particular offset, you might be better off using - * at() or operator[] - * - */ + Pointer to the data in the secure array + + You can use this for memcpy and similar functions. If you are trying + to obtain data at a particular offset, you might be better off using + at() or operator[] + */ const char *constData() const; /** - * Returns a reference to the byte at the index position - * - * \param index the zero-based offset to obtain - */ + Returns a reference to the byte at the index position + + \param index the zero-based offset to obtain + */ char & at(int index); /** - * Returns a reference to the byte at the index position - * - * \param index the zero-based offset to obtain - */ + Returns a reference to the byte at the index position + + \param index the zero-based offset to obtain + */ const char & at(int index) const; /** - * Returns the number of bytes in the array - */ + Returns the number of bytes in the array + */ int size() const; /** - * Test if the array contains any bytes. - * - * This is equivalent to testing (size() != 0). Note that if - * the array is allocated, isEmpty() is false (even if no data - * has been added) - * - * \return true if the array has zero length, otherwise false - */ + Test if the array contains any bytes. + + This is equivalent to testing (size() != 0). Note that if + the array is allocated, isEmpty() is false (even if no data + has been added) + + \return true if the array has zero length, otherwise false + */ bool isEmpty() const; /** - * Change the length of this array - * If the new length is less than the old length, the extra information - * is (safely) discarded. If the new length is equal to or greater than - * the old length, the existing data is copied into the array. - * - * \param size the new length - */ + Change the length of this array + If the new length is less than the old length, the extra information + is (safely) discarded. If the new length is equal to or greater than + the old length, the existing data is copied into the array. + + \param size the new length + */ bool resize(int size); - /** - * Fill the data array with a specified character - * - * \param fillChar the character to use as the fill - * \param fillToPosition the number of characters to fill - * to. If not specified (or -1), fills array to - * current length. - * - * \note This function does not extend the array - if - * you ask for fill beyond the current length, only - * the current length will be used. - * \note The number of characters is 1 based, so if - * you ask for fill('x', 10), it will fill from - * - */ + /** + Fill the data array with a specified character + + \param fillChar the character to use as the fill + \param fillToPosition the number of characters to fill + to. If not specified (or -1), fills array to + current length. + + \note This function does not extend the array - if + you ask for fill beyond the current length, only + the current length will be used. + \note The number of characters is 1 based, so if + you ask for fill('x', 10), it will fill from + */ void fill(char fillChar, int fillToPosition = -1); /** - * Copy the contents of the secure array out to a - * standard QByteArray. Note that this performs a deep copy - * of the data. - */ + Copy the contents of the secure array out to a + standard QByteArray. Note that this performs a deep copy + of the data. + */ QByteArray toByteArray() const; /** - * Append a secure byte array to the end of this array - */ + Append a secure byte array to the end of this array + */ SecureArray & append(const SecureArray &a); /** - * Append a secure byte array to the end of this array - */ + Append a secure byte array to the end of this array + */ SecureArray & operator+=(const SecureArray &a); protected: /** - * Assign the contents of a provided byte array to this - * object. - * - * \param from the byte array to copy - */ + Assign the contents of a provided byte array to this + object. + + \param from the byte array to copy + */ void set(const SecureArray &from); /** - * Assign the contents of a provided byte array to this - * object. - * - * \param from the byte array to copy - */ + Assign the contents of a provided byte array to this + object. + + \param from the byte array to copy + */ void set(const QByteArray &from); private: @@ -289,27 +283,27 @@ private: }; /** - * Equality operator. Returns true if the two SecureArray - * arguments have the same data (and the same length, of course). - * - * \relates SecureArray - **/ + Equality operator. Returns true if the two SecureArray + arguments have the same data (and the same length, of course). + + \relates SecureArray +*/ QCA_EXPORT bool operator==(const SecureArray &a, const SecureArray &b); /** - * Inequality operator. Returns true if the two SecureArray - * arguments have different length, or the same length but - * different data - * - * \relates SecureArray - **/ + Inequality operator. Returns true if the two SecureArray + arguments have different length, or the same length but + different data + + \relates SecureArray +*/ QCA_EXPORT bool operator!=(const SecureArray &a, const SecureArray &b); /** - * Returns an array that is the result of concatenating a and b - * - * \relates SecureArray - **/ + Returns an array that is the result of concatenating a and b + + \relates SecureArray +*/ QCA_EXPORT const SecureArray operator+(const SecureArray &a, const SecureArray &b); /** @@ -319,184 +313,183 @@ QCA_EXPORT const SecureArray operator+(const SecureArray &a, const SecureArray & BigInteger provides arbitrary precision integers. \code - if ( BigInteger("3499543804349") == - BigInteger("38493290803248") + BigInteger( 343 ) ) - { - // do something - } +if ( BigInteger("3499543804349") == + BigInteger("38493290803248") + BigInteger( 343 ) ) +{ + // do something +} \endcode - **/ +*/ class QCA_EXPORT BigInteger { public: /** - * Constructor. Creates a new BigInteger, initialised to zero. - */ + Constructor. Creates a new BigInteger, initialised to zero. + */ BigInteger(); /** - * \overload - * - * \param n an alternative integer initialisation value. - */ + \overload + + \param n an alternative integer initialisation value. + */ BigInteger(int n); /** - * \overload - * - * \param c an alternative initialisation value, encoded as a character array - * - * \code - * BigInteger b ( "9890343" ); - * \endcode - */ + \overload + + \param c an alternative initialisation value, encoded as a character array + + \code +BigInteger b ( "9890343" ); + \endcode + */ BigInteger(const char *c); /** - * \overload - * - * \param s an alternative initialisation value, encoded as a string - */ + \overload + + \param s an alternative initialisation value, encoded as a string + */ BigInteger(const QString &s); /** - * \overload - * - * \param a an alternative initialisation value, encoded as SecureArray - */ + \overload + + \param a an alternative initialisation value, encoded as SecureArray + */ BigInteger(const QCA::SecureArray &a); /** - * \overload - * - * \param from an alternative initialisation value, encoded as a %BigInteger - */ + \overload + + \param from an alternative initialisation value, encoded as a %BigInteger + */ BigInteger(const BigInteger &from); ~BigInteger(); /** - * Assignment operator - * - * \param from the BigInteger to copy from - * - * \code - * BigInteger a; // a is zero - * BigInteger b( 500 ); - * a = b; // a is now 500 - * \endcode - */ + Assignment operator + + \param from the BigInteger to copy from + + \code +BigInteger a; // a is zero +BigInteger b( 500 ); +a = b; // a is now 500 + \endcode + */ BigInteger & operator=(const BigInteger &from); /** - * \overload - * - * \param s the QString containing an integer representation - * - * \sa bool fromString(const QString &s) - * - * \note it is the application's responsibility to make sure - * that the QString represents a valid integer (ie it only - * contains numbers and an optional minus sign at the start) - * - **/ + \overload + + \param s the QString containing an integer representation + + \sa bool fromString(const QString &s) + + \note it is the application's responsibility to make sure + that the QString represents a valid integer (ie it only + contains numbers and an optional minus sign at the start) + */ BigInteger & operator=(const QString &s); /** - * Increment in place operator - * - * \param b the amount to increment by - * - * \code - * BigInteger a; // a is zero - * BigInteger b( 500 ); - * a += b; // a is now 500 - * a += b; // a is now 1000 - * \endcode - **/ + Increment in place operator + + \param b the amount to increment by + + \code +BigInteger a; // a is zero +BigInteger b( 500 ); +a += b; // a is now 500 +a += b; // a is now 1000 + \endcode + */ BigInteger & operator+=(const BigInteger &b); /** - * Decrement in place operator - * - * \param b the amount to decrement by - * - * \code - * BigInteger a; // a is zero - * BigInteger b( 500 ); - * a -= b; // a is now -500 - * a -= b; // a is now -1000 - * \endcode - **/ + Decrement in place operator + + \param b the amount to decrement by + + \code +BigInteger a; // a is zero +BigInteger b( 500 ); +a -= b; // a is now -500 +a -= b; // a is now -1000 + \endcode + */ BigInteger & operator-=(const BigInteger &b); - /** - * Output %BigInteger as a byte array, useful for storage or - * transmission. The format is a binary integer in sign-extended - * network-byte-order. - * - * \sa void fromArray(const SecureArray &a); - */ + /** + Output %BigInteger as a byte array, useful for storage or + transmission. The format is a binary integer in sign-extended + network-byte-order. + + \sa void fromArray(const SecureArray &a); + */ QCA::SecureArray toArray() const; /** - * Assign from an array. The input is expected to be a binary integer - * in sign-extended network-byte-order. - * - * \param a a SecureArray that represents an integer - * - * \sa BigInteger(const SecureArray &a); - * \sa SecureArray toArray() const; - */ + Assign from an array. The input is expected to be a binary integer + in sign-extended network-byte-order. + + \param a a SecureArray that represents an integer + + \sa BigInteger(const SecureArray &a); + \sa SecureArray toArray() const; + */ void fromArray(const QCA::SecureArray &a); - /** - * Convert %BigInteger to a QString - * - * \code - * QString aString; - * BigInteger aBiggishInteger( 5878990 ); - * aString = aBiggishInteger.toString(); // aString is now "5878990" - * \endcode - */ + /** + Convert %BigInteger to a QString + + \code +QString aString; +BigInteger aBiggishInteger( 5878990 ); +aString = aBiggishInteger.toString(); // aString is now "5878990" + \endcode + */ QString toString() const; /** - * Assign from a QString - * - * \param s a QString that represents an integer - * - * \note it is the application's responsibility to make sure - * that the QString represents a valid integer (ie it only - * contains numbers and an optional minus sign at the start) - * - * \sa BigInteger(const QString &s) - * \sa BigInteger & operator=(const QString &s) - */ + Assign from a QString + + \param s a QString that represents an integer + + \note it is the application's responsibility to make sure + that the QString represents a valid integer (ie it only + contains numbers and an optional minus sign at the start) + + \sa BigInteger(const QString &s) + \sa BigInteger & operator=(const QString &s) + */ bool fromString(const QString &s); - /** - * Compare this value with another %BigInteger - * - * Normally it is more readable to use one of the operator overloads, - * so you don't need to use this method directly. - * - * \param n the BigInteger to compare with - * - * \return zero if the values are the same, negative if the argument - * is less than the value of this BigInteger, and positive if the argument - * value is greater than this BigInteger - * - * \code - * BigInteger a( "400" ); - * BigInteger b( "-400" ); - * BigInteger c( " 200 " ); - * int result; - * result = a.compare( b ); // return positive 400 > -400 - * result = a.compare( c ); // return positive, 400 > 200 - * result = b.compare( c ); // return negative, -400 < 200 - * \endcode - **/ + /** + Compare this value with another %BigInteger + + Normally it is more readable to use one of the operator overloads, + so you don't need to use this method directly. + + \param n the BigInteger to compare with + + \return zero if the values are the same, negative if the argument + is less than the value of this BigInteger, and positive if the argument + value is greater than this BigInteger + + \code +BigInteger a( "400" ); +BigInteger b( "-400" ); +BigInteger c( " 200 " ); +int result; +result = a.compare( b ); // return positive 400 > -400 +result = a.compare( c ); // return positive, 400 > 200 +result = b.compare( c ); // return negative, -400 < 200 + \endcode + */ int compare(const BigInteger &n) const; private: @@ -505,80 +498,80 @@ private: }; /** - * Equality operator. Returns true if the two BigInteger values - * are the same, including having the same sign. - * - * \relates BigInteger - **/ + Equality operator. Returns true if the two BigInteger values + are the same, including having the same sign + + \relates BigInteger +*/ inline bool operator==(const BigInteger &a, const BigInteger &b) { return (0 == a.compare( b ) ); } /** - * Inequality operator. Returns true if the two BigInteger values - * are different in magnitude, sign or both - * - * \relates BigInteger - **/ + Inequality operator. Returns true if the two BigInteger values + are different in magnitude, sign or both + + \relates BigInteger +*/ inline bool operator!=(const BigInteger &a, const BigInteger &b) { return (0 != a.compare( b ) ); } /** - * Less than or equal operator. Returns true if the BigInteger value - * on the left hand side is equal to or less than the BigInteger value - * on the right hand side. - * - * \relates BigInteger - **/ + Less than or equal operator. Returns true if the BigInteger value + on the left hand side is equal to or less than the BigInteger value + on the right hand side. + + \relates BigInteger +*/ inline bool operator<=(const BigInteger &a, const BigInteger &b) { return (a.compare( b ) <= 0 ); } /** - * Greater than or equal operator. Returns true if the BigInteger value - * on the left hand side is equal to or greater than the BigInteger value - * on the right hand side. - * - * \relates BigInteger - **/ + Greater than or equal operator. Returns true if the BigInteger value + on the left hand side is equal to or greater than the BigInteger value + on the right hand side. + + \relates BigInteger +*/ inline bool operator>=(const BigInteger &a, const BigInteger &b) { return (a.compare( b ) >= 0 ); } /** - * Less than operator. Returns true if the BigInteger value - * on the left hand side is less than the BigInteger value - * on the right hand side. - * - * \relates BigInteger - **/ + Less than operator. Returns true if the BigInteger value + on the left hand side is less than the BigInteger value + on the right hand side. + + \relates BigInteger +*/ inline bool operator<(const BigInteger &a, const BigInteger &b) { return (a.compare( b ) < 0 ); } /** - * Greater than operator. Returns true if the BigInteger value - * on the left hand side is greater than the BigInteger value - * on the right hand side. - * - * \relates BigInteger - **/ + Greater than operator. Returns true if the BigInteger value + on the left hand side is greater than the BigInteger value + on the right hand side. + + \relates BigInteger +*/ inline bool operator>(const BigInteger &a, const BigInteger &b) { return (a.compare( b ) > 0 ); } /** - * Stream operator. - * - * \relates BigInteger - **/ + Stream operator + + \relates BigInteger +*/ QCA_EXPORT QTextStream &operator<<(QTextStream &stream, const BigInteger &b); } diff --git a/src/qca_plugin.h b/src/qca_plugin.h index 723e448c..c0dc50cc 100644 --- a/src/qca_plugin.h +++ b/src/qca_plugin.h @@ -27,45 +27,46 @@ #include "qca_core.h" #include <QMutex> -namespace QCA +namespace QCA { + +class ProviderItem; + +class ProviderManager { - class ProviderItem; +public: + ProviderManager(); + ~ProviderManager(); - class ProviderManager - { - public: - ProviderManager(); - ~ProviderManager(); + void scan(); + bool add(Provider *p, int priority); + void unload(const QString &name); + void unloadAll(); + void setDefault(Provider *p); + Provider *find(Provider *p) const; + Provider *find(const QString &name) const; + Provider *findFor(const QString &name, const QString &type) const; + void changePriority(const QString &name, int priority); + int getPriority(const QString &name); + QStringList allFeatures() const; + ProviderList providers() const; - void scan(); - bool add(Provider *p, int priority); - void unload(const QString &name); - void unloadAll(); - void setDefault(Provider *p); - Provider *find(Provider *p) const; - Provider *find(const QString &name) const; - Provider *findFor(const QString &name, const QString &type) const; - void changePriority(const QString &name, int priority); - int getPriority(const QString &name); - QStringList allFeatures() const; - ProviderList providers() const; + static void mergeFeatures(QStringList *a, const QStringList &b); - static void mergeFeatures(QStringList *a, const QStringList &b); + QString diagnosticText() const; + void appendDiagnosticText(const QString &str); + void clearDiagnosticText(); - QString diagnosticText() const; - void appendDiagnosticText(const QString &str); - void clearDiagnosticText(); +private: + mutable QMutex logMutex, providerMutex; + QString dtext; + QList<ProviderItem*> providerItemList; + ProviderList providerList; + Provider *def; + bool scanned_static; + void addItem(ProviderItem *i, int priority); + bool haveAlready(const QString &name) const; +}; - private: - mutable QMutex logMutex, providerMutex; - QString dtext; - QList<ProviderItem*> providerItemList; - ProviderList providerList; - Provider *def; - bool scanned_static; - void addItem(ProviderItem *i, int priority); - bool haveAlready(const QString &name) const; - }; } #endif diff --git a/src/qca_systemstore.h b/src/qca_systemstore.h index 64956e1c..48bcdb56 100644 --- a/src/qca_systemstore.h +++ b/src/qca_systemstore.h @@ -25,10 +25,11 @@ #include "qca_cert.h" -namespace QCA -{ - bool qca_have_systemstore(); - CertificateCollection qca_get_systemstore(const QString &provider); +namespace QCA { + +bool qca_have_systemstore(); +CertificateCollection qca_get_systemstore(const QString &provider); + } #endif